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("01A.FillTheMatrixA")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("01A.FillTheMatrixA")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("66399844-35aa-4d7d-958f-71a699620b2d")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.081081 | 84 | 0.745919 | [
"MIT"
] | DimitarGaydardzhiev/TelerikAcademy | 02. C# Part 2/02. Multidimensional-Arrays/01A.FillTheMatrixA/Properties/AssemblyInfo.cs | 1,412 | C# |
using UnityEngine;
using System.Collections;
public class Respawn : MonoBehaviour
{
public Transform RespawnNode;
void OnTriggerEnter2D(Collider2D other)
{
other.transform.position = RespawnNode.position;
}
}
| 18.153846 | 56 | 0.724576 | [
"MIT"
] | choang05/Asset1 | Assets/Easy Indicators/Demos/Demo1- 2D Fighter/Scripts/Respawn.cs | 238 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using Leelite.Framework.Domain.Aggregate;
namespace Leelite.Modules.MessageCenter.Models.TemplateAgg
{
/// <summary>
/// 消息模版
/// </summary>
public class Template : AggregateRoot<int>
{
/// <summary>
/// 平台Id
/// </summary>
public int PlatformId { get; set; }
/// <summary>
/// 消息类型编码
/// </summary>
public string MessageTypeCode { get; set; }
/// <summary>
/// 模版名称
/// </summary>
public string Name { get; set; }
/// <summary>
/// 模版描述
/// </summary>
public string Description { get; set; }
/// <summary>
/// 第三方模版编码
/// </summary>
public string TemplateCode { get; set; }
/// <summary>
/// 内容模版
/// 使用StringTemplate进行渲染
/// </summary>
public string ContentTemplate { get; set; }
/// <summary>
/// 链接模版
/// 使用StringTemplate进行渲染
/// </summary>
public string UrlTemplate { get; set; }
}
}
| 22.117647 | 58 | 0.504433 | [
"MIT"
] | liduopie/LeeliteCore | src/Modules/Message/Leelite.Modules.MessageCenter/Models/TemplateAgg/Template.cs | 1,224 | 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 rds-2014-10-31.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.RDS.Model
{
/// <summary>
/// Container for the parameters to the CreateDBSnapshot operation.
/// Creates a snapshot of a DB instance. The source DB instance must be in the <code>available</code>
/// or <code>storage-optimization</code>state.
/// </summary>
public partial class CreateDBSnapshotRequest : AmazonRDSRequest
{
private string _dbInstanceIdentifier;
private string _dbSnapshotIdentifier;
private List<Tag> _tags = new List<Tag>();
/// <summary>
/// Empty constructor used to set properties independently even when a simple constructor is available
/// </summary>
public CreateDBSnapshotRequest() { }
/// <summary>
/// Instantiates CreateDBSnapshotRequest with the parameterized properties
/// </summary>
/// <param name="dbSnapshotIdentifier">The identifier for the DB snapshot. Constraints: <ul> <li> Can't be null, empty, or blank </li> <li> Must contain from 1 to 255 letters, numbers, or hyphens </li> <li> First character must be a letter </li> <li> Can't end with a hyphen or contain two consecutive hyphens </li> </ul> Example: <code>my-snapshot-id</code> </param>
/// <param name="dbInstanceIdentifier">The identifier of the DB instance that you want to create the snapshot of. Constraints: <ul> <li> Must match the identifier of an existing DBInstance. </li> </ul></param>
public CreateDBSnapshotRequest(string dbSnapshotIdentifier, string dbInstanceIdentifier)
{
_dbSnapshotIdentifier = dbSnapshotIdentifier;
_dbInstanceIdentifier = dbInstanceIdentifier;
}
/// <summary>
/// Gets and sets the property DBInstanceIdentifier.
/// <para>
/// The identifier of the DB instance that you want to create the snapshot of.
/// </para>
///
/// <para>
/// Constraints:
/// </para>
/// <ul> <li>
/// <para>
/// Must match the identifier of an existing DBInstance.
/// </para>
/// </li> </ul>
/// </summary>
[AWSProperty(Required=true)]
public string DBInstanceIdentifier
{
get { return this._dbInstanceIdentifier; }
set { this._dbInstanceIdentifier = value; }
}
// Check to see if DBInstanceIdentifier property is set
internal bool IsSetDBInstanceIdentifier()
{
return this._dbInstanceIdentifier != null;
}
/// <summary>
/// Gets and sets the property DBSnapshotIdentifier.
/// <para>
/// The identifier for the DB snapshot.
/// </para>
///
/// <para>
/// Constraints:
/// </para>
/// <ul> <li>
/// <para>
/// Can't be null, empty, or blank
/// </para>
/// </li> <li>
/// <para>
/// Must contain from 1 to 255 letters, numbers, or hyphens
/// </para>
/// </li> <li>
/// <para>
/// First character must be a letter
/// </para>
/// </li> <li>
/// <para>
/// Can't end with a hyphen or contain two consecutive hyphens
/// </para>
/// </li> </ul>
/// <para>
/// Example: <code>my-snapshot-id</code>
/// </para>
/// </summary>
[AWSProperty(Required=true)]
public string DBSnapshotIdentifier
{
get { return this._dbSnapshotIdentifier; }
set { this._dbSnapshotIdentifier = value; }
}
// Check to see if DBSnapshotIdentifier property is set
internal bool IsSetDBSnapshotIdentifier()
{
return this._dbSnapshotIdentifier != null;
}
/// <summary>
/// Gets and sets the property Tags.
/// </summary>
public List<Tag> Tags
{
get { return this._tags; }
set { this._tags = value; }
}
// Check to see if Tags property is set
internal bool IsSetTags()
{
return this._tags != null && this._tags.Count > 0;
}
}
} | 35.034483 | 375 | 0.58937 | [
"Apache-2.0"
] | Singh400/aws-sdk-net | sdk/src/Services/RDS/Generated/Model/CreateDBSnapshotRequest.cs | 5,080 | C# |
using System;
using System.Collections.Generic;
namespace NaniWeb.Data
{
public class Chapter
{
public int Id { get; set; }
public int Volume { get; set; }
public decimal ChapterNumber { get; set; }
public string Name { get; set; }
public int SeriesId { get; set; }
public DateTime ReleaseDate { get; set; }
public Series Series { get; set; }
public List<Page> Pages { get; set; }
}
} | 25.722222 | 50 | 0.589633 | [
"MIT"
] | Dinokin/NaniWeb | NaniWeb/Data/Chapter.cs | 465 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace AssemblyDefender.Net.IL
{
public enum ILNodeType
{
Instruction,
Label,
Block,
}
}
| 12.6 | 33 | 0.746032 | [
"MIT"
] | nickyandreev/AssemblyDefender | src/AssemblyDefender.Net/IL/ILNodeType.cs | 191 | C# |
namespace Dit.Umb.Mutobo.Interfaces
{
public interface ISliderItem
{
}
} | 12.285714 | 36 | 0.662791 | [
"MIT"
] | Dreadhorn/MUTOBO | Dit.Umb.Mutobo/Interfaces/ISliderItem.cs | 88 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNative.Cdn.Latest
{
/// <summary>
/// Defines web application firewall policy for Azure CDN.
/// Latest API Version: 2020-09-01.
/// </summary>
[Obsolete(@"The 'latest' version is deprecated. Please migrate to the resource in the top-level module: 'azure-native:cdn:Policy'.")]
[AzureNativeResourceType("azure-native:cdn/latest:Policy")]
public partial class Policy : Pulumi.CustomResource
{
/// <summary>
/// Describes custom rules inside the policy.
/// </summary>
[Output("customRules")]
public Output<Outputs.CustomRuleListResponse?> CustomRules { get; private set; } = null!;
/// <summary>
/// Describes Azure CDN endpoints associated with this Web Application Firewall policy.
/// </summary>
[Output("endpointLinks")]
public Output<ImmutableArray<Outputs.CdnEndpointResponse>> EndpointLinks { get; private set; } = null!;
/// <summary>
/// Gets a unique read-only string that changes whenever the resource is updated.
/// </summary>
[Output("etag")]
public Output<string?> Etag { get; private set; } = null!;
/// <summary>
/// Resource location.
/// </summary>
[Output("location")]
public Output<string> Location { get; private set; } = null!;
/// <summary>
/// Describes managed rules inside the policy.
/// </summary>
[Output("managedRules")]
public Output<Outputs.ManagedRuleSetListResponse?> ManagedRules { get; private set; } = null!;
/// <summary>
/// Resource name.
/// </summary>
[Output("name")]
public Output<string> Name { get; private set; } = null!;
/// <summary>
/// Describes policySettings for policy
/// </summary>
[Output("policySettings")]
public Output<Outputs.PolicySettingsResponse?> PolicySettings { get; private set; } = null!;
/// <summary>
/// Provisioning state of the WebApplicationFirewallPolicy.
/// </summary>
[Output("provisioningState")]
public Output<string> ProvisioningState { get; private set; } = null!;
/// <summary>
/// Describes rate limit rules inside the policy.
/// </summary>
[Output("rateLimitRules")]
public Output<Outputs.RateLimitRuleListResponse?> RateLimitRules { get; private set; } = null!;
[Output("resourceState")]
public Output<string> ResourceState { get; private set; } = null!;
/// <summary>
/// The pricing tier (defines a CDN provider, feature list and rate) of the CdnWebApplicationFirewallPolicy.
/// </summary>
[Output("sku")]
public Output<Outputs.SkuResponse> Sku { get; private set; } = null!;
/// <summary>
/// Read only system data
/// </summary>
[Output("systemData")]
public Output<Outputs.SystemDataResponse> SystemData { get; private set; } = null!;
/// <summary>
/// Resource tags.
/// </summary>
[Output("tags")]
public Output<ImmutableDictionary<string, string>?> Tags { get; private set; } = null!;
/// <summary>
/// Resource type.
/// </summary>
[Output("type")]
public Output<string> Type { get; private set; } = null!;
/// <summary>
/// Create a Policy resource with the given unique name, arguments, and options.
/// </summary>
///
/// <param name="name">The unique name of the resource</param>
/// <param name="args">The arguments used to populate this resource's properties</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public Policy(string name, PolicyArgs args, CustomResourceOptions? options = null)
: base("azure-native:cdn/latest:Policy", name, args ?? new PolicyArgs(), MakeResourceOptions(options, ""))
{
}
private Policy(string name, Input<string> id, CustomResourceOptions? options = null)
: base("azure-native:cdn/latest:Policy", name, null, MakeResourceOptions(options, id))
{
}
private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id)
{
var defaultOptions = new CustomResourceOptions
{
Version = Utilities.Version,
Aliases =
{
new Pulumi.Alias { Type = "azure-nextgen:cdn/latest:Policy"},
new Pulumi.Alias { Type = "azure-native:cdn:Policy"},
new Pulumi.Alias { Type = "azure-nextgen:cdn:Policy"},
new Pulumi.Alias { Type = "azure-native:cdn/v20190615:Policy"},
new Pulumi.Alias { Type = "azure-nextgen:cdn/v20190615:Policy"},
new Pulumi.Alias { Type = "azure-native:cdn/v20190615preview:Policy"},
new Pulumi.Alias { Type = "azure-nextgen:cdn/v20190615preview:Policy"},
new Pulumi.Alias { Type = "azure-native:cdn/v20200331:Policy"},
new Pulumi.Alias { Type = "azure-nextgen:cdn/v20200331:Policy"},
new Pulumi.Alias { Type = "azure-native:cdn/v20200415:Policy"},
new Pulumi.Alias { Type = "azure-nextgen:cdn/v20200415:Policy"},
new Pulumi.Alias { Type = "azure-native:cdn/v20200901:Policy"},
new Pulumi.Alias { Type = "azure-nextgen:cdn/v20200901:Policy"},
},
};
var merged = CustomResourceOptions.Merge(defaultOptions, options);
// Override the ID if one was specified for consistency with other language SDKs.
merged.Id = id ?? merged.Id;
return merged;
}
/// <summary>
/// Get an existing Policy resource's state with the given name, ID, and optional extra
/// properties used to qualify the lookup.
/// </summary>
///
/// <param name="name">The unique name of the resulting resource.</param>
/// <param name="id">The unique provider ID of the resource to lookup.</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public static Policy Get(string name, Input<string> id, CustomResourceOptions? options = null)
{
return new Policy(name, id, options);
}
}
public sealed class PolicyArgs : Pulumi.ResourceArgs
{
/// <summary>
/// Describes custom rules inside the policy.
/// </summary>
[Input("customRules")]
public Input<Inputs.CustomRuleListArgs>? CustomRules { get; set; }
/// <summary>
/// Gets a unique read-only string that changes whenever the resource is updated.
/// </summary>
[Input("etag")]
public Input<string>? Etag { get; set; }
/// <summary>
/// Resource location.
/// </summary>
[Input("location")]
public Input<string>? Location { get; set; }
/// <summary>
/// Describes managed rules inside the policy.
/// </summary>
[Input("managedRules")]
public Input<Inputs.ManagedRuleSetListArgs>? ManagedRules { get; set; }
/// <summary>
/// The name of the CdnWebApplicationFirewallPolicy.
/// </summary>
[Input("policyName")]
public Input<string>? PolicyName { get; set; }
/// <summary>
/// Describes policySettings for policy
/// </summary>
[Input("policySettings")]
public Input<Inputs.PolicySettingsArgs>? PolicySettings { get; set; }
/// <summary>
/// Describes rate limit rules inside the policy.
/// </summary>
[Input("rateLimitRules")]
public Input<Inputs.RateLimitRuleListArgs>? RateLimitRules { get; set; }
/// <summary>
/// Name of the Resource group within the Azure subscription.
/// </summary>
[Input("resourceGroupName", required: true)]
public Input<string> ResourceGroupName { get; set; } = null!;
/// <summary>
/// The pricing tier (defines a CDN provider, feature list and rate) of the CdnWebApplicationFirewallPolicy.
/// </summary>
[Input("sku", required: true)]
public Input<Inputs.SkuArgs> Sku { get; set; } = null!;
[Input("tags")]
private InputMap<string>? _tags;
/// <summary>
/// Resource tags.
/// </summary>
public InputMap<string> Tags
{
get => _tags ?? (_tags = new InputMap<string>());
set => _tags = value;
}
public PolicyArgs()
{
}
}
}
| 39.476395 | 137 | 0.581648 | [
"Apache-2.0"
] | pulumi-bot/pulumi-azure-native | sdk/dotnet/Cdn/Latest/Policy.cs | 9,198 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Core;
using System.Data.Entity.Core.Objects;
using System.Linq;
namespace Ministry.RepoLayer.ObjContext.Abstract
{
/// <summary>
/// Base Repository
/// </summary>
/// <typeparam name="TContext">The type of the context.</typeparam>
/// <typeparam name="TEntity">The type of the entity.</typeparam>
/// <typeparam name="TEntityBase">The type of the entity base.</typeparam>
/// <typeparam name="TEntityId">The type of the entity id.</typeparam>
public abstract class RepositoryBase<TContext, TEntity, TEntityBase, TEntityId> : IRepository<TEntity, TEntityId>
where TEntityBase : class
where TEntity : class, TEntityBase
where TContext : IContextWrapper
{
/// <summary>
/// When called from a child, initializes a new instance of the repository class.
/// </summary>
/// <param name="contextWrapper">The context wrapper.</param>
protected RepositoryBase(TContext contextWrapper)
{
Context = contextWrapper;
}
/// <summary>
/// Gets or sets the context.
/// </summary>
/// <value>
/// The context.
/// </value>
protected TContext Context { get; set; }
/// <summary>
/// Gets the entity set.
/// </summary>
protected abstract IObjectSet<TEntityBase> EntitySet { get; }
/// <summary>
/// Gets the entity set.
/// </summary>
protected abstract IQueryable<TEntity> QuerySet { get; }
/// <summary>
/// Gets all the relationship types.
/// </summary>
/// <returns>Relationship Types</returns>
public IQueryable<TEntity> All()
{
var query = QuerySet;
return query;
}
/// <summary>
/// Gets the relationship types by id.
/// </summary>
/// <param name="id">The id.</param>
/// <returns>Relationship Types</returns>
public abstract TEntity ById(TEntityId id);
/// <summary>
/// Adds the specified entity.
/// </summary>
/// <param name="entity">The entity.</param>
public void Add(TEntity entity)
{
EntitySet.AddObject(entity);
}
/// <summary>
/// Deletes the specified entity.
/// </summary>
/// <param name="entity">The entity.</param>
public void Delete(TEntity entity)
{
EntitySet.DeleteObject(entity);
}
/// <summary>
/// Edits the specified entity.
/// </summary>
/// <param name="entity">The entity.</param>
public void Edit(TEntity entity)
{
Context.ChangeObjectState(entity, EntityState.Modified);
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public virtual void Dispose()
{
}
}
}
| 31.481818 | 117 | 0.543171 | [
"MIT"
] | ministryotech/entity-framework-repolayer | Ministry.RepoLayer.ObjectContext-EF6/RepositoryBase.cs | 3,463 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;
using System.Messaging;
using System.IO;
using System.Threading;
namespace Adf
{
/// <summary>
/// 任务队列管理器
/// </summary>
public class Mq : IDisposable
{
private MessageQueue[] messageQueue;
private LogManager logger;
private bool initLogger = false;
private bool disposed = false;
private int queueCount;
private int queueIndex;
private static TimeSpan errorReceiveSleep = TimeSpan.FromSeconds(5);
private int receiveRuningCount = 0;
/// <summary>
/// Name
/// </summary>
public string Name
{
get;
private set;
}
/// <summary>
/// 是否正在接收
/// </summary>
public bool Receiving
{
get;
private set;
}
/// <summary>
/// 异常时重连间隔,单位:秒,默认:60seconds
/// </summary>
public int ReconnectInterval
{
get;
private set;
}
int availableThread;
/// <summary>
/// initialize a instance
/// </summary>
/// <param name="name"></param>
public Mq(string name)
: this(name,new LogManager(name))
{
this.initLogger = true;
}
/// <summary>
/// initialize a instance
/// </summary>
/// <param name="name"></param>
/// <param name="logger"></param>
public Mq(string name, LogManager logger)
{
var configs = ((Config.IpGroupSection)ConfigurationManager.GetSection(name));
if (configs == null)
{
throw new ConfigurationErrorsException("not find config " + name);
}
this.Name = name;
this.Receiving = false;
this.ReconnectInterval = 60000;
var servers = configs.IpList;
this.messageQueue = new MessageQueue[servers.Count];
for (int i = 0, l = servers.Count; i < l; i++)
{
this.messageQueue[i] = new MessageQueue(servers[i].Ip);
//if (!MessageQueue.Exists(servers[i].Ip))
// throw new ApplicationException(string.Format("Not Find Queue. {0}",servers[i].Ip));
}
this.queueCount = this.messageQueue.Length;
this.queueIndex = 0;
//
this.logger = logger;
}
/// <summary>
/// 可用接收线程数
/// </summary>
public int GetAvailableThread()
{
return this.availableThread;
}
/// <summary>
/// 发送
/// </summary>
public void Send<T>(T message)
{
if (this.disposed)
throw new ObjectDisposedException(this.GetType().Name);
var m = new Message(message);
if (this.queueCount == 1)
{
this.messageQueue[0].Send(m);
return;
}
var count = this.queueCount;
lock (this.messageQueue)
{
while (true)
{
try
{
var index = this.queueIndex++;
if (this.queueIndex == this.queueCount)
this.queueIndex = 0;
this.messageQueue[index].Send(m);
break;
}
catch (Exception e)
{
this.logger.Exception(e);
if (count == 1)
throw;
}
count--;
}
}
}
/// <summary>
/// 异步接收
/// </summary>
/// <param name="action"></param>
/// <param name="maxThreadSize"></param>
/// <exception cref="MqException">MqException 已调用过 Receive了</exception>
/// <exception cref="System.Messaging.MessageQueueException"> System.Messaging.MessageQueueException</exception>
public void Receive<T>(int maxThreadSize, Action<T> action)
{
if (this.disposed)
throw new ObjectDisposedException(this.GetType().Name);
if (this.Receiving)
throw new MqException("Has Been Received.");
this.Receiving = true;
this.availableThread = maxThreadSize;
var results = new IAsyncResult[ this.messageQueue.Length ];
try
{
for (var i = 0; i < this.messageQueue.Length; i++)
{
this.messageQueue[i].ReceiveCompleted += new ReceiveCompletedEventHandler(ReceiveCompleted<T>);
results[i] = this.messageQueue[i].BeginReceive(MessageQueue.InfiniteTimeout, new ReceiveState<T>()
{
Action = action,
Count = 0,
MaxCount = maxThreadSize,
ArrayIndex = i
});
}
}
catch
{
foreach (var result in results)
{
if (result != null)
result.AsyncWaitHandle.Close();
}
this.Receiving = false;
throw;
}
}
/// <summary>
/// 完成一个接收
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void ReceiveCompleted<T>(object sender, ReceiveCompletedEventArgs e)
{
var mq = (MessageQueue)sender;
var state = (ReceiveState<T>)e.AsyncResult.AsyncState;
Message message = null;
try
{
message = mq.EndReceive(e.AsyncResult);
}
catch (MessageQueueException exception)
{
//已dispose
if (this.disposed)
return;
this.logger.Exception(exception);
//只要出现 队列错误,均视为队列失效,重建队列
mq = this.ReconnectQueue<T>(mq, state.ArrayIndex, out message);
}
catch (Exception exception)
{
this.logger.Exception(exception);
message = null;
}
//
if (message != null)
{
lock (state)
{
state.Count++;
Interlocked.Decrement(ref this.availableThread);
//run
new Thread(() => {
Interlocked.Increment(ref this.receiveRuningCount);
try
{
if (message != null)
{
message.Formatter = new XmlMessageFormatter(new[] { typeof(T) });
state.Action((T)message.Body);
}
}
catch (Exception exception)
{
this.logger.Exception(exception);
}
finally
{
lock (state)
{
state.Count--;
Interlocked.Increment(ref this.availableThread);
Monitor.Pulse(state);
}
Interlocked.Decrement(ref this.receiveRuningCount);
}
}).Start();
if (state.Count == state.MaxCount)
{
Monitor.Wait(state);
}
}
}
//new receive
while (this.Receiving)
{
try
{
mq.BeginReceive(MessageQueue.InfiniteTimeout, state);
break;
}
catch (Exception exception)
{
this.logger.Exception(exception);
Thread.Sleep(errorReceiveSleep);
}
}
}
/// <summary>
/// 重建一个失败的队列
/// </summary>
/// <param name="mq"></param>
/// <param name="queueIndex">队列所在索引</param>
/// <param name="message">接收到的消息</param>
/// <returns></returns>
private MessageQueue ReconnectQueue<T>(MessageQueue mq, int queueIndex,out Message message)
{
this.logger.Warning.WriteTimeLine("Queue Error, Reconnect: {0}",mq.Path);
//Reconnect
MessageQueue newmq = null;
message = null;
while (this.Receiving)
{
try
{
newmq = new MessageQueue(mq.Path);
message = newmq.Receive(MessageQueue.InfiniteTimeout);
break;
}
catch (Exception exception)
{
this.logger.Warning.WriteTimeLine("Reconnect Fail, after {2} seconds to continue: {0},{1}", exception.GetType(), exception.Message, this.ReconnectInterval);
//
try { newmq.Dispose(); }
catch { }
//
Thread.Sleep(this.ReconnectInterval);
//Thread.Sleep(5000);
continue;
}
}
this.logger.Warning.WriteTimeLine("Reconnect Success: {0}", mq.Path);
//replace && destry old
newmq.ReceiveCompleted += new ReceiveCompletedEventHandler(ReceiveCompleted<T>);
this.messageQueue[queueIndex] = newmq;
try { mq.Dispose(); }
catch { }
//return
return newmq;
}
/// <summary>
/// 资源释放
/// </summary>
public void Dispose()
{
if (!this.disposed)
{
this.Receiving = false;
this.disposed = true;
//释放队列
foreach (var m in this.messageQueue)
{
m.Dispose();
}
if (this.initLogger)
{
//释放日志
this.logger.Dispose();
}
else
{
//刷新日志
this.logger.Flush();
}
//确保所有接收器均已完成
while (this.receiveRuningCount > 0)
Thread.Sleep(10);
}
}
class ReceiveState<T>
{
public int ArrayIndex;
public int Count;
public int MaxCount;
public Action<T> Action;
}
}
}
| 31.066667 | 176 | 0.424267 | [
"MIT"
] | aooshi/adf | Adf/Mq.cs | 11,430 | C# |
//----------------------------------------------------------------------
//
// Copyright (c) Microsoft Corporation.
// All rights reserved.
//
// This code is licensed under the MIT License.
//
// 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 Microsoft.Identity.Client.Internal;
using Microsoft.Identity.Client.UI;
namespace Microsoft.Identity.Client
{
/// <summary>
/// Contains UI properties for interactive flows, such as the parent window (on Windows), or the parent activity (on Xamarin.Android), and
/// which browser to use (on Xamarin.Android and Xamarin.iOS)
/// </summary>
public sealed class UIParent
{
static UIParent()
{
ModuleInitializer.EnsureModuleInitialized();
}
internal CoreUIParent CoreUIParent { get; }
/// <summary>
/// Platform agnostic default constructor.
/// </summary>
public UIParent()
{
CoreUIParent = new CoreUIParent();
}
/// <summary>
/// Platform agnostic constructor that allows building an UIParent from a NetStandard assembly.
/// </summary>
/// <remarks>Interactive auth is not currently implemented in .net core</remarks>
/// <param name="parent">An owner window to which to attach the webview to.
/// On Android, it is mandatory to pass in an Activity.
/// On all other platforms, it is not required.
/// On .net desktop, it is optional - you can either pass a System.Windows.Forms.IWin32Window or an System.IntPtr
/// to a window handle or null. This is used to center the webview. </param>
/// <param name="useEmbeddedWebview">Flag to determine between embedded vs system browser. Currently affects only iOS and Android. See https://aka.ms/msal-net-uses-web-browser </param>
public UIParent(object parent, bool useEmbeddedWebview)
{
ThrowPlatformNotSupported();
}
/// <summary>
/// Checks if the system weview can be used.
/// </summary>
public static bool IsSystemWebviewAvailable() // This is part of the NetStandard "interface"
{
ThrowPlatformNotSupported();
return false;
}
/// <summary>
/// For the rare case when an application actually uses the netstandard implementation
/// i.e. other frameworks - e.g. Xamarin.MAC - or MSAL.netstandard loaded via reflection
/// </summary>
private static void ThrowPlatformNotSupported()
{
throw new PlatformNotSupportedException("Interactive Authentication flows are not supported when the NetStandard assembly is used at runtime. " +
"Consider using Device Code Flow https://aka.ms/msal-device-code-flow or " +
"Integrated Windows Auth https://aka.ms/msal-net-iwa");
}
}
} | 45.466667 | 192 | 0.63563 | [
"MIT"
] | stefangossner/microsoft-authentication-library-for-dotnet | src/Microsoft.Identity.Client/Platforms/netstandard13/UIParent.cs | 4,094 | 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.Reflection;
namespace Microsoft.CSharp.RuntimeBinder.Semantics
{
// ----------------------------------------------------------------------------
//
// EventSymbol
//
// EventSymbol - a symbol representing an event. The symbol points to the AddOn and RemoveOn methods
// that handle adding and removing delegates to the event. If the event wasn't imported, it
// also points to the "implementation" of the event -- a field or property symbol that is always
// private.
// ----------------------------------------------------------------------------
internal sealed class EventSymbol : Symbol
{
public EventInfo AssociatedEventInfo;
public new bool isStatic; // Static member?
// If this is true then tell the user to call the accessors directly.
public bool isOverride;
public CType type; // Type of the event.
public MethodSymbol methAdd; // Adder method (always has same parent)
public MethodSymbol methRemove; // Remover method (always has same parent)
public AggregateDeclaration declaration; // containing declaration
public bool IsWindowsRuntimeEvent { get; set; }
// ----------------------------------------------------------------------------
// EventSymbol
// ----------------------------------------------------------------------------
public AggregateDeclaration containingDeclaration()
{
return declaration;
}
}
}
| 37.0625 | 104 | 0.536818 | [
"MIT"
] | Aevitas/corefx | src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Symbols/EventSymbol.cs | 1,779 | C# |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using Couchbase.Core.Configuration.Server;
using Couchbase.Core.IO.Connections;
using Couchbase.Core.IO.Operations;
using Couchbase.Core.IO.Operations.Errors;
using Couchbase.Management.Buckets;
namespace Couchbase.Core
{
internal interface IClusterNode : IDisposable
{
IBucket Owner { get; set; }
NodeAdapter NodesAdapter { get; set; }
HostEndpoint BootstrapEndpoint { get; }
IPEndPoint EndPoint { get; }
BucketType BucketType { get; }
/// <summary>
/// Endpoints by which this node may be referenced for key/value operations.
/// </summary>
/// <remarks>
/// May change over time depending on bootstrap status.
/// </remarks>
IReadOnlyCollection<IPEndPoint> KeyEndPoints { get; }
Uri QueryUri { get; set; }
Uri AnalyticsUri { get; set; }
Uri SearchUri { get; set; }
Uri ViewsUri { get; set; }
Uri ManagementUri { get; set; }
ErrorMap ErrorMap { get; set; }
short[] ServerFeatures { get; set; }
IConnectionPool ConnectionPool { get; }
List<Exception> Exceptions { get; set; } //TODO catch and hold until first operation per RFC
bool IsAssigned { get; }
bool HasViews { get; }
bool HasAnalytics { get; }
bool HasQuery { get; }
bool HasSearch { get; }
bool HasKv { get; }
bool Supports(ServerFeatures feature);
DateTime? LastViewActivity { get; }
DateTime? LastQueryActivity { get; }
DateTime? LastSearchActivity { get; }
DateTime? LastAnalyticsActivity { get; }
DateTime? LastKvActivity { get; }
Task<Manifest> GetManifest();
/// <summary>
/// Selects the <see cref="IBucket"/> this <see cref="ClusterNode" /> is associated to.
/// </summary>
/// <param name="bucket">The <see cref="IBucket"/>.</param>
/// <param name="cancellationToken">The cancellation token.</param>
Task SelectBucketAsync(IBucket bucket, CancellationToken cancellationToken = default);
Task<BucketConfig> GetClusterMap();
Task<uint?> GetCid(string fullyQualifiedName);
Task ExecuteOp(IOperation op, CancellationToken token = default(CancellationToken),
TimeSpan? timeout = null);
Task ExecuteOp(IConnection connection, IOperation op, CancellationToken token = default(CancellationToken),
TimeSpan? timeout = null);
Task SendAsync(IOperation op, CancellationToken token = default(CancellationToken),
TimeSpan? timeout = null);
/// <summary>
/// Notifies when the <see cref="KeyEndPoints"/> collection is changed.
/// </summary>
event NotifyCollectionChangedEventHandler KeyEndPointsChanged;
}
}
| 37.632911 | 115 | 0.643458 | [
"Apache-2.0"
] | andy-williams/couchbase-net-client | src/Couchbase/Core/IClusterNode.cs | 2,973 | C# |
// -------------------------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// -------------------------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Antlr4.Runtime;
using Antlr4.Runtime.Tree;
using Microsoft.Health.Fhir.Liquid.Converter.Exceptions;
using Microsoft.Health.Fhir.Liquid.Converter.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace Microsoft.Health.Fhir.Liquid.Converter.OutputProcessors
{
public static class PostProcessor
{
public static JObject Process(string input)
{
var jsonObject = ParseJson(input);
return MergeJson(jsonObject);
}
public static JObject ParseJson(string input)
{
var stream = new AntlrInputStream(input);
var lexer = new jsonLexer(stream);
var tokens = new CommonTokenStream(lexer);
var errorBuilder = new StringBuilder();
var parser = new jsonParser(tokens, new StringWriter(new StringBuilder()), new StringWriter(errorBuilder));
lexer.RemoveErrorListeners();
parser.RemoveErrorListeners();
parser.AddErrorListener(new JsonParserErrorListener());
parser.BuildParseTree = true;
var tree = parser.json();
if (parser.NumberOfSyntaxErrors > 0)
{
throw new PostprocessException(FhirConverterErrorCode.JsonParsingError, string.Format(Resources.JsonParsingError, errorBuilder));
}
var listener = new JsonListener();
ParseTreeWalker.Default.Walk(listener, tree);
var result = listener.GetResult().ToString();
return JsonConvert.DeserializeObject<JObject>(result, new JsonSerializerSettings { DateParseHandling = DateParseHandling.None });
}
public static JObject MergeJson(JObject obj)
{
try
{
var mergedEntity = new JArray();
var resourceKeyToIndexMap = new Dictionary<string, int>();
if (obj.TryGetValue("entry", out var entries))
{
foreach (var entry in entries)
{
var resourceKey = GetKey(entry);
if (resourceKeyToIndexMap.ContainsKey(resourceKey))
{
var index = resourceKeyToIndexMap[resourceKey];
mergedEntity[index] = Merge((JObject)mergedEntity[index], (JObject)entry);
}
else
{
mergedEntity.Add(entry);
resourceKeyToIndexMap[resourceKey] = mergedEntity.Count - 1;
}
}
obj["entry"] = mergedEntity;
}
}
catch (Exception ex)
{
throw new PostprocessException(FhirConverterErrorCode.JsonMergingError, string.Format(Resources.JsonMergingError, ex.Message), ex);
}
return obj;
}
private static JObject Merge(JObject obj1, JObject obj2)
{
var setting = new JsonMergeSettings
{
MergeArrayHandling = MergeArrayHandling.Union,
};
obj1.Merge(obj2, setting);
return obj1;
}
private static string GetKey(JToken obj)
{
var resourceType = obj.SelectToken("$.resource.resourceType")?.Value<string>();
if (resourceType != null)
{
var key = resourceType;
var versionId = obj.SelectToken("$.resource.meta.versionId")?.Value<string>();
key += versionId != null ? $"_{versionId}" : string.Empty;
var resourceId = obj.SelectToken("$.resource.id")?.Value<string>();
key += resourceId != null ? $"_{resourceId}" : string.Empty;
return key;
}
return JsonConvert.SerializeObject(obj);
}
}
}
| 37.478632 | 147 | 0.537514 | [
"MIT"
] | BradBarnich/FHIR-Converter | src/Microsoft.Health.Fhir.Liquid.Converter/OutputProcessors/PostProcessor.cs | 4,387 | C# |
using System;
namespace SmartSystemMenu.Hooks
{
class BasicHookEventArgs : EventArgs
{
public IntPtr WParam { get; private set; }
public IntPtr LParam { get; private set; }
public BasicHookEventArgs(IntPtr wParam, IntPtr lParam)
{
WParam = wParam;
LParam = lParam;
}
}
}
| 19.5 | 63 | 0.586895 | [
"MIT"
] | AlexanderPro/SmartSystemMenu | SmartSystemMenu/Hooks/BasicHookEventArgs.cs | 353 | C# |
// Copyright (c) Robin Boerdijk - All rights reserved - See LICENSE file for license terms
using System;
namespace MDSDK.Dicom.Serialization.ValueRepresentations
{
internal sealed class DecimalString : AsciiEncodedMultiValue, IMultiValue<decimal>, IMultiValue<double>, IMultiValue<float>
{
public DecimalString() : base("DS") { }
decimal[] IMultiValue<decimal>.ReadValues(DicomStreamReader reader) => ReadAndConvertValues(reader, decimal.Parse);
decimal IMultiValue<decimal>.ReadSingleValue(DicomStreamReader reader) => ReadAndConvertSingleValue(reader, decimal.Parse);
void IMultiValue<decimal>.WriteValues(DicomStreamWriter writer, decimal[] values) => ConvertAndWriteValues(writer, Convert.ToString, values);
void IMultiValue<decimal>.WriteSingleValue(DicomStreamWriter writer, decimal value) => ConvertAndWriteSingleValue(writer, Convert.ToString, value);
double[] IMultiValue<double>.ReadValues(DicomStreamReader reader) => ReadAndConvertValues(reader, double.Parse);
double IMultiValue<double>.ReadSingleValue(DicomStreamReader reader) => ReadAndConvertSingleValue(reader, double.Parse);
void IMultiValue<double>.WriteValues(DicomStreamWriter writer, double[] values) => ConvertAndWriteValues(writer, Convert.ToString, values);
void IMultiValue<double>.WriteSingleValue(DicomStreamWriter writer, double value) => ConvertAndWriteSingleValue(writer, Convert.ToString, value);
float[] IMultiValue<float>.ReadValues(DicomStreamReader reader) => ReadAndConvertValues(reader, float.Parse);
float IMultiValue<float>.ReadSingleValue(DicomStreamReader reader) => ReadAndConvertSingleValue(reader, float.Parse);
void IMultiValue<float>.WriteValues(DicomStreamWriter writer, float[] values) => ConvertAndWriteValues(writer, Convert.ToString, values);
void IMultiValue<float>.WriteSingleValue(DicomStreamWriter writer, float value) => ConvertAndWriteSingleValue(writer, Convert.ToString, value);
}
}
| 56.25 | 155 | 0.772346 | [
"MIT"
] | mdsdk/Dicom.Serialization | MDSDK.Dicom.Serialization/ValueRepresentations/DecimalString.cs | 2,027 | C# |
/*
* Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
* See https://github.com/openiddict/openiddict-core for more information concerning
* the license and the contributors participating to this project.
*/
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using MongoDB.Driver;
using Moq;
using Xunit;
namespace OpenIddict.MongoDb.Tests;
public class OpenIddictMongoDbContextTests
{
[Fact]
public async Task GetDatabaseAsync_ThrowsAnExceptionForCanceledToken()
{
// Arrange
var services = new ServiceCollection();
var provider = services.BuildServiceProvider();
var options = Mock.Of<IOptionsMonitor<OpenIddictMongoDbOptions>>();
var token = new CancellationToken(canceled: true);
var context = new OpenIddictMongoDbContext(options, provider);
// Act and assert
var exception = await Assert.ThrowsAsync<TaskCanceledException>(async delegate
{
await context.GetDatabaseAsync(token);
});
Assert.Equal(token, exception.CancellationToken);
}
[Fact]
public async Task GetDatabaseAsync_PrefersDatabaseRegisteredInOptionsToDatabaseRegisteredInDependencyInjectionContainer()
{
// Arrange
var services = new ServiceCollection();
services.AddSingleton(Mock.Of<IMongoDatabase>());
var provider = services.BuildServiceProvider();
var database = Mock.Of<IMongoDatabase>();
var options = Mock.Of<IOptionsMonitor<OpenIddictMongoDbOptions>>(
mock => mock.CurrentValue == new OpenIddictMongoDbOptions
{
Database = database
});
var context = new OpenIddictMongoDbContext(options, provider);
// Act and assert
Assert.Same(database, await context.GetDatabaseAsync(CancellationToken.None));
}
[Fact]
public async Task GetDatabaseAsync_ThrowsAnExceptionWhenDatabaseCannotBeFound()
{
// Arrange
var services = new ServiceCollection();
var provider = services.BuildServiceProvider();
var options = Mock.Of<IOptionsMonitor<OpenIddictMongoDbOptions>>(
mock => mock.CurrentValue == new OpenIddictMongoDbOptions
{
Database = null
});
var context = new OpenIddictMongoDbContext(options, provider);
// Act and assert
var exception = await Assert.ThrowsAsync<InvalidOperationException>(async delegate
{
await context.GetDatabaseAsync(CancellationToken.None);
});
Assert.Equal(SR.GetResourceString(SR.ID0262), exception.Message);
}
[Fact]
public async Task GetDatabaseAsync_UsesDatabaseRegisteredInDependencyInjectionContainer()
{
// Arrange
var services = new ServiceCollection();
services.AddSingleton(Mock.Of<IMongoDatabase>());
var database = Mock.Of<IMongoDatabase>();
services.AddSingleton(database);
var provider = services.BuildServiceProvider();
var options = Mock.Of<IOptionsMonitor<OpenIddictMongoDbOptions>>(
mock => mock.CurrentValue == new OpenIddictMongoDbOptions
{
Database = null
});
var context = new OpenIddictMongoDbContext(options, provider);
// Act and assert
Assert.Same(database, await context.GetDatabaseAsync(CancellationToken.None));
}
}
| 32.435185 | 125 | 0.672852 | [
"Apache-2.0"
] | Darthruneis/openiddict-core | test/OpenIddict.MongoDb.Tests/OpenIddictMongoDbContextTests.cs | 3,505 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameController : MonoBehaviour
{
public static GameController instance = null;
public RouteManger routeManger = new RouteManger();
public RouteNet routeNet;
private void Awake() { //防止存在多个单例
if (instance == null)
instance = this;
else
Destroy(gameObject);
}
}
| 23.222222 | 55 | 0.665072 | [
"Apache-2.0"
] | TastSong/AIBikeRobot | Assets/AIBikeRobot/Scripts/GameController.cs | 436 | C# |
// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Linq;
using ICSharpCode.Decompiler.Metadata;
using ICSharpCode.Decompiler.Semantics;
using ICSharpCode.Decompiler.TypeSystem.Implementation;
using ICSharpCode.Decompiler.Util;
namespace ICSharpCode.Decompiler.TypeSystem
{
/// <summary>
/// Contains extension methods for the type system.
/// </summary>
public static class TypeSystemExtensions
{
#region GetAllBaseTypes
/// <summary>
/// Gets all base types.
/// </summary>
/// <remarks>This is the reflexive and transitive closure of <see cref="IType.DirectBaseTypes"/>.
/// Note that this method does not return all supertypes - doing so is impossible due to contravariance
/// (and undesirable for covariance as the list could become very large).
///
/// The output is ordered so that base types occur before derived types.
/// </remarks>
public static IEnumerable<IType> GetAllBaseTypes(this IType type)
{
if (type == null)
throw new ArgumentNullException(nameof(type));
var collector = new BaseTypeCollector();
collector.CollectBaseTypes(type);
return collector;
}
/// <summary>
/// Gets all non-interface base types.
/// </summary>
/// <remarks>
/// When <paramref name="type"/> is an interface, this method will also return base interfaces (return same output as GetAllBaseTypes()).
///
/// The output is ordered so that base types occur before derived types.
/// </remarks>
public static IEnumerable<IType> GetNonInterfaceBaseTypes(this IType type)
{
if (type == null)
throw new ArgumentNullException(nameof(type));
var collector = new BaseTypeCollector();
collector.SkipImplementedInterfaces = true;
collector.CollectBaseTypes(type);
return collector;
}
#endregion
#region GetAllBaseTypeDefinitions
/// <summary>
/// Gets all base type definitions.
/// The output is ordered so that base types occur before derived types.
/// </summary>
/// <remarks>
/// This is equivalent to type.GetAllBaseTypes().Select(t => t.GetDefinition()).Where(d => d != null).Distinct().
/// </remarks>
public static IEnumerable<ITypeDefinition> GetAllBaseTypeDefinitions(this IType type)
{
if (type == null)
throw new ArgumentNullException(nameof(type));
return type.GetAllBaseTypes().Select(t => t.GetDefinition()).Where(d => d != null).Distinct();
}
/// <summary>
/// Gets whether this type definition is derived from the base type definition.
/// </summary>
public static bool IsDerivedFrom(this ITypeDefinition type, ITypeDefinition baseType)
{
if (type == null)
throw new ArgumentNullException(nameof(type));
if (baseType == null)
return false;
if (type.Compilation != baseType.Compilation)
{
throw new InvalidOperationException("Both arguments to IsDerivedFrom() must be from the same compilation.");
}
return type.GetAllBaseTypeDefinitions().Contains(baseType);
}
/// <summary>
/// Gets whether this type definition is derived from a given known type.
/// </summary>
public static bool IsDerivedFrom(this ITypeDefinition type, KnownTypeCode baseType)
{
if (type == null)
throw new ArgumentNullException(nameof(type));
if (baseType == KnownTypeCode.None)
return false;
return IsDerivedFrom(type, type.Compilation.FindType(baseType).GetDefinition());
}
#endregion
#region GetDeclaringTypeDefinitionsOrThis
/// <summary>
/// Returns all declaring type definitions of this type definition.
/// The output is ordered so that inner types occur before outer types.
/// </summary>
public static IEnumerable<ITypeDefinition> GetDeclaringTypeDefinitions(this ITypeDefinition definition)
{
if (definition == null)
{
throw new ArgumentNullException(nameof(definition));
}
while (definition != null)
{
yield return definition;
definition = definition.DeclaringTypeDefinition;
}
}
#endregion
#region IsOpen / IsUnbound / IsKnownType
sealed class TypeClassificationVisitor : TypeVisitor
{
internal bool isOpen;
internal IEntity typeParameterOwner;
int typeParameterOwnerNestingLevel;
public override IType VisitTypeParameter(ITypeParameter type)
{
isOpen = true;
// If both classes and methods, or different classes (nested types)
// are involved, find the most specific one
var newNestingLevel = GetNestingLevel(type.Owner);
if (newNestingLevel > typeParameterOwnerNestingLevel)
{
typeParameterOwner = type.Owner;
typeParameterOwnerNestingLevel = newNestingLevel;
}
return base.VisitTypeParameter(type);
}
static int GetNestingLevel(IEntity entity)
{
var level = 0;
while (entity != null)
{
level++;
entity = entity.DeclaringTypeDefinition;
}
return level;
}
}
/// <summary>
/// Gets whether the type is an open type (contains type parameters).
/// </summary>
/// <example>
/// <code>
/// class X<T> {
/// List<T> open;
/// X<X<T[]>> open;
/// X<string> closed;
/// int closed;
/// }
/// </code>
/// </example>
public static bool IsOpen(this IType type)
{
if (type == null)
throw new ArgumentNullException(nameof(type));
var v = new TypeClassificationVisitor();
type.AcceptVisitor(v);
return v.isOpen;
}
/// <summary>
/// Gets the entity that owns the type parameters occurring in the specified type.
/// If both class and method type parameters are present, the method is returned.
/// Returns null if the specified type is closed.
/// </summary>
/// <seealso cref="IsOpen"/>
static IEntity GetTypeParameterOwner(IType type)
{
if (type == null)
throw new ArgumentNullException(nameof(type));
var v = new TypeClassificationVisitor();
type.AcceptVisitor(v);
return v.typeParameterOwner;
}
/// <summary>
/// Gets whether the type is unbound (is a generic type, but no type arguments were provided).
/// </summary>
/// <remarks>
/// In "<c>typeof(List<Dictionary<,>>)</c>", only the Dictionary is unbound, the List is considered
/// bound despite containing an unbound type.
/// This method returns false for partially parameterized types (<c>Dictionary<string, ></c>).
/// </remarks>
public static bool IsUnbound(this IType type)
{
if (type == null)
throw new ArgumentNullException(nameof(type));
return (type is ITypeDefinition || type is UnknownType) && type.TypeParameterCount > 0;
}
/// <summary>
/// Gets whether the type is the specified known type.
/// For generic known types, this returns true for any parameterization of the type (and also for the definition itself).
/// </summary>
public static bool IsKnownType(this IType type, KnownTypeCode knownType)
{
var def = type.GetDefinition();
return def != null && def.KnownTypeCode == knownType;
}
/// <summary>
/// Gets whether the type is the specified known type.
/// For generic known types, this returns true for any parameterization of the type (and also for the definition itself).
/// </summary>
internal static bool IsKnownType(this IType type, KnownAttribute knownType)
{
var def = type.GetDefinition();
return def != null && def.FullTypeName.IsKnownType(knownType);
}
public static bool IsKnownType(this FullTypeName typeName, KnownTypeCode knownType)
{
return typeName == KnownTypeReference.Get(knownType).TypeName;
}
public static bool IsKnownType(this TopLevelTypeName typeName, KnownTypeCode knownType)
{
return typeName == KnownTypeReference.Get(knownType).TypeName;
}
internal static bool IsKnownType(this FullTypeName typeName, KnownAttribute knownType)
{
return typeName == knownType.GetTypeName();
}
internal static bool IsKnownType(this TopLevelTypeName typeName, KnownAttribute knownType)
{
return typeName == knownType.GetTypeName();
}
#endregion
#region GetDelegateInvokeMethod
/// <summary>
/// Gets the invoke method for a delegate type.
/// </summary>
/// <remarks>
/// Returns null if the type is not a delegate type; or if the invoke method could not be found.
/// </remarks>
public static IMethod GetDelegateInvokeMethod(this IType type)
{
if (type == null)
throw new ArgumentNullException(nameof(type));
if (type.Kind == TypeKind.Delegate)
return type.GetMethods(m => m.Name == "Invoke", GetMemberOptions.IgnoreInheritedMembers).FirstOrDefault();
else
return null;
}
#endregion
public static IType SkipModifiers(this IType ty)
{
while (ty is ModifiedType mt)
{
ty = mt.ElementType;
}
return ty;
}
public static bool HasReadonlyModifier(this IMethod accessor)
{
return accessor.ThisIsRefReadOnly && accessor.DeclaringTypeDefinition?.IsReadOnly == false;
}
public static bool IsAnyPointer(this TypeKind typeKind)
{
return typeKind switch
{
TypeKind.Pointer => true,
TypeKind.FunctionPointer => true,
_ => false
};
}
#region GetType/Member
/// <summary>
/// Gets all type definitions in the compilation.
/// This may include types from referenced assemblies that are not accessible in the main assembly.
/// </summary>
public static IEnumerable<ITypeDefinition> GetAllTypeDefinitions(this ICompilation compilation)
{
return compilation.Modules.SelectMany(a => a.TypeDefinitions);
}
/// <summary>
/// Gets all top level type definitions in the compilation.
/// This may include types from referenced assemblies that are not accessible in the main assembly.
/// </summary>
public static IEnumerable<ITypeDefinition> GetTopLevelTypeDefinitions(this ICompilation compilation)
{
return compilation.Modules.SelectMany(a => a.TopLevelTypeDefinitions);
}
#endregion
#region Resolve on collections
public static IReadOnlyList<IType> Resolve(this IList<ITypeReference> typeReferences, ITypeResolveContext context)
{
if (typeReferences == null)
throw new ArgumentNullException(nameof(typeReferences));
if (typeReferences.Count == 0)
return EmptyList<IType>.Instance;
else
return new ProjectedList<ITypeResolveContext, ITypeReference, IType>(context, typeReferences, (c, t) => t.Resolve(c));
}
// There is intentionally no Resolve() overload for IList<IMemberReference>: the resulting IList<Member> would
// contains nulls when there are resolve errors.
#endregion
#region IAssembly.GetTypeDefinition()
/// <summary>
/// Retrieves the specified type in this compilation.
/// Returns an <see cref="UnknownType"/> if the type cannot be found in this compilation.
/// </summary>
/// <remarks>
/// There can be multiple types with the same full name in a compilation, as a
/// full type name is only unique per assembly.
/// If there are multiple possible matches, this method will return just one of them.
/// When possible, use <see cref="IModule.GetTypeDefinition"/> instead to
/// retrieve a type from a specific assembly.
/// </remarks>
public static IType FindType(this ICompilation compilation, FullTypeName fullTypeName)
{
if (compilation == null)
throw new ArgumentNullException(nameof(compilation));
foreach (var asm in compilation.Modules)
{
var def = asm.GetTypeDefinition(fullTypeName);
if (def != null)
return def;
}
return new UnknownType(fullTypeName);
}
/// <summary>
/// Gets the type definition for the specified unresolved type.
/// Returns null if the unresolved type does not belong to this assembly.
/// </summary>
public static ITypeDefinition GetTypeDefinition(this IModule module, FullTypeName fullTypeName)
{
if (module == null)
throw new ArgumentNullException("assembly");
var topLevelTypeName = fullTypeName.TopLevelTypeName;
var typeDef = module.GetTypeDefinition(topLevelTypeName);
if (typeDef == null)
return null;
var typeParameterCount = topLevelTypeName.TypeParameterCount;
for (var i = 0; i < fullTypeName.NestingLevel; i++)
{
var name = fullTypeName.GetNestedTypeName(i);
typeParameterCount += fullTypeName.GetNestedTypeAdditionalTypeParameterCount(i);
typeDef = FindNestedType(typeDef, name, typeParameterCount);
if (typeDef == null)
break;
}
return typeDef;
}
static ITypeDefinition FindNestedType(ITypeDefinition typeDef, string name, int typeParameterCount)
{
foreach (var nestedType in typeDef.NestedTypes)
{
if (nestedType.Name == name && nestedType.TypeParameterCount == typeParameterCount)
return nestedType;
}
return null;
}
#endregion
#region IEntity.GetAttribute
/// <summary>
/// Gets whether the entity has an attribute of the specified attribute type (or derived attribute types).
/// </summary>
/// <param name="entity">The entity on which the attributes are declared.</param>
/// <param name="attributeType">The attribute type to look for.</param>
/// <param name="inherit">
/// Specifies whether attributes inherited from base classes and base members
/// (if the given <paramref name="entity"/> in an <c>override</c>)
/// should be returned.
/// </param>
public static bool HasAttribute(this IEntity entity, KnownAttribute attributeType, bool inherit = false)
{
return GetAttribute(entity, attributeType, inherit) != null;
}
/// <summary>
/// Gets the attribute of the specified attribute type (or derived attribute types).
/// </summary>
/// <param name="entity">The entity on which the attributes are declared.</param>
/// <param name="attributeType">The attribute type to look for.</param>
/// <param name="inherit">
/// Specifies whether attributes inherited from base classes and base members
/// (if the given <paramref name="entity"/> in an <c>override</c>)
/// should be returned.
/// </param>
/// <returns>
/// Returns the attribute that was found; or <c>null</c> if none was found.
/// If inherit is true, an from the entity itself will be returned if possible;
/// and the base entity will only be searched if none exists.
/// </returns>
public static IAttribute GetAttribute(this IEntity entity, KnownAttribute attributeType, bool inherit = false)
{
return GetAttributes(entity, inherit).FirstOrDefault(a => a.AttributeType.IsKnownType(attributeType));
}
/// <summary>
/// Gets the attributes on the entity.
/// </summary>
/// <param name="entity">The entity on which the attributes are declared.</param>
/// <param name="inherit">
/// Specifies whether attributes inherited from base classes and base members
/// (if the given <paramref name="entity"/> in an <c>override</c>)
/// should be returned.
/// </param>
/// <returns>
/// Returns the list of attributes that were found.
/// If inherit is true, attributes from the entity itself are returned first;
/// followed by attributes inherited from the base entity.
/// </returns>
public static IEnumerable<IAttribute> GetAttributes(this IEntity entity, bool inherit)
{
if (inherit)
{
if (entity is ITypeDefinition td)
{
return InheritanceHelper.GetAttributes(td);
}
else if (entity is IMember m)
{
return InheritanceHelper.GetAttributes(m);
}
else
{
throw new NotSupportedException("Unknown entity type");
}
}
else
{
return entity.GetAttributes();
}
}
#endregion
#region IParameter.GetAttribute
/// <summary>
/// Gets whether the parameter has an attribute of the specified attribute type (or derived attribute types).
/// </summary>
/// <param name="parameter">The parameter on which the attributes are declared.</param>
/// <param name="attributeType">The attribute type to look for.</param>
public static bool HasAttribute(this IParameter parameter, KnownAttribute attributeType)
{
return GetAttribute(parameter, attributeType) != null;
}
/// <summary>
/// Gets the attribute of the specified attribute type (or derived attribute types).
/// </summary>
/// <param name="parameter">The parameter on which the attributes are declared.</param>
/// <param name="attributeType">The attribute type to look for.</param>
/// <returns>
/// Returns the attribute that was found; or <c>null</c> if none was found.
/// </returns>
public static IAttribute GetAttribute(this IParameter parameter, KnownAttribute attributeType)
{
return parameter.GetAttributes().FirstOrDefault(a => a.AttributeType.IsKnownType(attributeType));
}
#endregion
#region IAssembly.GetTypeDefinition(string,string,int)
/// <summary>
/// Gets the type definition for a top-level type.
/// </summary>
/// <remarks>This method uses ordinal name comparison, not the compilation's name comparer.</remarks>
public static ITypeDefinition GetTypeDefinition(this IModule module, string namespaceName, string name, int typeParameterCount = 0)
{
if (module == null)
throw new ArgumentNullException("assembly");
return module.GetTypeDefinition(new TopLevelTypeName(namespaceName, name, typeParameterCount));
}
#endregion
#region ResolveResult
public static ISymbol GetSymbol(this ResolveResult rr)
{
if (rr is LocalResolveResult)
{
return ((LocalResolveResult)rr).Variable;
}
else if (rr is MemberResolveResult)
{
return ((MemberResolveResult)rr).Member;
}
else if (rr is TypeResolveResult)
{
return ((TypeResolveResult)rr).Type.GetDefinition();
}
else if (rr is ConversionResolveResult)
{
return ((ConversionResolveResult)rr).Input.GetSymbol();
}
return null;
}
#endregion
public static IType GetElementTypeFromIEnumerable(this IType collectionType, ICompilation compilation, bool allowIEnumerator, out bool? isGeneric)
{
var foundNonGenericIEnumerable = false;
foreach (var baseType in collectionType.GetAllBaseTypes())
{
var baseTypeDef = baseType.GetDefinition();
if (baseTypeDef != null)
{
var typeCode = baseTypeDef.KnownTypeCode;
if (typeCode == KnownTypeCode.IEnumerableOfT || (allowIEnumerator && typeCode == KnownTypeCode.IEnumeratorOfT))
{
var pt = baseType as ParameterizedType;
if (pt != null)
{
isGeneric = true;
return pt.GetTypeArgument(0);
}
}
if (typeCode == KnownTypeCode.IEnumerable || (allowIEnumerator && typeCode == KnownTypeCode.IEnumerator))
foundNonGenericIEnumerable = true;
}
}
// System.Collections.IEnumerable found in type hierarchy -> Object is element type.
if (foundNonGenericIEnumerable)
{
isGeneric = false;
return compilation.FindType(KnownTypeCode.Object);
}
isGeneric = null;
return SpecialType.UnknownType;
}
public static bool FullNameIs(this IMember member, string type, string name)
{
return member.Name == name && member.DeclaringType?.FullName == type;
}
public static KnownAttribute IsBuiltinAttribute(this ITypeDefinition type)
{
return KnownAttributes.IsKnownAttributeType(type);
}
public static IType WithoutNullability(this IType type)
{
return type.ChangeNullability(Nullability.Oblivious);
}
public static bool IsDirectImportOf(this ITypeDefinition type, IModule module)
{
var moduleReference = type.ParentModule;
foreach (var asmRef in module.PEFile.AssemblyReferences)
{
if (asmRef.FullName == moduleReference.FullAssemblyName)
return true;
if (asmRef.Name == "netstandard" && asmRef.GetPublicKeyToken() != null)
{
var referencedModule = module.Compilation.FindModuleByReference(asmRef);
if (referencedModule != null && !referencedModule.PEFile.GetTypeForwarder(type.FullTypeName).IsNil)
return true;
}
}
return false;
}
public static IModule FindModuleByReference(this ICompilation compilation, IAssemblyReference assemblyName)
{
foreach (var module in compilation.Modules)
{
if (string.Equals(module.FullAssemblyName, assemblyName.FullName, StringComparison.OrdinalIgnoreCase))
{
return module;
}
}
foreach (var module in compilation.Modules)
{
if (string.Equals(module.Name, assemblyName.Name, StringComparison.OrdinalIgnoreCase))
{
return module;
}
}
return null;
}
}
}
| 34.425121 | 148 | 0.710871 | [
"MIT"
] | AndreyBespamyatnov/Pharmacist | src/ICSharpCode.Decompiler/TypeSystem/TypeSystemExtensions.cs | 21,378 | C# |
// Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
namespace Microsoft.CodeAnalysis.Diagnostics
{
/// <summary>
/// The first event placed into a compilation's event queue.
/// </summary>
public sealed class CompilationStartedEvent : CompilationEvent
{
public CompilationStartedEvent(Compilation compilation) : base(compilation) { }
public override string ToString()
{
return "CompilationStartedEvent";
}
}
}
| 36 | 184 | 0.691176 | [
"Apache-2.0"
] | enginekit/copy_of_roslyn | Src/Compilers/Core/Portable/DiagnosticAnalyzer/CompilationStartedEvent.cs | 614 | C# |
//
// AudioFormat.cs:
//
// Authors:
// Miguel de Icaza (miguel@xamarin.com)
// Marek Safar (marek.safar@gmail.com)
//
// Copyright 2012 Xamarin Inc
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
#nullable enable
using System;
using System.IO;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using CoreFoundation;
using Foundation;
using ObjCRuntime;
using OSStatus = System.Int32;
using AudioFileID = System.IntPtr;
namespace AudioToolbox {
// AudioFormatListItem
#if !NET
[Watch (6,0)]
#endif
[StructLayout (LayoutKind.Sequential)]
public struct AudioFormat
{
public AudioStreamBasicDescription AudioStreamBasicDescription;
public AudioChannelLayoutTag AudioChannelLayoutTag;
#if !WATCH
public unsafe static AudioFormat? GetFirstPlayableFormat (AudioFormat[] formatList)
{
if (formatList is null)
ObjCRuntime.ThrowHelper.ThrowArgumentNullException (nameof (formatList));
if (formatList.Length < 2)
ObjCRuntime.ThrowHelper.ThrowArgumentNullException (nameof (formatList));
fixed (AudioFormat* item = &formatList[0]) {
uint index;
int size = sizeof (uint);
var ptr_size = sizeof (AudioFormat) * formatList.Length;
if (AudioFormatPropertyNative.AudioFormatGetProperty (AudioFormatProperty.FirstPlayableFormatFromList, ptr_size, item, ref size, out index) != 0)
return null;
return formatList [index];
}
}
#endif
public override string ToString ()
{
return AudioChannelLayoutTag + ":" + AudioStreamBasicDescription.ToString ();
}
}
#if !WATCH
public enum AudioFormatError : int // Implictly cast to OSType
{
None = 0,
Unspecified = 0x77686174, // 'what'
UnsupportedProperty = 0x70726f70, // 'prop'
BadPropertySize = 0x2173697a, // '!siz'
BadSpecifierSize = 0x21737063, // '!spc'
UnsupportedDataFormat = 0x666d743f, // 'fmt?'
UnknownFormat = 0x21666d74 // '!fmt'
// TODO: Not documented
// '!dat'
}
[StructLayout (LayoutKind.Sequential)]
public struct AudioValueRange
{
public double Minimum;
public double Maximum;
}
public enum AudioBalanceFadeType : uint // UInt32 in AudioBalanceFades
{
MaxUnityGain = 0,
EqualPower = 1
}
public class AudioBalanceFade
{
#if !COREBUILD
[StructLayout (LayoutKind.Sequential)]
struct Layout
{
public float LeftRightBalance;
public float BackFrontFade;
public AudioBalanceFadeType Type;
public IntPtr ChannelLayoutWeak;
}
public AudioBalanceFade (AudioChannelLayout channelLayout)
{
if (channelLayout is null)
ObjCRuntime.ThrowHelper.ThrowArgumentNullException (nameof (channelLayout));
this.ChannelLayout = channelLayout;
}
public float LeftRightBalance { get; set; }
public float BackFrontFade { get; set; }
public AudioBalanceFadeType Type { get; set; }
public AudioChannelLayout ChannelLayout { get; private set; }
public unsafe float[]? GetBalanceFade ()
{
var type_size = sizeof (Layout);
var str = ToStruct ();
var ptr = Marshal.AllocHGlobal (type_size);
(*(Layout *) ptr) = str;
int size;
if (AudioFormatPropertyNative.AudioFormatGetPropertyInfo (AudioFormatProperty.BalanceFade, type_size, ptr, out size) != 0)
return null;
AudioFormatError res;
var data = new float[size / sizeof (float)];
fixed (float* data_ptr = data) {
res = AudioFormatPropertyNative.AudioFormatGetProperty (AudioFormatProperty.BalanceFade, type_size, ptr, ref size, data_ptr);
}
Marshal.FreeHGlobal (str.ChannelLayoutWeak);
Marshal.FreeHGlobal (ptr);
return res == 0 ? data : null;
}
Layout ToStruct ()
{
var l = new Layout ()
{
LeftRightBalance = LeftRightBalance,
BackFrontFade = BackFrontFade,
Type = Type,
};
if (ChannelLayout is not null) {
int temp;
l.ChannelLayoutWeak = ChannelLayout.ToBlock (out temp);
}
return l;
}
#endif // !COREBUILD
}
public enum PanningMode : uint // UInt32 in AudioPanningInfo
{
SoundField = 3,
VectorBasedPanning = 4
}
public class AudioPanningInfo
{
#if !COREBUILD
[StructLayout (LayoutKind.Sequential)]
struct Layout
{
public PanningMode PanningMode;
public AudioChannelFlags CoordinateFlags;
public float Coord0, Coord1, Coord2;
public float GainScale;
public IntPtr OutputChannelMapWeak;
}
public AudioPanningInfo (AudioChannelLayout outputChannelMap)
{
if (outputChannelMap is null)
ObjCRuntime.ThrowHelper.ThrowArgumentNullException (nameof (outputChannelMap));
this.OutputChannelMap = outputChannelMap;
}
public PanningMode PanningMode { get; set; }
public AudioChannelFlags CoordinateFlags { get; set; }
public float[] Coordinates { get; private set; } = Array.Empty<float> ();
public float GainScale { get; set; }
public AudioChannelLayout OutputChannelMap { get; private set; }
public unsafe float[]? GetPanningMatrix ()
{
var type_size = sizeof (Layout);
var str = ToStruct ();
var ptr = Marshal.AllocHGlobal (type_size);
*((Layout *)ptr) = str;
int size;
if (AudioFormatPropertyNative.AudioFormatGetPropertyInfo (AudioFormatProperty.PanningMatrix, type_size, ptr, out size) != 0)
return null;
AudioFormatError res;
var data = new float[size / sizeof (float)];
fixed (float* data_ptr = data) {
res = AudioFormatPropertyNative.AudioFormatGetProperty (AudioFormatProperty.PanningMatrix, type_size, ptr, ref size, data_ptr);
}
Marshal.FreeHGlobal (str.OutputChannelMapWeak);
Marshal.FreeHGlobal (ptr);
return res == 0 ? data : null;
}
Layout ToStruct ()
{
var l = new Layout ()
{
PanningMode = PanningMode,
CoordinateFlags = CoordinateFlags,
Coord0 = Coordinates [0],
Coord1 = Coordinates [1],
Coord2 = Coordinates [2],
GainScale = GainScale
};
if (OutputChannelMap is not null) {
int temp;
l.OutputChannelMapWeak = OutputChannelMap.ToBlock (out temp);
}
return l;
}
#endif // !COREBUILD
}
static partial class AudioFormatPropertyNative
{
[DllImport (Constants.AudioToolboxLibrary)]
public extern static AudioFormatError AudioFormatGetPropertyInfo (AudioFormatProperty propertyID, int inSpecifierSize, ref AudioFormatType inSpecifier,
out uint outPropertyDataSize);
[DllImport (Constants.AudioToolboxLibrary)]
public extern static AudioFormatError AudioFormatGetPropertyInfo (AudioFormatProperty propertyID, int inSpecifierSize, ref AudioStreamBasicDescription inSpecifier,
out uint outPropertyDataSize);
[DllImport (Constants.AudioToolboxLibrary)]
public extern static AudioFormatError AudioFormatGetPropertyInfo (AudioFormatProperty propertyID, int inSpecifierSize, ref AudioFormatInfo inSpecifier,
out uint outPropertyDataSize);
[DllImport (Constants.AudioToolboxLibrary)]
public extern static AudioFormatError AudioFormatGetPropertyInfo (AudioFormatProperty propertyID, int inSpecifierSize, ref int inSpecifier,
out int outPropertyDataSize);
[DllImport (Constants.AudioToolboxLibrary)]
public extern static AudioFormatError AudioFormatGetPropertyInfo (AudioFormatProperty propertyID, int inSpecifierSize, IntPtr inSpecifier,
out int outPropertyDataSize);
[DllImport (Constants.AudioToolboxLibrary)]
public unsafe extern static AudioFormatError AudioFormatGetProperty (AudioFormatProperty propertyID, int inSpecifierSize, ref AudioFormatType inSpecifier,
ref uint ioDataSize, IntPtr outPropertyData);
[DllImport (Constants.AudioToolboxLibrary)]
public unsafe extern static AudioFormatError AudioFormatGetProperty (AudioFormatProperty propertyID, int inSpecifierSize, ref int inSpecifier,
ref int ioDataSize, IntPtr outPropertyData);
[DllImport (Constants.AudioToolboxLibrary)]
public unsafe extern static AudioFormatError AudioFormatGetProperty (AudioFormatProperty propertyID, int inSpecifierSize, IntPtr inSpecifier,
ref int ioDataSize, IntPtr outPropertyData);
[DllImport (Constants.AudioToolboxLibrary)]
public unsafe extern static AudioFormatError AudioFormatGetProperty (AudioFormatProperty propertyID, int inSpecifierSize, IntPtr inSpecifier,
ref int ioDataSize, out IntPtr outPropertyData);
[DllImport (Constants.AudioToolboxLibrary)]
public unsafe extern static AudioFormatError AudioFormatGetProperty (AudioFormatProperty propertyID, int inSpecifierSize, IntPtr inSpecifier,
ref int ioDataSize, out int outPropertyData);
[DllImport (Constants.AudioToolboxLibrary)]
public unsafe extern static AudioFormatError AudioFormatGetProperty (AudioFormatProperty propertyID, int inSpecifierSize, ref int inSpecifier,
ref int ioDataSize, out int outPropertyData);
[DllImport (Constants.AudioToolboxLibrary)]
public unsafe extern static AudioFormatError AudioFormatGetProperty (AudioFormatProperty propertyID, int inSpecifierSize, IntPtr inSpecifier,
IntPtr ioDataSize, IntPtr outPropertyData);
[DllImport (Constants.AudioToolboxLibrary)]
public unsafe extern static AudioFormatError AudioFormatGetProperty (AudioFormatProperty propertyID, int inSpecifierSize, ref AudioFormatInfo inSpecifier,
ref uint ioDataSize, AudioFormat* outPropertyData);
[DllImport (Constants.AudioToolboxLibrary)]
public unsafe extern static AudioFormatError AudioFormatGetProperty (AudioFormatProperty propertyID, int inSpecifierSize, ref AudioStreamBasicDescription inSpecifier,
ref uint ioDataSize, int* outPropertyData);
[DllImport (Constants.AudioToolboxLibrary)]
public unsafe extern static AudioFormatError AudioFormatGetProperty (AudioFormatProperty propertyID, int inSpecifierSize, ref int inSpecifier,
ref int ioDataSize, int* outPropertyData);
[DllImport (Constants.AudioToolboxLibrary)]
public unsafe extern static AudioFormatError AudioFormatGetProperty (AudioFormatProperty propertyID, int inSpecifierSize, IntPtr* inSpecifier,
ref int ioDataSize, int* outPropertyData);
[DllImport (Constants.AudioToolboxLibrary)]
public unsafe extern static AudioFormatError AudioFormatGetProperty (AudioFormatProperty propertyID, int inSpecifierSize, IntPtr* inSpecifier,
ref int ioDataSize, float* outPropertyData);
[DllImport (Constants.AudioToolboxLibrary)]
public unsafe extern static AudioFormatError AudioFormatGetProperty (AudioFormatProperty propertyID, int inSpecifierSize, IntPtr inSpecifier,
ref int ioDataSize, float* outPropertyData);
[DllImport (Constants.AudioToolboxLibrary)]
public extern static AudioFormatError AudioFormatGetProperty (AudioFormatProperty inPropertyID, int inSpecifierSize, ref AudioStreamBasicDescription inSpecifier,
ref int ioPropertyDataSize, out IntPtr outPropertyData);
[DllImport (Constants.AudioToolboxLibrary)]
public extern static AudioFormatError AudioFormatGetProperty (AudioFormatProperty inPropertyID, int inSpecifierSize, ref AudioStreamBasicDescription inSpecifier,
ref int ioPropertyDataSize, out uint outPropertyData);
[DllImport (Constants.AudioToolboxLibrary)]
public extern static AudioFormatError AudioFormatGetProperty (AudioFormatProperty inPropertyID, int inSpecifierSize, IntPtr inSpecifier, ref int ioPropertyDataSize,
ref AudioStreamBasicDescription outPropertyData);
[DllImport (Constants.AudioToolboxLibrary)]
public unsafe extern static AudioFormatError AudioFormatGetProperty (AudioFormatProperty inPropertyID, int inSpecifierSize, AudioFormat* inSpecifier, ref int ioPropertyDataSize,
out uint outPropertyData);
}
// Properties are used from various types (most suitable should be used)
enum AudioFormatProperty : uint // UInt32 AudioFormatPropertyID
{
FormatInfo = 0x666d7469, // 'fmti'
FormatName = 0x666e616d, // 'fnam'
EncodeFormatIDs = 0x61636f66, // 'acof'
DecodeFormatIDs = 0x61636966, // 'acif'
FormatList = 0x666c7374, // 'flst'
ASBDFromESDS = 0x65737364, // 'essd' // TODO: FromElementaryStreamDescriptor
ChannelLayoutFromESDS = 0x6573636c, // 'escl' // TODO:
OutputFormatList = 0x6f666c73, // 'ofls'
FirstPlayableFormatFromList = 0x6670666c, // 'fpfl'
FormatIsVBR = 0x66766272, // 'fvbr'
FormatIsExternallyFramed = 0x66657866, // 'fexf'
FormatIsEncrypted = 0x63727970, // 'cryp'
Encoders = 0x6176656e, // 'aven'
Decoders = 0x61766465, // 'avde'
AvailableEncodeChannelLayoutTags = 0x6165636c, // 'aecl'
AvailableEncodeNumberChannels = 0x61766e63, // 'avnc'
AvailableEncodeBitRates = 0x61656272, // 'aebr'
AvailableEncodeSampleRates = 0x61657372, // 'aesr'
ASBDFromMPEGPacket = 0x61646d70, // 'admp' // TODO:
BitmapForLayoutTag = 0x626d7467, // 'bmtg'
MatrixMixMap = 0x6d6d6170, // 'mmap'
ChannelMap = 0x63686d70, // 'chmp'
NumberOfChannelsForLayout = 0x6e63686d, // 'nchm'
AreChannelLayoutsEquivalent = 0x63686571, // 'cheq' // TODO:
ChannelLayoutHash = 0x63686861, // 'chha'
ValidateChannelLayout = 0x7661636c, // 'vacl'
ChannelLayoutForTag = 0x636d706c, // 'cmpl'
TagForChannelLayout = 0x636d7074, // 'cmpt'
ChannelLayoutName = 0x6c6f6e6d, // 'lonm'
ChannelLayoutSimpleName = 0x6c6f6e6d, // 'lsnm'
ChannelLayoutForBitmap = 0x636d7062, // 'cmpb'
ChannelName = 0x636e616d, // 'cnam'
ChannelShortName = 0x63736e6d, // 'csnm'
TagsForNumberOfChannels = 0x74616763, // 'tagc'
PanningMatrix = 0x70616e6d, // 'panm'
BalanceFade = 0x62616c66, // 'balf'
ID3TagSize = 0x69643373, // 'id3s' // TODO:
ID3TagToDictionary = 0x69643364, // 'id3d' // TODO:
#if !MONOMAC
#if NET
[UnsupportedOSPlatform ("ios8.0")]
#if IOS
[Obsolete ("Starting with ios8.0.", DiagnosticId = "BI1234", UrlFormat = "https://github.com/xamarin/xamarin-macios/wiki/Obsolete")]
#endif
#else
[Deprecated (PlatformName.iOS, 8, 0)]
#endif
HardwareCodecCapabilities = 0x68776363, // 'hwcc'
#endif
}
#endif // !WATCH
}
| 36.527094 | 179 | 0.755428 | [
"BSD-3-Clause"
] | SotoiGhost/xamarin-macios | src/AudioToolbox/AudioFormat.cs | 14,830 | C# |
// -----------------------------------------------------------------------------
// GENERATED CODE - DO NOT EDIT
// -----------------------------------------------------------------------------
using System;
using System.Linq;
using System.Collections.Generic;
using Hl7.Fhir.Model;
using Hl7.Fhir.Utility;
using System.Xml.Serialization;
using System.Xml;
using System.Xml.Linq;
using System.Threading;
namespace Hl7.Fhir.CustomSerializer
{
public partial class FhirCustomXmlReader
{
public void Parse(Hl7.Fhir.Model.DataRequirement.DateFilterComponent result, XmlReader reader, OperationOutcome outcome, string locationPath, CancellationToken cancellationToken)
{
// skip ignored elements
while (ShouldSkipNodeType(reader.NodeType))
if (!reader.Read())
return;
if (reader.MoveToFirstAttribute())
{
do
{
switch (reader.Name)
{
case "id":
result.ElementId = reader.Value;
break;
}
} while (reader.MoveToNextAttribute());
reader.MoveToElement();
}
if (reader.IsEmptyElement)
return;
// otherwise proceed to read all the other nodes
while (reader.Read())
{
if (cancellationToken.IsCancellationRequested)
return;
if (reader.IsStartElement())
{
switch (reader.Name)
{
case "extension":
var newItem_extension = new Hl7.Fhir.Model.Extension();
Parse(newItem_extension, reader, outcome, locationPath + ".extension["+result.Extension.Count+"]", cancellationToken); // 20
result.Extension.Add(newItem_extension);
break;
case "path":
result.PathElement = new Hl7.Fhir.Model.FhirString();
Parse(result.PathElement as Hl7.Fhir.Model.FhirString, reader, outcome, locationPath + ".path", cancellationToken); // 40
break;
case "searchParam":
result.SearchParamElement = new Hl7.Fhir.Model.FhirString();
Parse(result.SearchParamElement as Hl7.Fhir.Model.FhirString, reader, outcome, locationPath + ".searchParam", cancellationToken); // 50
break;
case "valueDateTime":
result.Value = new Hl7.Fhir.Model.FhirDateTime();
Parse(result.Value as Hl7.Fhir.Model.FhirDateTime, reader, outcome, locationPath + ".value", cancellationToken); // 60
break;
case "valuePeriod":
result.Value = new Hl7.Fhir.Model.Period();
Parse(result.Value as Hl7.Fhir.Model.Period, reader, outcome, locationPath + ".value", cancellationToken); // 60
break;
case "valueDuration":
result.Value = new Hl7.Fhir.Model.Duration();
Parse(result.Value as Hl7.Fhir.Model.Duration, reader, outcome, locationPath + ".value", cancellationToken); // 60
break;
default:
// Property not found
HandlePropertyNotFound(reader, outcome, locationPath + "." + reader.Name);
break;
}
}
else if (reader.NodeType == XmlNodeType.EndElement || reader.IsStartElement() && reader.IsEmptyElement)
{
break;
}
}
}
public async System.Threading.Tasks.Task ParseAsync(Hl7.Fhir.Model.DataRequirement.DateFilterComponent result, XmlReader reader, OperationOutcome outcome, string locationPath, CancellationToken cancellationToken)
{
// skip ignored elements
while (ShouldSkipNodeType(reader.NodeType))
if (!await reader.ReadAsync().ConfigureAwait(false))
return;
if (reader.MoveToFirstAttribute())
{
do
{
switch (reader.Name)
{
case "id":
result.ElementId = reader.Value;
break;
}
} while (reader.MoveToNextAttribute());
reader.MoveToElement();
}
if (reader.IsEmptyElement)
return;
// otherwise proceed to read all the other nodes
while (await reader.ReadAsync().ConfigureAwait(false))
{
if (cancellationToken.IsCancellationRequested)
return;
if (reader.IsStartElement())
{
switch (reader.Name)
{
case "extension":
var newItem_extension = new Hl7.Fhir.Model.Extension();
await ParseAsync(newItem_extension, reader, outcome, locationPath + ".extension["+result.Extension.Count+"]", cancellationToken); // 20
result.Extension.Add(newItem_extension);
break;
case "path":
result.PathElement = new Hl7.Fhir.Model.FhirString();
await ParseAsync(result.PathElement as Hl7.Fhir.Model.FhirString, reader, outcome, locationPath + ".path", cancellationToken); // 40
break;
case "searchParam":
result.SearchParamElement = new Hl7.Fhir.Model.FhirString();
await ParseAsync(result.SearchParamElement as Hl7.Fhir.Model.FhirString, reader, outcome, locationPath + ".searchParam", cancellationToken); // 50
break;
case "valueDateTime":
result.Value = new Hl7.Fhir.Model.FhirDateTime();
await ParseAsync(result.Value as Hl7.Fhir.Model.FhirDateTime, reader, outcome, locationPath + ".value", cancellationToken); // 60
break;
case "valuePeriod":
result.Value = new Hl7.Fhir.Model.Period();
await ParseAsync(result.Value as Hl7.Fhir.Model.Period, reader, outcome, locationPath + ".value", cancellationToken); // 60
break;
case "valueDuration":
result.Value = new Hl7.Fhir.Model.Duration();
await ParseAsync(result.Value as Hl7.Fhir.Model.Duration, reader, outcome, locationPath + ".value", cancellationToken); // 60
break;
default:
// Property not found
await HandlePropertyNotFoundAsync(reader, outcome, locationPath + "." + reader.Name);
break;
}
}
else if (reader.NodeType == XmlNodeType.EndElement || reader.IsStartElement() && reader.IsEmptyElement)
{
break;
}
}
}
}
}
| 35.378882 | 214 | 0.652914 | [
"BSD-3-Clause"
] | brianpos/fhir-net-web-api | src/Hl7.Fhir.Custom.Serializers/Generated/FhirCustomXmlReader.DataRequirement.DateFilterComponent.cs | 5,698 | C# |
using System;
using System.Linq;
namespace Eolina;
public class LowerToken : ICheckToken, IMapActionToken, IFilterActionToken
{
public BoolValue CheckAction(Value value)
=> value switch
{
ArrayValue arrayValue => arrayValue.Value.All(x => x.IsLower()).ToBoolValue(),
StringValue stringValue => stringValue.Value.IsLower().ToBoolValue(),
BoolValue => throw MismatchException.ReceivedBool(),
_ => throw new ArgumentException("Expected value")
};
public Value MapAction<TValue>(TValue value)
where TValue : Value
=> value switch
{
ArrayValue arrayValue => arrayValue.Value.Select(x => x.ToLower()).ToArrayValue(),
StringValue stringValue => stringValue.Value.ToLower().ToStringValue(),
BoolValue => throw MismatchException.ReceivedBool(),
_ => throw new ArgumentException("Expected value")
};
public Value FilterAction<TValue>(TValue value)
where TValue : Value
=> value switch
{
StringValue stringValue => stringValue.Value
.Where(char.IsLower)
.Join(string.Empty)
.ToStringValue(),
ArrayValue arrayValue => arrayValue.Value
.Where(x => x.IsLower())
.ToArrayValue(),
BoolValue => throw MismatchException.ReceivedBool(),
_ => throw new ArgumentException("Expected value")
};
public string TokenRepresentation()
=> "<LowerToken>";
} | 29.792453 | 94 | 0.60038 | [
"MIT"
] | shift-eleven/Eolina | Eolina/Parsing/Tokens/LowerToken.cs | 1,581 | C# |
using System;
public class Truck : Vehicles
{
public Truck(double fuelQuantity, double consumptionPerKm) : base(fuelQuantity, consumptionPerKm + 1.6)
{
}
public override void Refuel(double amountOfFuel)
{
this.FuelQuantity += amountOfFuel * 0.95;
}
}
| 20.428571 | 107 | 0.674825 | [
"MIT"
] | valkin88/CSharp-Fundamentals | CSharp OOP Basics/Polymorphism - Exercises/Vehicles/Vehicles/Truck.cs | 288 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// Dieser Code wurde von einem Tool generiert.
// Laufzeitversion:4.0.30319.42000
//
// Änderungen an dieser Datei können falsches Verhalten verursachen und gehen verloren, wenn
// der Code erneut generiert wird.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Faidv2.Properties {
using System;
/// <summary>
/// Eine stark typisierte Ressourcenklasse zum Suchen von lokalisierten Zeichenfolgen usw.
/// </summary>
// Diese Klasse wurde von der StronglyTypedResourceBuilder automatisch generiert
// -Klasse über ein Tool wie ResGen oder Visual Studio automatisch generiert.
// Um einen Member hinzuzufügen oder zu entfernen, bearbeiten Sie die .ResX-Datei und führen dann ResGen
// mit der /str-Option erneut aus, oder Sie erstellen Ihr VS-Projekt neu.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
public class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Gibt die zwischengespeicherte ResourceManager-Instanz zurück, die von dieser Klasse verwendet wird.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
public static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Faidv2.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Überschreibt die CurrentUICulture-Eigenschaft des aktuellen Threads für alle
/// Ressourcenzuordnungen, die diese stark typisierte Ressourcenklasse verwenden.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
public static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Sucht eine lokalisierte Zeichenfolge, die Formatfehler {0} ähnelt.
/// </summary>
public static string KonvertierungFormatFehler {
get {
return ResourceManager.GetString("KonvertierungFormatFehler", resourceCulture);
}
}
/// <summary>
/// Sucht eine lokalisierte Zeichenfolge, die Kontostand manuell gesetzt: ähnelt.
/// </summary>
public static string KonvertierungKontostandManuell {
get {
return ResourceManager.GetString("KonvertierungKontostandManuell", resourceCulture);
}
}
/// <summary>
/// Sucht eine lokalisierte Zeichenfolge, die Einkommen ähnelt.
/// </summary>
public static string KonvertierungMonatlicheVerbuchungAltEinkommenIdent {
get {
return ResourceManager.GetString("KonvertierungMonatlicheVerbuchungAltEinkommenIdent", resourceCulture);
}
}
/// <summary>
/// Sucht eine lokalisierte Zeichenfolge, die m ähnelt.
/// </summary>
public static string KonvertierungMonatlicheVerbuchungAltIdent {
get {
return ResourceManager.GetString("KonvertierungMonatlicheVerbuchungAltIdent", resourceCulture);
}
}
/// <summary>
/// Sucht eine lokalisierte Zeichenfolge, die Zinsen ähnelt.
/// </summary>
public static string KonvertierungMonatlicheVerbuchungAltZinsenIdent {
get {
return ResourceManager.GetString("KonvertierungMonatlicheVerbuchungAltZinsenIdent", resourceCulture);
}
}
/// <summary>
/// Sucht eine lokalisierte Zeichenfolge, die Monatliche ähnelt.
/// </summary>
public static string KonvertierungMonatlicheVerbuchungGleichsetzenIdent {
get {
return ResourceManager.GetString("KonvertierungMonatlicheVerbuchungGleichsetzenIdent", resourceCulture);
}
}
/// <summary>
/// Sucht eine lokalisierte Zeichenfolge, die Verbuchung ähnelt.
/// </summary>
public static string KonvertierungMonatlicheVerbuchungIdent {
get {
return ResourceManager.GetString("KonvertierungMonatlicheVerbuchungIdent", resourceCulture);
}
}
}
}
| 44.094488 | 173 | 0.604643 | [
"MIT"
] | Erukaron/Faidv2 | Faidv2/Properties/Resources.Designer.cs | 5,617 | C# |
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
namespace System.Data.Entity.Core.Metadata.Edm.Provider
{
using System.Collections.ObjectModel;
using System.Data.Entity.Core.Common;
using System.Data.Entity.Hierarchy;
using System.Data.Entity.Spatial;
using System.Data.Entity.Utilities;
using System.Linq;
using System.Threading;
using System.Xml;
internal class ClrProviderManifest : DbProviderManifest
{
private const int s_PrimitiveTypeCount = EdmConstants.NumPrimitiveTypes;
private ReadOnlyCollection<PrimitiveType> _primitiveTypesArray;
private ReadOnlyCollection<PrimitiveType> _primitiveTypes;
private static readonly ClrProviderManifest _instance = new ClrProviderManifest();
// <summary>
// A private constructor to prevent other places from instantiating this class
// </summary>
private ClrProviderManifest()
{
}
// <summary>
// Gets the EDM provider manifest singleton instance
// </summary>
internal static ClrProviderManifest Instance
{
get { return _instance; }
}
// <summary>
// Returns the namespace used by this provider manifest
// </summary>
public override string NamespaceName
{
get { return EdmConstants.ClrPrimitiveTypeNamespace; }
}
// <summary>
// Returns the primitive type corresponding to the given CLR type
// </summary>
// <param name="clrType"> The CLR type for which the PrimitiveType object is retrieved </param>
// <param name="primitiveType"> The retrieved primitive type </param>
// <returns> True if a primitive type is returned </returns>
internal bool TryGetPrimitiveType(Type clrType, out PrimitiveType primitiveType)
{
primitiveType = null;
PrimitiveTypeKind resolvedTypeKind;
if (TryGetPrimitiveTypeKind(clrType, out resolvedTypeKind))
{
InitializePrimitiveTypes();
primitiveType = _primitiveTypesArray[(int)resolvedTypeKind];
return true;
}
return false;
}
// <summary>
// Returns the <see cref="PrimitiveTypeKind" /> corresponding to the given CLR type
// </summary>
// <param name="clrType"> The CLR type for which the PrimitiveTypeKind value should be resolved </param>
// <param name="resolvedPrimitiveTypeKind"> The PrimitiveTypeKind value to which the CLR type resolves, if any. </param>
// <returns> True if the CLR type represents a primitive (EDM) type; otherwise false. </returns>
internal static bool TryGetPrimitiveTypeKind(Type clrType, out PrimitiveTypeKind resolvedPrimitiveTypeKind)
{
PrimitiveTypeKind? primitiveTypeKind = null;
if (!clrType.IsEnum()) // Enums return the TypeCode of their underlying type
{
// As an optimization, short-circuit when the provided type has a known type code.
switch (Type.GetTypeCode(clrType))
{
// PrimitiveTypeKind.Binary = byte[] = TypeCode.Object
case TypeCode.Boolean:
primitiveTypeKind = PrimitiveTypeKind.Boolean;
break;
case TypeCode.Byte:
primitiveTypeKind = PrimitiveTypeKind.Byte;
break;
case TypeCode.DateTime:
primitiveTypeKind = PrimitiveTypeKind.DateTime;
break;
// PrimitiveTypeKind.DateTimeOffset = System.DateTimeOffset = TypeCode.Object
case TypeCode.Decimal:
primitiveTypeKind = PrimitiveTypeKind.Decimal;
break;
case TypeCode.Double:
primitiveTypeKind = PrimitiveTypeKind.Double;
break;
// PrimitiveTypeKind.Geography = System.Data.Entity.Spatial.DbGeometry (or subtype) = TypeCode.Object
// PrimitiveTypeKind.Geometry = System.Data.Entity.Spatial.DbGeometry (or subtype) = TypeCode.Object
// PrimitiveTypeKind.Guid = System.Guid = TypeCode.Object
case TypeCode.Int16:
primitiveTypeKind = PrimitiveTypeKind.Int16;
break;
case TypeCode.Int32:
primitiveTypeKind = PrimitiveTypeKind.Int32;
break;
case TypeCode.Int64:
primitiveTypeKind = PrimitiveTypeKind.Int64;
break;
case TypeCode.SByte:
primitiveTypeKind = PrimitiveTypeKind.SByte;
break;
case TypeCode.Single:
primitiveTypeKind = PrimitiveTypeKind.Single;
break;
case TypeCode.String:
primitiveTypeKind = PrimitiveTypeKind.String;
break;
// PrimitiveTypeKind.Time = System.TimeSpan = TypeCode.Object
case TypeCode.Object:
{
if (typeof(byte[]) == clrType)
{
primitiveTypeKind = PrimitiveTypeKind.Binary;
}
else if (typeof(DateTimeOffset) == clrType)
{
primitiveTypeKind = PrimitiveTypeKind.DateTimeOffset;
}
// DbGeography/Geometry are abstract so subtypes must be allowed
else if (typeof(DbGeography).IsAssignableFrom(clrType))
{
primitiveTypeKind = PrimitiveTypeKind.Geography;
}
else if (typeof(DbGeometry).IsAssignableFrom(clrType))
{
primitiveTypeKind = PrimitiveTypeKind.Geometry;
}
else if (typeof(Guid) == clrType)
{
primitiveTypeKind = PrimitiveTypeKind.Guid;
}
else if (typeof(HierarchyId) == clrType)
{
primitiveTypeKind = PrimitiveTypeKind.HierarchyId;
}
else if (typeof(TimeSpan) == clrType)
{
primitiveTypeKind = PrimitiveTypeKind.Time;
}
break;
}
}
}
if (primitiveTypeKind.HasValue)
{
resolvedPrimitiveTypeKind = primitiveTypeKind.Value;
return true;
}
else
{
resolvedPrimitiveTypeKind = default(PrimitiveTypeKind);
return false;
}
}
// <summary>
// Returns all the functions in this provider manifest
// </summary>
// <returns> A collection of functions </returns>
public override ReadOnlyCollection<EdmFunction> GetStoreFunctions()
{
return Helper.EmptyEdmFunctionReadOnlyCollection;
}
// <summary>
// Returns all the FacetDescriptions for a particular type
// </summary>
// <param name="type"> the type to return FacetDescriptions for. </param>
// <returns> The FacetDescriptions for the type given. </returns>
public override ReadOnlyCollection<FacetDescription> GetFacetDescriptions(EdmType type)
{
if (Helper.IsPrimitiveType(type)
&& (type).DataSpace == DataSpace.OSpace)
{
// we don't have our own facets, just defer to the edm primitive type facets
var basePrimitive = (PrimitiveType)type.BaseType;
return basePrimitive.ProviderManifest.GetFacetDescriptions(basePrimitive);
}
return Helper.EmptyFacetDescriptionEnumerable;
}
// <summary>
// Initializes all the primitive types
// </summary>
private void InitializePrimitiveTypes()
{
if (_primitiveTypes != null)
{
return;
}
var primitiveTypes = new PrimitiveType[s_PrimitiveTypeCount];
primitiveTypes[(int)PrimitiveTypeKind.Binary] = CreatePrimitiveType(typeof(Byte[]), PrimitiveTypeKind.Binary);
primitiveTypes[(int)PrimitiveTypeKind.Boolean] = CreatePrimitiveType(typeof(Boolean), PrimitiveTypeKind.Boolean);
primitiveTypes[(int)PrimitiveTypeKind.Byte] = CreatePrimitiveType(typeof(Byte), PrimitiveTypeKind.Byte);
primitiveTypes[(int)PrimitiveTypeKind.DateTime] = CreatePrimitiveType(typeof(DateTime), PrimitiveTypeKind.DateTime);
primitiveTypes[(int)PrimitiveTypeKind.Time] = CreatePrimitiveType(typeof(TimeSpan), PrimitiveTypeKind.Time);
primitiveTypes[(int)PrimitiveTypeKind.DateTimeOffset] = CreatePrimitiveType(
typeof(DateTimeOffset), PrimitiveTypeKind.DateTimeOffset);
primitiveTypes[(int)PrimitiveTypeKind.Decimal] = CreatePrimitiveType(typeof(Decimal), PrimitiveTypeKind.Decimal);
primitiveTypes[(int)PrimitiveTypeKind.Double] = CreatePrimitiveType(typeof(Double), PrimitiveTypeKind.Double);
primitiveTypes[(int)PrimitiveTypeKind.Geography] = CreatePrimitiveType(typeof(DbGeography), PrimitiveTypeKind.Geography);
primitiveTypes[(int)PrimitiveTypeKind.Geometry] = CreatePrimitiveType(typeof(DbGeometry), PrimitiveTypeKind.Geometry);
primitiveTypes[(int)PrimitiveTypeKind.Guid] = CreatePrimitiveType(typeof(Guid), PrimitiveTypeKind.Guid);
primitiveTypes[(int)PrimitiveTypeKind.HierarchyId] = CreatePrimitiveType(typeof(HierarchyId), PrimitiveTypeKind.HierarchyId);
primitiveTypes[(int)PrimitiveTypeKind.Int16] = CreatePrimitiveType(typeof(Int16), PrimitiveTypeKind.Int16);
primitiveTypes[(int)PrimitiveTypeKind.Int32] = CreatePrimitiveType(typeof(Int32), PrimitiveTypeKind.Int32);
primitiveTypes[(int)PrimitiveTypeKind.Int64] = CreatePrimitiveType(typeof(Int64), PrimitiveTypeKind.Int64);
primitiveTypes[(int)PrimitiveTypeKind.SByte] = CreatePrimitiveType(typeof(SByte), PrimitiveTypeKind.SByte);
primitiveTypes[(int)PrimitiveTypeKind.Single] = CreatePrimitiveType(typeof(Single), PrimitiveTypeKind.Single);
primitiveTypes[(int)PrimitiveTypeKind.String] = CreatePrimitiveType(typeof(String), PrimitiveTypeKind.String);
var readOnlyTypesArray = new ReadOnlyCollection<PrimitiveType>(primitiveTypes);
var readOnlyTypes = new ReadOnlyCollection<PrimitiveType>(primitiveTypes.Where(t => t != null).ToList());
// Set the result to _primitiveTypes at the end
Interlocked.CompareExchange(ref _primitiveTypesArray, readOnlyTypesArray, null);
Interlocked.CompareExchange(ref _primitiveTypes, readOnlyTypes, null);
}
// <summary>
// Initialize the primitive type with the given
// </summary>
// <param name="clrType"> The CLR type of this type </param>
// <param name="primitiveTypeKind"> The primitive type kind of the primitive type </param>
private PrimitiveType CreatePrimitiveType(Type clrType, PrimitiveTypeKind primitiveTypeKind)
{
// Figures out the base type
var baseType = MetadataItem.EdmProviderManifest.GetPrimitiveType(primitiveTypeKind);
var primitiveType = new PrimitiveType(clrType, baseType, this);
primitiveType.SetReadOnly();
return primitiveType;
}
public override ReadOnlyCollection<PrimitiveType> GetStoreTypes()
{
InitializePrimitiveTypes();
return _primitiveTypes;
}
public override TypeUsage GetEdmType(TypeUsage storeType)
{
Check.NotNull(storeType, "storeType");
throw new NotImplementedException();
}
public override TypeUsage GetStoreType(TypeUsage edmType)
{
Check.NotNull(edmType, "edmType");
throw new NotImplementedException();
}
// <summary>
// Providers should override this to return information specific to their provider.
// This method should never return null.
// </summary>
// <param name="informationType"> The name of the information to be retrieved. </param>
// <returns> An XmlReader at the begining of the information requested. </returns>
protected override XmlReader GetDbInformation(string informationType)
{
throw new NotImplementedException();
}
}
}
| 48.411552 | 137 | 0.59135 | [
"Apache-2.0"
] | Icehunter/entityframework | src/EntityFramework/Core/Metadata/Edm/Provider/ClrProviderManifest.cs | 13,410 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Windows.Markup;
namespace SwagOverFlow.WPF.UI
{
//https://www.codeproject.com/Tips/873562/Markup-Extension-for-Generic-Classes-2
public class TypeArgumentsConverter : TypeConverter
{
public override Boolean CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
if (sourceType == typeof(Type)) return true;
if (context == null) return false;
var resolver = context.GetService(typeof(IXamlTypeResolver)) as IXamlTypeResolver;
return resolver != null;
}
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
if (value == null || value is IList<Type>) return value;
Type valueType = value as Type;
if (valueType != null)
{
return new List<Type> { valueType };
}
string valueString = value as string;
if (valueString != null && context != null)
{
var resolver = context.GetService(typeof(IXamlTypeResolver)) as IXamlTypeResolver;
if (resolver != null)
{
var list = valueString.Split(',').Select(s => resolver.Resolve(s.Trim())).ToList();
if (list.All(t => t != null)) return list;
}
}
throw GetConvertFromException(value);
}
}
}
| 28.042553 | 103 | 0.709408 | [
"MIT"
] | adiamante/SwagOverFlow | SwagOverFlow/SwagOverFlow.WPF/UI/TypeArgumentsConverter.cs | 1,320 | C# |
// Adam Dernis © 2022
using System.Numerics;
namespace AlgoNet.Clustering
{
/// <summary>
/// A shape defining how to handle <see cref="Vector3"/>s in a geometric space.
/// </summary>
public struct Vector3Shape : IGeometricSpace<Vector3>
{
/// <inheritdoc/>
public bool AreEqual(Vector3 it1, Vector3 it2)
{
return it1 == it2;
}
/// <inheritdoc/>
public Vector3 Average(Vector3[] items)
{
Vector3 sumVector = Vector3.Zero;
int count = 0;
foreach (var item in items)
{
sumVector += item;
count++;
}
sumVector /= count;
return sumVector;
}
/// <inheritdoc/>
public double FindDistanceSquared(Vector3 it1, Vector3 it2)
{
return (it1 - it2).LengthSquared();
}
/// <inheritdoc/>
public Vector3 GetCell(Vector3 value, double window)
{
var shape = new FloatShape();
Vector3 rounded = value;
rounded.X = shape.GetCell(rounded.X, window);
rounded.Y = shape.GetCell(rounded.Y, window);
rounded.Z = shape.GetCell(rounded.Z, window);
return rounded;
}
/// <inheritdoc/>
public Vector3 WeightedAverage((Vector3, double)[] items)
{
Vector3 sumVector = Vector3.Zero;
double totalWeight = 0;
foreach (var item in items)
{
sumVector += item.Item1 * (float)item.Item2;
totalWeight += item.Item2;
}
sumVector /= (float)totalWeight;
return sumVector;
}
}
}
| 27.4375 | 83 | 0.507403 | [
"MIT"
] | Avid29/AlgoNet | src/AlgoNet.Clustering/Shapes/Vector3Shape.cs | 1,759 | C# |
//
// System.Diagnostics.Design.ProcessDesigner
//
// Authors:
// Gert Driesen (drieseng@users.sourceforge.net)
//
// (C) 2004 Novell
//
//
// 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.Collections;
using System.ComponentModel.Design;
namespace System.Diagnostics.Design
{
public class ProcessDesigner : ComponentDesigner
{
public ProcessDesigner ()
{
}
[MonoTODO]
protected override void PreFilterProperties (IDictionary properties)
{
throw new NotImplementedException ();
}
}
}
| 31.755102 | 73 | 0.751285 | [
"Apache-2.0"
] | 121468615/mono | mcs/class/System.Design/System.Diagnostics.Design/ProcessDesigner.cs | 1,556 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
namespace Cynosura.Template.Core.Requests.Files.Models
{
public class FileModel
{
[DisplayName("Id")]
public int Id { get; set; }
[DisplayName("Creation Date")]
public DateTime CreationDate { get; set; }
[DisplayName("Modification Date")]
public DateTime ModificationDate { get; set; }
[DisplayName("Creation User")]
public int? CreationUserId { get; set; }
public Users.Models.UserShortModel CreationUser { get; set; }
[DisplayName("Modification User")]
public int? ModificationUserId { get; set; }
public Users.Models.UserShortModel ModificationUser { get; set; }
[DisplayName("Name")]
public string Name { get; set; }
[DisplayName("Content Type")]
public string ContentType { get; set; }
[DisplayName("Url")]
public string Url { get; set; }
[DisplayName("Group")]
public int GroupId { get; set; }
public FileGroups.Models.FileGroupShortModel Group { get; set; }
}
}
| 28.4 | 73 | 0.623239 | [
"MIT"
] | CynosuraPlatform/Cynosura.Template | src/Cynosura.Template.Core/Requests/Files/Models/FileModel.cs | 1,138 | C# |
/*
* Original author: Nicholas Shulman <nicksh .at. u.washington.edu>,
* MacCoss Lab, Department of Genome Sciences, UW
*
* Copyright 2009 University of Washington - Seattle, WA
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections;
using System.Collections.Generic;
namespace pwiz.Common.Collections
{
public class ImmutableDictionary<TKey,TValue> : ImmutableCollection<KeyValuePair<TKey,TValue>>, IDictionary<TKey,TValue>
{
public ImmutableDictionary(IDictionary<TKey,TValue> dict) : base(dict)
{
}
protected ImmutableDictionary()
{
}
protected IDictionary<TKey, TValue> Dictionary { get { return (IDictionary<TKey, TValue>) Collection;} set { Collection = value;} }
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public bool ContainsKey(TKey key)
{
return Dictionary.ContainsKey(key);
}
public void Add(TKey key, TValue value)
{
throw new InvalidOperationException();
}
public bool Remove(TKey key)
{
throw new InvalidOperationException();
}
public bool TryGetValue(TKey key, out TValue value)
{
return Dictionary.TryGetValue(key, out value);
}
public TValue this[TKey key]
{
get { return Dictionary[key]; }
set { throw new InvalidOperationException(); }
}
public ICollection<TKey> Keys
{
get { return new ImmutableCollection<TKey>(Dictionary.Keys); }
}
public ICollection<TValue> Values
{
get { return new ImmutableCollection<TValue>(Dictionary.Values); }
}
}
}
| 30.910256 | 140 | 0.612194 | [
"Apache-2.0"
] | CSi-Studio/pwiz | pwiz_tools/Shared/Common/Collections/ImmutableDictionary.cs | 2,413 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JimmysComics
{
using System.Collections.ObjectModel;
using Windows.UI.Xaml.Media.Imaging;
class ComicQueryManager
{
public ObservableCollection<ComicQuery> AvailableQueries { get; private set; }
public ObservableCollection<object> CurrentQueryResults { get; private set; }
public string Title { get; set; }
public ComicQueryManager()
{
UpdateAvailableQueries();
CurrentQueryResults = new ObservableCollection<object>();
}
private void UpdateAvailableQueries()
{
AvailableQueries = new ObservableCollection<ComicQuery> {
new ComicQuery("LINQ makes queries easy", "A sample query",
"Let's show Jimmy how flexible LINQ is",
CreateImageFromAssets("purple_250x250.jpg")),
new ComicQuery("Expensive comics", "Comics over $500",
"Comics whose value is over 500 bucks."
+ " Jimmy can use this to figure out which comics are most coveted.",
CreateImageFromAssets("captain_amazing_250x250.jpg")),
new ComicQuery("LINQ is versatile 1", "Modify every item returned from the query",
"This code will add a string onto the end of each string in an array.",
CreateImageFromAssets("bluegray_250x250.jpg")),
new ComicQuery("LINQ is versatile 2", "Perform calculations on collections",
"LINQ provides extension methods for your collections (and anything else"
+ " that implements IEnumerable<T>).",
CreateImageFromAssets("purple_250x250.jpg")),
new ComicQuery("LINQ is versatile 3",
"Store all or part of your results in a new sequence",
"Sometimes you’ll want to keep your results from a LINQ query around.",
CreateImageFromAssets("bluegray_250x250.jpg")),
new ComicQuery("Group comics by price range",
"Combine Jimmy's values into groups",
"Jimmy buys a lot of cheap comic books, some midrange comic books, and"
+ " a few expensive ones, and he wants to know what his options are"
+ " before he decides what comics to buy.",
CreateImageFromAssets("captain_amazing_250x250.jpg")),
new ComicQuery("Join purchases with prices",
"Let's see if Jimmy drives a hard bargain",
"This query creates a list of Purchase classes that contain Jimmy's purchases"
+ " and compares them with the prices he found on Greg's List.",
CreateImageFromAssets("captain_amazing_250x250.jpg")),
new ComicQuery("All comics in the collection",
"Get all of the comics in the collection",
"This query returns all of the comics",
CreateImageFromAssets("captain_amazing_zoom_250x250.jpg")),
};
}
private static BitmapImage CreateImageFromAssets(string imageFilename)
{
return new BitmapImage(new Uri("ms-appx:///Assets/" + imageFilename));
}
public void UpdateQueryResults(ComicQuery query)
{
Title = query.Title;
switch (query.Title)
{
case "LINQ makes queries easy": LinqMakesQueriesEasy(); break;
case "Expensive comics": ExpensiveComics(); break;
case "LINQ is versatile 1": LinqIsVersatile1(); break;
case "LINQ is versatile 2": LinqIsVersatile2(); break;
case "LINQ is versatile 3": LinqIsVersatile3(); break;
case "Group comics by price range":
CombineJimmysValuesIntoGroups();
break;
case "Join purchases with prices":
JoinPurchasesWithPrices();
break;
case "All comics in the collection": AllComics(); break;
}
}
public static IEnumerable<Comic> BuildCatalog()
{
return new List<Comic> {
new Comic { Name = "Johnny America vs. the Pinko", Issue = 6, Year = 1949, CoverPrice = "10 cents",
MainVillain = "The Pinko", Cover = CreateImageFromAssets("Captain Amazing Issue 6 cover.png"),
Synopsis = "Captain Amazing must save America from Communists as The Pinko and his"
+ " communist henchmen threaten to take over Fort Knox and steal all of the nation's gold." },
new Comic { Name = "Rock and Roll (limited edition)", Issue = 19, Year = 1957, CoverPrice = "10 cents",
MainVillain = "Doctor Vortran", Cover = CreateImageFromAssets("Captain Amazing Issue 19 cover.png"),
Synopsis = "Doctor Vortran wreaks havoc with the nation's youth with his radio wave device that"
+ " uses the latest dance craze to send rock and roll fans into a mind-control trance." },
new Comic { Name = "Woman’s Work", Issue = 36, Year = 1968, CoverPrice = "12 cents",
MainVillain = "Hysterianna", Cover = CreateImageFromAssets("Captain Amazing Issue 36 cover.png"),
Synopsis = "The Captain faces his first female foe, Hysterianna, whose incredible telepathic"
+ " and telekinetic abilities have allowed her to raise an all-girl army that"
+ " even the Captain has trouble resisting." },
new Comic { Name = "Hippie Madness (misprinted)", Issue = 57, Year = 1973, CoverPrice = "20 cents",
MainVillain = "The Mayor", Cover = CreateImageFromAssets("Captain Amazing Issue 57 cover.png"),
Synopsis = "A zombie apocalypse threatens Objectville when The Mayor rigs the election by"
+ " introducing his zombification agent into the city's cigarette supply." },
new Comic { Name = "Revenge of the New Wave Freak (damaged)", Issue = 68, Year = 1984,
CoverPrice = "75 cents", MainVillain = "The Swindler",
Cover = CreateImageFromAssets("Captain Amazing Issue 68 cover.png"),
Synopsis = "A tainted batch of eye makeup turns Dr. Alvin Mudd into the Captain's new nemesis,"
+ " in The Swindler's first appearance in a Captain Amazing comic." },
new Comic { Name = "Black Monday", Issue = 74, Year = 1986, CoverPrice = "75 cents",
MainVillain = "The Mayor", Cover = CreateImageFromAssets("Captain Amazing Issue 74 cover.png"),
Synopsis = "The Mayor returns to throw Objectville into a financial crisis by directing his"
+ " zombie creation powers to the floor of the Objectville Stock Exchange." },
new Comic { Name = "Tribal Tattoo Madness", Issue = 83, Year = 1996, CoverPrice = "Two bucks",
MainVillain = "Mokey Man", Cover = CreateImageFromAssets("Captain Amazing Issue 83 cover.png"),
Synopsis = "Monkey Man escapes from his island prison and wreaks havoc with his circus sideshow"
+ " of tattooed henchmen that and their deadly grunge ray." },
new Comic { Name = "The Death of an Object", Issue = 97, Year = 2013, CoverPrice = "Four bucks",
MainVillain = "The Swindler", Cover = CreateImageFromAssets("Captain Amazing Issue 97 cover.png"),
Synopsis = "The Swindler's clone army attacks Objectville in a ruse to trap and kill the "
+ " Captain. Can the scientists of Objectville find a way to bring him back?" },
};
}
private static Dictionary<int, decimal> GetPrices()
{
return new Dictionary<int, decimal> {
{ 6, 3600M }, { 19, 500M }, { 36, 650M }, { 57, 13525M },
{ 68, 250M }, { 74, 75M }, { 83, 25.75M }, { 97, 35.25M },
};
}
private void LinqMakesQueriesEasy()
{
int[] values = new int[] { 0, 12, 44, 36, 92, 54, 13, 8 };
var result = from v in values
where v < 37
orderby v
select v;
foreach (int i in result)
CurrentQueryResults.Add(
new
{
Title = i.ToString(),
Image = CreateImageFromAssets("purple_250x250.jpg"),
}
);
}
private void ExpensiveComics()
{
IEnumerable<Comic> comics = BuildCatalog();
Dictionary<int, decimal> values = GetPrices();
var mostExpensive = from comic in comics
where values[comic.Issue] > 500
orderby values[comic.Issue] descending
select comic;
foreach (Comic comic in mostExpensive)
CurrentQueryResults.Add(
new
{
Title = String.Format("{0} is worth {1:c}",
comic.Name, values[comic.Issue]),
Image = CreateImageFromAssets("captain_amazing_250x250.jpg"),
}
);
}
private void LinqIsVersatile1()
{
string[] sandwiches = { "ham and cheese", "salami with mayo",
"turkey and swiss", "chicken cutlet" };
var sandwichesOnRye =
from sandwich in sandwiches
select sandwich + " on rye";
foreach (var sandwich in sandwichesOnRye)
CurrentQueryResults.Add(CreateAnonymousListViewItem(sandwich, "bluegray_250x250.jpg"));
}
private void LinqIsVersatile2()
{
Random random = new Random();
List<int> listOfNumbers = new List<int>();
int length = random.Next(50, 150);
for (int i = 0; i < length; i++)
listOfNumbers.Add(random.Next(100));
CurrentQueryResults.Add(CreateAnonymousListViewItem(
String.Format("There are {0} numbers", listOfNumbers.Count())));
CurrentQueryResults.Add(
CreateAnonymousListViewItem(String.Format("The smallest is {0}", listOfNumbers.Min())));
CurrentQueryResults.Add(
CreateAnonymousListViewItem(String.Format("The biggest is {0}", listOfNumbers.Max())));
CurrentQueryResults.Add(
CreateAnonymousListViewItem(String.Format("The sum is {0}", listOfNumbers.Sum())));
CurrentQueryResults.Add(CreateAnonymousListViewItem(
String.Format("The average is {0:F2}", listOfNumbers.Average())));
}
private void LinqIsVersatile3()
{
List<int> listOfNumbers = new List<int>();
for (int i = 1; i <= 10000; i++)
listOfNumbers.Add(i);
var under50sorted =
from number in listOfNumbers
where number < 50
orderby number descending
select number;
var firstFive = under50sorted.Take(6);
List<int> shortList = firstFive.ToList();
foreach (int n in shortList)
CurrentQueryResults.Add(CreateAnonymousListViewItem(n.ToString(), "bluegray_250x250.jpg"));
}
private object CreateAnonymousListViewItem(string title,
string imageFilename = "purple_250x250.jpg")
{
return new
{
Title = title,
Image = CreateImageFromAssets(imageFilename),
};
}
private void CombineJimmysValuesIntoGroups()
{
Dictionary<int, decimal> values = GetPrices();
var priceGroups =
from pair in values
group pair.Key by Purchase.EvaluatePrice(pair.Value)
into priceGroup
orderby priceGroup.Key descending
select priceGroup;
foreach (var group in priceGroups)
{
string message = String.Format("I found {0} {1} comics: issues ",
group.Count(), group.Key);
foreach (var issue in group)
message += issue.ToString() + " ";
CurrentQueryResults.Add(
CreateAnonymousListViewItem(message, "captain_amazing_250x250.jpg"));
}
}
private void JoinPurchasesWithPrices()
{
IEnumerable<Comic> comics = BuildCatalog();
Dictionary<int, decimal> values = GetPrices();
IEnumerable<Purchase> purchases = Purchase.FindPurchases();
var results =
from comic in comics
join purchase in purchases
on comic.Issue equals purchase.Issue
orderby comic.Issue ascending
select new
{
Comic = comic,
Price = purchase.Price,
Title = comic.Name,
Subtitle = "Issue #" + comic.Issue,
Description = String.Format("Bought for {0:c}", purchase.Price),
Image = CreateImageFromAssets("captain_amazing_250x250.jpg"),
};
decimal gregsListValue = 0;
decimal totalSpent = 0;
foreach (var result in results)
{
gregsListValue += values[result.Comic.Issue];
totalSpent += result.Price;
CurrentQueryResults.Add(result);
}
Title = String.Format("I spent {0:c} on comics worth {1:c}",
totalSpent, gregsListValue);
}
private void AllComics()
{
foreach (Comic comic in BuildCatalog())
{
var result = new
{
Image = CreateImageFromAssets("captain_amazing_zoom_250x250.jpg"),
Title = comic.Name,
Subtitle = "Issue #" + comic.Issue,
Description = "The Captain versus " + comic.MainVillain,
Comic = comic,
};
CurrentQueryResults.Add(result);
}
}
}
}
| 47.04908 | 121 | 0.529209 | [
"MIT"
] | JianGuoWan/third-edition | VS2012/Chapter_14/JimmysComics/JimmysComics/ComicQueryManager.cs | 15,344 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _03.Exact_Sum_of_Real_Numbers
{
class Program
{
static void Main(string[] args)
{
var n = int.Parse(Console.ReadLine());
var sum = 0m;
for (int i = 0; i < n; i++)
{
var number = decimal.Parse(Console.ReadLine());
sum += number;
}
Console.WriteLine(sum);
}
}
}
| 19 | 63 | 0.522556 | [
"MIT"
] | AneliaDoychinova/Programming-Fundamentals | 04. Data Types and Variables/Lab Data Types and Variables/03. Exact Sum of Real Numbers/03. Exact Sum of Real Numbers.cs | 534 | C# |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
using System;
using System.Collections.Generic;
using Aliyun.Acs.Core.Transform;
using Aliyun.Acs.aliyuncvc.Model.V20191030;
namespace Aliyun.Acs.aliyuncvc.Transform.V20191030
{
public class CreateMeetingInternationalResponseUnmarshaller
{
public static CreateMeetingInternationalResponse Unmarshall(UnmarshallerContext context)
{
CreateMeetingInternationalResponse createMeetingInternationalResponse = new CreateMeetingInternationalResponse();
createMeetingInternationalResponse.HttpResponse = context.HttpResponse;
createMeetingInternationalResponse.ErrorCode = context.IntegerValue("CreateMeetingInternational.ErrorCode");
createMeetingInternationalResponse.Message = context.StringValue("CreateMeetingInternational.Message");
createMeetingInternationalResponse.Success = context.BooleanValue("CreateMeetingInternational.Success");
createMeetingInternationalResponse.RequestId = context.StringValue("CreateMeetingInternational.RequestId");
CreateMeetingInternationalResponse.CreateMeetingInternational_MeetingInfo meetingInfo = new CreateMeetingInternationalResponse.CreateMeetingInternational_MeetingInfo();
meetingInfo.MeetingCode = context.StringValue("CreateMeetingInternational.MeetingInfo.MeetingCode");
meetingInfo.MeetingUUID = context.StringValue("CreateMeetingInternational.MeetingInfo.MeetingUUID");
createMeetingInternationalResponse.MeetingInfo = meetingInfo;
return createMeetingInternationalResponse;
}
}
}
| 48.520833 | 172 | 0.804208 | [
"Apache-2.0"
] | chys0404/aliyun-openapi-net-sdk | aliyun-net-sdk-aliyuncvc/Aliyuncvc/Transform/V20191030/CreateMeetingInternationalResponseUnmarshaller.cs | 2,329 | C# |
namespace ObjectSql.Core
{
public class EntityInsertionInformation
{
public int[] PropertiesIndexesToInsert { get; private set; }
public EntityInsertionInformation(int[] propertiesIndexesToInsert)
{
PropertiesIndexesToInsert = propertiesIndexesToInsert;
}
}
}
| 21.230769 | 68 | 0.782609 | [
"Apache-2.0"
] | andrew-bn/ObjectSql | src/ObjectSql/Core/EntityInsertionInformation.cs | 278 | C# |
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Xml.Serialization;
namespace StackExchange.Opserver.Data.SQL.QueryPlans
{
public partial class ShowPlanXML
{
[XmlIgnore]
public List<BaseStmtInfoType> Statements
{
get
{
if (BatchSequence == null) return new List<BaseStmtInfoType>();
return BatchSequence.SelectMany(bs =>
bs.SelectMany(b => b.Items?.SelectMany(bst => bst.Statements))
).ToList();
}
}
}
public partial class BaseStmtInfoType
{
public virtual IEnumerable<BaseStmtInfoType> Statements
{
get { yield return this; }
}
public bool IsMinor
{
get {
switch (StatementType)
{
case "COND":
case "RETURN NONE":
return true;
}
return false;
}
}
private const string declareFormat = "Declare {0} {1} = {2};";
private static readonly Regex emptyLineRegex = new Regex(@"^\s+$[\r\n]*", RegexOptions.Compiled | RegexOptions.Multiline);
private static readonly Regex initParamsTrimRegex = new Regex(@"^\s*(begin|end)\s*", RegexOptions.Compiled | RegexOptions.IgnoreCase);
private static readonly Regex paramRegex = new Regex(@"^\(( [^\(\)]* ( ( (?<Open>\() [^\(\)]* )+ ( (?<Close-Open>\)) [^\(\)]* )+ )* (?(Open)(?!)) )\)", RegexOptions.Compiled | RegexOptions.IgnorePatternWhitespace);
private static readonly Regex paramSplitRegex = new Regex(@",(?=[@])", RegexOptions.Compiled | RegexOptions.IgnorePatternWhitespace);
public string ParameterDeclareStatement
{
get
{
//TODO: Cross-statement vars declared in an assign, used later
return this is StmtSimpleType ss ? GetDeclareStatement(ss.QueryPlan) : "";
}
}
public string StatementTextWithoutInitialParams
{
get
{
//TODO: Pair these down, seeing what looks good for now
return this is StmtSimpleType ss ? emptyLineRegex.Replace(paramRegex.Replace(ss.StatementText ?? "", ""), "").Trim() : "";
}
}
public string StatementTextWithoutInitialParamsTrimmed
{
get
{
var orig = StatementTextWithoutInitialParams;
return orig?.Length == 0 ? string.Empty : initParamsTrimRegex.Replace(orig, string.Empty).Trim();
}
}
private string GetDeclareStatement(QueryPlanType queryPlan)
{
if (queryPlan?.ParameterList == null || queryPlan.ParameterList.Length == 0) return "";
var result = StringBuilderCache.Get();
var paramTypeList = paramRegex.Match(StatementText);
if (!paramTypeList.Success) return "";
// TODO: get test cases and move this to a single multi-match regex
var paramTypes = paramSplitRegex.Split(paramTypeList.Groups[1].Value).Select(p => p.Split(StringSplits.Space));
foreach (var p in queryPlan.ParameterList)
{
var paramType = paramTypes.FirstOrDefault(pt => pt[0] == p.Column);
if (paramType != null)
{
result.AppendFormat(declareFormat, p.Column, paramType[1], p.ParameterCompiledValue)
.AppendLine();
}
}
return result.Length > 0 ? result.Insert(0, "-- Compiled Params\n").ToStringRecycle() : result.ToStringRecycle();
}
}
public partial class StmtCondType
{
public override IEnumerable<BaseStmtInfoType> Statements
{
get
{
yield return this;
if (Then?.Statements != null)
{
foreach (var s in Then.Statements.Items) yield return s;
}
if (Else?.Statements != null)
{
foreach (var s in Else.Statements.Items) yield return s;
}
}
}
}
}
| 36.694915 | 222 | 0.539723 | [
"MIT"
] | KennethScott/Opserver | Opserver.Core/Data/SQL/QueryPlans/ShowPlanXML.cs | 4,332 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the backup-2018-11-15.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.Backup.Model
{
/// <summary>
/// Container for the parameters to the DescribeRegionSettings operation.
/// Returns the current service opt-in settings for the region. If the service has a value
/// set to true, AWS Backup will attempt to protect that service's resources in this region,
/// when included in an on-demand backup or scheduled backup plan. If the value is set
/// to false for a service, AWS Backup will not attempt to protect that service's resources
/// in this region.
/// </summary>
public partial class DescribeRegionSettingsRequest : AmazonBackupRequest
{
}
} | 36.02381 | 104 | 0.730998 | [
"Apache-2.0"
] | NGL321/aws-sdk-net | sdk/src/Services/Backup/Generated/Model/DescribeRegionSettingsRequest.cs | 1,513 | C# |
using ToDoList.ViewModel;
using ToDoListApp3;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
namespace ToDoList
{
public sealed partial class Login : Page
{
public Login()
{
this.InitializeComponent();
DataContext = MainViewModel.Singleton();
getViewModel().loadLocalSettings();
RESTManager restManager = new RESTManager();
restManager.getTasks(MainViewModel.OwnerId, getViewModel());
}
private MainViewModel getViewModel()
{
return DataContext as MainViewModel;
}
private void Task_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (ToDoListBox.SelectedItem == null)
{
return;
}
else
{
getViewModel().CurrentTask = (ToDoTask)ToDoListBox.SelectedItem;
Window.Current.Content = new DetailsPage();
}
}
private void AddTask_Click(object sender, RoutedEventArgs e)
{
Window.Current.Content = new AddTask();
}
private void Refresh_Click(object sender, RoutedEventArgs e)
{
Window.Current.Content = new Login();
}
private void Logout_Click(object sender, RoutedEventArgs e)
{
getViewModel().removeLocalSettings();
DataContext = null;
Window.Current.Content = new MainPage();
}
}
}
| 26.596491 | 86 | 0.5719 | [
"MIT"
] | joannawetesko/to-do-list | ToDoListApp/View/ListPage.xaml.cs | 1,518 | C# |
using Panuon.UI.Silver.Core;
using Panuon.UI.Silver.Internal.Controls;
using Panuon.UI.Silver.Internal.Converters;
using Panuon.UI.Silver.Internal.Utils;
using System;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Media;
namespace Panuon.UI.Silver
{
public class CalendarX : Control
{
#region Fields
private CalendarXDayPresenter _dayPresenter;
private CalendarXMonthPresenter _monthPresenter;
private CalendarXYearPresenter _yearPresenter;
private CalendarXWeekPresenter _weekPresenter;
private RepeatButton _backwardButton;
private RepeatButton _previousButton;
private RepeatButton _nextButton;
private RepeatButton _forwardButton;
private Button _yearButton;
private Button _monthButton;
private bool _isInternalSet;
#endregion
#region Ctor
static CalendarX()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(CalendarX), new FrameworkPropertyMetadata(typeof(CalendarX)));
}
#endregion
#region Events
public event SelectedDatesChangedRoutedEventHandler SelectedDatesChanged
{
add { AddHandler(SelectedDatesChangedEvent, value); }
remove { RemoveHandler(SelectedDatesChangedEvent, value); }
}
public static readonly RoutedEvent SelectedDatesChangedEvent =
EventManager.RegisterRoutedEvent("SelectedDatesChanged", RoutingStrategy.Bubble, typeof(SelectedDatesChangedRoutedEventHandler), typeof(CalendarX));
public event SelectedDateChangedRoutedEventHandler SelectedDateChanged
{
add { AddHandler(SelectedDateChangedEvent, value); }
remove { RemoveHandler(SelectedDateChangedEvent, value); }
}
public static readonly RoutedEvent SelectedDateChangedEvent =
EventManager.RegisterRoutedEvent("SelectedDateChanged", RoutingStrategy.Bubble, typeof(SelectedDateChangedRoutedEventHandler), typeof(CalendarX));
#endregion
#region Overrides
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
_backwardButton = Template?.FindName("PART_BackwardButton", this) as RepeatButton;
_backwardButton.Click += BackwardButton_Click;
_previousButton = Template?.FindName("PART_PreviousButton", this) as RepeatButton;
_previousButton.Click += PreviousButton_Click;
_nextButton = Template?.FindName("PART_NextButton", this) as RepeatButton;
_nextButton.Click += NextButton_Click;
_forwardButton = Template?.FindName("PART_ForwardButton", this) as RepeatButton;
_forwardButton.Click += ForwardButton_Click;
_yearButton = Template?.FindName("PART_YearButton", this) as Button;
BindingUtils.BindingProperty(_yearButton, Button.ContentProperty, this, CurrentYearProperty, "D4");
_yearButton.Click += YearButton_Click;
_monthButton = Template?.FindName("PART_MonthButton", this) as Button;
BindingUtils.BindingProperty(_monthButton, Button.ContentProperty, this, CurrentMonthProperty, new LocalizedMonthStringConverter());
_monthButton.Click += MonthButton_Click;
_weekPresenter = Template?.FindName("PART_WeekPresenter", this) as CalendarXWeekPresenter;
BindingUtils.BindingProperty(_weekPresenter, CalendarXWeekPresenter.FirstDayOfWeekProperty, this, FirstDayOfWeekProperty);
_dayPresenter = Template?.FindName("PART_DayPresenter", this) as CalendarXDayPresenter;
BindingUtils.BindingProperty(_dayPresenter, CalendarXDayPresenter.ItemContainerStyleProperty, this, CalendarXItemStyleProperty);
_monthPresenter = Template?.FindName("PART_MonthPresenter", this) as CalendarXMonthPresenter;
BindingUtils.BindingProperty(_monthPresenter, CalendarXMonthPresenter.ItemContainerStyleProperty, this, CalendarXItemStyleProperty);
_yearPresenter = Template?.FindName("PART_YearPresenter", this) as CalendarXYearPresenter;
BindingUtils.BindingProperty(_yearPresenter, CalendarXYearPresenter.ItemContainerStyleProperty, this, CalendarXItemStyleProperty);
_dayPresenter.Selected += DayPresenter_Selected;
_dayPresenter.Unselected += DayPresenter_Unselected;
_monthPresenter.Selected += MonthPresenter_Selected;
_monthPresenter.Unselected += MonthPresenter_Unselected;
_yearPresenter.Selected += YearPresenter_Selected;
_yearPresenter.Unselected += YearPresenter_Unselected;
_weekPresenter.UpdateWeeks();
var dayDate = SelectedDate ?? DateTime.Now.Date;
UpdateDays(dayDate.Year, dayDate.Month);
UpdateMonths(dayDate.Year, dayDate.Month);
UpdateYears(dayDate.Year, dayDate.Month);
}
#endregion
#region Properties
#region HeaderHeight
public double HeaderHeight
{
get { return (double)GetValue(HeaderHeightProperty); }
set { SetValue(HeaderHeightProperty, value); }
}
public static readonly DependencyProperty HeaderHeightProperty =
DependencyProperty.Register("HeaderHeight", typeof(double), typeof(CalendarX));
#endregion
#region HeaderBackground
public Brush HeaderBackground
{
get { return (Brush)GetValue(HeaderBackgroundProperty); }
set { SetValue(HeaderBackgroundProperty, value); }
}
public static readonly DependencyProperty HeaderBackgroundProperty =
DependencyProperty.Register("HeaderBackground", typeof(Brush), typeof(CalendarX));
#endregion
#region ForwardButtonStyle
public Style ForwardButtonStyle
{
get { return (Style)GetValue(ForwardButtonStyleProperty); }
set { SetValue(ForwardButtonStyleProperty, value); }
}
public static readonly DependencyProperty ForwardButtonStyleProperty =
DependencyProperty.Register("ForwardButtonStyle", typeof(Style), typeof(CalendarX));
#endregion
#region PreviousButtonStyle
public Style PreviousButtonStyle
{
get { return (Style)GetValue(PreviousButtonStyleProperty); }
set { SetValue(PreviousButtonStyleProperty, value); }
}
public static readonly DependencyProperty PreviousButtonStyleProperty =
DependencyProperty.Register("PreviousButtonStyle", typeof(Style), typeof(CalendarX));
#endregion
#region NextButtonStyle
public Style NextButtonStyle
{
get { return (Style)GetValue(NextButtonStyleProperty); }
set { SetValue(NextButtonStyleProperty, value); }
}
public static readonly DependencyProperty NextButtonStyleProperty =
DependencyProperty.Register("NextButtonStyle", typeof(Style), typeof(CalendarX));
#endregion
#region YearButtonStyle
public Style YearButtonStyle
{
get { return (Style)GetValue(YearButtonStyleProperty); }
set { SetValue(YearButtonStyleProperty, value); }
}
public static readonly DependencyProperty YearButtonStyleProperty =
DependencyProperty.Register("YearButtonStyle", typeof(Style), typeof(CalendarX));
#endregion
#region MonthButtonStyle
public Style MonthButtonStyle
{
get { return (Style)GetValue(MonthButtonStyleProperty); }
set { SetValue(MonthButtonStyleProperty, value); }
}
public static readonly DependencyProperty MonthButtonStyleProperty =
DependencyProperty.Register("MonthButtonStyle", typeof(Style), typeof(CalendarX));
#endregion
#region CalendarXItemStyle
public Style CalendarXItemStyle
{
get { return (Style)GetValue(CalendarXItemStyleProperty); }
set { SetValue(CalendarXItemStyleProperty, value); }
}
public static readonly DependencyProperty CalendarXItemStyleProperty =
DependencyProperty.Register("CalendarXItemStyle", typeof(Style), typeof(CalendarX));
#endregion
#region BackwardButtonStyle
public Style BackwardButtonStyle
{
get { return (Style)GetValue(BackwardButtonStyleProperty); }
set { SetValue(BackwardButtonStyleProperty, value); }
}
public static readonly DependencyProperty BackwardButtonStyleProperty =
DependencyProperty.Register("BackwardButtonStyle", typeof(Style), typeof(CalendarX));
#endregion
#region IsTodayHighlighted
public bool IsTodayHighlighted
{
get { return (bool)GetValue(IsTodayHighlightedProperty); }
set { SetValue(IsTodayHighlightedProperty, value); }
}
public static readonly DependencyProperty IsTodayHighlightedProperty =
DependencyProperty.Register("IsTodayHighlighted", typeof(bool), typeof(CalendarX));
#endregion
#region Mode
public CalendarXMode Mode
{
get { return (CalendarXMode)GetValue(ModeProperty); }
set { SetValue(ModeProperty, value); }
}
public static readonly DependencyProperty ModeProperty =
DependencyProperty.Register("Mode", typeof(CalendarXMode), typeof(CalendarX));
#endregion
#region FirstDayOfWeek
public DayOfWeek FirstDayOfWeek
{
get { return (DayOfWeek)GetValue(FirstDayOfWeekProperty); }
set { SetValue(FirstDayOfWeekProperty, value); }
}
public static readonly DependencyProperty FirstDayOfWeekProperty =
DependencyProperty.Register("FirstDayOfWeek", typeof(DayOfWeek), typeof(CalendarX));
#endregion
#region MaxDate
public DateTime? MaxDate
{
get { return (DateTime?)GetValue(MaxDateProperty); }
set { SetValue(MaxDateProperty, value); }
}
public static readonly DependencyProperty MaxDateProperty =
DependencyProperty.Register("MaxDate", typeof(DateTime?), typeof(CalendarX), new PropertyMetadata(OnMaxDateChanged));
#endregion
#region MinDate
public DateTime? MinDate
{
get { return (DateTime?)GetValue(MinDateProperty); }
set { SetValue(MinDateProperty, value); }
}
public static readonly DependencyProperty MinDateProperty =
DependencyProperty.Register("MinDate", typeof(DateTime?), typeof(CalendarX), new PropertyMetadata(OnMinDateChanged));
#endregion
#region SelectedDate
public DateTime? SelectedDate
{
get { return (DateTime?)GetValue(SelectedDateProperty); }
set { SetValue(SelectedDateProperty, value); }
}
public static readonly DependencyProperty SelectedDateProperty =
DependencyProperty.Register("SelectedDate", typeof(DateTime?), typeof(CalendarX), new PropertyMetadata(null, OnSelectedDateChanged));
#endregion
#region SelectedDates
public ObservableCollection<DateTime> SelectedDates
{
get { return (ObservableCollection<DateTime>)GetValue(SelectedDatesProperty); }
set { SetValue(SelectedDatesProperty, value); }
}
public static readonly DependencyProperty SelectedDatesProperty =
DependencyProperty.Register("SelectedDates", typeof(ObservableCollection<DateTime>), typeof(CalendarX), new PropertyMetadata(OnSelectedDatesChanged));
#endregion
#endregion
#region Internal Properties
#region CurrentYear
internal int CurrentYear
{
get { return (int)GetValue(CurrentYearProperty); }
set { SetValue(CurrentYearProperty, value); }
}
internal static readonly DependencyProperty CurrentYearProperty =
DependencyProperty.Register("CurrentYear", typeof(int), typeof(CalendarX));
#endregion
#region CurrentMonth
internal int CurrentMonth
{
get { return (int)GetValue(CurrentMonthProperty); }
set { SetValue(CurrentMonthProperty, value); }
}
internal static readonly DependencyProperty CurrentMonthProperty =
DependencyProperty.Register("CurrentMonth", typeof(int), typeof(CalendarX), new PropertyMetadata(1));
#endregion
#region CurrentPanel
internal int CurrentPanel
{
get { return (int)GetValue(CurrentPanelProperty); }
set { SetValue(CurrentPanelProperty, value); }
}
internal static readonly DependencyProperty CurrentPanelProperty =
DependencyProperty.Register("CurrentPanel", typeof(int), typeof(CalendarX));
#endregion
#endregion
#region Methods
#endregion
#region Event Handlers
private static void OnMaxDateChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var calendar = d as CalendarX;
calendar.OnDateLimitChanged();
}
private static void OnMinDateChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var calendar = d as CalendarX;
calendar.OnDateLimitChanged();
}
private void MonthButton_Click(object sender, RoutedEventArgs e)
{
switch (Mode)
{
case CalendarXMode.Date:
case CalendarXMode.DateRange:
case CalendarXMode.MultipleDate:
case CalendarXMode.YearMonth:
CurrentPanel = 1;
break;
}
}
private void YearButton_Click(object sender, RoutedEventArgs e)
{
switch (Mode)
{
default:
CurrentPanel = 2;
break;
}
}
private void NextButton_Click(object sender, RoutedEventArgs e)
{
try
{
var date = new DateTime(CurrentYear, CurrentMonth, 1);
switch (CurrentPanel)
{
case 0:
date = date.AddMonths(1);
break;
case 1:
date = date.AddYears(1);
break;
case 2:
date = date.AddYears(7);
break;
default:
return;
}
UpdateDays(date.Year, date.Month);
UpdateMonths(date.Year, date.Month);
UpdateYears(date.Year, date.Month);
}
catch
{
}
}
private void BackwardButton_Click(object sender, RoutedEventArgs e)
{
try
{
var date = new DateTime(CurrentYear, CurrentMonth, 1);
switch (CurrentPanel)
{
case 0:
date = date.AddYears(-1);
break;
default:
return;
}
UpdateDays(date.Year, date.Month);
UpdateMonths(date.Year, date.Month);
UpdateYears(date.Year, date.Month);
}
catch
{
}
}
private void PreviousButton_Click(object sender, RoutedEventArgs e)
{
try
{
var date = new DateTime(CurrentYear, CurrentMonth, 1);
switch (CurrentPanel)
{
case 0:
date = date.AddMonths(-1);
break;
case 1:
date = date.AddYears(-1);
break;
case 2:
date = date.AddYears(-7);
break;
default:
return;
}
UpdateDays(date.Year, date.Month);
UpdateMonths(date.Year, date.Month);
UpdateYears(date.Year, date.Month);
}
catch
{
}
}
private void ForwardButton_Click(object sender, RoutedEventArgs e)
{
try
{
var date = new DateTime(CurrentYear, CurrentMonth, 1);
switch (CurrentPanel)
{
case 0:
date = date.AddYears(1);
break;
default:
return;
}
UpdateDays(date.Year, date.Month);
UpdateMonths(date.Year, date.Month);
UpdateYears(date.Year, date.Month);
}
catch
{
}
}
private static void OnSelectedDateChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var calendar = d as CalendarX;
if (calendar == null)
{
return;
}
calendar.OnSelectedDateChanged();
}
private static void OnSelectedDatesChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var calendar = d as CalendarX;
if (calendar == null)
{
return;
}
if (e.OldValue != null)
{
(e.OldValue as ObservableCollection<DateTime>).CollectionChanged -= calendar.CalendarX_CollectionChanged;
}
if (e.NewValue != null)
{
(e.NewValue as ObservableCollection<DateTime>).CollectionChanged -= calendar.CalendarX_CollectionChanged;
(e.NewValue as ObservableCollection<DateTime>).CollectionChanged += calendar.CalendarX_CollectionChanged;
calendar.OnSelectedDatesChanged();
}
calendar.RaiseSelectedDatesChanged();
}
private void CalendarX_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
OnSelectedDatesChanged();
}
private void DayPresenter_Unselected(object sender, SelectedDateChangedEventArgs e)
{
var dateTime = (DateTime)e.SelectedDate;
_isInternalSet = true;
if (SelectedDates == null)
{
SelectedDates = new ObservableCollection<DateTime>();
}
switch (Mode)
{
case CalendarXMode.Date:
break;
case CalendarXMode.DateRange:
SelectedDate = null;
break;
case CalendarXMode.MultipleDate:
if (SelectedDates.Contains(dateTime))
{
SelectedDates.Remove(dateTime);
}
SelectedDate = null;
break;
}
UpdateDays(CurrentYear, CurrentMonth);
UpdateYears(CurrentYear, CurrentMonth);
UpdateMonths(CurrentYear, CurrentMonth);
_isInternalSet = false;
}
private void DayPresenter_Selected(object sender, SelectedDateChangedEventArgs e)
{
var dateTime = (DateTime)e.SelectedDate;
_isInternalSet = true;
if (SelectedDates == null)
{
SelectedDates = new ObservableCollection<DateTime>();
}
switch (Mode)
{
case CalendarXMode.MultipleDate:
if (!SelectedDates.Any(x => x.Date.Equals(dateTime)))
{
SelectedDates.Add(dateTime);
}
break;
case CalendarXMode.Date:
SelectedDates.Clear();
SelectedDates.Add(dateTime);
break;
case CalendarXMode.DateRange:
for (int i = 0; i < SelectedDates.Count - 1; i++)
{
SelectedDates.RemoveAt(0);
}
SelectedDates.Add(dateTime);
break;
}
SelectedDate = dateTime;
UpdateDays(dateTime.Year, dateTime.Month);
_isInternalSet = false;
}
private void MonthPresenter_Unselected(object sender, SelectedDateChangedEventArgs e)
{
var dateTime = (DateTime)e.SelectedDate;
switch (Mode)
{
case CalendarXMode.Date:
case CalendarXMode.DateRange:
case CalendarXMode.MultipleDate:
CurrentPanel = 0;
break;
}
UpdateMonths(CurrentYear, CurrentMonth);
UpdateDays(CurrentYear, CurrentMonth);
}
private void MonthPresenter_Selected(object sender, SelectedDateChangedEventArgs e)
{
var dateTime = (DateTime)e.SelectedDate;
_isInternalSet = true;
if (SelectedDates == null)
{
SelectedDates = new ObservableCollection<DateTime>();
}
switch (Mode)
{
case CalendarXMode.Date:
case CalendarXMode.DateRange:
case CalendarXMode.MultipleDate:
CurrentPanel = 0;
break;
case CalendarXMode.YearMonth:
SelectedDate = dateTime;
SelectedDates.Clear();
SelectedDates.Add(dateTime);
break;
}
UpdateYears(dateTime.Year, dateTime.Month);
UpdateMonths(dateTime.Year, dateTime.Month);
UpdateDays(dateTime.Year, dateTime.Month);
_isInternalSet = false;
}
private void YearPresenter_Unselected(object sender, SelectedDateChangedEventArgs e)
{
var dateTime = (DateTime)e.SelectedDate;
switch (Mode)
{
case CalendarXMode.Date:
case CalendarXMode.DateRange:
case CalendarXMode.MultipleDate:
case CalendarXMode.YearMonth:
CurrentPanel = 1;
break;
}
UpdateYears(CurrentYear, CurrentMonth);
UpdateMonths(CurrentYear, CurrentMonth);
UpdateDays(CurrentYear, CurrentMonth);
}
private void YearPresenter_Selected(object sender, SelectedDateChangedEventArgs e)
{
var dateTime = (DateTime)e.SelectedDate;
_isInternalSet = true;
if (SelectedDates == null)
{
SelectedDates = new ObservableCollection<DateTime>();
}
switch (Mode)
{
case CalendarXMode.Date:
case CalendarXMode.DateRange:
case CalendarXMode.MultipleDate:
case CalendarXMode.YearMonth:
CurrentPanel = 1;
break;
case CalendarXMode.Year:
SelectedDate = dateTime;
SelectedDates.Clear();
SelectedDates.Add(dateTime);
break;
}
UpdateYears(dateTime.Year, dateTime.Month);
UpdateMonths(dateTime.Year, dateTime.Month);
UpdateDays(dateTime.Year, dateTime.Month);
_isInternalSet = false;
}
#endregion
#region Functions
private void OnSelectedDatesChanged()
{
if (_dayPresenter == null)
{
return;
}
if (!_isInternalSet)
{
UpdateDays(CurrentYear, CurrentMonth);
UpdateMonths(CurrentYear, CurrentMonth);
UpdateYears(CurrentYear, CurrentMonth);
}
RaiseSelectedDatesChanged();
}
private void OnSelectedDateChanged()
{
if (_dayPresenter == null)
{
return;
}
if (!_isInternalSet)
{
if (SelectedDates == null)
{
SelectedDates = new ObservableCollection<DateTime>();
}
if (SelectedDate != null && !SelectedDates.Contains((DateTime)SelectedDate))
{
_isInternalSet = true;
SelectedDates.Add((DateTime)SelectedDate);
_isInternalSet = false;
}
var date = SelectedDate ?? new DateTime(CurrentYear, CurrentMonth, 1);
UpdateDays(date.Year, date.Month);
UpdateMonths(date.Year, date.Month);
UpdateYears(date.Year, date.Month);
}
RaiseSelectedDateChanged();
}
private void UpdateDays(int year, int month)
{
if (_dayPresenter == null)
{
return;
}
CurrentYear = year;
CurrentMonth = month;
BindingUtils.BindingProperty(_dayPresenter, CalendarXDayPresenter.ModeProperty, this, ModeProperty);
BindingUtils.BindingProperty(_dayPresenter, CalendarXDayPresenter.FirstDayOfWeekProperty, this, FirstDayOfWeekProperty);
BindingUtils.BindingProperty(_dayPresenter, CalendarXDayPresenter.MinDateProperty, this, MinDateProperty);
BindingUtils.BindingProperty(_dayPresenter, CalendarXDayPresenter.MaxDateProperty, this, MaxDateProperty);
BindingUtils.BindingProperty(_dayPresenter, CalendarXDayPresenter.IsTodayHighlightedProperty, this, IsTodayHighlightedProperty);
_dayPresenter.Mode = Mode;
_dayPresenter.FirstDayOfWeek = FirstDayOfWeek;
_dayPresenter.MinDate = MinDate;
_dayPresenter.MaxDate = MaxDate;
_dayPresenter.IsTodayHighlighted = IsTodayHighlighted;
try
{
var date = new DateTime(CurrentYear, CurrentMonth, 1);
_dayPresenter.Update(date.Year, date.Month, SelectedDates);
}
catch
{
}
}
private void UpdateMonths(int year, int month)
{
if (_monthPresenter == null)
{
return;
}
CurrentYear = year;
CurrentMonth = month;
_monthPresenter.FirstDayOfWeek = FirstDayOfWeek;
_monthPresenter.MinDate = MinDate;
_monthPresenter.MaxDate = MaxDate;
try
{
var date = new DateTime(CurrentYear, CurrentMonth, 1);
_monthPresenter.Update(date.Year, date.Month);
}
catch
{
}
}
private void UpdateYears(int year, int month)
{
if (_monthPresenter == null)
{
return;
}
CurrentYear = year;
CurrentMonth = month;
_yearPresenter.FirstDayOfWeek = FirstDayOfWeek;
_yearPresenter.MinDate = MinDate;
_yearPresenter.MaxDate = MaxDate;
try
{
var date = new DateTime(CurrentYear, CurrentMonth, 1);
_yearPresenter.Update(date.Year, date.Month);
}
catch
{
}
}
private void OnDateLimitChanged()
{
_isInternalSet = true;
if (SelectedDates == null)
{
SelectedDates = new ObservableCollection<DateTime>();
}
if (SelectedDate != null && MinDate != null && SelectedDate < MinDate)
{
var date = (DateTime)SelectedDate;
if (SelectedDates.Contains(date))
{
SelectedDates.Remove(date);
}
SelectedDate = MinDate;
SelectedDates.Add((DateTime)SelectedDate);
}
else if(SelectedDate != null && MaxDate != null && SelectedDate > MaxDate)
{
var date = (DateTime)SelectedDate;
if (SelectedDates.Contains(date))
{
SelectedDates.Remove(date);
}
SelectedDate = MaxDate;
SelectedDates.Add((DateTime)SelectedDate);
}
if (SelectedDates != null)
{
for (int i = SelectedDates.Count - 1; i >= 0; i--)
{
var date = SelectedDates[i];
if (date < MinDate || date > MaxDate)
{
SelectedDates.RemoveAt(i);
}
}
}
UpdateDays(CurrentYear, CurrentMonth);
UpdateMonths(CurrentYear, CurrentMonth);
UpdateYears(CurrentYear, CurrentMonth);
}
private void RaiseSelectedDatesChanged()
{
RaiseEvent(new SelectedDatesChangedRoutedEventArgs(SelectedDatesChangedEvent, SelectedDates));
}
private void RaiseSelectedDateChanged()
{
RaiseEvent(new SelectedDateChangedRoutedEventArgs(SelectedDateChangedEvent, SelectedDate));
}
#endregion
}
}
| 35.63432 | 162 | 0.570091 | [
"MIT"
] | sillsun/PanuonUI.Silver | SharedResources/Panuon.UI.Silver/Controls/CalendarX.cs | 30,113 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace mostdev_hungergames.model.impl
{
class BattleAxe : BattleItem
{
public BattleAxe()
{
this.Name = "Battle Axe";
this.AttackBonus = 10;
}
}
}
| 14.625 | 40 | 0.705128 | [
"MIT"
] | TomL-dev/mostdev-hungergames | mostdev-hungergames/model/impl/BattleAxe.cs | 236 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Telerik.Sitefinity.Newsletters.SendGrid.Services.Dto
{
/// <summary>
/// A static class containing the SendGrid event type names.
/// </summary>
public static class SendGridEventTypes
{
/// <summary>
/// Bounce event type name.
/// </summary>
public static readonly string Bounce = "Bounce";
/// <summary>
/// Dropped event type name.
/// </summary>
public static readonly string Dropped = "Dropped";
//// TODO: fill in the other event types according to
//// https://sendgrid.com/docs/API_Reference/Webhooks/event.html
}
}
| 27.107143 | 72 | 0.633729 | [
"Apache-2.0"
] | Sitefinity/NewslettersSendGrid | Telerik.Sitefinity.Newsletters.SendGrid/Services/Dto/SendGridEventTypes.cs | 761 | C# |
using System.ComponentModel.DataAnnotations;
namespace TavssStudent.Models
{
public class SuperVisor
{
[Required]
public string Name { get; set; }
}
} | 15.25 | 44 | 0.644809 | [
"MIT"
] | AhmedKhalil777/Tasvss.Students.Blazor | TavssStudent/TavssStudent/Models/CourseModels/SuperVisor.cs | 185 | C# |
using System;
using System.Data.SQLite;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;
using Newtonsoft.Json.Linq;
using System.Linq;
namespace Discord_Point_Bot
{
public class SQLite
{
private static SQLite instance = null;
private SQLiteConnection connection;
public static SQLite Instance()
{
if (instance == null)
instance = new SQLite();
return instance;
}
public static void Free()
{
if (instance != null)
instance.Close();
}
SQLite()
{
try
{
connection = new SQLiteConnection("Data Source=local.db");
connection.Open();
Console.WriteLine("SQLite is connected");
TabaleInit();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
private void Close()
{
connection.Close();
Console.WriteLine("SQLite is disconnected");
}
private void TabaleInit()
{
SQLiteCommand command = new SQLiteCommand(
"CREATE TABLE IF NOT EXISTS User (user TEXT, donate TEXT, attendance TEXT, point INTEGER)"
, connection
);
command.ExecuteNonQuery();
command = new SQLiteCommand(
"CREATE TABLE IF NOT EXISTS Bet (title TEXT, date TEXT, event TEXT)"
, connection
);
command.ExecuteNonQuery();
}
/*
* Manage SQL Table 'User'
*
*/
public void UserTableInsert(string id, string attendance, int point)
{
Console.WriteLine($"new row in User {id}");
SQLiteCommand command = new SQLiteCommand(
$"INSERT INTO User (user, donate, attendance, point) values ('{id}', '', '{attendance}', {point})",
connection
);
command.ExecuteNonQuery();
}
public void UserUpdate(string id, string donate = null, string attendance = null, int point = -1)
{
string target = "";
if (donate != null)
target = $"donate='{donate}'";
else if (attendance != null)
target = $"attendance='{attendance}'";
else if (point != -1)
target = $"point={point}";
SQLiteCommand command = new SQLiteCommand(
$"UPDATE User SET {target} WHERE user={id}",
connection
);
command.ExecuteNonQuery();
}
public User GetUser(string id)
{
Console.WriteLine($"get User {id}");
User result = new User();
SQLiteCommand cmd = new SQLiteCommand(
$"SELECT * FROM User WHERE user='{id}'",
connection
);
SQLiteDataReader reader = cmd.ExecuteReader();
if (!reader.HasRows)
{
UserTableInsert(id, "null", 0);
result.Donate = "";
result.Attendance = "null";
result.Point = 0;
return result;
}
while (reader.Read())
{
result.Donate = reader["donate"].ToString();
result.Attendance = reader["attendance"].ToString();
result.Point = int.Parse(reader["point"].ToString());
}
reader.Close();
return result;
}
/*
* Manage SQL Table Bet
*
*/
public void BetTableInsert(string title, string data)
{
Console.WriteLine($"new row in Bet {title}");
SQLiteCommand command = new SQLiteCommand(
$"INSERT INTO Bet (title, date, event) values ('{title}', '{DateTime.Now:MMddyyyyHHmmss}', '{data}')",
connection
);
command.ExecuteNonQuery();
}
public List<Event> GetBetList()
{
List<Event> events = new List<Event>();
Event block;
JObject json;
Form form;
SQLiteCommand cmd = new SQLiteCommand(
$"SELECT * FROM Bet",
connection
);
SQLiteDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
block = new Event();
json = JObject.Parse(reader["event"].ToString());
block.title = json["title"].ToString();
block.author = json["author"].ToString();
block.date = json["date"].ToString();
foreach (JToken token in json["events"].Children())
{
form = new Form();
form.form = token["form"].ToString();
block.forms.Add(form);
foreach (JToken u in token["users"].Children())
form.users.Add(u.ToObject<BetUser>());
}
events.Add(block);
}
reader.Close();
return events;
}
public void BetUpdate(string date, string data)
{
SQLiteCommand command = new SQLiteCommand(
$"UPDATE Bet SET event='{data}' WHERE date='{date}'",
connection
);
command.ExecuteNonQuery();
}
public void BetDelete(string date)
{
SQLiteCommand command = new SQLiteCommand(
$"DELETE From Bet WHERE date='{date}'",
connection
);
command.ExecuteNonQuery();
}
}
}
| 30.968421 | 118 | 0.473148 | [
"MIT"
] | Yechan0815/Discord-Point-Bot | Discord-Point-Bot/SQLite.cs | 5,886 | C# |
using System;
using System.Drawing;
using System.Collections.Generic;
using System.Linq;
namespace PixelPalette.Algorithm {
public static class ColorHelpers {
public static float GetDistance(Color a, Color b) {
return MathF.Sqrt(MathF.Pow(a.R-b.R, 2)+MathF.Pow(a.G-b.G, 2)+MathF.Pow(a.B-b.B, 2));
}
public static float GetDistance((int R, int G, int B) a, Color b) {
return MathF.Sqrt(MathF.Pow(a.R-b.R, 2)+MathF.Pow(a.G-b.G, 2)+MathF.Pow(a.B-b.B, 2));
}
public static float GetDistance(Color a, (int R, int G, int B) b) {
return GetDistance(b, a);
}
public static int GetMinDistanceIndex(Color color, Color[] colorPalette) {
int minDistance = int.MaxValue;
int minDistanceId = -1;
for (int i = 0; i < colorPalette.Length; i++) {
int distance = (int) ColorHelpers.GetDistance(colorPalette[i], color);
if (distance < minDistance) {
minDistance = distance;
minDistanceId = i;
}
}
return minDistanceId;
}
public static int GetMinDistanceIndex((int R, int G, int B) color, Color[] colorPalette) {
int minDistance = int.MaxValue;
int minDistanceId = -1;
for (int i = 0; i < colorPalette.Length; i++) {
int distance = (int) ColorHelpers.GetDistance(colorPalette[i], color);
if (distance < minDistance) {
minDistance = distance;
minDistanceId = i;
}
}
return minDistanceId;
}
public static Color GetMinDistance(Color color, Color[] colorPalette) {
return colorPalette[GetMinDistanceIndex(color, colorPalette)];
}
public static Color GetMinDistance((int R, int G, int B) color, Color[] colorPalette) {
return colorPalette[GetMinDistanceIndex(color, colorPalette)];
}
public static Color AverageColors(Color a, Color b) {
return Color.FromArgb(((int) a.R+b.R)/2, ((int) a.G+b.G)/2, ((int) a.B+b.B)/2);
}
public static Color AverageColors(List<Color> colors) {
int r = 0;
int g = 0;
int b = 0;
foreach (var color in colors) {
r += color.R;
g += color.G;
b += color.B;
}
return Color.FromArgb(r/colors.Count, g/colors.Count, b/colors.Count);
}
public static double CalculateAverageError(Bitmap a, Bitmap b) {
Color[] aColors = BitmapConvert.ColorArrayFromBitmap(a);
Color[] bColors = BitmapConvert.ColorArrayFromBitmap(b);
double error = 0;
for (int i = 0; i < aColors.Length; i++) {
error += GetDistance(aColors[i], bColors[i]);
}
return error/aColors.Length;
}
public static double CalculateAverageBrightnessError(Bitmap a, Bitmap b) {
Color[] aColors = BitmapConvert.ColorArrayFromBitmap(a);
Color[] bColors = BitmapConvert.ColorArrayFromBitmap(b);
double error = 0;
for (int i = 0; i < aColors.Length; i++) {
error += aColors[i].GetBrightness()-bColors[i].GetBrightness();
}
return error/aColors.Length;
}
}
} | 38.455556 | 98 | 0.546085 | [
"MIT"
] | Tygrak/PixelPalette | Algorithm/ColorHelpers.cs | 3,461 | C# |
using System.Numerics;
namespace BlazorCanvas.Example4.Core.Components
{
public class Transform : BaseComponent
{
public Transform(GameObject owner) : base(owner)
{
}
public Vector2 Position { get; set; } = Vector2.Zero;
public Vector2 Direction { get; set; } = Vector2.One;
}
} | 23.714286 | 61 | 0.63253 | [
"MIT"
] | BDisp/BlazorCanvas | BlazorCanvas.Example4/Core/Components/Transform.cs | 332 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AwsNative.IoTTwinMaker
{
public static class GetEntity
{
/// <summary>
/// Resource schema for AWS::IoTTwinMaker::Entity
/// </summary>
public static Task<GetEntityResult> InvokeAsync(GetEntityArgs args, InvokeOptions? options = null)
=> Pulumi.Deployment.Instance.InvokeAsync<GetEntityResult>("aws-native:iottwinmaker:getEntity", args ?? new GetEntityArgs(), options.WithDefaults());
/// <summary>
/// Resource schema for AWS::IoTTwinMaker::Entity
/// </summary>
public static Output<GetEntityResult> Invoke(GetEntityInvokeArgs args, InvokeOptions? options = null)
=> Pulumi.Deployment.Instance.Invoke<GetEntityResult>("aws-native:iottwinmaker:getEntity", args ?? new GetEntityInvokeArgs(), options.WithDefaults());
}
public sealed class GetEntityArgs : Pulumi.InvokeArgs
{
/// <summary>
/// The ID of the entity.
/// </summary>
[Input("entityId", required: true)]
public string EntityId { get; set; } = null!;
/// <summary>
/// The ID of the workspace.
/// </summary>
[Input("workspaceId", required: true)]
public string WorkspaceId { get; set; } = null!;
public GetEntityArgs()
{
}
}
public sealed class GetEntityInvokeArgs : Pulumi.InvokeArgs
{
/// <summary>
/// The ID of the entity.
/// </summary>
[Input("entityId", required: true)]
public Input<string> EntityId { get; set; } = null!;
/// <summary>
/// The ID of the workspace.
/// </summary>
[Input("workspaceId", required: true)]
public Input<string> WorkspaceId { get; set; } = null!;
public GetEntityInvokeArgs()
{
}
}
[OutputType]
public sealed class GetEntityResult
{
/// <summary>
/// The ARN of the entity.
/// </summary>
public readonly string? Arn;
/// <summary>
/// A map that sets information about a component type.
/// </summary>
public readonly object? Components;
/// <summary>
/// The date and time when the entity was created.
/// </summary>
public readonly string? CreationDateTime;
/// <summary>
/// The description of the entity.
/// </summary>
public readonly string? Description;
/// <summary>
/// The name of the entity.
/// </summary>
public readonly string? EntityName;
/// <summary>
/// A Boolean value that specifies whether the entity has child entities or not.
/// </summary>
public readonly bool? HasChildEntities;
/// <summary>
/// The ID of the parent entity.
/// </summary>
public readonly string? ParentEntityId;
/// <summary>
/// The current status of the entity.
/// </summary>
public readonly Outputs.EntityStatus? Status;
/// <summary>
/// A key-value pair to associate with a resource.
/// </summary>
public readonly object? Tags;
/// <summary>
/// The last date and time when the entity was updated.
/// </summary>
public readonly string? UpdateDateTime;
[OutputConstructor]
private GetEntityResult(
string? arn,
object? components,
string? creationDateTime,
string? description,
string? entityName,
bool? hasChildEntities,
string? parentEntityId,
Outputs.EntityStatus? status,
object? tags,
string? updateDateTime)
{
Arn = arn;
Components = components;
CreationDateTime = creationDateTime;
Description = description;
EntityName = entityName;
HasChildEntities = hasChildEntities;
ParentEntityId = parentEntityId;
Status = status;
Tags = tags;
UpdateDateTime = updateDateTime;
}
}
}
| 30.527397 | 162 | 0.573704 | [
"Apache-2.0"
] | pulumi/pulumi-aws-native | sdk/dotnet/IoTTwinMaker/GetEntity.cs | 4,457 | C# |
/*
* Copyright(c) 2019 Samsung Electronics Co., Ltd.
*
* 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;
namespace Tizen.NUI.Components
{
/**
* Helper class for LayoutManagers to abstract measurements depending on the View's orientation.
* It is developed to easily support vertical and horizontal orientations in a LayoutManager but
* can also be used to abstract calls around view bounds and child measurements with margins and
* decorations.
*
* @see #createHorizontalHelper(RecyclerView.LayoutManager)
* @see #createVerticalHelper(RecyclerView.LayoutManager)
*/
internal abstract class OrientationHelper
{
public static readonly int HORIZONTAL = 0;
public static readonly int VERTICAL = 1;
private static readonly int INVALID_SIZE = -1;
protected FlexibleView.LayoutManager mLayoutManager;
private float mLastTotalSpace = INVALID_SIZE;
public OrientationHelper(FlexibleView.LayoutManager layoutManager)
{
mLayoutManager = layoutManager;
}
/**
* Call this method after onLayout method is complete if state is NOT pre-layout.
* This method records information like layout bounds that might be useful in the next layout
* calculations.
*/
public void OnLayoutComplete()
{
mLastTotalSpace = GetTotalSpace();
}
/**
* Returns the layout space change between the previous layout pass and current layout pass.
* Make sure you call {@link #onLayoutComplete()} at the end of your LayoutManager's
* {@link RecyclerView.LayoutManager#onLayoutChildren(RecyclerView.Recycler,
* RecyclerView.State)} method.
*
* @return The difference between the current total space and previous layout's total space.
* @see #onLayoutComplete()
*/
public float GetTotalSpaceChange()
{
return INVALID_SIZE == mLastTotalSpace ? 0 : GetTotalSpace() - mLastTotalSpace;
}
/**
* Returns the start of the view including its decoration and margin.
* For example, for the horizontal helper, if a View's left is at pixel 20, has 2px left
* decoration and 3px left margin, returned value will be 15px.
*
* @param view The view element to check
* @return The first pixel of the element
* @see #getDecoratedEnd(android.view.View)
*/
public abstract float GetViewHolderStart(FlexibleView.ViewHolder holder);
/**
* Returns the end of the view including its decoration and margin.
* For example, for the horizontal helper, if a View's right is at pixel 200, has 2px right
* decoration and 3px right margin, returned value will be 205.
*
* @param view The view element to check
* @return The last pixel of the element
* @see #getDecoratedStart(android.view.View)
*/
public abstract float GetViewHolderEnd(FlexibleView.ViewHolder holder);
/**
* Returns the space occupied by this View in the current orientation including decorations and
* margins.
*
* @param view The view element to check
* @return Total space occupied by this view
* @see #getDecoratedMeasurementInOther(View)
*/
public abstract float GetViewHolderMeasurement(FlexibleView.ViewHolder holder);
/**
* Returns the space occupied by this View in the perpendicular orientation including
* decorations and margins.
*
* @param view The view element to check
* @return Total space occupied by this view in the perpendicular orientation to current one
* @see #getDecoratedMeasurement(View)
*/
public abstract float GetViewHolderMeasurementInOther(FlexibleView.ViewHolder holder);
/**
* Returns the start position of the layout after the start padding is added.
*
* @return The very first pixel we can draw.
*/
public abstract float GetStartAfterPadding();
/**
* Returns the end position of the layout after the end padding is removed.
*
* @return The end boundary for this layout.
*/
public abstract float GetEndAfterPadding();
/**
* Returns the end position of the layout without taking padding into account.
*
* @return The end boundary for this layout without considering padding.
*/
public abstract float GetEnd();
/**
* Offsets all children's positions by the given amount.
*
* @param amount Value to add to each child's layout parameters
*/
public abstract void OffsetChildren(float amount, bool immediate);
/**
* Returns the total space to layout. This number is the difference between
* {@link #getEndAfterPadding()} and {@link #getStartAfterPadding()}.
*
* @return Total space to layout children
*/
public abstract float GetTotalSpace();
/**
* Offsets the child in this orientation.
*
* @param view View to offset
* @param offset offset amount
*/
internal abstract void OffsetChild(FlexibleView.ViewHolder holder, int offset);
/**
* Returns the padding at the end of the layout. For horizontal helper, this is the right
* padding and for vertical helper, this is the bottom padding. This method does not check
* whether the layout is RTL or not.
*
* @return The padding at the end of the layout.
*/
public abstract float GetEndPadding();
/**
* Creates an OrientationHelper for the given LayoutManager and orientation.
*
* @param layoutManager LayoutManager to attach to
* @param orientation Desired orientation. Should be {@link #HORIZONTAL} or {@link #VERTICAL}
* @return A new OrientationHelper
*/
public static OrientationHelper CreateOrientationHelper(
FlexibleView.LayoutManager layoutManager, int orientation)
{
if (orientation == HORIZONTAL)
{
return CreateHorizontalHelper(layoutManager);
}
else if (orientation == VERTICAL)
{
return CreateVerticalHelper(layoutManager);
}
throw new ArgumentException("invalid orientation");
}
/**
* Creates a horizontal OrientationHelper for the given LayoutManager.
*
* @param layoutManager The LayoutManager to attach to.
* @return A new OrientationHelper
*/
public static OrientationHelper CreateHorizontalHelper(FlexibleView.LayoutManager layoutManager)
{
return new HorizontalHelper(layoutManager);
}
/**
* Creates a vertical OrientationHelper for the given LayoutManager.
*
* @param layoutManager The LayoutManager to attach to.
* @return A new OrientationHelper
*/
public static OrientationHelper CreateVerticalHelper(FlexibleView.LayoutManager layoutManager)
{
return new VerticalHelper(layoutManager);
}
}
internal class HorizontalHelper : OrientationHelper
{
public HorizontalHelper(FlexibleView.LayoutManager layoutManager): base(layoutManager)
{
}
public override float GetEndAfterPadding()
{
return mLayoutManager.GetWidth() - mLayoutManager.GetPaddingRight();
}
public override float GetEnd()
{
return mLayoutManager.GetWidth();
}
public override void OffsetChildren(float amount, bool immediate)
{
mLayoutManager.OffsetChildrenHorizontal(amount, immediate);
}
public override float GetStartAfterPadding()
{
return mLayoutManager.GetPaddingLeft();
}
public override float GetViewHolderMeasurement(FlexibleView.ViewHolder holder)
{
return holder.Right - holder.Left;
}
public override float GetViewHolderMeasurementInOther(FlexibleView.ViewHolder holder)
{
return holder.Bottom - holder.Top;
}
public override float GetViewHolderEnd(FlexibleView.ViewHolder holder)
{
return holder.Right;
}
public override float GetViewHolderStart(FlexibleView.ViewHolder holder)
{
return holder.Left;
}
public override float GetTotalSpace()
{
return mLayoutManager.GetWidth() - mLayoutManager.GetPaddingLeft()
- mLayoutManager.GetPaddingRight();
}
internal override void OffsetChild(FlexibleView.ViewHolder holder, int offset)
{
//holder.offsetLeftAndRight(offset);
}
public override float GetEndPadding()
{
return mLayoutManager.GetPaddingRight();
}
}
internal class VerticalHelper : OrientationHelper
{
public VerticalHelper(FlexibleView.LayoutManager layoutManager) : base(layoutManager)
{
}
public override float GetEndAfterPadding()
{
return mLayoutManager.GetHeight() - mLayoutManager.GetPaddingBottom();
}
public override float GetEnd()
{
return mLayoutManager.GetHeight();
}
public override void OffsetChildren(float amount, bool immediate)
{
mLayoutManager.OffsetChildrenVertical(amount, immediate);
}
public override float GetStartAfterPadding()
{
return mLayoutManager.GetPaddingTop();
}
public override float GetViewHolderMeasurement(FlexibleView.ViewHolder holder)
{
return holder.Bottom - holder.Top;
}
public override float GetViewHolderMeasurementInOther(FlexibleView.ViewHolder holder)
{
return holder.Right - holder.Left;
}
public override float GetViewHolderEnd(FlexibleView.ViewHolder holder)
{
return holder.Bottom;
}
public override float GetViewHolderStart(FlexibleView.ViewHolder holder)
{
return holder.Top;
}
public override float GetTotalSpace()
{
return mLayoutManager.GetHeight() - mLayoutManager.GetPaddingTop()
- mLayoutManager.GetPaddingBottom();
}
internal override void OffsetChild(FlexibleView.ViewHolder holder, int offset)
{
//holder.offsetTopAndBottom(offset);
}
public override float GetEndPadding()
{
return mLayoutManager.GetPaddingBottom();
}
}
}
| 33.80758 | 104 | 0.627372 | [
"Apache-2.0"
] | agnelovaz/TizenFX | src/Tizen.NUI.Components/Controls/FlexibleView/OrientationHelper.cs | 11,598 | C# |
// Copyright (c) 2002-2019 "Neo4j,"
// Neo4j Sweden AB [http://neo4j.com]
//
// This file is part of Neo4j.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Threading;
using System.Threading.Tasks;
using FluentAssertions;
using Neo4j.Driver.Internal;
using Neo4j.Driver.Internal.Result;
using Xunit;
namespace Neo4j.Driver.Tests
{
public class ConsumableCursorTests
{
[Fact]
public async void ShouldErrorWhenAccessRecordsAfterConsume()
{
var result = ResultCursorCreator.CreateResultCursor(1, 3);
await result.ConsumeAsync();
await ThrowsResultConsumedException(async () => await result.FetchAsync());
await ThrowsResultConsumedException(async () => await result.PeekAsync());
ThrowsResultConsumedException(() => result.Current);
}
[Fact]
public async void ShouldErrorWhenAccessRecordsViaExtensionMethodsAfterConsume()
{
var result = ResultCursorCreator.CreateResultCursor(1, 3);
await result.ConsumeAsync();
await ThrowsResultConsumedException(async () => await result.SingleAsync());
await ThrowsResultConsumedException(async () => await result.ToListAsync());
await ThrowsResultConsumedException(async () => await result.ForEachAsync(r => { }));
}
[Fact]
public async void ShouldAllowKeysAndConsumeAfterConsume()
{
var result = ResultCursorCreator.CreateResultCursor(1, 3);
var summary0 = await result.ConsumeAsync();
var keys1 = await result.KeysAsync();
var summary1 = await result.ConsumeAsync();
var keys2 = await result.KeysAsync();
var summary2 = await result.ConsumeAsync();
summary1.Should().Be(summary0);
summary2.Should().Be(summary0);
keys1.Should().BeEquivalentTo(keys2);
}
public static void ThrowsResultConsumedException(Func<object> func)
{
var ex = Xunit.Record.Exception(func);
ex.Should().NotBeNull();
ex.Should().BeOfType<ResultConsumedException>();
}
public static async Task ThrowsResultConsumedException<T>(Func<Task<T>> func)
{
var ex = await Xunit.Record.ExceptionAsync(func);
ex.Should().NotBeNull();
ex.Should().BeOfType<ResultConsumedException>();
}
private static class ResultCursorCreator
{
public static IInternalResultCursor CreateResultCursor(int keySize, int recordSize = 1,
Func<Task<IResultSummary>> getSummaryFunc = null,
CancellationTokenSource cancellationTokenSource = null)
{
var cursor = ResultCursorTests.ResultCursorCreator.
CreateResultCursor(keySize, recordSize, getSummaryFunc, cancellationTokenSource);
return new ConsumableResultCursor(cursor);
}
}
}
} | 37 | 101 | 0.649493 | [
"Apache-2.0"
] | gjmwoods/neo4j-dotnet-driver | Neo4j.Driver/Neo4j.Driver.Tests/Result/ConsumableCursorTests.cs | 3,552 | C# |
//-----------------------------------------------------------------------
// <copyright file="CounterActor.cs" company="Akka.NET Project">
// Copyright (C) 2009-2021 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2021 .NET Foundation <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
namespace Akka.Persistence.TestKit.Tests
{
using System;
using System.Threading.Tasks;
using Actor;
using Akka.TestKit;
using Xunit;
public class CounterActor : UntypedPersistentActor
{
public CounterActor(string id)
{
this.PersistenceId = id;
}
private int _value = 0;
public override string PersistenceId { get; }
protected override void OnCommand(object message)
{
switch (message as string)
{
case "inc":
_value++;
Persist(message, _ => { });
break;
case "dec":
_value++;
Persist(message, _ => { });
break;
case "read":
Sender.Tell(_value, Self);
break;
default:
return;
}
}
protected override void OnRecover(object message)
{
switch (message as string)
{
case "inc":
_value++;
break;
case "dec":
_value++;
break;
default:
return;
}
}
}
public class CounterActorTests : PersistenceTestKit
{
[Fact]
public async Task CounterActor_internal_state_will_be_lost_if_underlying_persistence_store_is_not_available()
{
await WithJournalWrite(write => write.Fail(), async () =>
{
var counterProps = Props.Create(() => new CounterActor("test"));
var actor = ActorOf(counterProps, "counter");
Watch(actor);
actor.Tell("inc", TestActor);
await ExpectMsgAsync<Terminated>(TimeSpan.FromSeconds(3));
// need to restart actor
actor = ActorOf(counterProps, "counter1");
actor.Tell("read", TestActor);
var value = await ExpectMsgAsync<int>(TimeSpan.FromSeconds(3));
value.ShouldBe(0);
});
}
}
}
| 28.771739 | 117 | 0.45221 | [
"Apache-2.0"
] | rogeralsing/pigeon | src/core/Akka.Persistence.TestKit.Tests/Actors/CounterActor.cs | 2,649 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the connect-2017-08-08.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.Connect.Model
{
/// <summary>
/// Request processing failed due to an error or failure with the service.
/// </summary>
#if !NETSTANDARD
[Serializable]
#endif
public partial class InternalServiceException : AmazonConnectException
{
/// <summary>
/// Constructs a new InternalServiceException with the specified error
/// message.
/// </summary>
/// <param name="message">
/// Describes the error encountered.
/// </param>
public InternalServiceException(string message)
: base(message) {}
/// <summary>
/// Construct instance of InternalServiceException
/// </summary>
/// <param name="message"></param>
/// <param name="innerException"></param>
public InternalServiceException(string message, Exception innerException)
: base(message, innerException) {}
/// <summary>
/// Construct instance of InternalServiceException
/// </summary>
/// <param name="innerException"></param>
public InternalServiceException(Exception innerException)
: base(innerException) {}
/// <summary>
/// Construct instance of InternalServiceException
/// </summary>
/// <param name="message"></param>
/// <param name="innerException"></param>
/// <param name="errorType"></param>
/// <param name="errorCode"></param>
/// <param name="requestId"></param>
/// <param name="statusCode"></param>
public InternalServiceException(string message, Exception innerException, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode)
: base(message, innerException, errorType, errorCode, requestId, statusCode) {}
/// <summary>
/// Construct instance of InternalServiceException
/// </summary>
/// <param name="message"></param>
/// <param name="errorType"></param>
/// <param name="errorCode"></param>
/// <param name="requestId"></param>
/// <param name="statusCode"></param>
public InternalServiceException(string message, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode)
: base(message, errorType, errorCode, requestId, statusCode) {}
#if !NETSTANDARD
/// <summary>
/// Constructs a new instance of the InternalServiceException class with serialized data.
/// </summary>
/// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is null. </exception>
/// <exception cref="T:System.Runtime.Serialization.SerializationException">The class name is null or <see cref="P:System.Exception.HResult" /> is zero (0). </exception>
protected InternalServiceException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
: base(info, context)
{
}
/// <summary>
/// Sets the <see cref="T:System.Runtime.Serialization.SerializationInfo" /> with information about the exception.
/// </summary>
/// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is a null reference (Nothing in Visual Basic). </exception>
#if BCL35
[System.Security.Permissions.SecurityPermission(
System.Security.Permissions.SecurityAction.LinkDemand,
Flags = System.Security.Permissions.SecurityPermissionFlag.SerializationFormatter)]
#endif
[System.Security.SecurityCritical]
// These FxCop rules are giving false-positives for this method
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2134:MethodsMustOverrideWithConsistentTransparencyFxCopRule")]
public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
{
base.GetObjectData(info, context);
}
#endif
}
} | 47.209677 | 178 | 0.680219 | [
"Apache-2.0"
] | DetlefGolze/aws-sdk-net | sdk/src/Services/Connect/Generated/Model/InternalServiceException.cs | 5,854 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Eat : MonoBehaviour
{
[SerializeField] private string selectableTag = "Selectable";
private Transform _selection;
public PlayerStats stats;
public GameObject Text;
private GameObject Food;
public Raycast rayScript;
private void Update()
{
Food = rayScript.rayHitted;
if (rayScript.rayHitted.CompareTag(selectableTag) && Input.GetKeyDown(KeyCode.F))
{
stats.Eat();
print("key was pressed");
Food.gameObject.SetActive(false);
}
if (rayScript.rayHitted.CompareTag(selectableTag))
{
Text.gameObject.SetActive(true);
}
else
Text.gameObject.SetActive(false);
}
}
| 22.636364 | 86 | 0.690763 | [
"MIT"
] | suomilanittaja/My-Spring-Car | Assets/Scripts/Eat.cs | 749 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System;
namespace NestedPrefabUtil
{
[InitializeOnLoad]
public class Startup
{
static Startup()
{
Debug.Log("OnSceneLoaded");
PrefabUtility.prefabInstanceUpdated += OnPrefabModified;
//EditorApplication.update += Update;
}
static bool _ignore;
static void OnPrefabModified(GameObject go_)
{
if(_ignore)
{
return;
}
var nested = go_.GetComponent<NestedPrefab>();
// process referenced prefabs
if(null != nested)
{
foreach(var id in nested._idSet)
{
var rPath = AssetDatabase.GUIDToAssetPath(id);
var rgo = AssetDatabase.LoadAssetAtPath(rPath, typeof(GameObject)) as GameObject;
Debug.Log("id is " + id + " path is " + rPath);
var instance = GameObject.Instantiate(rgo);
List<GameObject> _go2ReplaceList = new List<GameObject>();
LoopChilds(instance, (child) =>
{
Debug.Log("child name : " + child.name + " go name : " + go_.name);
Debug.Log(child.GetComponent<NestedPrefab>() == null);
Debug.Log(child.name == go_.name);
if (null != child.GetComponent<NestedPrefab>() && child.name == go_.name)
{
Debug.Log("AddReplace");
_go2ReplaceList.Add(child);
}
});
for(int i = 0; i < _go2ReplaceList.Count; i++)
{
var newGo = GameObject.Instantiate(go_);
var oldGo = _go2ReplaceList[i];
newGo.name = oldGo.name;
newGo.transform.parent = oldGo.transform.parent;
newGo.transform.position = oldGo.transform.position;
newGo.transform.localScale = oldGo.transform.localScale;
newGo.transform.rotation = oldGo.transform.rotation;
GameObject.DestroyImmediate(oldGo);
}
_ignore = true;
PrefabUtility.ReplacePrefab(instance, rgo);
_ignore = false;
AssetDatabase.Refresh();
AssetDatabase.SaveAssets();
GameObject.DestroyImmediate(instance);
}
var prefab = PrefabUtility.GetPrefabParent(go_);
var path4Id = AssetDatabase.GetAssetPath(prefab);
nested._guid = AssetDatabase.AssetPathToGUID(path4Id);
Debug.Log(nested.ToString());
}
//process nested prefabs in children
var root = PrefabUtility.GetPrefabParent(go_);
var path = AssetDatabase.GetAssetPath(root);
Dictionary<GameObject, GameObject> replaceDic = new Dictionary<GameObject, GameObject>();
LoopChilds(go_, (child) =>
{
if (go_ == child)
{
return;
}
var childNested = child.GetComponent<NestedPrefab>();
if (null != childNested)
{
var guid = AssetDatabase.AssetPathToGUID(path);
Debug.Log("path is " + path + " guid is " + guid);
childNested.AddRefrerencePrefab(guid);
var srcAsset = AssetDatabase.LoadAssetAtPath(AssetDatabase.GUIDToAssetPath(childNested._guid), typeof(GameObject));
replaceDic[childNested.gameObject] = srcAsset as GameObject;
}
});
foreach(var pair in replaceDic)
{
_ignore = true;
PrefabUtility.ReplacePrefab(pair.Key, pair.Value);
_ignore = false;
}
AssetDatabase.Refresh();
AssetDatabase.SaveAssets(); ;
}
static void LoopChilds(GameObject root_, Action<GameObject> process_)
{
if (null != process_)
{
process_(root_);
}
foreach (Transform child in root_.transform)
{
LoopChilds(child.gameObject, process_);
}
}
[MenuItem("Test/DebugNestPrefab")]
static void DebugNestPrefab()
{
var go = Selection.activeGameObject;
if(null == go)
{
return;
}
var nested = go.GetComponent<NestedPrefab>();
if(null != nested)
{
Debug.Log(nested._guid);
if (nested._idSet.Count < 1)
{
Debug.Log("Empty ");
}
else
{
foreach (var id in nested._idSet)
{
Debug.Log(id);
}
}
}
}
//static void Update()
//{
//}
}
}
| 37.475524 | 135 | 0.47117 | [
"MIT"
] | wohenlihai1988/NestedPrefab | Assets/NestedPrefab/Editor/NestedPrefabUtil.cs | 5,361 | 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("POSH-Launcher")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("POSH-Launcher")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[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("6653c802-b34e-4bab-b869-d7849e025b2b")]
// 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"
] | suegy/scbot | POSH-Launcher/Properties/AssemblyInfo.cs | 1,402 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
namespace Microsoft.Data.SqlClient.Reliability
{
/// <summary>
/// Contains information that is required for the <see cref="SqlRetryPolicy.Retrying"/> event.
/// </summary>
public class SqlRetryingEventArgs : EventArgs
{
/// <summary>
/// Initializes a new instance of the <see cref="SqlRetryingEventArgs"/> class.
/// </summary>
/// <param name="currentRetryCount">The current retry attempt count.</param>
/// <param name="delay">The delay that indicates how long the current thread will be suspended before the next iteration is invoked.</param>
/// <param name="lastException">The exception that caused the retry conditions to occur.</param>
public SqlRetryingEventArgs(int currentRetryCount, TimeSpan delay, Exception lastException)
{
this.CurrentRetryCount = currentRetryCount;
this.Delay = delay;
this.LastException = lastException;
}
/// <summary>
/// Gets the current retry count.
/// </summary>
public int CurrentRetryCount { get; private set; }
/// <summary>
/// Gets the delay that indicates how long the current thread will be suspended before the next iteration is invoked.
/// </summary>
public TimeSpan Delay { get; private set; }
/// <summary>
/// Gets the exception that caused the retry conditions to occur.
/// </summary>
public Exception LastException { get; private set; }
}
}
| 40.674419 | 148 | 0.650086 | [
"MIT"
] | scoriani/SqlClient | src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/Reliability/SqlRetryingEventArgs.cs | 1,751 | C# |
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using Google.Api.Gax;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace Google.Cloud.Spanner.Data
{
/// <summary>
/// Represents batched commands to execute against a Spanner database.
/// Currently only DML commands are supported in batch mode.
/// <para>
/// You can create an instance of <see cref="SpannerBatchCommand"/> with no
/// initial commands.
/// You can then add commands to a <see cref="SpannerBatchCommand"/> using the
/// <see cref="Add(SpannerCommandTextBuilder, SpannerParameterCollection)"/> or
/// <see cref="Add(string, SpannerParameterCollection)"/> or <see cref="Add(SpannerCommand)"/> methods.
/// </para>
/// <para>
/// For batched DML commands use <see cref="ExecuteNonQueryAsync(CancellationToken)"/> or
/// <see cref="ExecuteNonQuery" /> to execute the batched commands.
/// </para>
/// </summary>
public sealed partial class SpannerBatchCommand
{
private int _commandTimeout;
private SpannerBatchCommandType _commandType;
internal SpannerBatchCommand(SpannerConnection connection)
{
Connection = GaxPreconditions.CheckNotNull(connection, nameof(connection));
}
internal SpannerBatchCommand(SpannerTransaction transaction)
{
Transaction = GaxPreconditions.CheckNotNull(transaction, nameof(transaction));
Connection = transaction.SpannerConnection; // Never null
}
// Visible for testing
internal IList<SpannerCommand> Commands { get; } = new List<SpannerCommand>();
/// <summary>
/// Gets or sets the wait time before terminating the attempt to execute a command and generating an error.
/// Defaults to the timeout from the connection string.
/// </summary>
/// <remarks>
/// A value of '0' normally indicates that no timeout should be used (it waits an infinite amount of time).
/// However, if you specify AllowImmediateTimeouts=true in the connection string, '0' will cause a timeout
/// that expires immediately. This is normally used only for testing purposes.
/// </remarks>
public int CommandTimeout
{
get => _commandTimeout;
set => _commandTimeout = GaxPreconditions.CheckArgumentRange(value, nameof(value), 0, int.MaxValue);
}
/// <summary>
/// The connection to the data source. This is never null.
/// </summary>
public SpannerConnection Connection { get; }
/// <summary>
/// The transaction to use when executing this command. If this is null, the command will be executed without a transaction.
/// </summary>
public SpannerTransaction Transaction { get; }
/// <summary>
/// The type of this batch command. If initialy set to <see cref="SpannerBatchCommandType.None"/>, this value will be
/// calculated when the first command is added to the batch.
/// <para>Only DML commands are currently supported in batch mode.</para>
/// <para>You can set this property freely as long as there are no commands in this bacth command.
/// Once there are commands in this batch command an attempt to change this property's value will throw
/// and <see cref="ArgumentException"/>.</para>
/// </summary>
public SpannerBatchCommandType CommandType
{
get => _commandType;
set
{
GaxPreconditions.CheckEnumValue(value, nameof(value));
GaxPreconditions.CheckArgument(Commands.Count == 0 || _commandType == value, nameof(value), "Cannot change the type of this batch command because it already contains commands.");
_commandType = value;
}
}
/// <summary>
/// The statement tag to send to Cloud Spanner for this command.
/// </summary>
public string Tag { get; set; }
/// <summary>
/// The RPC priority to use for this command. The default priority is Unspecified.
/// </summary>
public Priority Priority { get; set; }
/// <summary>
/// Adds a command to the collection of batch commands to be executed by this <see cref="SpannerBatchCommand"/>.
/// </summary>
/// <param name="commandText"> The command text to be added. Must not be null or empty.
/// Currently only DML commands are supported in batch operations.</param>
/// <param name="parameters">The parameters associated with <paramref name="commandText"/>.
/// If <paramref name="commandText"/> doesn't require parameters then <paramref name="parameters"/>
/// can be either <code>null</code> or empty.</param>
public void Add(string commandText, SpannerParameterCollection parameters = null)
{
GaxPreconditions.CheckNotNullOrEmpty(commandText, nameof(commandText));
SpannerCommand command = new SpannerCommand(commandText, parameters);
ValidateAndSetCommandType(command.SpannerCommandTextBuilder.SpannerCommandType);
Commands.Add(command);
}
/// <summary>
/// Adds a command to the collection of batch commands to be executed by this <see cref="SpannerBatchCommand"/>.
/// Only <see cref="SpannerCommand.CommandText"/> and <see cref="SpannerCommand.Parameters"/> will be taken into
/// account. Other <see cref="SpannerCommand"/> properties like <see cref="SpannerCommand.SpannerConnection"/>
/// and <see cref="SpannerCommand.DbTransaction"/> will be ignored.
/// </summary>
/// <param name="command">The command to be added.</param>
public void Add(SpannerCommand command) =>
Add(GaxPreconditions.CheckNotNull(command, nameof(command)).CommandText, command.Parameters);
/// <summary>
/// Adds a command to the collection of batch commands to be executed by this <see cref="SpannerBatchCommand"/>.
/// </summary>
/// <param name="commandTextBuilder"> A <see cref="SpannerCommandTextBuilder"/> representing the command to be added.
/// Must not be null or empty.
/// Currently only DML commands are supported in batch operations.</param>
/// <param name="parameters">The parameters associated with <paramref name="commandTextBuilder"/>.
/// If <paramref name="commandTextBuilder"/> doesn't require parameters then <paramref name="parameters"/>
/// can be either <code>null</code> or empty.</param>
public void Add(SpannerCommandTextBuilder commandTextBuilder, SpannerParameterCollection parameters = null) =>
Add(GaxPreconditions.CheckNotNull(commandTextBuilder, nameof(commandTextBuilder)).CommandText, parameters);
private void ValidateAndSetCommandType(SpannerCommandType spannerCommandType)
{
// CommandType is either set manually or because other commands had been added.
// Check compatibility between the command being added and the set CommandType.
if(CommandType != SpannerBatchCommandType.None)
{
GaxPreconditions.CheckState(
spannerCommandType == SpannerCommandType.Dml && CommandType == SpannerBatchCommandType.BatchDml,
$"{spannerCommandType} is not compatible with {CommandType}");
}
// CommandType is not set. This is the first command being added to the batch.
// If the type of the command is batch supported, set CommandType to the supporting value.
else
{
GaxPreconditions.CheckState(spannerCommandType == SpannerCommandType.Dml, "Only DML commands are supported in batch mode.");
CommandType = SpannerBatchCommandType.BatchDml;
}
}
/// <summary>
/// Executes the batch commands sequentially.
/// If a command fails, execution is halted and this method will throw an <see cref="SpannerBatchNonQueryException"/>
/// containing information about the failure and the number of affected rows by each of the commands
/// that executed successfully before the failure ocurred.
/// </summary>
/// <returns>The number of rows affected by each of the executed commands.</returns>
public IEnumerable<long> ExecuteNonQuery() =>
Task.Run(() => ExecuteNonQueryAsync(CancellationToken.None)).ResultWithUnwrappedExceptions();
/// <summary>
/// Executes the batch commands sequentially. The execution of this method overall is asynchronous.
/// </summary>
/// <param name="cancellationToken">A cancellation token for the operation.</param>
/// <returns>A task that once completed will indicate the number of rows
/// affected by each of the executed commands.
/// If a command fails, execution is halted and this method will return a faulted task with an <see cref="SpannerBatchNonQueryException"/>
/// containing information about the failure and the number of affected rows by each of the commands
/// that executed successfully before the failure ocurred.
/// </returns>
public Task<IReadOnlyList<long>> ExecuteNonQueryAsync(CancellationToken cancellationToken = default) =>
CreateExecutableCommand().ExecuteNonQueryAsync(cancellationToken);
private ExecutableCommand CreateExecutableCommand() =>
new ExecutableCommand(this);
}
} | 52.517949 | 194 | 0.6639 | [
"Apache-2.0"
] | AlexandrTrf/google-cloud-dotnet | apis/Google.Cloud.Spanner.Data/Google.Cloud.Spanner.Data/SpannerBatchCommand.cs | 10,243 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的一般信息由以下
// 控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("MetaWorkLib")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("azthinker@sina.com")]
[assembly: AssemblyProduct("MetaWorkLib")]
[assembly: AssemblyCopyright("杨斌,azthinker@sina.comCopyright © 2018")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 会使此程序集中的类型
//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型
//请将此类型的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("1713b63b-298d-4975-9c16-74986b7c9ea6")]
// 程序集的版本信息由下列四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
// 可以指定所有值,也可以使用以下所示的 "*" 预置版本号和修订号
//通过使用 "*",如下所示:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.2.2.0")]
[assembly: AssemblyFileVersion("1.2.2.0")]
| 26.459459 | 71 | 0.721144 | [
"Apache-2.0"
] | AzThinker/CodeToolSolution | MetaWorkLib/Properties/AssemblyInfo.cs | 1,320 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
namespace Microsoft.Teams.Samples.LinkUnfurlerForReddit
{
/// <summary>
/// The Reddit options are used to configure the Reddit Link Unfurler.
/// </summary>
public sealed class RedditOptions
{
/// <summary>
/// Gets or sets the Client User Agent is the user agent that will be reported to the Reddit API.
/// </summary>
/// <remarks>
/// See https://github.com/reddit-archive/reddit/wiki/API#rules for rules around the user-agent string.
/// </remarks>
public string ClientUserAgent { get; set; }
/// <summary>
/// Gets or sets the BotFramework Connection Name for the registered auth providers.
/// </summary>
/// <remarks>
/// https://docs.microsoft.com/en-us/azure/bot-service/bot-builder-concept-authentication?view=azure-bot-service-4.0#about-the-bot-framework-token-service .
/// </remarks>
public string BotFrameworkConnectionName { get; set; }
/// <summary>
/// Gets or sets the AppId for Reddit.
/// </summary>
/// <value>The AppId.</value>
/// <remarks>
/// Apps registered at: https://www.reddit.com/prefs/apps .
/// </remarks>
public string AppId { get; set; }
/// <summary>
/// Gets or sets the App Password for Reddit.
/// </summary>
/// <value>The AppId.</value>
/// <remarks>
/// This is the 'secret' from https://www.reddit.com/prefs/apps .
/// </remarks>
public string AppPassword { get; set; }
}
} | 37.355556 | 164 | 0.59072 | [
"MIT"
] | 0723Cu/Microsoft-Teams-Samples | samples/msgext-link-unfurling-reddit/csharp/dotnet/RedditApi/RedditOptions.cs | 1,681 | C# |
using Microsoft.VisualStudio.TestTools.UnitTesting;
using scheduler.Core.Entities;
using scheduler.Persistence;
namespace scheduler.Persistance.UnitTests
{
[TestClass]
public class EfRepositoryIntegrationTests
{
[TestMethod]
public void EfRepository_ShouldCreate()
{
// Arrange
var efContext = new EfContext();
var entity = new Entity
{
Id = 1,
};
var repository = new EfRepository<Entity>(efContext);
// Act
repository.Insert(entity);
// Assert
Assert.IsNotNull(repository);
}
[TestMethod]
public void EfRepository_ShouldInsert()
{
// Arrange
var efContext = new EfContext();
var entities = FakeEntity.FakeEntities();
var repository = new EfRepository<Entity>(efContext);
// Act
foreach (var item in entities)
{
repository.Insert(item);
}
// Assert
Assert.IsNotNull(repository);
}
}
} | 22.115385 | 65 | 0.529565 | [
"MIT"
] | toddbadams/accounts-microservice | tba.Persistance.UnitTests/EfRepositoryIntegrationTests.cs | 1,152 | C# |
/**
* Copyright (c) 2019 LG Electronics, Inc.
*
* This software contains code licensed as described in LICENSE.
*
*/
using UnityEngine;
namespace Simulator.Bridge.Data
{
public class Detected3DObject
{
public uint Id;
public string Label;
public double Score;
public Vector3 Position;
public Quaternion Rotation;
public Vector3 Scale;
public Vector3 LinearVelocity;
public Vector3 AngularVelocity;
}
public class Detected3DObjectData
{
public string Name;
public string Frame;
public double Time;
public uint Sequence;
public Detected3DObject[] Data;
}
public class Detected3DObjectArray
{
public Detected3DObject[] Data;
}
}
| 19.625 | 64 | 0.635669 | [
"Apache-2.0",
"BSD-3-Clause"
] | 0x8BADFOOD/simulator | Assets/Scripts/Bridge/Data/Detected3DObject.cs | 785 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Azure.Core;
using Azure.ResourceManager.Core;
using Azure.ResourceManager.Resources.Models;
namespace Azure.ResourceManager.Resources
{
/// <summary>
/// A class representing collection of ResourceGroupContainer and their operations over a ResourceGroup.
/// </summary>
public class ResourceGroupContainer : ResourceContainerBase<ResourceGroup, ResourceGroupData>
{
/// <summary>
/// Initializes a new instance of the <see cref="ResourceGroupContainer"/> class for mocking.
/// </summary>
protected ResourceGroupContainer()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ResourceGroupContainer"/> class.
/// </summary>
/// <param name="subscription"> The parent subscription. </param>
internal ResourceGroupContainer(SubscriptionOperations subscription)
: base(subscription)
{
}
/// <inheritdoc/>
protected override ResourceType ValidResourceType => SubscriptionOperations.ResourceType;
/// <summary>
/// Gets the parent resource of this resource.
/// </summary>
protected new SubscriptionOperations Parent { get {return base.Parent as SubscriptionOperations;} }
private ResourceGroupsRestOperations RestClient
{
get
{
string subscriptionId;
if (Id is null || !Id.TryGetSubscriptionId(out subscriptionId))
subscriptionId = Guid.NewGuid().ToString();
return new ResourceGroupsRestOperations(Diagnostics, Pipeline, subscriptionId, BaseUri);
}
}
/// <summary>
/// Returns the resource from Azure if it exists.
/// </summary>
/// <param name="resourceGroupName"> The name of the resource you want to get. </param>
/// <param name="cancellationToken"> A token to allow the caller to cancel the call to the service.
/// The default value is <see cref="CancellationToken.None" />. </param>
/// <returns> Whether or not the resource existed. </returns>
public virtual ResourceGroup TryGet(string resourceGroupName, CancellationToken cancellationToken = default)
{
using var scope = Diagnostics.CreateScope("ResourceGroupContainer.TryGet");
scope.Start();
try
{
return Get(resourceGroupName, cancellationToken).Value;
}
catch (RequestFailedException e) when (e.Status == 404)
{
return null;
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Returns the resource from Azure if it exists.
/// </summary>
/// <param name="resourceGroupName"> The name of the resource you want to get. </param>
/// <param name="cancellationToken"> A token to allow the caller to cancel the call to the service.
/// The default value is <see cref="CancellationToken.None" />. </param>
/// <returns> Whether or not the resource existed. </returns>
public virtual async Task<ResourceGroup> TryGetAsync(string resourceGroupName, CancellationToken cancellationToken = default)
{
using var scope = Diagnostics.CreateScope("ResourceGroupContainer.TryGet");
scope.Start();
try
{
return await GetAsync(resourceGroupName, cancellationToken).ConfigureAwait(false);
}
catch (RequestFailedException e) when (e.Status == 404)
{
return null;
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Determines whether or not the azure resource exists in this container.
/// </summary>
/// <param name="resourceGroupName"> The name of the resource you want to check. </param>
/// <param name="cancellationToken"> A token to allow the caller to cancel the call to the service.
/// The default value is <see cref="CancellationToken.None" />. </param>
/// <returns> Whether or not the resource existed. </returns>
public virtual bool CheckIfExists(string resourceGroupName, CancellationToken cancellationToken = default)
{
using var scope = Diagnostics.CreateScope("ResourceGroupContainer.CheckIfExists");
scope.Start();
try
{
return RestClient.CheckExistence(resourceGroupName, cancellationToken).Value;
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Determines whether or not the azure resource exists in this container.
/// </summary>
/// <param name="resourceGroupName"> The name of the resource you want to check. </param>
/// <param name="cancellationToken"> A token to allow the caller to cancel the call to the service.
/// The default value is <see cref="CancellationToken.None" />. </param>
/// <returns> Whether or not the resource existed. </returns>
public virtual async Task<bool> CheckIfExistsAsync(string resourceGroupName, CancellationToken cancellationToken = default)
{
using var scope = Diagnostics.CreateScope("ResourceGroupContainer.CheckIfExists");
scope.Start();
try
{
var response = await RestClient.CheckExistenceAsync(resourceGroupName, cancellationToken).ConfigureAwait(false);
return response.Value;
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Constructs an object used to create a resource group.
/// </summary>
/// <param name="location"> The location of the resource group. </param>
/// <param name="tags"> The tags of the resource group. </param>
/// <param name="managedBy"> Who the resource group is managed by. </param>
/// <returns> A builder with <see cref="ResourceGroup"/> and <see cref="ResourceGroupData"/>. </returns>
/// <exception cref="ArgumentNullException"> Location cannot be null. </exception>
internal ResourceGroupBuilder Construct(Location location, IDictionary<string, string> tags = default, string managedBy = default)
{
if (location is null)
throw new ArgumentNullException(nameof(location));
var model = new ResourceGroupData(location);
if (!(tags is null))
model.Tags.ReplaceWith(tags);
model.ManagedBy = managedBy;
return new ResourceGroupBuilder(this, model);
}
/// <summary>
/// The operation to create or update a resource group. Please note some properties can be set only during creation.
/// </summary>
/// <param name="name"> The name of the resource group. </param>
/// <param name="resourceDetails"> The desired resource group configuration. </param>
/// <param name="cancellationToken"> A token to allow the caller to cancel the call to the service. The default value is <see cref="CancellationToken.None" />. </param>
/// <returns> A response with the <see cref="Response{ResourceGroup}"/> operation for this resource. </returns>
/// <exception cref="ArgumentException"> Name of the resource group cannot be null or a whitespace. </exception>
/// <exception cref="ArgumentNullException"> resourceDetails cannot be null. </exception>
public Response<ResourceGroup> CreateOrUpdate(string name, ResourceGroupData resourceDetails, CancellationToken cancellationToken = default)
{
if (string.IsNullOrWhiteSpace(name))
throw new ArgumentException("name cannot be null or a whitespace.", nameof(name));
if (resourceDetails is null)
throw new ArgumentNullException(nameof(resourceDetails));
using var scope = Diagnostics.CreateScope("ResourceGroupContainer.CreateOrUpdate");
scope.Start();
try
{
var operation = StartCreateOrUpdate(name, resourceDetails, cancellationToken);
return operation.WaitForCompletion(cancellationToken);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// The operation to create or update a resource group. Please note some properties can be set only during creation.
/// </summary>
/// <param name="name"> The name of the resource group. </param>
/// <param name="resourceDetails"> The desired resource group configuration. </param>
/// <param name="cancellationToken"> A token to allow the caller to cancel the call to the service. The default value is <see cref="CancellationToken.None" />. </param>
/// <returns> A <see cref="Task"/> that on completion returns a response with the <see cref="Response{ResourceGroup}"/> operation for this resource group. </returns>
/// <exception cref="ArgumentException"> Name of the resource group cannot be null or a whitespace. </exception>
/// <exception cref="ArgumentNullException"> resourceDetails cannot be null. </exception>
public virtual async Task<Response<ResourceGroup>> CreateOrUpdateAsync(string name, ResourceGroupData resourceDetails, CancellationToken cancellationToken = default)
{
if (string.IsNullOrWhiteSpace(name))
throw new ArgumentException("name cannot be null or a whitespace.", nameof(name));
if (resourceDetails is null)
throw new ArgumentNullException(nameof(resourceDetails));
using var scope = Diagnostics.CreateScope("ResourceGroupContainer.CreateOrUpdate");
scope.Start();
try
{
var operation = await StartCreateOrUpdateAsync(name, resourceDetails, cancellationToken).ConfigureAwait(false);
return await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// The operation to create or update a resource group. Please note some properties can be set only during creation.
/// </summary>
/// <param name="name"> The name of the resource group. </param>
/// <param name="resourceDetails"> The desired resource group configuration. </param>
/// <param name="cancellationToken"> A token to allow the caller to cancel the call to the service. The default value is <see cref="CancellationToken.None" />. </param>
/// <returns> An <see cref="Operation{ResourceGroup}"/> that allows polling for completion of the operation. </returns>
/// <remarks>
/// <see href="https://azure.github.io/azure-sdk/dotnet_introduction.html#dotnet-longrunning">Details on long running operation object.</see>
/// </remarks>
/// <exception cref="ArgumentException"> Name of the resource group cannot be null or a whitespace. </exception>
/// <exception cref="ArgumentNullException"> resourceDetails cannot be null. </exception>
public ResourceGroupCreateOrUpdateOperation StartCreateOrUpdate(string name, ResourceGroupData resourceDetails, CancellationToken cancellationToken = default)
{
if (string.IsNullOrWhiteSpace(name))
throw new ArgumentException("name cannot be null or a whitespace.", nameof(name));
if (resourceDetails is null)
throw new ArgumentNullException(nameof(resourceDetails));
using var scope = Diagnostics.CreateScope("ResourceGroupContainer.StartCreateOrUpdate");
scope.Start();
try
{
var originalResponse = RestClient.CreateOrUpdate(name, resourceDetails, cancellationToken);
return new ResourceGroupCreateOrUpdateOperation(Parent, originalResponse);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// The operation to create or update a resource group. Please note some properties can be set only during creation.
/// </summary>
/// <param name="name"> The name of the resource group. </param>
/// <param name="resourceDetails"> The desired resource group configuration. </param>
/// <param name="cancellationToken"> A token to allow the caller to cancel the call to the service. The default value is <see cref="CancellationToken.None" />. </param>
/// <returns> A <see cref="Task"/> that on completion returns an <see cref="Operation{ResourceGroup}"/> that allows polling for completion of the operation. </returns>
/// <remarks>
/// <see href="https://azure.github.io/azure-sdk/dotnet_introduction.html#dotnet-longrunning">Details on long running operation object.</see>
/// </remarks>
/// <exception cref="ArgumentException"> Name of the resource group cannot be null or a whitespace. </exception>
/// <exception cref="ArgumentNullException"> resourceDetails cannot be null. </exception>
public virtual async Task<ResourceGroupCreateOrUpdateOperation> StartCreateOrUpdateAsync(string name, ResourceGroupData resourceDetails, CancellationToken cancellationToken = default)
{
if (string.IsNullOrWhiteSpace(name))
throw new ArgumentException("name cannot be null or a whitespace.", nameof(name));
if (resourceDetails is null)
throw new ArgumentNullException(nameof(resourceDetails));
using var scope = Diagnostics.CreateScope("ResourceGroupContainer.StartCreateOrUpdate");
scope.Start();
try
{
var originalResponse = await RestClient.CreateOrUpdateAsync(name, resourceDetails, cancellationToken).ConfigureAwait(false);
return new ResourceGroupCreateOrUpdateOperation(Parent, originalResponse);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// List the resource groups for this subscription.
/// </summary>
/// <param name="filter"> The filter to apply on the operation.<br><br>You can filter by tag names and values. For example, to filter for a tag name and value, use $filter=tagName eq 'tag1' and tagValue eq 'Value1'. </param>
/// <param name="top"> The number of results to return. If null is passed, returns all resource groups. </param>
/// <param name="cancellationToken"> A token to allow the caller to cancel the call to the service. The default value is <see cref="CancellationToken.None" />. </param>
/// <returns> A collection of resource operations that may take multiple service requests to iterate over. </returns>
[ForwardsClientCalls]
public virtual Pageable<ResourceGroup> GetAll(string filter = null, int? top = null, CancellationToken cancellationToken = default)
{
Page<ResourceGroup> FirstPageFunc(int? pageSizeHint)
{
using var scope = Diagnostics.CreateScope("ResourceGroupContainer.GetAll");
scope.Start();
try
{
var response = RestClient.List(filter, top, cancellationToken);
return Page.FromValues(response.Value.Value.Select(data => new ResourceGroup(Parent, data)), response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
Page<ResourceGroup> NextPageFunc(string nextLink, int? pageSizeHint)
{
using var scope = Diagnostics.CreateScope("ResourceGroupContainer.GetAll");
scope.Start();
try
{
var response = RestClient.ListNextPage(nextLink, filter, top, cancellationToken);
return Page.FromValues(response.Value.Value.Select(data => new ResourceGroup(Parent, data)), response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
return PageableHelpers.CreateEnumerable(FirstPageFunc, NextPageFunc);
}
/// <summary>
/// List the resource groups for this subscription.
/// </summary>
/// <param name="filter"> The filter to apply on the operation.<br><br>You can filter by tag names and values. For example, to filter for a tag name and value, use $filter=tagName eq 'tag1' and tagValue eq 'Value1'. </param>
/// <param name="top"> The number of results to return. If null is passed, returns all resource groups. </param>
/// <param name="cancellationToken"> A token to allow the caller to cancel the call to the service. The default value is <see cref="CancellationToken.None" />. </param>
/// <returns> An async collection of resource operations that may take multiple service requests to iterate over. </returns>
[ForwardsClientCalls]
public virtual AsyncPageable<ResourceGroup> GetAllAsync(string filter = null, int? top = null, CancellationToken cancellationToken = default)
{
async Task<Page<ResourceGroup>> FirstPageFunc(int? pageSizeHint)
{
using var scope = Diagnostics.CreateScope("ResourceGroupContainer.GetAll");
scope.Start();
try
{
var response = await RestClient.ListAsync(filter, top, cancellationToken).ConfigureAwait(false);
return Page.FromValues(response.Value.Value.Select(data => new ResourceGroup(Parent, data)), response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
async Task<Page<ResourceGroup>> NextPageFunc(string nextLink, int? pageSizeHint)
{
using var scope = Diagnostics.CreateScope("ResourceGroupContainer.GetAll");
scope.Start();
try
{
var response = await RestClient.ListNextPageAsync(nextLink, filter, top, cancellationToken).ConfigureAwait(false);
return Page.FromValues(response.Value.Value.Select(data => new ResourceGroup(Parent, data)), response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
return PageableHelpers.CreateAsyncEnumerable(FirstPageFunc, NextPageFunc);
}
/// <summary>
/// Gets details for this resource group from the service.
/// </summary>
/// <param name="resourceGroupName"> The name of the resource group get. </param>
/// <param name="cancellationToken"> A token to allow the caller to cancel the call to the service. The default value is <see cref="CancellationToken.None" />. </param>
/// <returns> A response with the <see cref="Response{ResourceGroup}"/> operation for this resource group. </returns>
/// <exception cref="ArgumentException"> resourceGroupName cannot be null or a whitespace. </exception>
public Response<ResourceGroup> Get(string resourceGroupName, CancellationToken cancellationToken = default)
{
using var scope = Diagnostics.CreateScope("ResourceGroupContainer.Get");
scope.Start();
try
{
var result = RestClient.Get(resourceGroupName, cancellationToken);
return Response.FromValue(new ResourceGroup(Parent, result), result.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Gets details for this resource group from the service.
/// </summary>
/// <param name="resourceGroupName"> The name of the resource group get. </param>
/// <param name="cancellationToken"> A token to allow the caller to cancel the call to the service. The default value is <see cref="CancellationToken.None" />. </param>
/// <returns> A <see cref="Task"/> that on completion returns a response with the <see cref="Response{ResourceGroup}"/> operation for this resource group. </returns>
/// <exception cref="ArgumentException"> resourceGroupName cannot be null or a whitespace. </exception>
public virtual async Task<Response<ResourceGroup>> GetAsync(string resourceGroupName, CancellationToken cancellationToken = default)
{
using var scope = Diagnostics.CreateScope("ResourceGroupContainer.Get");
scope.Start();
try
{
var result = await RestClient.GetAsync(resourceGroupName, cancellationToken).ConfigureAwait(false);
return Response.FromValue(new ResourceGroup(Parent, result), result.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
}
}
| 51.082005 | 264 | 0.613824 | [
"MIT"
] | OlhaTkachenko/azure-sdk-for-net | sdk/resourcemanager/Azure.ResourceManager/src/Generated/Resources/ResourceGroupContainer.cs | 22,427 | C# |
using COMMONConfig.Frontend.Models;
using COMMONConfig.Frontend.ViewModel.AbstractClasses;
using COMMONConfig.Frontend.Views.UserContols;
using gov.sandia.sld.common.configuration;
namespace COMMONConfig.Frontend.ViewModel
{
public class SystemDeviceViewModel : ADeviceControlViewModel
{
public override AbstractUserControl MakeControl()
{
return new GenericDeviceUserControl();
}
protected override DeviceType GetDeviceType()
{
return DeviceType.System;
}
private int CountDevices()
{
return 1;
}
protected override string GetDeviceName()
{
return "System";
}
}
} | 24.166667 | 64 | 0.642759 | [
"MIT"
] | gaybro8777/common | src/COMMONConfig/Frontend/ViewModel/SystemDeviceViewModel.cs | 727 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;
using System.Windows;
namespace FileExplorer.WPF.UserControls
{
public class VirtualStackPanelView : ViewBase
{
public static readonly DependencyProperty OrientationProperty =
VirtualStackPanel.OrientationProperty.AddOwner(typeof(VirtualStackPanelView));
public Orientation Orientation
{
get { return (Orientation)GetValue(OrientationProperty); }
set { SetValue(OrientationProperty, value); }
}
public static readonly DependencyProperty SmallChangesProperty =
VirtualStackPanel.SmallChangesProperty.AddOwner(typeof(VirtualStackPanelView));
public uint SmallChanges
{
get { return (uint)GetValue(SmallChangesProperty); }
set { SetValue(SmallChangesProperty, value); }
}
public static readonly DependencyProperty ItemContainerStyleProperty =
ItemsControl.ItemContainerStyleProperty.AddOwner(typeof(VirtualStackPanelView));
public Style ItemContainerStyle
{
get { return (Style)GetValue(ItemContainerStyleProperty); }
set { SetValue(ItemContainerStyleProperty, value); }
}
public static readonly DependencyProperty ItemTemplateProperty =
ItemsControl.ItemTemplateProperty.AddOwner(typeof(VirtualStackPanelView));
public DataTemplate ItemTemplate
{
get { return (DataTemplate)GetValue(ItemTemplateProperty); }
set { SetValue(ItemTemplateProperty, value); }
}
public static readonly DependencyProperty ItemWidthProperty =
VirtualStackPanel.ItemWidthProperty.AddOwner(typeof(VirtualStackPanelView));
public double ItemWidth
{
get { return (double)GetValue(ItemWidthProperty); }
set { SetValue(ItemWidthProperty, value); }
}
public static readonly DependencyProperty ItemHeightProperty =
VirtualStackPanel.ItemHeightProperty.AddOwner(typeof(VirtualStackPanelView));
public double ItemHeight
{
get { return (double)GetValue(ItemHeightProperty); }
set { SetValue(ItemHeightProperty, value); }
}
public static readonly DependencyProperty HorizontalContentAlignmentProperty =
StackPanel.HorizontalAlignmentProperty.AddOwner(typeof(VirtualStackPanelView));
public HorizontalAlignment HorizontalContentAlignment
{
get { return (HorizontalAlignment)GetValue(HorizontalContentAlignmentProperty); }
set { SetValue(HorizontalContentAlignmentProperty, value); }
}
public static readonly DependencyProperty CacheItemCountProperty =
DependencyProperty.Register("CacheItemCount", typeof(int),
typeof(VirtualStackPanelView), new UIPropertyMetadata(0));
public int CacheItemCount
{
get { return (int)GetValue(CacheItemCountProperty); }
set { SetValue(CacheItemCountProperty, value); }
}
private GridViewColumnCollection _columns = new GridViewColumnCollection();
public GridViewColumnCollection Columns
{
get { return _columns; }
}
public static readonly DependencyProperty ColumnHeaderContainerStyleProperty =
GridView.ColumnHeaderContainerStyleProperty.AddOwner(typeof(VirtualStackPanelView));
public Style ColumnHeaderContainerStyle
{
get { return (Style)GetValue(ColumnHeaderContainerStyleProperty); }
set { SetValue(ColumnHeaderContainerStyleProperty, value); }
}
public static readonly DependencyProperty ColumnHeaderTemplateProperty =
GridView.ColumnHeaderTemplateProperty.AddOwner(typeof(VirtualStackPanelView));
public static readonly DependencyProperty ColumnHeaderTemplateSelectorProperty =
GridView.ColumnHeaderTemplateSelectorProperty.AddOwner(typeof(VirtualStackPanelView));
public static readonly DependencyProperty ColumnHeaderStringFormatProperty =
GridView.ColumnHeaderStringFormatProperty.AddOwner(typeof(VirtualStackPanelView));
public static readonly DependencyProperty AllowsColumnReorderProperty =
GridView.AllowsColumnReorderProperty.AddOwner(typeof(VirtualStackPanelView));
public static readonly DependencyProperty ColumnHeaderContextMenuProperty =
GridView.ColumnHeaderContextMenuProperty.AddOwner(typeof(VirtualStackPanelView));
public static readonly DependencyProperty ColumnHeaderToolTipProperty =
GridView.ColumnHeaderToolTipProperty.AddOwner(typeof(VirtualStackPanelView));
protected override object DefaultStyleKey
{
get
{
return new ComponentResourceKey(GetType(), "virtualStackPanelViewDSK");
}
}
protected override object ItemContainerDefaultStyleKey
{
get
{
return new ComponentResourceKey(GetType(), "virtualStackPanelViewItemDSK");
}
}
}
}
| 41.098485 | 104 | 0.672627 | [
"MIT"
] | chengming0916/FileExplorer | src/FileExplorer3/app/FileExplorer3.WPF/BaseControls/VirutalStackPanelView.cs | 5,427 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using SistemaConsultorio.Dominio;
using WcfSistemaConsultorio;
namespace WfaSistemaConsultorio
{
public partial class FrmPrincipal : Form
{
private PacienteServico servicoPaciente = new PacienteServico();
DentistaServico servicoDentista = new DentistaServico();
private ConsultaServico servicoConsulta = new ConsultaServico();
public FrmPrincipal()
{
InitializeComponent();
IniciarFormulario();
}
public void IniciarFormulario()
{
try
{
var lstDentistas = new Dictionary<int, string>();
var lista = servicoDentista.BuscarTodos();
if (lista == null)
{
lstDentistas.Add(0, "Nenhum dentista cadastrado");
}
else
{
foreach (var item in lista)
{
lstDentistas.Add(item.Id, item.Nome);
}
}
cmbDentistaAgenda.DataSource = new BindingSource(lstDentistas, null);
cmbDentistaAgenda.DisplayMember = "Value";
cmbDentistaAgenda.ValueMember = "Key";
atualizarAgenda(Convert.ToInt32(cmbDentistaAgenda.SelectedValue));
}
catch
{
MessageBox.Show("Aparentemente o banco de dados não esta configurado corretamente, entre em contato com o administrador do sistema");
}
}
private void atualizarAgenda(int idDentista)
{
Dentista dentista = new Dentista();
dentista = servicoDentista.Buscar(idDentista);
if (dentista != null)
{
dgvAgendaDia.Rows.Clear();
gerarAgendaDiaria(dentista);
}
}
private void gerarAgendaDiaria (Dentista dentista)
{
var consultasHoje = servicoConsulta.Buscar(dentista, Convert.ToDateTime(DateTime.Now.ToString("dd/MM/yyyy"))).OrderBy(c => c.HoraMarcada);
if (consultasHoje == null)
{
MessageBox.Show("Esse dentista não possui pacientes hoje");
}
else
{
foreach (var item in consultasHoje)
{
int linha = dgvAgendaDia.Rows.Add();
dgvAgendaDia.Rows[linha].Cells[0].Value = item.IdConsulta;
dgvAgendaDia.Rows[linha].Cells[1].Value = item.HoraMarcada.Value.ToString("HH:mm");
dgvAgendaDia.Rows[linha].Cells[2].Value = servicoPaciente.Buscar(item.IdPaciente).Nome; //esta busca retorna um Paciente
dgvAgendaDia.Rows[linha].Cells[3].Value = imagemStatus(item.Status);
dgvAgendaDia.Rows[linha].Cells[4].Value = item.IdPaciente;
}
}
}
private void dgvAgendaDia_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == 2 && e.RowIndex != -1)
{
DataGridView dgv = sender as DataGridView;
int id = Convert.ToInt32(dgv.Rows[e.RowIndex].Cells[4].Value);
Paciente p = servicoPaciente.Buscar(id);
Vizualizar.FrmVizualizarPaciente verPaciente = new Vizualizar.FrmVizualizarPaciente(p);
verPaciente.Show();
}
if (e.ColumnIndex == 3 && e.RowIndex != -1)
{
var Id = Convert.ToInt32(dgvAgendaDia.Rows[e.RowIndex].Cells[0].Value);
Consulta c = servicoConsulta.Buscar(Id);
string s = c.Status;
switch (s)
{
case "Confirmado":
c.Status = "Desmarcado";
break;
case "Desmarcado":
c.Status = "Ja chegou";
break;
case "Ja chegou":
c.Status = "Em atendimento";
break;
case "Em atendimento":
c.Status = "Nao confirmado";
break;
case "Nao confirmado":
c.Status = "Confirmado";
break;
default:
c.Status = "Nao confirmado";
break;
}
servicoConsulta.Atualizar(c);
atualizarAgenda(Convert.ToInt32(cmbDentistaAgenda.SelectedValue));
}
}
private Bitmap imagemStatus (string s)
{
var imagem = new Bitmap(Properties.Resources.Circle_Grey);
switch(s)
{
case "Confirmado":
imagem = new Bitmap(Properties.Resources.Circle_Blue);
break;
case "Desmarcado":
imagem = new Bitmap(Properties.Resources.Circle_Red);
break;
case "Nao confirmado":
imagem = new Bitmap(Properties.Resources.Circle_Grey);
break;
case "Ja chegou":
imagem = new Bitmap(Properties.Resources.Circle_Orange);
break;
case "Em atendimento":
imagem = new Bitmap(Properties.Resources.Circle_Green);
break;
default:
imagem = new Bitmap(Properties.Resources.address171);
break;
}
return imagem;
}
private void dentistaToolStripMenuItem_Click(object sender, EventArgs e)
{
FrmCadastrarDentista FormDentista = new FrmCadastrarDentista();
FormDentista.ShowDialog();
}
private void pacienteToolStripMenuItem_Click(object sender, EventArgs e)
{
FrmCadastarPaciente FormPaciente = new FrmCadastarPaciente();
FormPaciente.ShowDialog();
}
private void consultaToolStripMenuItem_Click(object sender, EventArgs e)
{
Agenda.FrmAgendaCompleta agenda = new Agenda.FrmAgendaCompleta();
agenda.Show();
FrmCadastrarConsulta FormConsulta = new FrmCadastrarConsulta();
FormConsulta.Show();
}
private void consultasToolStripMenuItem_Click(object sender, EventArgs e)
{
Agenda.FrmAgendaCompleta form = new Agenda.FrmAgendaCompleta();
form.Show();
}
private void dentistasToolStripMenuItem1_Click(object sender, EventArgs e)
{
Agenda.FrmDentistas form = new Agenda.FrmDentistas();
form.Show();
}
private void pacientesToolStripMenuItem_Click(object sender, EventArgs e)
{
Agenda.FrmPacientes form = new Agenda.FrmPacientes();
form.Show();
}
private void reportarProblemaToolStripMenuItem1_Click(object sender, EventArgs e)
{
Suporte.FrmReportarProblema form = new Suporte.FrmReportarProblema();
form.Show();
}
private void cmbDentistaAgenda_SelectionChangeCommitted(object sender, EventArgs e)
{
atualizarAgenda(Convert.ToInt32(cmbDentistaAgenda.SelectedValue));
}
private void FrmPrincipal_Activated(object sender, EventArgs e)
{
atualizarAgenda(Convert.ToInt32(cmbDentistaAgenda.SelectedValue));
}
private void btnAdicionarLembrete_Click(object sender, EventArgs e)
{
Inicio.FrmLembrete lembrete = new Inicio.FrmLembrete();
lembrete.ShowDialog();
RichTextBox postit = new RichTextBox();
postit.ReadOnly = true;
postit.BorderStyle = BorderStyle.None;
postit.Font = new Font(FontFamily.GenericSansSerif, 15F);
postit.ForeColor = Color.FromArgb(64, 64, 64);
postit.Width = 200;
postit.Height = 200;
postit.BackColor = lembrete.cor;
postit.Text = lembrete.texto;
flowLayoutPanel1.Controls.Add(postit);
}
}
}
| 38.302632 | 151 | 0.528112 | [
"MIT"
] | MarcosJAOJR/Consult-rio-Odonto-Consultas | WfaSistemaConsultorio/Inicio/FrmPrincipal.cs | 8,737 | C# |
// LeoSingleton.CommonLibs - Common Libraries for TypeScript and .NET Core
// Copyright (c) Leo C. Singleton IV <leo@leosingleton.com>
// See LICENSE in the project root for license information.
namespace LeoSingleton.CommonLibs
{
/// <summary>
/// .NET's built-in BinaryReader/BinaryWriter doesn't support network byte order, nor does the BitConverter class.
/// So we build our own...
/// </summary>
public static class BinaryConverter
{
/// <summary>
/// Reads an unsigned 64-bit integer from a binary buffer
/// </summary>
/// <param name="buffer">Input buffer</param>
/// <param name="startIndex">Starting offset, in bytes</param>
/// <returns>Unsigned 64-bit integer</returns>
public static ulong ReadUInt64(byte[] buffer, int startIndex)
{
return ((ulong)buffer[startIndex] << 56) |
((ulong)buffer[startIndex + 1] << 48) |
((ulong)buffer[startIndex + 2] << 40) |
((ulong)buffer[startIndex + 3] << 32) |
((ulong)buffer[startIndex + 4] << 24) |
((ulong)buffer[startIndex + 5] << 16) |
((ulong)buffer[startIndex + 6] << 8) |
(ulong)buffer[startIndex + 7];
}
/// <summary>
/// Writes an unsigned 64-bit integer to a binary buffer
/// </summary>
/// <param name="buffer">Output buffer</param>
/// <param name="startIndex">Starting offset, in bytes</param>
/// <param name="value">Unsigned 64-bit integer</param>
public static void Write(byte[] buffer, int startIndex, ulong value)
{
buffer[startIndex] = (byte)((value & 0xff00000000000000) >> 56);
buffer[startIndex + 1] = (byte)((value & 0xff000000000000) >> 48);
buffer[startIndex + 2] = (byte)((value & 0xff0000000000) >> 40);
buffer[startIndex + 3] = (byte)((value & 0xff00000000) >> 32);
buffer[startIndex + 4] = (byte)((value & 0xff000000) >> 24);
buffer[startIndex + 5] = (byte)((value & 0xff0000) >> 16);
buffer[startIndex + 6] = (byte)((value & 0xff00) >> 8);
buffer[startIndex + 7] = (byte)(value & 0xff);
}
/// <summary>
/// Reads a signed 32-bit integer from a binary buffer
/// </summary>
/// <param name="buffer">Input buffer</param>
/// <param name="startIndex">Starting offset, in bytes</param>
/// <returns>Signed 32-bit integer</returns>
public static int ReadInt32(byte[] buffer, int startIndex)
{
return (buffer[startIndex] << 24) |
(buffer[startIndex + 1] << 16) |
(buffer[startIndex + 2] << 8) |
buffer[startIndex + 3];
}
/// <summary>
/// Writes a signed 32-bit integer to a binary buffer
/// </summary>
/// <param name="buffer">Output buffer</param>
/// <param name="startIndex">Starting offset, in bytes</param>
/// <param name="value">Signed 32-bit integer</param>
public static void Write(byte[] buffer, int startIndex, int value)
{
buffer[startIndex] = (byte)((value & 0xff000000) >> 24);
buffer[startIndex + 1] = (byte)((value & 0xff0000) >> 16);
buffer[startIndex + 2] = (byte)((value & 0xff00) >> 8);
buffer[startIndex + 3] = (byte)(value & 0xff);
}
/// <summary>
/// Reads an unsigned 16-bit integer from a binary buffer
/// </summary>
/// <param name="buffer">Input buffer</param>
/// <param name="startIndex">Starting offset, in bytes</param>
/// <returns>Unsigned 16-bit integer</returns>
public static ushort ReadUInt16(byte[] buffer, int startIndex)
{
return (ushort)((buffer[startIndex] << 8) | buffer[startIndex + 1]);
}
/// <summary>
/// Writes an unsigned 16-bit integer to a binary buffer
/// </summary>
/// <param name="buffer">Output buffer</param>
/// <param name="startIndex">Starting offset, in bytes</param>
/// <param name="value">Unsigned 16-bit integer</param>
public static void Write(byte[] buffer, int startIndex, ushort value)
{
buffer[startIndex] = (byte)((value & 0xff00) >> 8);
buffer[startIndex + 1] = (byte)(value & 0xff);
}
/// <summary>
/// Reads a signed 16-bit integer from a binary buffer
/// </summary>
/// <param name="buffer">Input buffer</param>
/// <param name="startIndex">Starting offset, in bytes</param>
/// <returns>Signed 16-bit integer</returns>
public static short ReadInt16(byte[] buffer, int startIndex)
{
return (short)((buffer[startIndex] << 8) | buffer[startIndex + 1]);
}
/// <summary>
/// Writes an signed 16-bit integer to a binary buffer
/// </summary>
/// <param name="buffer">Output buffer</param>
/// <param name="startIndex">Starting offset, in bytes</param>
/// <param name="value">Signed 16-bit integer</param>
public static void Write(byte[] buffer, int startIndex, short value)
{
buffer[startIndex] = (byte)((value & 0xff00) >> 8);
buffer[startIndex + 1] = (byte)(value & 0xff);
}
}
}
| 43.91129 | 118 | 0.554821 | [
"MIT"
] | leosingleton/commonlibs | dotnet/CommonLibs/BinaryConverter.cs | 5,447 | C# |
//******************************************************************************************************
// SystemSettings.xaml.cs - Gbtc
//
// Copyright © 2010, Grid Protection Alliance. All Rights Reserved.
//
// Licensed to the Grid Protection Alliance (GPA) under one or more contributor license agreements. See
// the NOTICE file distributed with this work for additional information regarding copyright ownership.
// The GPA licenses this file to you under the Eclipse Public License -v 1.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.opensource.org/licenses/eclipse-1.0.php
//
// Unless agreed to in writing, the subject software distributed under the License is distributed on an
// "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the
// License for the specific language governing permissions and limitations.
//
// Code Modification History:
// ----------------------------------------------------------------------------------------------------
// 04/09/2010 - Mehulbhai P Thakkar
// Generated original version of source code.
//
//******************************************************************************************************
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Animation;
using System.Windows.Navigation;
using openPDCManager.ModalDialogs;
using openPDCManager.Utilities;
namespace openPDCManager.Pages.Manage
{
public partial class SystemSettings : Page
{
#region [ Constructor ]
public SystemSettings()
{
InitializeComponent();
this.Loaded += new RoutedEventHandler(SystemSettings_Loaded);
ButtonSave.Click += new RoutedEventHandler(ButtonSave_Click);
ButtonClear.Click += new RoutedEventHandler(ButtonClear_Click);
}
#endregion
#region [ Controls Event Handlers ]
void ButtonClear_Click(object sender, RoutedEventArgs e)
{
Storyboard sb = new Storyboard();
sb = Application.Current.Resources["ButtonPressAnimation"] as Storyboard;
sb.Completed += new EventHandler(delegate(object obj, EventArgs es) { sb.Stop(); });
Storyboard.SetTarget(sb, ButtonClearTransform);
sb.Begin();
//Load Default Settings.
ProxyClient.SetDefaultSystemSettings(true);
LoadSettingsFromIsolatedStorage();
SystemMessages sm = new SystemMessages(new Message() { UserMessage = "Successfully Restored Default System Settings", SystemMessage = string.Empty, UserMessageType = MessageType.Success },
ButtonType.OkOnly);
sm.ShowPopup();
}
void ButtonSave_Click(object sender, RoutedEventArgs e)
{
Storyboard sb = new Storyboard();
sb = Application.Current.Resources["ButtonPressAnimation"] as Storyboard;
sb.Completed += new EventHandler(delegate(object obj, EventArgs es) { sb.Stop(); });
Storyboard.SetTarget(sb, ButtonSaveTransform);
sb.Begin();
if (!string.IsNullOrEmpty(TextBoxDefaultWidth.Text))
IsolatedStorageManager.SaveIntoIsolatedStorage("DefaultWidth", Convert.ToInt32(TextBoxDefaultWidth.Text));
if (!string.IsNullOrEmpty(TextBoxDefaultHeight.Text))
IsolatedStorageManager.SaveIntoIsolatedStorage("DefaultHeight", Convert.ToInt32(TextBoxDefaultHeight.Text));
if (!string.IsNullOrEmpty(TextBoxMinimumWidth.Text))
IsolatedStorageManager.SaveIntoIsolatedStorage("MinimumWidth", Convert.ToInt32(TextBoxMinimumWidth.Text));
if (!string.IsNullOrEmpty(TextBoxMinimumHeight.Text))
IsolatedStorageManager.SaveIntoIsolatedStorage("MinimumHeight", Convert.ToInt32(TextBoxMinimumHeight.Text));
IsolatedStorageManager.SaveIntoIsolatedStorage("ResizeWithBrowser", CheckboxResizeWithBrowser.IsChecked);
IsolatedStorageManager.SaveIntoIsolatedStorage("MaintainAspectRatio", CheckboxMaintainAspectRatio.IsChecked);
IsolatedStorageManager.SaveIntoIsolatedStorage("ForceIPv4", CheckboxForceIPv4.IsChecked);
if (!string.IsNullOrEmpty(TextBoxNumberOfMessagesOnMonitor.Text))
IsolatedStorageManager.SaveIntoIsolatedStorage("NumberOfMessagesOnMonitor", Convert.ToInt32(TextBoxNumberOfMessagesOnMonitor.Text));
LoadSettingsFromIsolatedStorage();
SystemMessages sm = new SystemMessages(new Message() { UserMessage = "Successfully Saved System Settings", SystemMessage = string.Empty, UserMessageType = MessageType.Success },
ButtonType.OkOnly);
sm.ShowPopup();
}
#endregion
#region [ Page Event Handlers ]
void SystemSettings_Loaded(object sender, RoutedEventArgs e)
{
LoadSettingsFromIsolatedStorage();
}
// Executes when the user navigates to this page.
protected override void OnNavigatedTo(NavigationEventArgs e)
{
}
#endregion
#region [ Methods ]
void LoadSettingsFromIsolatedStorage()
{
TextBoxDefaultWidth.Text = IsolatedStorageManager.LoadFromIsolatedStorage("DefaultWidth").ToString();
TextBoxDefaultHeight.Text = IsolatedStorageManager.LoadFromIsolatedStorage("DefaultHeight").ToString();
TextBoxMinimumWidth.Text = IsolatedStorageManager.LoadFromIsolatedStorage("MinimumWidth").ToString();
TextBoxMinimumHeight.Text = IsolatedStorageManager.LoadFromIsolatedStorage("MinimumHeight").ToString();
TextBoxNumberOfMessagesOnMonitor.Text = IsolatedStorageManager.LoadFromIsolatedStorage("NumberOfMessagesOnMonitor").ToString();
CheckboxResizeWithBrowser.IsChecked = (bool)IsolatedStorageManager.LoadFromIsolatedStorage("ResizeWithBrowser");
CheckboxMaintainAspectRatio.IsChecked = (bool)IsolatedStorageManager.LoadFromIsolatedStorage("MaintainAspectRatio");
CheckboxForceIPv4.IsChecked = (bool)IsolatedStorageManager.LoadFromIsolatedStorage("ForceIPv4");
}
#endregion
}
}
| 42.330882 | 191 | 0.7358 | [
"MIT"
] | GridProtectionAlliance/openPDC | Source/Applications/openPDCManager/Silverlight/Pages/Manage/SystemSettings.xaml.cs | 5,760 | C# |
using System;
using System.Threading.Tasks;
using AutoStep.Language;
using AutoStep.Tests.Builders;
using AutoStep.Tests.Utils;
using Xunit;
using Xunit.Abstractions;
namespace AutoStep.Tests.Language.Interaction.Parser
{
/// <summary>
/// Method Definition Parsing behaviour is the same for traits and components,
/// so these tests should cover declaring them in both places.
/// </summary>
public class MethodDefinitionTests : InteractionsCompilerTestBase
{
public MethodDefinitionTests(ITestOutputHelper outputHelper) : base(outputHelper)
{
}
[Fact]
public async Task DeclareMethod()
{
const string Test = @"
Component: button
method(name1, name2): call('label')
";
await CompileAndAssertSuccess(Test, cfg => cfg
.Component("button", 2, 17, comp => comp
.Method("method", 4, 21, m => m
.Argument("name1", 4, 28)
.Argument("name2", 4, 35)
.Call("call", 4, 43, 4, 55, c => c
.String("label", 48)
)
)
));
}
[Fact]
public async Task UnterminatedDeclaration()
{
const string Test = @"
Component: button
method(name1, name2: call('label')
";
await CompileAndAssertErrors(Test, cfg => cfg
.Component("button", 2, 17, comp => comp
.Method("method", 4, 21, m => m
.Argument("name1", 4, 28)
.Argument("name2", 4, 35)
.Call("call", 4, 42, 4, 54, c => c
.String("label", 47)
)
)
),
LanguageMessageFactory.Create(null, CompilerMessageLevel.Error, CompilerMessageCode.InteractionMethodDeclUnterminated, 4, 40, 4, 40));
}
[Fact]
public async Task MissingExtraArg()
{
const string Test = @"
Component: button
method(name1, ): call('label')
";
await CompileAndAssertErrors(Test, cfg => cfg
.Component("button", 2, 17, comp => comp
.Method("method", 4, 21, 4, 35, m => m
.Argument("name1", 4, 28)
.Call("call", 4, 38, 4, 50, c => c
.String("label", 43)
)
)
),
LanguageMessageFactory.Create(null, CompilerMessageLevel.Error, CompilerMessageCode.InteractionMethodDeclMissingParameter, 4, 33, 4, 35));
}
[Fact]
public async Task MethodCanHaveDocumentation()
{
const string Test = @"
Component: button
## Method Documentation Line 1
## Indented
## Another line
method(name1, name2): call('label')
";
string Docs = string.Join(Environment.NewLine, new[]
{
"Method Documentation Line 1",
" Indented",
" Another line"
});
await CompileAndAssertSuccess(Test, cfg => cfg
.Component("button", 2, 17, comp => comp
.Method("method", 7, 21, m => m
.Argument("name1", 7, 28)
.Argument("name2", 7, 35)
.Documentation(Docs)
.Call("call", 7, 43, 7, 55, c => c
.String("label", 48)
)
)
));
}
[Fact]
public async Task MethodCanHaveDocumentationPadding()
{
const string Test = @"
Component: button
##
## Method Documentation Line 1
## Indented
## Another line
##
method(name1, name2): call('label')
";
string Docs = string.Join(Environment.NewLine, new[]
{
"Method Documentation Line 1",
" Indented",
" Another line",
});
await CompileAndAssertSuccess(Test, cfg => cfg
.Component("button", 2, 17, comp => comp
.Method("method", 9, 21, m => m
.Argument("name1", 9, 28)
.Argument("name2", 9, 35)
.Documentation(Docs)
.Call("call", 9, 43, 9, 55, c => c
.String("label", 48)
)
)
));
}
[Fact]
public async Task MethodCanHaveDocumentationBlankLines()
{
const string Test = @"
Component: button
##
## Method Documentation Line 1
## Indented
##
## Another line
##
method(name1, name2): call('label')
";
string Docs = string.Join(Environment.NewLine, new[]
{
"Method Documentation Line 1",
" Indented",
"",
" Another line",
});
await CompileAndAssertSuccess(Test, cfg => cfg
.Component("button", 2, 17, comp => comp
.Method("method", 10, 21, m => m
.Argument("name1", 10, 28)
.Argument("name2", 10, 35)
.Documentation(Docs)
.Call("call", 10, 43, 10, 55, c => c
.String("label", 48)
)
)
));
}
[Fact]
public async Task MethodDefinitionMissingSeparator()
{
const string Test = @"
Component: button
method(name1 name2): call('label')
";
await CompileAndAssertErrors(Test, cfg => cfg
.Component("button", 2, 17, comp => comp
.Method("method", 4, 21, 4, 39, m => m
.Argument("name1", 4, 28)
.Call("call", 4, 42, 4, 54, c => c
.String("label", 47)
)
)
),
LanguageMessageFactory.Create(null, CompilerMessageLevel.Error, CompilerMessageCode.InteractionMethodDeclMissingParameterSeparator, 4, 34, 4, 38));
}
[Fact]
public async Task MethodDefinitionUnexpectedString()
{
const string Test = @"
Component: button
method(name1, 'something'): call('label')
";
await CompileAndAssertErrors(Test, cfg => cfg
.Component("button", 2, 17, comp => comp
.Method("method", 4, 21, 4, 46, m => m
.Argument("name1", 4, 28)
.Call("call", 4, 49, 4, 61, c => c
.String("label", 54)
)
)
),
LanguageMessageFactory.Create(null, CompilerMessageLevel.Error, CompilerMessageCode.InteractionMethodDeclUnexpectedContent, 4, 35, 4, 45));
}
[Fact]
public async Task MethodDefinitionUnexpectedFloat()
{
const string Test = @"
Component: button
method(name1, 123.5): call('label')
";
await CompileAndAssertErrors(Test, cfg => cfg
.Component("button", 2, 17, comp => comp
.Method("method", 4, 21, 4, 40, m => m
.Argument("name1", 4, 28)
.Call("call", 4, 43, 4, 55, c => c
.String("label", 48)
)
)
),
LanguageMessageFactory.Create(null, CompilerMessageLevel.Error, CompilerMessageCode.InteractionMethodDeclUnexpectedContent, 4, 35, 4, 39));
}
[Fact]
public async Task MethodDefinitionUnexpectedInt()
{
const string Test = @"
Component: button
method(name1, 123): call('label')
";
await CompileAndAssertErrors(Test, cfg => cfg
.Component("button", 2, 17, comp => comp
.Method("method", 4, 21, 4, 38, m => m
.Argument("name1", 4, 28)
.Call("call", 4, 41, 4, 53, c => c
.String("label", 46)
)
)
),
LanguageMessageFactory.Create(null, CompilerMessageLevel.Error, CompilerMessageCode.InteractionMethodDeclUnexpectedContent, 4, 35, 4, 37));
}
[Fact]
public async Task MethodDefinitionUnexpectedConstant()
{
const string Test = @"
Component: button
method(name1, TAB): call('label')
";
await CompileAndAssertErrors(Test, cfg => cfg
.Component("button", 2, 17, comp => comp
.Method("method", 4, 21, 4, 38, m => m
.Argument("name1", 4, 28)
.Call("call", 4, 41, 4, 53, c => c
.String("label", 46)
)
)
),
LanguageMessageFactory.Create(null, CompilerMessageLevel.Error, CompilerMessageCode.InteractionMethodDeclUnexpectedContent, 4, 35, 4, 37));
}
[Fact]
public async Task MethodDefinitionUnterminatedString()
{
const string Test = @"
Component: button
method(name1, 'something): call()
";
await CompileAndAssertErrors(Test, cfg => cfg
.Component("button", 2, 17, comp => comp
.Method("method", 4, 21, 4, 53, m => m
.Argument("name1", 4, 28)
)
),
LanguageMessageFactory.Create(null, CompilerMessageLevel.Error, CompilerMessageCode.InteractionUnterminatedString, 4, 35, 4, 53));
}
[Fact]
public async Task MethodDefinitionUnterminatedStringCanContinueParseWithPartialDefinitionMatch()
{
const string Test = @"
Component: button
method(name1, 'something): call()
-> call2()
method2(): needs-defining
";
await CompileAndAssertErrors(Test, cfg => cfg
.Component("button", 2, 17, comp => comp
.Method("method", 4, 21, 5, 26, m => m
.Argument("name1", 4, 28)
.Call("call2", 5, 28, 5, 34)
)
.Method("method2", 7, 21, m => m
.NeedsDefining()
)
),
LanguageMessageFactory.Create(null, CompilerMessageLevel.Error, CompilerMessageCode.InteractionUnterminatedString, 4, 35, 4, 53));
}
[Fact]
public async Task MethodDefinitionUnterminatedStringCanContinueParseWithCallOnNextLine()
{
const string Test = @"
Component: button
method(name1, 'something):
-> call()
method2(): needs-defining
";
await CompileAndAssertErrors(Test, cfg => cfg
.Component("button", 2, 17, comp => comp
.Method("method", 4, 21, 5, 26, m => m
.Argument("name1", 4, 28)
.Call("call", 5, 28, 5, 33)
)
.Method("method2", 7, 21, m => m
.NeedsDefining()
)
),
LanguageMessageFactory.Create(null, CompilerMessageLevel.Error, CompilerMessageCode.InteractionUnterminatedString, 4, 35, 4, 46));
}
[Fact]
public async Task MethodDefinitionUnterminatedStringCanContinueParse()
{
const string Test = @"
Component: button
method(name1, 'something): call()
method2(): needs-defining
";
await CompileAndAssertErrors(Test, cfg => cfg
.Component("button", 2, 17, comp => comp
.Method("method", 4, 21, 4, 53, m => m
.Argument("name1", 4, 28)
)
.Method("method2", 6, 21, m => m
.NeedsDefining()
)
),
LanguageMessageFactory.Create(null, CompilerMessageLevel.Error, CompilerMessageCode.InteractionUnterminatedString, 4, 35, 4, 53));
}
}
}
| 35.138021 | 163 | 0.434077 | [
"MIT"
] | SivaGudivada/AutoStep | tests/AutoStep.Tests/Language/Interaction/Parser/MethodDefinitionTests.cs | 13,495 | C# |
using System;
using System.ComponentModel;
using System.Net;
namespace KryptonSparkle.Interfaces
{
public interface IKryptonSparkleDownloadProgress
{
/// <summary>
/// event to fire when the form asks the application to be relaunched
/// </summary>
event EventHandler InstallAndRelaunch;
/// <summary>
/// Gets or sets the temporary file name where the new items are downloaded
/// </summary>
string TempFileName { get; set; }
/// <summary>
/// Gets or sets a flag indicating if the downloaded file matches its listed
/// DSA hash.
/// </summary>
bool IsDownloadDSAValid { get; set; }
/// <summary>
/// Show the UI and waits
/// </summary>
void ShowDialog();
/// <summary>
/// Called when the download progress changes
/// </summary>
/// <param name="sender">not used.</param>
/// <param name="e">used to resolve the progress of the download. Also contains the total size of the download</param>
void OnClientDownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e);
/// <summary>
/// Event called when the download of the binary is complete
/// </summary>
/// <param name="sender">not used.</param>
/// <param name="e">not used.</param>
void OnClientDownloadFileCompleted(object sender, AsyncCompletedEventArgs e);
}
} | 33.818182 | 126 | 0.610215 | [
"BSD-3-Clause"
] | Krypton-Suite-Legacy-Archive/Krypton-Toolkit-Suite-Extended-NET-5.470 | Source/Krypton Toolkit Suite Extended/Componentisation/Krypton Sparkle/Interfaces/IKryptonSparkleDownloadProgress.cs | 1,490 | C# |
using System.Collections.Generic;
namespace Hexalith.DataIntegrations.Domain.States
{
public interface IDataIntegrationState
{
dynamic? Data { get; set; }
string Description { get; set; }
string Document { get; set; }
string DocumentName { get; set; }
string DocumentType { get; set; }
string Name { get; set; }
void Apply(IEnumerable<object> events);
}
} | 26.625 | 49 | 0.624413 | [
"MIT"
] | Hexalith/Hexalith | src/Modules/Shared/Hexalith.DataIntegrations.Common/Domain/States/IDataIntegrationState.cs | 428 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the neptune-2014-10-31.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Serialization;
using Amazon.Neptune.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
namespace Amazon.Neptune.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for AddSourceIdentifierToSubscription operation
/// </summary>
public class AddSourceIdentifierToSubscriptionResponseUnmarshaller : XmlResponseUnmarshaller
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public override AmazonWebServiceResponse Unmarshall(XmlUnmarshallerContext context)
{
AddSourceIdentifierToSubscriptionResponse response = new AddSourceIdentifierToSubscriptionResponse();
context.Read();
int targetDepth = context.CurrentDepth;
while (context.ReadAtDepth(targetDepth))
{
if (context.IsStartElement)
{
if(context.TestExpression("AddSourceIdentifierToSubscriptionResult", 2))
{
UnmarshallResult(context, response);
continue;
}
if (context.TestExpression("ResponseMetadata", 2))
{
response.ResponseMetadata = ResponseMetadataUnmarshaller.Instance.Unmarshall(context);
}
}
}
return response;
}
private static void UnmarshallResult(XmlUnmarshallerContext context, AddSourceIdentifierToSubscriptionResponse response)
{
int originalDepth = context.CurrentDepth;
int targetDepth = originalDepth + 1;
if (context.IsStartOfDocument)
targetDepth += 2;
while (context.ReadAtDepth(originalDepth))
{
if (context.IsStartElement || context.IsAttribute)
{
if (context.TestExpression("EventSubscription", targetDepth))
{
var unmarshaller = EventSubscriptionUnmarshaller.Instance;
response.EventSubscription = unmarshaller.Unmarshall(context);
continue;
}
}
}
return;
}
/// <summary>
/// Unmarshaller error response to exception.
/// </summary>
/// <param name="context"></param>
/// <param name="innerException"></param>
/// <param name="statusCode"></param>
/// <returns></returns>
public override AmazonServiceException UnmarshallException(XmlUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode)
{
ErrorResponse errorResponse = ErrorResponseUnmarshaller.GetInstance().Unmarshall(context);
if (errorResponse.Code != null && errorResponse.Code.Equals("SourceNotFound"))
{
return new SourceNotFoundException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("SubscriptionNotFound"))
{
return new SubscriptionNotFoundException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
return new AmazonNeptuneException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
private static AddSourceIdentifierToSubscriptionResponseUnmarshaller _instance = new AddSourceIdentifierToSubscriptionResponseUnmarshaller();
internal static AddSourceIdentifierToSubscriptionResponseUnmarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static AddSourceIdentifierToSubscriptionResponseUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 39.022059 | 173 | 0.619371 | [
"Apache-2.0"
] | Bio2hazard/aws-sdk-net | sdk/src/Services/Neptune/Generated/Model/Internal/MarshallTransformations/AddSourceIdentifierToSubscriptionResponseUnmarshaller.cs | 5,307 | C# |
using System;
using System.Linq;
using HotChocolate;
using StrawberryShake.CodeGeneration.Descriptors.TypeDescriptors;
namespace StrawberryShake.CodeGeneration.Extensions
{
public static class TypeDescriptorExtensions
{
public static bool IsLeafType(this ITypeDescriptor typeDescriptor) =>
typeDescriptor.Kind == TypeKind.LeafType;
public static bool IsEntityType(this ITypeDescriptor typeDescriptor) =>
typeDescriptor.Kind == TypeKind.EntityType;
public static bool IsDataType(this ITypeDescriptor typeDescriptor) =>
typeDescriptor.Kind == TypeKind.DataType ||
typeDescriptor.Kind == TypeKind.ComplexDataType;
public static bool ContainsEntity(this ITypeDescriptor typeDescriptor)
{
return typeDescriptor switch
{
ListTypeDescriptor listTypeDescriptor =>
listTypeDescriptor.InnerType.ContainsEntity(),
ComplexTypeDescriptor namedTypeDescriptor =>
namedTypeDescriptor.Properties.Any(
prop => prop.Type.IsEntityType() || prop.Type.ContainsEntity()),
NonNullTypeDescriptor nonNullTypeDescriptor =>
nonNullTypeDescriptor.InnerType.ContainsEntity(),
_ => false
};
}
public static bool IsInterface(this ITypeDescriptor typeDescriptor) =>
typeDescriptor is InterfaceTypeDescriptor;
public static bool IsNullableType(this ITypeDescriptor typeDescriptor) =>
typeDescriptor is not NonNullTypeDescriptor;
public static bool IsNonNullableType(this ITypeDescriptor typeDescriptor) =>
typeDescriptor is NonNullTypeDescriptor;
public static bool IsListType(this ITypeDescriptor typeDescriptor) =>
typeDescriptor is ListTypeDescriptor ||
typeDescriptor is NonNullTypeDescriptor { InnerType: ListTypeDescriptor };
public static ITypeDescriptor InnerType(this ITypeDescriptor typeDescriptor)
{
if (typeDescriptor is NonNullTypeDescriptor n)
{
return n.InnerType;
}
if (typeDescriptor is ListTypeDescriptor l)
{
return l.InnerType;
}
return typeDescriptor;
}
public static ITypeDescriptor NamedType(this ITypeDescriptor typeDescriptor)
{
return typeDescriptor
.InnerType()
.InnerType()
.InnerType()
.InnerType()
.InnerType()
.InnerType();
}
public static NameString GetName(this ITypeDescriptor typeDescriptor)
{
if (typeDescriptor.NamedType() is INamedTypeDescriptor namedType)
{
return namedType.Name;
}
throw new InvalidOperationException("Invalid type structure.");
}
public static RuntimeTypeInfo GetRuntimeType(this ITypeDescriptor typeDescriptor)
{
if (typeDescriptor.NamedType() is INamedTypeDescriptor namedType)
{
return namedType.RuntimeType;
}
throw new InvalidOperationException("Invalid type structure.");
}
}
}
| 35.326316 | 89 | 0.623957 | [
"MIT"
] | VarunSaiTeja/hotchocolate | src/StrawberryShake/CodeGeneration/src/CodeGeneration/Extensions/TypeDescriptorExtensions.cs | 3,356 | C# |
using Stl.Fusion.Bridge.Messages;
using Stl.OS;
namespace Stl.Fusion.Bridge.Internal;
public class PublisherChannelProcessor : WorkerBase
{
private ILogger? _log;
protected readonly IServiceProvider Services;
protected readonly IPublisherImpl PublisherImpl;
protected readonly ConcurrentDictionary<Symbol, SubscriptionProcessor> Subscriptions;
protected ILogger Log => _log ??= Services.LogFor(GetType());
public readonly IPublisher Publisher;
public readonly Channel<BridgeMessage> Channel;
public PublisherChannelProcessor(
IPublisher publisher,
Channel<BridgeMessage> channel,
IServiceProvider services)
{
Services = services;
Publisher = publisher;
PublisherImpl = (IPublisherImpl) publisher;
Channel = channel;
Subscriptions = new ConcurrentDictionary<Symbol, SubscriptionProcessor>();
}
protected override async Task RunInternal(CancellationToken cancellationToken)
{
try {
var reader = Channel.Reader;
while (await reader.WaitToReadAsync(cancellationToken).ConfigureAwait(false))
while (reader.TryRead(out var request)) {
switch (request) {
case ReplicaRequest rr:
await OnReplicaRequest(rr, cancellationToken).ConfigureAwait(false);
break;
default:
await OnUnsupportedRequest(request, cancellationToken).ConfigureAwait(false);
break;
}
}
}
finally {
// Awaiting for disposal here = cyclic task dependency;
// we should just ensure it starts right when this method
// completes.
_ = DisposeAsync();
}
}
protected virtual async ValueTask OnUnsupportedRequest(BridgeMessage request, CancellationToken cancellationToken)
{
if (request is ReplicaRequest rr) {
var reply = new PublicationAbsentsReply() {
PublisherId = rr.PublisherId,
PublicationId = rr.PublicationId,
};
await Channel.Writer
.WriteAsync(reply, cancellationToken)
.ConfigureAwait(false);
}
}
public virtual async ValueTask OnReplicaRequest(ReplicaRequest request, CancellationToken cancellationToken)
{
if (request.PublisherId != Publisher.Id) {
await OnUnsupportedRequest(request, cancellationToken).ConfigureAwait(false);
return;
}
var publicationId = request.PublicationId;
var publication = Publisher.Get(publicationId);
if (publication == null) {
await OnUnsupportedRequest(request, cancellationToken).ConfigureAwait(false);
return;
}
if (Subscriptions.TryGetValue(publicationId, out var subscriptionProcessor))
goto subscriptionExists;
lock (Lock) {
// Double check locking
if (Subscriptions.TryGetValue(publicationId, out subscriptionProcessor))
goto subscriptionExists;
subscriptionProcessor = PublisherImpl.SubscriptionProcessorFactory.Create(
PublisherImpl.SubscriptionProcessorGeneric,
publication, Channel, PublisherImpl.SubscriptionExpirationTime,
PublisherImpl.Clocks, Services);
Subscriptions[publicationId] = subscriptionProcessor;
}
_ = subscriptionProcessor.Run()
.ContinueWith(_ => Unsubscribe(publication, default), TaskScheduler.Default);
subscriptionExists:
await subscriptionProcessor.IncomingChannel.Writer
.WriteAsync(request, cancellationToken).ConfigureAwait(false);
}
public virtual async ValueTask Unsubscribe(
IPublication publication, CancellationToken cancellationToken)
{
var publicationId = publication.Id;
if (!Subscriptions.TryRemove(publicationId, out var subscriptionProcessor))
return;
await subscriptionProcessor.DisposeAsync().ConfigureAwait(false);
}
protected virtual async Task RemoveSubscriptions()
{
// We can unsubscribe in parallel
var subscriptions = Subscriptions;
for (var i = 0; i < 2; i++) {
while (!subscriptions.IsEmpty) {
var tasks = subscriptions
.Take(HardwareInfo.GetProcessorCountFactor(4, 4))
.ToList()
.Select(p => Task.Run(async () => {
var (publicationId, _) = (p.Key, p.Value);
var publication = Publisher.Get(publicationId);
if (publication != null)
await Unsubscribe(publication, default).ConfigureAwait(false);
}));
await Task.WhenAll(tasks).ConfigureAwait(false);
}
// We repeat this twice in case some new subscriptions
// were still in process while we were unsubscribing.
// Since we don't know for sure how long it might take,
// we optimistically assume 10 seconds is enough for this.
await Task.Delay(TimeSpan.FromSeconds(10)).ConfigureAwait(false);
}
}
protected override async Task DisposeAsyncCore()
{
await base.DisposeAsyncCore().ConfigureAwait(false);
await RemoveSubscriptions().ConfigureAwait(false);
PublisherImpl.OnChannelProcessorDisposed(this);
}
}
| 39.75 | 118 | 0.628032 | [
"MIT"
] | servicetitan/Stl | src/Stl.Fusion/Bridge/Internal/PublisherChannelProcessor.cs | 5,565 | C# |
using System;
using System.Collections;
namespace UnityWeld.Binding
{
/// <summary>
/// A list that exposes the type of its items as a property.
/// </summary>
public interface ITypedList : IList
{
/// <summary>
/// Specifies the type of items in the list.
/// </summary>
Type ItemType { get; }
}
}
| 19.833333 | 64 | 0.579832 | [
"MIT"
] | DevVidya/open-world-rpg | Assets/3rd Party/Unity_Weld/Runtime/Binding/ITypedList.cs | 357 | C# |
/*
The MIT License (MIT)
Copyright (c) 2013 - 2015 Timothy D Meadows II
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;
namespace Blackfeather.Extention
{
/// <summary>
/// Append an element to an array
/// </summary>
public static class AppendExtension
{
/// <summary>
/// Append an element to an array
/// </summary>
/// <typeparam name="T">Any matching type</typeparam>
/// <param name="source">Source array</param>
/// <param name="destination">Destination array</param>
/// <param name="sourceLength">Length of source array, if not supplied source.Length is used.</param>
/// <param name="destinationLength">Length of destination array, if not supplied destination.Length is used.</param>
/// <returns>Transformed array</returns>
public static T[] Append<T>(this T[] source, T[] destination, int sourceLength = 0, int destinationLength = 0)
{
var expandSourceLength = sourceLength > 0 ? sourceLength : source.Length;
var expandDestinationLength = destinationLength > 0 ? destinationLength : destination.Length;
var expanded = new T[expandSourceLength + expandDestinationLength];
Array.Copy(source, 0, expanded, 0, expandSourceLength);
Array.Copy(destination, 0, expanded, expandSourceLength, expandDestinationLength);
return expanded;
}
}
} | 44.618182 | 124 | 0.705786 | [
"MIT"
] | TimothyMeadows/blackfeather | Blackfeather-35/Extention/AppendExtension.cs | 2,456 | C# |
using com.bitscopic.hilleman.core.domain.exception;
using com.bitscopic.hilleman.core.domain.security;
using com.bitscopic.hilleman.core.domain.to;
using System;
namespace com.bitscopic.hilleman.core.utils
{
public static class WcfSvcUtils
{
public static String makeCallForWebAPI(Delegate d, object[] args, bool includeNullsInSerializedResult = true)
{
try
{
return SerializerUtils.serialize(d.DynamicInvoke(args), includeNullsInSerializedResult);
}
catch (System.Reflection.TargetInvocationException tie)
{
if (tie.GetBaseException() is HillemanBaseException)
{
return SerializerUtils.serialize(new RequestFault((HillemanBaseException)tie.GetBaseException()), includeNullsInSerializedResult);
}
else
{
return SerializerUtils.serialize(new RequestFault(tie.GetBaseException().Message), includeNullsInSerializedResult);
}
}
catch (ArgumentException) // wrong args supplied to delegate - mistake in code!!
{
// TBD - log?
return SerializerUtils.serialize(new RequestFault("There appears to be a problem with this call. Please contact tech support"), false);
}
catch (System.Reflection.TargetParameterCountException) // wrong number of args supplied to delegate - mistake in code!!
{
// TBD - log?
return SerializerUtils.serialize(new RequestFault("There appears to be a problem with this call. Please contact tech support"), false);
}
catch (HillemanBaseException hbe)
{
return SerializerUtils.serialize(new RequestFault(hbe), false);
}
catch (Exception e)
{
return SerializerUtils.serialize(new RequestFault(message: e.Message, innerExc: e), includeNullsInSerializedResult);
}
}
}
} | 43.55102 | 152 | 0.59747 | [
"Apache-2.0"
] | joel-bitscopic/hilleman-core | hilleman-core/src/utils/WcfSvcUtils.cs | 2,136 | C# |
using Deathville.Component;
using Godot;
using GodotApiTools.Extension;
namespace Deathville.GameObject.Combat
{
public class Weapon : Node2D
{
private const float OVERHEAT_DECAY_DELAY = 2f;
private const string ANIM_FIRE = "fire";
[Signal]
public delegate void Fired();
[Signal]
public delegate void HeatChanged(Weapon weapon);
[Signal]
public delegate void Overheated(Weapon weapon);
[Signal]
public delegate void Cooled(Weapon weapon);
[Export]
private float _projectilesPerSecond = 10f;
[Export(PropertyHint.Range, "0,1")]
private float _heatPerShot = .1f;
[Export]
private float _heatDecayPerSecond = .5f;
[Export]
private float _heatDecayDelay = .25f;
[Export]
private float _heatDecayMultiplier = 1.5f;
public bool IsPlayer;
public float CurrentHeat
{
get
{
return _currentHeat;
}
private set
{
_currentHeat = value;
EmitSignal(nameof(HeatChanged), this);
}
}
public Sprite Sprite
{
get
{
return _sprite;
}
}
private float _currentHeat;
private float _decayTracker = 0f;
private bool _canDecay = true;
private bool _overheated = false;
private float _timeToNextShot = 0f;
private AnimationPlayer _animationPlayer;
private Sprite _sprite;
private Position2D _chamberPosition;
private ProjectileSpawnerComponent _projectileSpawnerComponent;
private ChooseStreamPlayerComponent _chooseStreamPlayerComponent;
public override void _Ready()
{
_projectileSpawnerComponent = this.GetFirstNodeOfType<ProjectileSpawnerComponent>();
_chooseStreamPlayerComponent = this.GetFirstNodeOfType<ChooseStreamPlayerComponent>();
_chamberPosition = GetNode<Position2D>("ChamberPosition");
_sprite = GetNode<Sprite>("Sprite");
_animationPlayer = GetNode<AnimationPlayer>("AnimationPlayer");
Connect(nameof(Fired), this, nameof(OnFired));
_projectileSpawnerComponent.Connect(nameof(ProjectileSpawnerComponent.ProjectileSpawned), this, nameof(OnProjectileSpawned));
}
public override void _Process(float delta)
{
_timeToNextShot = Mathf.Clamp(_timeToNextShot - delta / (IsPlayer ? Engine.TimeScale : 1f), 0f, float.MaxValue);
if (IsPlayer)
{
_animationPlayer.PlaybackSpeed = 1f / Engine.TimeScale;
}
if (_overheated)
{
UpdateCooldownOverheated();
}
else
{
UpdateCooldownStandard();
}
}
public void AttemptFire(Vector2 atTarget)
{
if (!_overheated && _timeToNextShot == 0f && CurrentHeat < 1f)
{
_projectileSpawnerComponent?.Spawn(IsPlayer, atTarget);
}
}
private void UpdateCooldownStandard()
{
if (IsPlayer)
{
var delta = GetProcessDeltaTime();
_decayTracker = Mathf.Clamp(_decayTracker - delta / Engine.TimeScale, 0f, float.MaxValue);
_canDecay = _decayTracker == 0f;
if (CurrentHeat > 0f && _canDecay)
{
var deltaDecay = _heatDecayPerSecond * delta / Engine.TimeScale;
var divisor = CurrentHeat * _heatDecayMultiplier;
var totalDelta = Mathf.Clamp(deltaDecay / divisor, deltaDecay, float.MaxValue);
CurrentHeat = Mathf.Clamp(CurrentHeat - totalDelta, 0f, 1f);
}
}
}
private void UpdateCooldownOverheated()
{
if (IsPlayer)
{
var delta = GetProcessDeltaTime();
_decayTracker = Mathf.Clamp(_decayTracker - delta / Engine.TimeScale, 0f, float.MaxValue);
_canDecay = _decayTracker == 0f;
if (CurrentHeat > 0f && _canDecay)
{
CurrentHeat = Mathf.Clamp(CurrentHeat - _heatDecayPerSecond * delta / Engine.TimeScale, 0f, 1f);
if (CurrentHeat == 0f)
{
_overheated = false;
EmitSignal(nameof(Cooled), this);
}
}
}
}
private void OnFired()
{
if (_animationPlayer.IsPlaying())
{
_animationPlayer.Seek(2f, true);
}
_animationPlayer.Play(ANIM_FIRE);
}
private void OnProjectileSpawned()
{
_timeToNextShot = 1f / _projectilesPerSecond;
if (IsPlayer)
{
CurrentHeat = Mathf.Clamp(CurrentHeat + _heatPerShot, 0f, 1f);
_decayTracker = _heatDecayDelay;
if (CurrentHeat == 1f)
{
_overheated = true;
_decayTracker = OVERHEAT_DECAY_DELAY;
}
}
_chooseStreamPlayerComponent.PlayAudio();
EmitSignal(nameof(Fired));
if (_overheated)
{
EmitSignal(nameof(Overheated), this);
}
}
}
} | 31.772727 | 137 | 0.537911 | [
"MIT"
] | firebelley/Deathville | scripts/GameObject/Combat/Weapon.cs | 5,592 | C# |
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace P03_FootballBetting.Data.Models
{
public class Town
{
public Town()
{
Teams = new HashSet<Team>();
}
[Key]
public int TownId { get; set; }
[Required]
[StringLength(85)]
public string Name { get; set; }
[ForeignKey(nameof(Country))]
public int CountryId { get; set; }
public virtual Country Country { get; set; }
public virtual ICollection<Team> Teams { get; set; }
}
}
| 21.965517 | 60 | 0.602826 | [
"MIT"
] | Plamen-Angelov/Entity-Framework | Entity Relations/FootballBetting/P03_FootballBetting.Data.Models/Town.cs | 639 | C# |
namespace Test.UC
{
partial class Gauge360Example
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.solidGauge1 = new LiveCharts.WinForms.SolidGauge();
this.solidGauge2 = new LiveCharts.WinForms.SolidGauge();
this.solidGauge3 = new LiveCharts.WinForms.SolidGauge();
this.solidGauge4 = new LiveCharts.WinForms.SolidGauge();
this.solidGauge5 = new LiveCharts.WinForms.SolidGauge();
this.solidGauge6 = new LiveCharts.WinForms.SolidGauge();
this.SuspendLayout();
//
// solidGauge1
//
this.solidGauge1.Location = new System.Drawing.Point(25, 13);
this.solidGauge1.Name = "solidGauge1";
this.solidGauge1.Size = new System.Drawing.Size(149, 151);
this.solidGauge1.TabIndex = 0;
this.solidGauge1.Text = "solidGauge1";
//
// solidGauge2
//
this.solidGauge2.Location = new System.Drawing.Point(220, 12);
this.solidGauge2.Name = "solidGauge2";
this.solidGauge2.Size = new System.Drawing.Size(149, 151);
this.solidGauge2.TabIndex = 1;
this.solidGauge2.Text = "solidGauge2";
//
// solidGauge3
//
this.solidGauge3.Location = new System.Drawing.Point(25, 170);
this.solidGauge3.Name = "solidGauge3";
this.solidGauge3.Size = new System.Drawing.Size(149, 151);
this.solidGauge3.TabIndex = 2;
this.solidGauge3.Text = "solidGauge3";
//
// solidGauge4
//
this.solidGauge4.Location = new System.Drawing.Point(220, 169);
this.solidGauge4.Name = "solidGauge4";
this.solidGauge4.Size = new System.Drawing.Size(149, 151);
this.solidGauge4.TabIndex = 3;
this.solidGauge4.Text = "solidGauge4";
//
// solidGauge5
//
this.solidGauge5.Location = new System.Drawing.Point(25, 347);
this.solidGauge5.Name = "solidGauge5";
this.solidGauge5.Size = new System.Drawing.Size(149, 151);
this.solidGauge5.TabIndex = 4;
this.solidGauge5.Text = "solidGauge5";
//
// solidGauge6
//
this.solidGauge6.Location = new System.Drawing.Point(220, 347);
this.solidGauge6.Name = "solidGauge6";
this.solidGauge6.Size = new System.Drawing.Size(149, 151);
this.solidGauge6.TabIndex = 5;
this.solidGauge6.Text = "solidGauge6";
//
// Gauge360Example
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.Color.White;
this.ClientSize = new System.Drawing.Size(732, 547);
this.Controls.Add(this.solidGauge6);
this.Controls.Add(this.solidGauge5);
this.Controls.Add(this.solidGauge4);
this.Controls.Add(this.solidGauge3);
this.Controls.Add(this.solidGauge2);
this.Controls.Add(this.solidGauge1);
this.Name = "Gauge360Example";
this.Text = "Gauge360Exampl";
this.ResumeLayout(false);
}
#endregion
private LiveCharts.WinForms.SolidGauge solidGauge1;
private LiveCharts.WinForms.SolidGauge solidGauge2;
private LiveCharts.WinForms.SolidGauge solidGauge3;
private LiveCharts.WinForms.SolidGauge solidGauge4;
private LiveCharts.WinForms.SolidGauge solidGauge5;
private LiveCharts.WinForms.SolidGauge solidGauge6;
}
} | 40.552632 | 107 | 0.576898 | [
"Apache-2.0"
] | DotNetFrameWork/NetWinformControl | HZH_Controls/Test/UC/UCTestLiveCharts/Gauge/360/Gauge360Example.Designer.cs | 4,625 | 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.Net.NetworkInformation;
using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;
internal static partial class Interop
{
internal static partial class IpHlpApi
{
internal const int IP_STATUS_BASE = 11000;
[StructLayout(LayoutKind.Sequential)]
internal struct IPOptions
{
internal byte ttl;
internal byte tos;
internal byte flags;
internal byte optionsSize;
internal IntPtr optionsData;
internal IPOptions(PingOptions? options)
{
ttl = 128;
tos = 0;
flags = 0;
optionsSize = 0;
optionsData = IntPtr.Zero;
if (options != null)
{
this.ttl = (byte)options.Ttl;
if (options.DontFragment)
{
flags = 2;
}
}
}
}
[StructLayout(LayoutKind.Sequential)]
internal struct IcmpEchoReply
{
internal uint address;
internal uint status;
internal uint roundTripTime;
internal ushort dataSize;
internal ushort reserved;
internal IntPtr data;
internal IPOptions options;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
internal struct Ipv6Address
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 6)]
internal byte[] Goo;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
// Replying address.
internal byte[] Address;
internal uint ScopeID;
}
[StructLayout(LayoutKind.Sequential)]
internal struct Icmp6EchoReply
{
internal Ipv6Address Address;
// Reply IP_STATUS.
internal uint Status;
// RTT in milliseconds.
internal uint RoundTripTime;
internal IntPtr data;
// internal IPOptions options;
// internal IntPtr data; data os after tjos
}
internal sealed class SafeCloseIcmpHandle : SafeHandleZeroOrMinusOneIsInvalid
{
public SafeCloseIcmpHandle() : base(true) { }
protected override bool ReleaseHandle()
{
return Interop.IpHlpApi.IcmpCloseHandle(handle);
}
}
[DllImport(Interop.Libraries.IpHlpApi, SetLastError = true)]
internal static extern SafeCloseIcmpHandle IcmpCreateFile();
[DllImport(Interop.Libraries.IpHlpApi, SetLastError = true)]
internal static extern SafeCloseIcmpHandle Icmp6CreateFile();
[DllImport(Interop.Libraries.IpHlpApi, SetLastError = true)]
internal static extern bool IcmpCloseHandle(IntPtr handle);
[DllImport(Interop.Libraries.IpHlpApi, SetLastError = true)]
internal static extern uint IcmpSendEcho2(
SafeCloseIcmpHandle icmpHandle,
SafeWaitHandle Event,
IntPtr apcRoutine,
IntPtr apcContext,
uint ipAddress,
[In] SafeLocalAllocHandle data,
ushort dataSize,
ref IPOptions options,
SafeLocalAllocHandle replyBuffer,
uint replySize,
uint timeout
);
[DllImport(Interop.Libraries.IpHlpApi, SetLastError = true)]
internal static extern uint Icmp6SendEcho2(
SafeCloseIcmpHandle icmpHandle,
SafeWaitHandle Event,
IntPtr apcRoutine,
IntPtr apcContext,
byte[] sourceSocketAddress,
byte[] destSocketAddress,
[In] SafeLocalAllocHandle data,
ushort dataSize,
ref IPOptions options,
SafeLocalAllocHandle replyBuffer,
uint replySize,
uint timeout
);
}
}
| 30.902985 | 85 | 0.571843 | [
"MIT"
] | belav/runtime | src/libraries/Common/src/Interop/Windows/IpHlpApi/Interop.ICMP.cs | 4,141 | C# |
//-----------------------------------------------------------------------
// <copyright file="TransformExtensions.cs" company="Lost Signal LLC">
// Copyright (c) Lost Signal LLC. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
namespace Lost
{
using System.Collections;
using UnityEngine;
public static class TransformExtensions
{
public static void Reset(this Transform transform)
{
transform.localScale = Vector3.one;
transform.localPosition = Vector3.zero;
transform.localRotation = Quaternion.identity;
}
public static void DestroyAllChildren(this Transform transform)
{
for (int i = transform.childCount - 1; i >= 0; i--)
{
Pooler.Destroy(transform.GetChild(i).gameObject);
}
}
public static void SafeSetActive(this Transform transform, bool active)
{
if (transform != null)
{
transform.gameObject.SafeSetActive(active);
}
}
public static Coroutine LookAt(this Transform transform, Transform lookAtTransform, float time)
{
return CoroutineRunner.Instance.StartCoroutine(LookAtCoroutine());
IEnumerator LookAtCoroutine()
{
Quaternion startRotation = transform.rotation;
float currentTime = 0.0f;
while (currentTime / time < 1.0f)
{
Quaternion lookAtRotation = Quaternion.LookRotation(lookAtTransform.position - transform.position);
transform.rotation = Quaternion.Lerp(startRotation, lookAtRotation, currentTime / time);
currentTime += Time.deltaTime;
yield return null;
}
transform.rotation = Quaternion.LookRotation(lookAtTransform.position - transform.position);
}
}
}
}
| 32.349206 | 119 | 0.540236 | [
"Unlicense",
"MIT"
] | LostSignal/Lost-Library | Lost/Lost.Extensions/Runtime/TransformExtensions.cs | 2,040 | C# |
using SO;
using System.Collections.Generic;
namespace PL
{
public abstract class CardP
{
public static IEnumerable<Deb> ListDeb()
{
foreach (Deb c in Cnn.ExecCmd("list_deb_cards"))
yield return c;
}
public static IEnumerable<Cred> ListCred()
{
foreach (Cred c in Cnn.ExecCmd("list_cred_cards"))
yield return c;
}
}
} | 21.75 | 62 | 0.549425 | [
"MIT"
] | peaceslasher/projectA | Cards/PL/CardP.cs | 437 | C# |
/*
MIT License
Copyright (c) 2022 ShuheiOi
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 AdolescenceNovel
{
public class GotoInitial : IGotoState
{
private static GotoInitial _singleton = null;
public static GotoInitial singleton
{
get
{
if (_singleton == null)
{
_singleton = new GotoInitial();
}
return _singleton;
}
}
public bool Execute(Goto nowstate, GotoContext context)
{
// TODO: 実装
SystemData.instance.Jump((int)(float)nowstate.line.Value());
return true;
}
}
}
| 34 | 78 | 0.678824 | [
"MIT"
] | ShuheiOi/AdolescenceNovel | Assets/Sources/Novel/Command/SystemCommand/goto/GotoInitial.cs | 1,704 | C# |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
namespace BuildXL.Utilities.Configuration
{
/// <summary>
/// The case of <see cref="IJavaScriptCommandGroup"/> when BuildXL provides the script execution semantics (e.g. Yarn, Rush)
/// </summary>
public interface IJavaScriptCommandGroupWithDependencies : IJavaScriptCommandGroup, IJavaScriptCommandWithDependencies
{
}
}
| 33.538462 | 129 | 0.720183 | [
"MIT"
] | BearerPipelineTest/BuildXL | Public/Src/Utilities/Configuration/Resolvers/IJavaScriptCommandGroupWithDependencies.cs | 438 | C# |
using Kholupov.Diploma.SimpleCrud.Models;
using Microsoft.EntityFrameworkCore;
namespace Kholupov.Diploma.SimpleCrud.Data
{
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
{
}
public DbSet<Category> Category { get; set; }
public DbSet<ApplicationType> ApplicationType { get; set; }
}
}
| 25.529412 | 99 | 0.707373 | [
"MIT"
] | teachmeskills-dotnet/TMS-DotNet04-Kholupov | src/Kholupov.Diploma.SimpleCrud/Data/ApplicationDbContext.cs | 436 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Axe.Windows.Core.Bases;
using Axe.Windows.Core.Enums;
using Axe.Windows.Core.Types;
using Axe.Windows.Rules.PropertyConditions;
using Axe.Windows.Rules.Resources;
using static Axe.Windows.Rules.PropertyConditions.BoolProperties;
namespace Axe.Windows.Rules.Library
{
[RuleInfo(ID = RuleId.IsKeyboardFocusableOnEmptyContainer)]
class IsKeyboardFocusableOnEmptyContainer : Rule
{
public IsKeyboardFocusableOnEmptyContainer()
{
this.Info.Description = Descriptions.IsKeyboardFocusableOnEmptyContainer;
this.Info.HowToFix = HowToFix.IsKeyboardFocusableOnEmptyContainer;
this.Info.Standard = A11yCriteriaId.Keyboard;
this.Info.PropertyID = PropertyType.UIA_IsKeyboardFocusablePropertyId;
this.Info.ErrorCode = EvaluationCode.Open;
}
public override bool PassesTest(IA11yElement e)
{
return false;
}
protected override Condition CreateCondition()
{
return IsNotKeyboardFocusable & IsEnabled & IsNotOffScreen & BoundingRectangle.Valid
& ElementGroups.EmptyContainer;
}
} // class
} // namespace
| 38.083333 | 102 | 0.692195 | [
"MIT"
] | AdrianaDJ/axe-windows | src/Rules/Library/IsKeyboardFocusableOnEmptyContainer.cs | 1,336 | C# |
// -----------------------------------------------------------------------
// <copyright file="ColumnAttribute.cs" company="MicroLite">
// Copyright 2012 - 2015 Project Contributors
//
// 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
//
// </copyright>
// -----------------------------------------------------------------------
namespace MicroLite.Mapping.Attributes
{
using System;
using System.Data;
/// <summary>
/// An attribute which can be applied to a property to specify the column name that the property maps to.
/// </summary>
/// <example>
/// <code>
/// // Option 1 - Column and property name match.
/// [Column("FirstName")]
/// public string FirstName
/// {
/// get;
/// set;
/// }
/// </code>
/// <code>
/// // Option 2 - Column and property name differ.
/// [Column("FName")]
/// public string FirstName
/// {
/// get;
/// set;
/// }
/// </code>
/// <code>
/// // Additionally, it is possible to restrict insert or updates to a column.
/// [Column("Created", allowInsert: true, allowUpdate: false)]
/// public DateTime Created
/// {
/// get;
/// set;
/// }
/// </code>
/// </example>
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public sealed class ColumnAttribute : Attribute
{
private readonly bool allowInsert;
private readonly bool allowUpdate;
private readonly DbType? dbType;
private readonly string name;
/// <summary>
/// Initialises a new instance of the <see cref="ColumnAttribute"/> class.
/// </summary>
/// <param name="name">The name of the column in the database table that the property maps to.</param>
public ColumnAttribute(string name)
: this(name, null, true, true)
{
}
/// <summary>
/// Initialises a new instance of the <see cref="ColumnAttribute"/> class.
/// </summary>
/// <param name="name">The name of the column in the database table that the property maps to.</param>
/// <param name="dbType">The type of the column in the database table that the property maps to.</param>
public ColumnAttribute(string name, DbType? dbType)
: this(name, dbType, true, true)
{
}
/// <summary>
/// Initialises a new instance of the <see cref="ColumnAttribute" /> class.
/// </summary>
/// <param name="name">The name of the column in the database table that the property maps to.</param>
/// <param name="allowInsert">true if the column value can be inserted, otherwise false.</param>
/// <param name="allowUpdate">true if the column value can be updated, otherwise false.</param>
public ColumnAttribute(string name, bool allowInsert, bool allowUpdate)
: this(name, null, allowInsert, allowUpdate)
{
}
/// <summary>
/// Initialises a new instance of the <see cref="ColumnAttribute" /> class.
/// </summary>
/// <param name="name">The name of the column in the database table that the property maps to.</param>
/// <param name="dbType">The type of the column in the database table that the property maps to.</param>
/// <param name="allowInsert">true if the column value can be inserted, otherwise false.</param>
/// <param name="allowUpdate">true if the column value can be updated, otherwise false.</param>
public ColumnAttribute(string name, DbType? dbType, bool allowInsert, bool allowUpdate)
{
this.name = name;
this.dbType = dbType;
this.allowInsert = allowInsert;
this.allowUpdate = allowUpdate;
}
/// <summary>
/// Gets a value indicating whether the column value is allowed to be inserted.
/// </summary>
public bool AllowInsert
{
get
{
return this.allowInsert;
}
}
/// <summary>
/// Gets a value indicating whether the column value is allowed to be updated.
/// </summary>
public bool AllowUpdate
{
get
{
return this.allowUpdate;
}
}
/// <summary>
/// Gets the type of the column in the database table that the property maps to.
/// </summary>
/// <remarks>If null, it will be resolved via TypeConverter.ResolveDbType.</remarks>
public DbType? DbType
{
get
{
return this.dbType;
}
}
/// <summary>
/// Gets the name of the column in the database table that the property maps to
/// </summary>
public string Name
{
get
{
return this.name;
}
}
}
} | 36.013514 | 113 | 0.53546 | [
"Apache-2.0"
] | CollaboratingPlatypus/MicroLite | MicroLite/Mapping/Attributes/ColumnAttribute.cs | 5,185 | C# |
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Xunit;
using Xunit.Extensions;
namespace NuGet.Test.Integration.NuGetCommandLine
{
public class NuGetRestoreCommandTest
{
[Fact]
public void RestoreCommand_FromPackagesConfigFile()
{
// Arrange
var tempPath = Path.GetTempPath();
var workingPath = Path.Combine(tempPath, Guid.NewGuid().ToString());
var repositoryPath = Path.Combine(workingPath, Guid.NewGuid().ToString());
var currentDirectory = Directory.GetCurrentDirectory();
try
{
Util.CreateDirectory(workingPath);
Util.CreateDirectory(repositoryPath);
Util.CreateTestPackage("packageA", "1.1.0", repositoryPath);
Util.CreateTestPackage("packageB", "2.2.0", repositoryPath);
Util.CreateFile(workingPath, "packages.config",
@"<packages>
<package id=""packageA"" version=""1.1.0"" targetFramework=""net45"" />
<package id=""packageB"" version=""2.2.0"" targetFramework=""net45"" />
</packages>");
string[] args = new string[] { "restore", "-PackagesDirectory", "outputDir", "-Source", repositoryPath };
// Act
Directory.SetCurrentDirectory(workingPath);
int r = Program.Main(args);
// Assert
Assert.Equal(0, r);
var packageFileA = Path.Combine(workingPath, @"outputDir\packageA.1.1.0\packageA.1.1.0.nupkg");
var packageFileB = Path.Combine(workingPath, @"outputDir\packageB.2.2.0\packageB.2.2.0.nupkg");
Assert.True(File.Exists(packageFileA));
Assert.True(File.Exists(packageFileB));
}
finally
{
Directory.SetCurrentDirectory(currentDirectory);
Util.DeleteDirectory(workingPath);
}
}
[Theory]
[InlineData("packages.config")]
[InlineData("packages.proj2.config")]
public void RestoreCommand_FromSolutionFile(string configFileName)
{
// Arrange
var tempPath = Path.GetTempPath();
var workingPath = Path.Combine(tempPath, Guid.NewGuid().ToString());
var repositoryPath = Path.Combine(workingPath, Guid.NewGuid().ToString());
var proj1Directory = Path.Combine(workingPath, "proj1");
var proj2Directory = Path.Combine(workingPath, "proj2");
var currentDirectory = Directory.GetCurrentDirectory();
var targetDir = ConfigurationManager.AppSettings["TargetDir"];
var nugetexe = Path.Combine(targetDir, "nuget.exe");
try
{
Util.CreateDirectory(workingPath);
Util.CreateDirectory(repositoryPath);
Util.CreateDirectory(proj1Directory);
Util.CreateDirectory(proj2Directory);
Util.CreateTestPackage("packageA", "1.1.0", repositoryPath);
Util.CreateTestPackage("packageB", "2.2.0", repositoryPath);
Util.CreateFile(workingPath, "a.sln",
@"
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 2012
Project(""{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}"") = ""proj1"", ""proj1\proj1.csproj"", ""{A04C59CC-7622-4223-B16B-CDF2ECAD438D}""
EndProject
Project(""{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}"") = ""proj2"", ""proj2\proj2.csproj"", ""{42641DAE-D6C4-49D4-92EA-749D2573554A}""
EndProject");
Util.CreateFile(proj1Directory, "proj1.csproj",
@"<Project ToolsVersion='4.0' DefaultTargets='Build'
xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
<PropertyGroup>
<OutputType>Library</OutputType>
<OutputPath>out</OutputPath>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
</PropertyGroup>
<ItemGroup>
<None Include='packages.config' />
</ItemGroup>
</Project>");
Util.CreateFile(proj1Directory, "packages.config",
@"<packages>
<package id=""packageA"" version=""1.1.0"" targetFramework=""net45"" />
</packages>");
Util.CreateFile(proj2Directory, "proj2.csproj",
@"<Project ToolsVersion='4.0' DefaultTargets='Build'
xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
<PropertyGroup>
<OutputType>Library</OutputType>
<OutputPath>out</OutputPath>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
</PropertyGroup>
<ItemGroup>
<None Include='packages.config' />
</ItemGroup>
</Project>");
Util.CreateFile(proj2Directory, configFileName,
@"<packages>
<package id=""packageB"" version=""2.2.0"" targetFramework=""net45"" />
</packages>");
// Act
var r = CommandRunner.Run(
nugetexe,
workingPath,
"restore -Source " + repositoryPath,
waitForExit: true);
// Assert
Assert.Equal(0, r.Item1);
var packageFileA = Path.Combine(workingPath, @"packages\packageA.1.1.0\packageA.1.1.0.nupkg");
var packageFileB = Path.Combine(workingPath, @"packages\packageB.2.2.0\packageB.2.2.0.nupkg");
Assert.True(File.Exists(packageFileA));
Assert.True(File.Exists(packageFileB));
}
finally
{
Directory.SetCurrentDirectory(currentDirectory);
Util.DeleteDirectory(workingPath);
}
}
// Tests that if the project file cannot be loaded, i.e. InvalidProjectFileException is thrown,
// Then packages listed in packages.config file will be restored.
[Fact]
public void RestoreCommand_ProjectCannotBeLoaded()
{
// Arrange
var tempPath = Path.GetTempPath();
var workingPath = Path.Combine(tempPath, Guid.NewGuid().ToString());
var repositoryPath = Path.Combine(workingPath, Guid.NewGuid().ToString());
var proj1Directory = Path.Combine(workingPath, "proj1");
var currentDirectory = Directory.GetCurrentDirectory();
var targetDir = ConfigurationManager.AppSettings["TargetDir"];
var nugetexe = Path.Combine(targetDir, "nuget.exe");
try
{
Util.CreateDirectory(workingPath);
Util.CreateDirectory(repositoryPath);
Util.CreateDirectory(proj1Directory);
Util.CreateTestPackage("packageA", "1.1.0", repositoryPath);
Util.CreateFile(workingPath, "a.sln",
@"
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 2012
Project(""{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}"") = ""proj1"", ""proj1\proj1.csproj"", ""{A04C59CC-7622-4223-B16B-CDF2ECAD438D}""
EndProject");
// The project contains an import statement to import an non-existing file.
// Thus, this project cannot be loaded successfully.
Util.CreateFile(proj1Directory, "proj1.csproj",
@"<Project ToolsVersion='4.0' DefaultTargets='Build'
xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
<PropertyGroup>
<OutputType>Library</OutputType>
<OutputPath>out</OutputPath>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
</PropertyGroup>
<Import Project='..\packages\a.targets' />
</Project>");
Util.CreateFile(proj1Directory, "packages.config",
@"<packages>
<package id=""packageA"" version=""1.1.0"" targetFramework=""net45"" />
</packages>");
string[] args = new string[] { "restore", "-Source", repositoryPath };
// Act
var r = CommandRunner.Run(
nugetexe,
workingPath,
"restore -Source " + repositoryPath,
waitForExit: true);
// Assert
Assert.Equal(0, r.Item1);
var packageFileA = Path.Combine(workingPath, @"packages\packageA.1.1.0\packageA.1.1.0.nupkg");
Assert.True(File.Exists(packageFileA));
}
finally
{
Directory.SetCurrentDirectory(currentDirectory);
Util.DeleteDirectory(workingPath);
}
}
// Tests that when -solutionDir is specified, the $(SolutionDir)\.nuget\NuGet.Config file
// will be used.
[Fact]
public void RestoreCommand_FromPackagesConfigFileWithOptionSolutionDir()
{
// Arrange
var tempPath = Path.GetTempPath();
var workingPath = Path.Combine(tempPath, Guid.NewGuid().ToString());
var repositoryPath = Path.Combine(workingPath, Guid.NewGuid().ToString());
var currentDirectory = Directory.GetCurrentDirectory();
try
{
Util.CreateDirectory(workingPath);
Util.CreateDirectory(repositoryPath);
Util.CreateDirectory(Path.Combine(workingPath, ".nuget"));
Util.CreateTestPackage("packageA", "1.1.0", repositoryPath);
Util.CreateTestPackage("packageB", "2.2.0", repositoryPath);
Util.CreateFile(workingPath, "packages.config",
@"<packages>
<package id=""packageA"" version=""1.1.0"" targetFramework=""net45"" />
<package id=""packageB"" version=""2.2.0"" targetFramework=""net45"" />
</packages>");
Util.CreateFile(Path.Combine(workingPath, ".nuget"), "nuget.config",
@"<?xml version=""1.0"" encoding=""utf-8""?>
<configuration>
<config>
<add key=""repositorypath"" value=""$\..\..\Packages2"" />
</config>
</configuration>");
string[] args = new string[] { "restore", "-Source", repositoryPath, "-solutionDir", workingPath };
// Act
Directory.SetCurrentDirectory(workingPath);
int r = Program.Main(args);
// Assert
Assert.Equal(0, r);
var packageFileA = Path.Combine(workingPath, @"packages2\packageA.1.1.0\packageA.1.1.0.nupkg");
var packageFileB = Path.Combine(workingPath, @"packages2\packageB.2.2.0\packageB.2.2.0.nupkg");
Assert.True(File.Exists(packageFileA));
Assert.True(File.Exists(packageFileB));
}
finally
{
Directory.SetCurrentDirectory(currentDirectory);
Util.DeleteDirectory(workingPath);
}
}
// Tests that when package restore is enabled and -RequireConsent is specified,
// the opt out message is displayed.
[Theory]
[InlineData("packages.config")]
[InlineData("packages.proj1.config")]
public void RestoreCommand_OptOutMessage(string configFileName)
{
// Arrange
var tempPath = Path.GetTempPath();
var workingPath = Path.Combine(tempPath, Guid.NewGuid().ToString());
var repositoryPath = Path.Combine(workingPath, Guid.NewGuid().ToString());
var proj1Directory = Path.Combine(workingPath, "proj1");
var proj2Directory = Path.Combine(workingPath, "proj2");
var currentDirectory = Directory.GetCurrentDirectory();
var targetDir = ConfigurationManager.AppSettings["TargetDir"];
var nugetexe = Path.Combine(targetDir, "nuget.exe");
try
{
Util.CreateDirectory(workingPath);
Util.CreateDirectory(repositoryPath);
Util.CreateDirectory(proj1Directory);
Util.CreateDirectory(proj2Directory);
Util.CreateTestPackage("packageA", "1.1.0", repositoryPath);
Util.CreateTestPackage("packageB", "2.2.0", repositoryPath);
Util.CreateFile(workingPath, "a.sln",
@"
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 2012
Project(""{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}"") = ""proj1"", ""proj1\proj1.csproj"", ""{A04C59CC-7622-4223-B16B-CDF2ECAD438D}""
EndProject
Project(""{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}"") = ""proj2"", ""proj2\proj2.csproj"", ""{42641DAE-D6C4-49D4-92EA-749D2573554A}""
EndProject");
Util.CreateFile(workingPath, "my.config",
@"
<?xml version=""1.0"" encoding=""utf-8""?>
<configuration>
<packageRestore>
<add key=""enabled"" value=""True"" />
</packageRestore>
</configuration>");
Util.CreateFile(proj1Directory, "proj1.csproj",
@"<Project ToolsVersion='4.0' DefaultTargets='Build'
xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
<PropertyGroup>
<OutputType>Library</OutputType>
<OutputPath>out</OutputPath>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
</PropertyGroup>
<ItemGroup>
<None Include='packages.config' />
</ItemGroup>
</Project>");
Util.CreateFile(proj1Directory, configFileName,
@"<packages>
<package id=""packageA"" version=""1.1.0"" targetFramework=""net45"" />
</packages>");
Util.CreateFile(proj2Directory, "proj2.csproj",
@"<Project ToolsVersion='4.0' DefaultTargets='Build'
xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
<PropertyGroup>
<OutputType>Library</OutputType>
<OutputPath>out</OutputPath>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
</PropertyGroup>
<ItemGroup>
<None Include='packages.config' />
</ItemGroup>
</Project>");
Util.CreateFile(proj2Directory, "packages.config",
@"<packages>
<package id=""packageB"" version=""2.2.0"" targetFramework=""net45"" />
</packages>");
// Act
var r = CommandRunner.Run(
nugetexe,
workingPath,
"restore -Source " + repositoryPath + " -ConfigFile my.config -RequireConsent",
waitForExit: true);
// Assert
Assert.Equal(0, r.Item1);
string optOutMessage = String.Format(
CultureInfo.CurrentCulture,
NuGetResources.RestoreCommandPackageRestoreOptOutMessage,
NuGet.Resources.NuGetResources.PackageRestoreConsentCheckBoxText.Replace("&", ""));
Assert.Contains(optOutMessage, r.Item2);
var packageFileA = Path.Combine(workingPath, @"packages\packageA.1.1.0\packageA.1.1.0.nupkg");
var packageFileB = Path.Combine(workingPath, @"packages\packageB.2.2.0\packageB.2.2.0.nupkg");
Assert.True(File.Exists(packageFileA));
Assert.True(File.Exists(packageFileB));
}
finally
{
Directory.SetCurrentDirectory(currentDirectory);
Util.DeleteDirectory(workingPath);
}
}
// Tests that when package restore is enabled and -RequireConsent is not specified,
// the opt out message is not displayed.
[Fact]
public void RestoreCommand_NoOptOutMessage()
{
// Arrange
var tempPath = Path.GetTempPath();
var workingPath = Path.Combine(tempPath, Guid.NewGuid().ToString());
var repositoryPath = Path.Combine(workingPath, Guid.NewGuid().ToString());
var proj1Directory = Path.Combine(workingPath, "proj1");
var proj2Directory = Path.Combine(workingPath, "proj2");
var currentDirectory = Directory.GetCurrentDirectory();
var targetDir = ConfigurationManager.AppSettings["TargetDir"];
var nugetexe = Path.Combine(targetDir, "nuget.exe");
try
{
Util.CreateDirectory(workingPath);
Util.CreateDirectory(repositoryPath);
Util.CreateDirectory(proj1Directory);
Util.CreateDirectory(proj2Directory);
Util.CreateTestPackage("packageA", "1.1.0", repositoryPath);
Util.CreateTestPackage("packageB", "2.2.0", repositoryPath);
Util.CreateFile(workingPath, "a.sln",
@"
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 2012
Project(""{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}"") = ""proj1"", ""proj1\proj1.csproj"", ""{A04C59CC-7622-4223-B16B-CDF2ECAD438D}""
EndProject
Project(""{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}"") = ""proj2"", ""proj2\proj2.csproj"", ""{42641DAE-D6C4-49D4-92EA-749D2573554A}""
EndProject");
Util.CreateFile(workingPath, "my.config",
@"
<?xml version=""1.0"" encoding=""utf-8""?>
<configuration>
<packageRestore>
<add key=""enabled"" value=""True"" />
</packageRestore>
</configuration>");
Util.CreateFile(proj1Directory, "proj1.csproj",
@"<Project ToolsVersion='4.0' DefaultTargets='Build'
xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
<PropertyGroup>
<OutputType>Library</OutputType>
<OutputPath>out</OutputPath>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
</PropertyGroup>
<ItemGroup>
<None Include='packages.config' />
</ItemGroup>
</Project>");
Util.CreateFile(proj1Directory, "packages.config",
@"<packages>
<package id=""packageA"" version=""1.1.0"" targetFramework=""net45"" />
</packages>");
Util.CreateFile(proj2Directory, "proj2.csproj",
@"<Project ToolsVersion='4.0' DefaultTargets='Build'
xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
<PropertyGroup>
<OutputType>Library</OutputType>
<OutputPath>out</OutputPath>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
</PropertyGroup>
<ItemGroup>
<None Include='packages.config' />
</ItemGroup>
</Project>");
Util.CreateFile(proj2Directory, "packages.config",
@"<packages>
<package id=""packageB"" version=""2.2.0"" targetFramework=""net45"" />
</packages>");
// Act
var r = CommandRunner.Run(
nugetexe,
workingPath,
"restore -Source " + repositoryPath + " -ConfigFile my.config",
waitForExit: true);
// Assert
Assert.Equal(0, r.Item1);
string optOutMessage = String.Format(
CultureInfo.CurrentCulture,
NuGetResources.RestoreCommandPackageRestoreOptOutMessage,
NuGet.Resources.NuGetResources.PackageRestoreConsentCheckBoxText.Replace("&", ""));
Assert.DoesNotContain(optOutMessage, r.Item2);
var packageFileA = Path.Combine(workingPath, @"packages\packageA.1.1.0\packageA.1.1.0.nupkg");
var packageFileB = Path.Combine(workingPath, @"packages\packageB.2.2.0\packageB.2.2.0.nupkg");
Assert.True(File.Exists(packageFileA));
Assert.True(File.Exists(packageFileB));
}
finally
{
Directory.SetCurrentDirectory(currentDirectory);
Util.DeleteDirectory(workingPath);
}
}
// Test that when a directory is passed to nuget.exe restore, and the directory contains
// just one solution file, restore will work on that solution file.
[Theory]
[InlineData("packages.config")]
[InlineData("packages.proj2.config")]
public void RestoreCommand_OneSolutionFileInDirectory(string configFileName)
{
// Arrange
var tempPath = Path.GetTempPath();
var workingPath = Path.Combine(tempPath, Guid.NewGuid().ToString());
var repositoryPath = Path.Combine(workingPath, Guid.NewGuid().ToString());
var proj1Directory = Path.Combine(workingPath, "proj1");
var proj2Directory = Path.Combine(workingPath, "proj2");
var currentDirectory = Directory.GetCurrentDirectory();
var targetDir = ConfigurationManager.AppSettings["TargetDir"];
var nugetexe = Path.Combine(targetDir, "nuget.exe");
try
{
Util.CreateDirectory(workingPath);
Util.CreateDirectory(repositoryPath);
Util.CreateDirectory(proj1Directory);
Util.CreateDirectory(proj2Directory);
Util.CreateTestPackage("packageA", "1.1.0", repositoryPath);
Util.CreateTestPackage("packageB", "2.2.0", repositoryPath);
Util.CreateFile(workingPath, "a.sln",
@"
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 2012
Project(""{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}"") = ""proj1"", ""proj1\proj1.csproj"", ""{A04C59CC-7622-4223-B16B-CDF2ECAD438D}""
EndProject
Project(""{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}"") = ""proj2"", ""proj2\proj2.csproj"", ""{42641DAE-D6C4-49D4-92EA-749D2573554A}""
EndProject");
Util.CreateFile(proj1Directory, "proj1.csproj",
@"<Project ToolsVersion='4.0' DefaultTargets='Build'
xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
<PropertyGroup>
<OutputType>Library</OutputType>
<OutputPath>out</OutputPath>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
</PropertyGroup>
<ItemGroup>
<None Include='packages.config' />
</ItemGroup>
</Project>");
Util.CreateFile(proj1Directory, "packages.config",
@"<packages>
<package id=""packageA"" version=""1.1.0"" targetFramework=""net45"" />
</packages>");
Util.CreateFile(proj2Directory, "proj2.csproj",
@"<Project ToolsVersion='4.0' DefaultTargets='Build'
xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
<PropertyGroup>
<OutputType>Library</OutputType>
<OutputPath>out</OutputPath>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
</PropertyGroup>
<ItemGroup>
<None Include='packages.config' />
</ItemGroup>
</Project>");
Util.CreateFile(proj2Directory, configFileName,
@"<packages>
<package id=""packageB"" version=""2.2.0"" targetFramework=""net45"" />
</packages>");
// Act
var r = CommandRunner.Run(
nugetexe,
tempPath,
"restore " + workingPath + " -Source " + repositoryPath,
waitForExit: true);
// Assert
Assert.Equal(0, r.Item1);
var packageFileA = Path.Combine(workingPath, @"packages\packageA.1.1.0\packageA.1.1.0.nupkg");
var packageFileB = Path.Combine(workingPath, @"packages\packageB.2.2.0\packageB.2.2.0.nupkg");
Assert.True(File.Exists(packageFileA));
Assert.True(File.Exists(packageFileB));
}
finally
{
Directory.SetCurrentDirectory(currentDirectory);
Util.DeleteDirectory(workingPath);
}
}
// Test that when a directory is passed to nuget.exe restore, and the directory contains
// multiple solution files, nuget.exe will generate an error.
[Fact]
public void RestoreCommand_MutipleSolutionFilesInDirectory()
{
// Arrange
var tempPath = Path.GetTempPath();
var workingPath = Path.Combine(tempPath, Guid.NewGuid().ToString());
var repositoryPath = Path.Combine(workingPath, Guid.NewGuid().ToString());
var proj1Directory = Path.Combine(workingPath, "proj1");
var proj2Directory = Path.Combine(workingPath, "proj2");
var currentDirectory = Directory.GetCurrentDirectory();
var targetDir = ConfigurationManager.AppSettings["TargetDir"];
var nugetexe = Path.Combine(targetDir, "nuget.exe");
try
{
Util.CreateDirectory(workingPath);
Util.CreateDirectory(repositoryPath);
Util.CreateDirectory(proj1Directory);
Util.CreateDirectory(proj2Directory);
Util.CreateTestPackage("packageA", "1.1.0", repositoryPath);
Util.CreateTestPackage("packageB", "2.2.0", repositoryPath);
Util.CreateFile(workingPath, "a.sln",
@"
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 2012
Project(""{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}"") = ""proj1"", ""proj1\proj1.csproj"", ""{A04C59CC-7622-4223-B16B-CDF2ECAD438D}""
EndProject
Project(""{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}"") = ""proj2"", ""proj2\proj2.csproj"", ""{42641DAE-D6C4-49D4-92EA-749D2573554A}""
EndProject");
Util.CreateFile(workingPath, "b.sln",
@"
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 2012
Project(""{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}"") = ""proj1"", ""proj1\proj1.csproj"", ""{A04C59CC-7622-4223-B16B-CDF2ECAD438D}""
EndProject
Project(""{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}"") = ""proj2"", ""proj2\proj2.csproj"", ""{42641DAE-D6C4-49D4-92EA-749D2573554A}""
EndProject");
Util.CreateFile(proj1Directory, "proj1.csproj",
@"<Project ToolsVersion='4.0' DefaultTargets='Build'
xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
<PropertyGroup>
<OutputType>Library</OutputType>
<OutputPath>out</OutputPath>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
</PropertyGroup>
<ItemGroup>
<None Include='packages.config' />
</ItemGroup>
</Project>");
Util.CreateFile(proj1Directory, "packages.config",
@"<packages>
<package id=""packageA"" version=""1.1.0"" targetFramework=""net45"" />
</packages>");
Util.CreateFile(proj2Directory, "proj2.csproj",
@"<Project ToolsVersion='4.0' DefaultTargets='Build'
xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
<PropertyGroup>
<OutputType>Library</OutputType>
<OutputPath>out</OutputPath>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
</PropertyGroup>
<ItemGroup>
<None Include='packages.config' />
</ItemGroup>
</Project>");
Util.CreateFile(proj2Directory, "packages.config",
@"<packages>
<package id=""packageB"" version=""2.2.0"" targetFramework=""net45"" />
</packages>");
// Act
var r = CommandRunner.Run(
nugetexe,
tempPath,
"restore " + workingPath + " -Source " + repositoryPath,
waitForExit: true);
// Assert
Assert.Equal(1, r.Item1);
Assert.Contains("This folder contains more than one solution file.", r.Item2);
var packageFileA = Path.Combine(workingPath, @"packages\packageA.1.1.0\packageA.1.1.0.nupkg");
var packageFileB = Path.Combine(workingPath, @"packages\packageB.2.2.0\packageB.2.2.0.nupkg");
Assert.False(File.Exists(packageFileA));
Assert.False(File.Exists(packageFileB));
}
finally
{
Directory.SetCurrentDirectory(currentDirectory);
Util.DeleteDirectory(workingPath);
}
}
// Test that when a directory is passed to nuget.exe restore, and the directory contains
// no solution files, nuget.exe will generate an error.
[Fact]
public void RestoreCommand_NoSolutionFilesInDirectory()
{
// Arrange
var tempPath = Path.GetTempPath();
var workingPath = Path.Combine(tempPath, Guid.NewGuid().ToString());
var repositoryPath = Path.Combine(workingPath, Guid.NewGuid().ToString());
var proj1Directory = Path.Combine(workingPath, "proj1");
var proj2Directory = Path.Combine(workingPath, "proj2");
var currentDirectory = Directory.GetCurrentDirectory();
var targetDir = ConfigurationManager.AppSettings["TargetDir"];
var nugetexe = Path.Combine(targetDir, "nuget.exe");
try
{
Util.CreateDirectory(workingPath);
Util.CreateDirectory(repositoryPath);
Util.CreateDirectory(proj1Directory);
Util.CreateDirectory(proj2Directory);
Util.CreateTestPackage("packageA", "1.1.0", repositoryPath);
Util.CreateTestPackage("packageB", "2.2.0", repositoryPath);
Util.CreateFile(proj1Directory, "proj1.csproj",
@"<Project ToolsVersion='4.0' DefaultTargets='Build'
xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
<PropertyGroup>
<OutputType>Library</OutputType>
<OutputPath>out</OutputPath>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
</PropertyGroup>
<ItemGroup>
<None Include='packages.config' />
</ItemGroup>
</Project>");
Util.CreateFile(proj1Directory, "packages.config",
@"<packages>
<package id=""packageA"" version=""1.1.0"" targetFramework=""net45"" />
</packages>");
Util.CreateFile(proj2Directory, "proj2.csproj",
@"<Project ToolsVersion='4.0' DefaultTargets='Build'
xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
<PropertyGroup>
<OutputType>Library</OutputType>
<OutputPath>out</OutputPath>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
</PropertyGroup>
<ItemGroup>
<None Include='packages.config' />
</ItemGroup>
</Project>");
Util.CreateFile(proj2Directory, "packages.config",
@"<packages>
<package id=""packageB"" version=""2.2.0"" targetFramework=""net45"" />
</packages>");
// Act
var r = CommandRunner.Run(
nugetexe,
tempPath,
"restore " + workingPath + " -Source " + repositoryPath,
waitForExit: true);
// Assert
Assert.Equal(1, r.Item1);
Assert.Contains("Cannot locate a solution file.", r.Item2);
var packageFileA = Path.Combine(workingPath, @"packages\packageA.1.1.0\packageA.1.1.0.nupkg");
var packageFileB = Path.Combine(workingPath, @"packages\packageB.2.2.0\packageB.2.2.0.nupkg");
Assert.False(File.Exists(packageFileA));
Assert.False(File.Exists(packageFileB));
}
finally
{
Directory.SetCurrentDirectory(currentDirectory);
Util.DeleteDirectory(workingPath);
}
}
// Tests that package restore loads the correct config file when -ConfigFile
// is specified.
[Fact]
public void RestoreCommand_ConfigFile()
{
// Arrange
var tempPath = Path.GetTempPath();
var workingPath = Path.Combine(tempPath, Guid.NewGuid().ToString());
var repositoryPath = Path.Combine(workingPath, Guid.NewGuid().ToString());
var proj1Directory = Path.Combine(workingPath, "proj1");
var currentDirectory = Directory.GetCurrentDirectory();
var targetDir = ConfigurationManager.AppSettings["TargetDir"];
var nugetexe = Path.Combine(targetDir, "nuget.exe");
try
{
Util.CreateDirectory(workingPath);
Util.CreateDirectory(repositoryPath);
Util.CreateDirectory(proj1Directory);
Util.CreateTestPackage("packageA", "1.1.0", repositoryPath);
Util.CreateFile(workingPath, "a.sln",
@"
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 2012
Project(""{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}"") = ""proj1"", ""proj1\proj1.csproj"", ""{A04C59CC-7622-4223-B16B-CDF2ECAD438D}""
EndProject");
Util.CreateFile(workingPath, "my.config",
String.Format(CultureInfo.InvariantCulture,
@"<?xml version=""1.0"" encoding=""utf-8""?>
<configuration>
<packageSources>
<add key=""mysouce"" value=""{0}"" />
</packageSources>
</configuration>", repositoryPath));
Util.CreateFile(proj1Directory, "proj1.csproj",
@"<Project ToolsVersion='4.0' DefaultTargets='Build'
xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
<PropertyGroup>
<OutputType>Library</OutputType>
<OutputPath>out</OutputPath>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
</PropertyGroup>
<ItemGroup>
<None Include='packages.config' />
</ItemGroup>
</Project>");
Util.CreateFile(proj1Directory, "packages.config",
@"<packages>
<package id=""packageA"" version=""1.1.0"" targetFramework=""net45"" />
</packages>");
// Act
// the package source listed in my.config will be used.
var r = CommandRunner.Run(
nugetexe,
workingPath,
"restore -ConfigFile my.config",
waitForExit: true);
// Assert
Assert.Equal(0, r.Item1);
var packageFileA = Path.Combine(workingPath, @"packages\packageA.1.1.0\packageA.1.1.0.nupkg");
Assert.True(File.Exists(packageFileA));
}
finally
{
Directory.SetCurrentDirectory(currentDirectory);
Util.DeleteDirectory(workingPath);
}
}
// Tests that when -PackageSaveMode is set to nuspec, the nuspec files, instead of
// nupkg files, are saved.
[Fact]
public void RestoreCommand_PackageSaveModeNuspec()
{
// Arrange
var tempPath = Path.GetTempPath();
var workingPath = Path.Combine(tempPath, Guid.NewGuid().ToString());
var repositoryPath = Path.Combine(workingPath, Guid.NewGuid().ToString());
var proj1Directory = Path.Combine(workingPath, "proj1");
var proj2Directory = Path.Combine(workingPath, "proj2");
var currentDirectory = Directory.GetCurrentDirectory();
var targetDir = ConfigurationManager.AppSettings["TargetDir"];
var nugetexe = Path.Combine(targetDir, "nuget.exe");
try
{
Util.CreateDirectory(workingPath);
Util.CreateDirectory(repositoryPath);
Util.CreateDirectory(proj1Directory);
Util.CreateDirectory(proj2Directory);
Util.CreateTestPackage("packageA", "1.1.0", repositoryPath);
Util.CreateTestPackage("packageB", "2.2.0", repositoryPath);
Util.CreateFile(workingPath, "a.sln",
@"
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 2012
Project(""{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}"") = ""proj1"", ""proj1\proj1.csproj"", ""{A04C59CC-7622-4223-B16B-CDF2ECAD438D}""
EndProject
Project(""{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}"") = ""proj2"", ""proj2\proj2.csproj"", ""{42641DAE-D6C4-49D4-92EA-749D2573554A}""
EndProject");
Util.CreateFile(proj1Directory, "proj1.csproj",
@"<Project ToolsVersion='4.0' DefaultTargets='Build'
xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
<PropertyGroup>
<OutputType>Library</OutputType>
<OutputPath>out</OutputPath>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
</PropertyGroup>
<ItemGroup>
<None Include='packages.config' />
</ItemGroup>
</Project>");
Util.CreateFile(proj1Directory, "packages.config",
@"<packages>
<package id=""packageA"" version=""1.1.0"" targetFramework=""net45"" />
</packages>");
Util.CreateFile(proj2Directory, "proj2.csproj",
@"<Project ToolsVersion='4.0' DefaultTargets='Build'
xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
<PropertyGroup>
<OutputType>Library</OutputType>
<OutputPath>out</OutputPath>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
</PropertyGroup>
<ItemGroup>
<None Include='packages.config' />
</ItemGroup>
</Project>");
Util.CreateFile(proj2Directory, "packages.config",
@"<packages>
<package id=""packageB"" version=""2.2.0"" targetFramework=""net45"" />
</packages>");
// Act
var r = CommandRunner.Run(
nugetexe,
workingPath,
"restore -Source " + repositoryPath + " -PackageSaveMode nuspec",
waitForExit: true);
// Assert
Assert.Equal(0, r.Item1);
var packageFileA = Path.Combine(workingPath, @"packages\packageA.1.1.0\packageA.1.1.0.nupkg");
var nuspecFileA = Path.Combine(workingPath, @"packages\packageA.1.1.0\packageA.1.1.0.nuspec");
var packageFileB = Path.Combine(workingPath, @"packages\packageB.2.2.0\packageB.2.2.0.nupkg");
var nuspecFileB = Path.Combine(workingPath, @"packages\packageB.2.2.0\packageB.2.2.0.nuspec");
Assert.True(!File.Exists(packageFileA));
Assert.True(!File.Exists(packageFileB));
Assert.True(File.Exists(nuspecFileA));
Assert.True(File.Exists(nuspecFileB));
}
finally
{
Directory.SetCurrentDirectory(currentDirectory);
Util.DeleteDirectory(workingPath);
}
}
// Tests restore from an http source.
[Fact]
public void RestoreCommand_FromHttpSource()
{
var targetDir = ConfigurationManager.AppSettings["TargetDir"];
var nugetexe = Path.Combine(targetDir, "nuget.exe");
var tempPath = Path.GetTempPath();
var workingDirectory = Path.Combine(tempPath, Guid.NewGuid().ToString());
var packageDirectory = Path.Combine(tempPath, Guid.NewGuid().ToString());
var mockServerEndPoint = "http://localhost:1234/";
try
{
// Arrange
Util.CreateDirectory(packageDirectory);
Util.CreateDirectory(workingDirectory);
var packageFileName = Util.CreateTestPackage("testPackage1", "1.1.0", packageDirectory);
var package = new ZipPackage(packageFileName);
MachineCache.Default.RemovePackage(package);
Util.CreateFile(
workingDirectory,
"packages.config",
@"
<packages>
<package id=""testPackage1"" version=""1.1.0"" />
</packages>");
var server = new MockServer(mockServerEndPoint);
bool getPackageByVersionIsCalled = false;
bool packageDownloadIsCalled = false;
server.Get.Add("/nuget/Packages(Id='testPackage1',Version='1.1.0')", r =>
new Action<HttpListenerResponse>(response =>
{
getPackageByVersionIsCalled = true;
response.ContentType = "application/atom+xml;type=entry;charset=utf-8";
var odata = server.ToOData(package);
MockServer.SetResponseContent(response, odata);
}));
server.Get.Add("/package/testPackage1", r =>
new Action<HttpListenerResponse>(response =>
{
packageDownloadIsCalled = true;
response.ContentType = "application/zip";
using (var stream = package.GetStream())
{
var content = stream.ReadAllBytes();
MockServer.SetResponseContent(response, content);
}
}));
server.Get.Add("/nuget", r => "OK");
server.Start();
// Act
var args = "restore packages.config -PackagesDirectory . -Source " + mockServerEndPoint + "nuget";
var r1 = CommandRunner.Run(
nugetexe,
workingDirectory,
args,
waitForExit: true);
server.Stop();
// Assert
Assert.Equal(0, r1.Item1);
Assert.True(getPackageByVersionIsCalled);
Assert.True(packageDownloadIsCalled);
}
finally
{
// Cleanup
Util.DeleteDirectory(packageDirectory);
Util.DeleteDirectory(workingDirectory);
}
}
}
}
| 42.008105 | 131 | 0.59153 | [
"ECL-2.0",
"Apache-2.0"
] | anaselhajjaji/nuget | test/Test.Integration/NuGetCommandLine/NuGetRestoreCommandTest.cs | 41,464 | C# |
namespace SoftGym.Services
{
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using CloudinaryDotNet;
using CloudinaryDotNet.Actions;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using SoftGym.Services.Contracts;
public class CloudinaryService : ICloudinaryService
{
private readonly Cloudinary cloudinary;
private readonly string defaultProfilePicUrl = @"https://res.cloudinary.com/dzivpr6fj/image/upload/v1586495920/ClubestPics/default-profile-picture-clipart-8_mwungz.jpg";
public CloudinaryService(Cloudinary cloudinary)
{
this.cloudinary = cloudinary;
}
public async Task<string> UploudAsync(IFormFile file)
{
if (file == null || this.IsFileValid(file) == false)
{
return this.defaultProfilePicUrl;
}
string url = " ";
byte[] fileBytes;
using (var stream = new MemoryStream())
{
file.CopyTo(stream);
fileBytes = stream.ToArray();
}
using (var uploadStream = new MemoryStream(fileBytes))
{
var uploadParams = new ImageUploadParams()
{
File = new FileDescription(file.FileName, uploadStream),
};
var result = await this.cloudinary.UploadAsync(uploadParams);
url = result.Uri.AbsoluteUri;
}
return url;
}
public async Task<string> UploudAsync(byte[] file)
{
byte[] imageBytes = file;
string url = " ";
using (var uploadStream = new MemoryStream(imageBytes))
{
var uploadParams = new ImageUploadParams()
{
File = new FileDescription(file.ToString(), uploadStream),
};
var result = await this.cloudinary.UploadAsync(uploadParams);
url = result.Uri.AbsoluteUri;
}
return url;
}
public async Task<string> UploadVideoAsync(IFormFile file)
{
string url = " ";
byte[] fileBytes;
using (var stream = new MemoryStream())
{
file.CopyTo(stream);
fileBytes = stream.ToArray();
}
using (var uploadStream = new MemoryStream(fileBytes))
{
var uploadParams = new VideoUploadParams()
{
File = new FileDescription(file.ToString(), uploadStream),
};
var result = await this.cloudinary.UploadAsync(uploadParams);
url = result.Uri.AbsoluteUri;
}
return url;
}
public bool IsFileValid(IFormFile photoFile)
{
if (photoFile == null)
{
return true;
}
string[] validTypes = new string[]
{
"image/x-png", "image/gif", "image/jpeg", "image/jpg", "image/png", "image/gif", "image/svg", "video/x-msvideo", "video/mp4",
};
if (validTypes.Contains(photoFile.ContentType) == false)
{
return false;
}
return true;
}
public bool IsVideoFileValid(IFormFile photoFile)
{
if (photoFile == null)
{
return true;
}
string[] validTypes = new string[]
{
"video/x-msvideo", "video/mp4", "video/x-flv", "video/x-ms-wmv", "video/quicktime",
};
if (validTypes.Contains(photoFile.ContentType) == false)
{
return false;
}
return true;
}
}
}
| 28.838235 | 177 | 0.507139 | [
"MIT"
] | PlamenMichev/SoftGym | Services/SoftGym.Services/CloudinaryService.cs | 3,924 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace DevionGames
{
public class MoveTo : MonoBehaviour
{
[SerializeField]
private string m_Tag="Player";
[SerializeField]
private float speed = 3f;
private Transform player;
[SerializeField]
private Vector3 m_Offset = Vector3.up;
void Start()
{
GameObject go = GameObject.FindGameObjectWithTag(this.m_Tag);
if (go != null)
player = go.transform;
transform.rotation = Random.rotation;
}
// Update is called once per frame
void Update()
{
if (player == null)
return;
Vector3 dir = (player.position+ this.m_Offset) - transform.position;
// dir.y = 0.0f;
transform.rotation = Quaternion.Lerp(transform.rotation, Quaternion.LookRotation(dir), Time.deltaTime*10f);
// transform.LookAt(player.position + this.m_Offset);
if (Vector3.Distance(transform.position, player.position + this.m_Offset) > 0.5f)
{
transform.Translate(new Vector3(0, 0, speed * Time.deltaTime));
}
else {
Destroy(gameObject);
}
}
}
} | 28.404255 | 119 | 0.5603 | [
"MIT"
] | jlarnett/WinstonLakeV2 | Assets/Asset Packs/Devion Games/Utilities/Scripts/Runtime/MoveTo.cs | 1,337 | 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: AssemblyConfiguration("")]
[assembly: AssemblyCompany("ZXing.Net Development")]
[assembly: AssemblyProduct("ZXing.Magick")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyDescription("ZXing.Net Bindings to Magick")]
[assembly: AssemblyInformationalVersion("0.16.4")]
// 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("e1d874e4-4e0f-4427-99d8-4b408f0f8db0")]
| 44.782609 | 85 | 0.76699 | [
"Apache-2.0"
] | LORDofDOOM/ZXing.Net | Source/Bindings/ZXing.Magick/Properties/AssemblyInfo.cs | 1,033 | C# |
/**
* MIT License
*
* Copyright (c) 2020 Philip Klatt
*
* 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 UtinniCore.Utinni;
using UtinniCoreDotNet.Callbacks;
namespace TJT.SWG
{
public class CuiImpl
{
public CuiImpl() { }
public void ReloadUi()
{
GameCallbacks.AddMainLoopCall(() =>
{
UtinniCore.Utinni.CuiMisc.cui_misc.ReloadUi();
});
}
public void RestartMusic()
{
GameCallbacks.AddMainLoopCall(() =>
{
CuiManager.RestartMusic();
});
}
}
}
| 32.470588 | 81 | 0.673309 | [
"MIT"
] | ModTheGalaxy/UtinniPlugins | The Jawa Toolbox/TheJawaToolboxDotNet/SWG/CuiImpl.cs | 1,658 | C# |
using System;
namespace Genocs.MassTransit.Contracts
{
public interface OrderFulfillmentFaulted
{
Guid OrderId { get; }
}
}
| 14.6 | 44 | 0.671233 | [
"MIT"
] | Genocs/mass-transit-course | src/05-saga-advanced/Genocs.MassTransit.Contracts/OrderFulfillmentFaulted.cs | 148 | C# |
// ***********************************************************************
// Copyright (c) 2015 Charlie Poole
//
// 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.
// ***********************************************************************
#if NET_4_0 || NET_4_5 || PORTABLE
using System.Threading.Tasks;
using NUnit.Framework;
using System;
#if NET_4_0
using Task = System.Threading.Tasks.TaskEx;
#endif
namespace NUnit.TestData
{
public class AsyncDummyFixture
{
[Test]
public async void AsyncVoid()
{
await Task.Delay(1); // To avoid warning message
}
[Test]
public async System.Threading.Tasks.Task AsyncTask()
{
await Task.Delay(1);
}
[Test]
public async Task<int> AsyncGenericTask()
{
return await Task.FromResult(1);
}
[Test]
public System.Threading.Tasks.Task NonAsyncTask()
{
return Task.Delay(0);
}
[Test]
public Task<int> NonAsyncGenericTask()
{
return Task.FromResult(1);
}
[TestCase(4)]
public async void AsyncVoidTestCase(int x)
{
await Task.Delay(0);
}
[TestCase(ExpectedResult = 1)]
public async void AsyncVoidTestCaseWithExpectedResult()
{
await Task.Run(() => 1);
}
[TestCase(4)]
public async System.Threading.Tasks.Task AsyncTaskTestCase(int x)
{
await Task.Delay(0);
}
[TestCase(ExpectedResult = 1)]
public async System.Threading.Tasks.Task AsyncTaskTestCaseWithExpectedResult()
{
await Task.Run(() => 1);
}
[TestCase(4)]
public async Task<int> AsyncGenericTaskTestCase()
{
return await Task.Run(() => 1);
}
[TestCase(ExpectedResult = 1)]
public async Task<int> AsyncGenericTaskTestCaseWithExpectedResult()
{
return await Task.Run(() => 1);
}
[TestCase(4)]
public System.Threading.Tasks.Task TaskTestCase(int x)
{
return Task.Delay(0);
}
[TestCase(ExpectedResult = 1)]
public System.Threading.Tasks.Task TaskTestCaseWithExpectedResult()
{
return Task.Run(() => 1);
}
[TestCase(4)]
public Task<int> GenericTaskTestCase()
{
return Task.Run(() => 1);
}
[TestCase(ExpectedResult = 1)]
public Task<int> GenericTaskTestCaseWithExpectedResult()
{
return Task.Run(() => 1);
}
private async Task<int> Throw()
{
Func<int> thrower = () => { throw new InvalidOperationException(); };
return await Task.Run( thrower );
}
}
}
#endif | 29.179104 | 86 | 0.576726 | [
"MIT"
] | JetBrains/nunit | src/NUnitFramework/testdata/AsyncDummyFixture.cs | 3,910 | C# |
using System.Collections.Generic;
using System.Linq;
namespace HGV.Divine
{
/// <summary>
/// Helper class for working with a single team.
/// </summary>
public class Team<TPlayer>
{
private readonly Dictionary<TPlayer, Rating> _PlayerRatings = new Dictionary<TPlayer, Rating>();
/// <summary>
/// Constructs a new team.
/// </summary>
public Team()
{
}
/// <summary>
/// Constructs a <see cref="Team"/> and populates it with the specified <paramref name="player"/>.
/// </summary>
/// <param name="player">The player to add.</param>
/// <param name="rating">The rating of the <paramref name="player"/>.</param>
public Team(TPlayer player, Rating rating)
{
AddPlayer(player, rating);
}
/// <summary>
/// Adds the <paramref name="player"/> to the team.
/// </summary>
/// <param name="player">The player to add.</param>
/// <param name="rating">The rating of the <paramref name="player"/>.</param>
/// <returns>The instance of the team (for chaining convenience).</returns>
public Team<TPlayer> AddPlayer(TPlayer player, Rating rating)
{
_PlayerRatings[player] = rating;
return this;
}
/// <summary>
/// Returns the <see cref="Team"/> as a simple dictionary.
/// </summary>
/// <returns>The <see cref="Team"/> as a simple dictionary.</returns>
public IDictionary<TPlayer, Rating> AsDictionary()
{
return _PlayerRatings;
}
}
/// <summary>
/// Helper class for working with a single team.
/// </summary>
public class Team : Team<Player>
{
/// <summary>
/// Constructs a new team.
/// </summary>
public Team()
{
}
/// <summary>
/// Constructs a <see cref="Team"/> and populates it with the specified <paramref name="player"/>.
/// </summary>
/// <param name="player">The player to add.</param>
/// <param name="rating">The rating of the <paramref name="player"/>.</param>
public Team(Player player, Rating rating)
: base(player, rating)
{
}
}
/// <summary>
/// Helper class for working with multiple teams.
/// </summary>
public static class Teams
{
/// <summary>
/// Concatenates multiple teams into a list of teams.
/// </summary>
/// <param name="teams">The teams to concatenate together.</param>
/// <returns>A sequence of teams.</returns>
public static IEnumerable<IDictionary<TPlayer, Rating>> Concat<TPlayer>(params Team<TPlayer>[] teams)
{
return teams.Select(t => t.AsDictionary());
}
}
} | 31.888889 | 109 | 0.549477 | [
"MIT"
] | HighGroundVision/Divine | src/Team.cs | 2,872 | 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("Wpf")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Wpf")]
[assembly: AssemblyCopyright("Copyright © 2021")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("04c91250-d415-49e0-aec5-e77f36ddf0e1")]
// 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.135135 | 84 | 0.744541 | [
"MIT"
] | stumathews/WpfStepByStep | Wpf1/Properties/AssemblyInfo.cs | 1,377 | 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 ec2-2016-11-15.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.EC2.Model
{
/// <summary>
/// This is the response object from the DescribeClientVpnTargetNetworks operation.
/// </summary>
public partial class DescribeClientVpnTargetNetworksResponse : AmazonWebServiceResponse
{
private List<TargetNetwork> _clientVpnTargetNetworks = new List<TargetNetwork>();
private string _nextToken;
/// <summary>
/// Gets and sets the property ClientVpnTargetNetworks.
/// <para>
/// Information about the associated target networks.
/// </para>
/// </summary>
public List<TargetNetwork> ClientVpnTargetNetworks
{
get { return this._clientVpnTargetNetworks; }
set { this._clientVpnTargetNetworks = value; }
}
// Check to see if ClientVpnTargetNetworks property is set
internal bool IsSetClientVpnTargetNetworks()
{
return this._clientVpnTargetNetworks != null && this._clientVpnTargetNetworks.Count > 0;
}
/// <summary>
/// Gets and sets the property NextToken.
/// <para>
/// The token to use to retrieve the next page of results. This value is <code>null</code>
/// when there are no more results to return.
/// </para>
/// </summary>
public string NextToken
{
get { return this._nextToken; }
set { this._nextToken = value; }
}
// Check to see if NextToken property is set
internal bool IsSetNextToken()
{
return this._nextToken != null;
}
}
} | 32.467532 | 101 | 0.6488 | [
"Apache-2.0"
] | ChristopherButtars/aws-sdk-net | sdk/src/Services/EC2/Generated/Model/DescribeClientVpnTargetNetworksResponse.cs | 2,500 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Security;
using System.Security.Authentication;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Security.Principal;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.HttpSys.Internal;
using Microsoft.Extensions.Logging;
namespace Microsoft.AspNetCore.Server.HttpSys
{
internal sealed class Request
{
private NativeRequestContext _nativeRequestContext;
private X509Certificate2 _clientCert;
// TODO: https://github.com/aspnet/HttpSysServer/issues/231
// private byte[] _providedTokenBindingId;
// private byte[] _referredTokenBindingId;
private BoundaryType _contentBoundaryType;
private long? _contentLength;
private RequestStream _nativeStream;
private AspNetCore.HttpSys.Internal.SocketAddress _localEndPoint;
private AspNetCore.HttpSys.Internal.SocketAddress _remoteEndPoint;
private IReadOnlyDictionary<int, ReadOnlyMemory<byte>> _requestInfo;
private bool _isDisposed = false;
internal Request(RequestContext requestContext, NativeRequestContext nativeRequestContext)
{
// TODO: Verbose log
RequestContext = requestContext;
_nativeRequestContext = nativeRequestContext;
_contentBoundaryType = BoundaryType.None;
RequestId = nativeRequestContext.RequestId;
UConnectionId = nativeRequestContext.ConnectionId;
SslStatus = nativeRequestContext.SslStatus;
KnownMethod = nativeRequestContext.VerbId;
Method = _nativeRequestContext.GetVerb();
RawUrl = nativeRequestContext.GetRawUrl();
var cookedUrl = nativeRequestContext.GetCookedUrl();
QueryString = cookedUrl.GetQueryString() ?? string.Empty;
var rawUrlInBytes = _nativeRequestContext.GetRawUrlInBytes();
var originalPath = RequestUriBuilder.DecodeAndUnescapePath(rawUrlInBytes);
PathBase = string.Empty;
Path = originalPath;
// 'OPTIONS * HTTP/1.1'
if (KnownMethod == HttpApiTypes.HTTP_VERB.HttpVerbOPTIONS && string.Equals(RawUrl, "*", StringComparison.Ordinal))
{
PathBase = string.Empty;
Path = string.Empty;
}
else
{
var prefix = requestContext.Server.Options.UrlPrefixes.GetPrefix((int)nativeRequestContext.UrlContext);
// Prefix may be null if the requested has been transfered to our queue
if (!(prefix is null))
{
if (originalPath.Length == prefix.PathWithoutTrailingSlash.Length)
{
// They matched exactly except for the trailing slash.
PathBase = originalPath;
Path = string.Empty;
}
else
{
// url: /base/path, prefix: /base/, base: /base, path: /path
// url: /, prefix: /, base: , path: /
PathBase = originalPath.Substring(0, prefix.PathWithoutTrailingSlash.Length); // Preserve the user input casing
Path = originalPath.Substring(prefix.PathWithoutTrailingSlash.Length);
}
}
else if (requestContext.Server.Options.UrlPrefixes.TryMatchLongestPrefix(IsHttps, cookedUrl.GetHost(), originalPath, out var pathBase, out var path))
{
PathBase = pathBase;
Path = path;
}
}
ProtocolVersion = _nativeRequestContext.GetVersion();
Headers = new RequestHeaders(_nativeRequestContext);
User = _nativeRequestContext.GetUser();
if (IsHttps)
{
GetTlsHandshakeResults();
}
// GetTlsTokenBindingInfo(); TODO: https://github.com/aspnet/HttpSysServer/issues/231
// Finished directly accessing the HTTP_REQUEST structure.
_nativeRequestContext.ReleasePins();
// TODO: Verbose log parameters
}
internal ulong UConnectionId { get; }
// No ulongs in public APIs...
public long ConnectionId => (long)UConnectionId;
internal ulong RequestId { get; }
private SslStatus SslStatus { get; }
private RequestContext RequestContext { get; }
// With the leading ?, if any
public string QueryString { get; }
public long? ContentLength
{
get
{
if (_contentBoundaryType == BoundaryType.None)
{
string transferEncoding = Headers[HttpKnownHeaderNames.TransferEncoding];
if (string.Equals("chunked", transferEncoding?.Trim(), StringComparison.OrdinalIgnoreCase))
{
_contentBoundaryType = BoundaryType.Chunked;
}
else
{
string length = Headers[HttpKnownHeaderNames.ContentLength];
long value;
if (length != null && long.TryParse(length.Trim(), NumberStyles.None,
CultureInfo.InvariantCulture.NumberFormat, out value))
{
_contentBoundaryType = BoundaryType.ContentLength;
_contentLength = value;
}
else
{
_contentBoundaryType = BoundaryType.Invalid;
}
}
}
return _contentLength;
}
}
public RequestHeaders Headers { get; }
internal HttpApiTypes.HTTP_VERB KnownMethod { get; }
internal bool IsHeadMethod => KnownMethod == HttpApiTypes.HTTP_VERB.HttpVerbHEAD;
public string Method { get; }
public Stream Body => EnsureRequestStream() ?? Stream.Null;
private RequestStream EnsureRequestStream()
{
if (_nativeStream == null && HasEntityBody)
{
_nativeStream = new RequestStream(RequestContext);
}
return _nativeStream;
}
public bool HasRequestBodyStarted => _nativeStream?.HasStarted ?? false;
public long? MaxRequestBodySize
{
get => EnsureRequestStream()?.MaxSize;
set
{
EnsureRequestStream();
if (_nativeStream != null)
{
_nativeStream.MaxSize = value;
}
}
}
public string PathBase { get; }
public string Path { get; }
public bool IsHttps => SslStatus != SslStatus.Insecure;
public string RawUrl { get; }
public Version ProtocolVersion { get; }
public bool HasEntityBody
{
get
{
// accessing the ContentLength property delay creates _contentBoundaryType
return (ContentLength.HasValue && ContentLength.Value > 0 && _contentBoundaryType == BoundaryType.ContentLength)
|| _contentBoundaryType == BoundaryType.Chunked;
}
}
private AspNetCore.HttpSys.Internal.SocketAddress RemoteEndPoint
{
get
{
if (_remoteEndPoint == null)
{
_remoteEndPoint = _nativeRequestContext.GetRemoteEndPoint();
}
return _remoteEndPoint;
}
}
private AspNetCore.HttpSys.Internal.SocketAddress LocalEndPoint
{
get
{
if (_localEndPoint == null)
{
_localEndPoint = _nativeRequestContext.GetLocalEndPoint();
}
return _localEndPoint;
}
}
// TODO: Lazy cache?
public IPAddress RemoteIpAddress => RemoteEndPoint.GetIPAddress();
public IPAddress LocalIpAddress => LocalEndPoint.GetIPAddress();
public int RemotePort => RemoteEndPoint.GetPort();
public int LocalPort => LocalEndPoint.GetPort();
public string Scheme => IsHttps ? Constants.HttpsScheme : Constants.HttpScheme;
// HTTP.Sys allows you to upgrade anything to opaque unless content-length > 0 or chunked are specified.
internal bool IsUpgradable => !HasEntityBody && ComNetOS.IsWin8orLater;
internal WindowsPrincipal User { get; }
public SslProtocols Protocol { get; private set; }
public CipherAlgorithmType CipherAlgorithm { get; private set; }
public int CipherStrength { get; private set; }
public HashAlgorithmType HashAlgorithm { get; private set; }
public int HashStrength { get; private set; }
public ExchangeAlgorithmType KeyExchangeAlgorithm { get; private set; }
public int KeyExchangeStrength { get; private set; }
public IReadOnlyDictionary<int, ReadOnlyMemory<byte>> RequestInfo
{
get
{
if (_requestInfo == null)
{
_requestInfo = _nativeRequestContext.GetRequestInfo();
}
return _requestInfo;
}
}
private void GetTlsHandshakeResults()
{
var handshake = _nativeRequestContext.GetTlsHandshake();
Protocol = handshake.Protocol;
// The OS considers client and server TLS as different enum values. SslProtocols choose to combine those for some reason.
// We need to fill in the client bits so the enum shows the expected protocol.
// https://docs.microsoft.com/windows/desktop/api/schannel/ns-schannel-_secpkgcontext_connectioninfo
// Compare to https://referencesource.microsoft.com/#System/net/System/Net/SecureProtocols/_SslState.cs,8905d1bf17729de3
#pragma warning disable CS0618 // Type or member is obsolete
if ((Protocol & SslProtocols.Ssl2) != 0)
{
Protocol |= SslProtocols.Ssl2;
}
if ((Protocol & SslProtocols.Ssl3) != 0)
{
Protocol |= SslProtocols.Ssl3;
}
#pragma warning restore CS0618 // Type or member is obsolete
if ((Protocol & SslProtocols.Tls) != 0)
{
Protocol |= SslProtocols.Tls;
}
if ((Protocol & SslProtocols.Tls11) != 0)
{
Protocol |= SslProtocols.Tls11;
}
if ((Protocol & SslProtocols.Tls12) != 0)
{
Protocol |= SslProtocols.Tls12;
}
CipherAlgorithm = handshake.CipherType;
CipherStrength = (int)handshake.CipherStrength;
HashAlgorithm = handshake.HashType;
HashStrength = (int)handshake.HashStrength;
KeyExchangeAlgorithm = handshake.KeyExchangeType;
KeyExchangeStrength = (int)handshake.KeyExchangeStrength;
}
public X509Certificate2 ClientCertificate
{
get
{
if (_clientCert == null && SslStatus == SslStatus.ClientCert)
{
try
{
_clientCert = _nativeRequestContext.GetClientCertificate();
}
catch (CryptographicException ce)
{
RequestContext.Logger.LogDebug(LoggerEventIds.ErrorInReadingCertificate, ce, "An error occurred reading the client certificate.");
}
catch (SecurityException se)
{
RequestContext.Logger.LogDebug(LoggerEventIds.ErrorInReadingCertificate, se, "An error occurred reading the client certificate.");
}
}
return _clientCert;
}
}
public bool CanDelegate => !(HasRequestBodyStarted || RequestContext.Response.HasStarted);
// Populates the client certificate. The result may be null if there is no client cert.
// TODO: Does it make sense for this to be invoked multiple times (e.g. renegotiate)? Client and server code appear to
// enable this, but it's unclear what Http.Sys would do.
public async Task<X509Certificate2> GetClientCertificateAsync(CancellationToken cancellationToken = default(CancellationToken))
{
if (SslStatus == SslStatus.Insecure)
{
// Non-SSL
return null;
}
// TODO: Verbose log
if (_clientCert != null)
{
return _clientCert;
}
cancellationToken.ThrowIfCancellationRequested();
var certLoader = new ClientCertLoader(RequestContext, cancellationToken);
try
{
await certLoader.LoadClientCertificateAsync().SupressContext();
// Populate the environment.
if (certLoader.ClientCert != null)
{
_clientCert = certLoader.ClientCert;
}
// TODO: Expose errors and exceptions?
}
catch (Exception)
{
if (certLoader != null)
{
certLoader.Dispose();
}
throw;
}
return _clientCert;
}
/* TODO: https://github.com/aspnet/WebListener/issues/231
private byte[] GetProvidedTokenBindingId()
{
return _providedTokenBindingId;
}
private byte[] GetReferredTokenBindingId()
{
return _referredTokenBindingId;
}
*/
// Only call from the constructor so we can directly access the native request blob.
// This requires Windows 10 and the following reg key:
// Set Key: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\HTTP\Parameters to Value: EnableSslTokenBinding = 1 [DWORD]
// Then for IE to work you need to set these:
// Key: HKLM\Software\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_ENABLE_TOKEN_BINDING
// Value: "iexplore.exe"=dword:0x00000001
// Key: HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_ENABLE_TOKEN_BINDING
// Value: "iexplore.exe"=dword:00000001
// TODO: https://github.com/aspnet/WebListener/issues/231
// TODO: https://github.com/aspnet/WebListener/issues/204 Move to NativeRequestContext
/*
private unsafe void GetTlsTokenBindingInfo()
{
var nativeRequest = (HttpApi.HTTP_REQUEST_V2*)_nativeRequestContext.RequestBlob;
for (int i = 0; i < nativeRequest->RequestInfoCount; i++)
{
var pThisInfo = &nativeRequest->pRequestInfo[i];
if (pThisInfo->InfoType == HttpApi.HTTP_REQUEST_INFO_TYPE.HttpRequestInfoTypeSslTokenBinding)
{
var pTokenBindingInfo = (HttpApi.HTTP_REQUEST_TOKEN_BINDING_INFO*)pThisInfo->pInfo;
_providedTokenBindingId = TokenBindingUtil.GetProvidedTokenIdFromBindingInfo(pTokenBindingInfo, out _referredTokenBindingId);
}
}
}
*/
internal uint GetChunks(ref int dataChunkIndex, ref uint dataChunkOffset, byte[] buffer, int offset, int size)
{
return _nativeRequestContext.GetChunks(ref dataChunkIndex, ref dataChunkOffset, buffer, offset, size);
}
// should only be called from RequestContext
internal void Dispose()
{
// TODO: Verbose log
_isDisposed = true;
_nativeRequestContext.Dispose();
(User?.Identity as WindowsIdentity)?.Dispose();
if (_nativeStream != null)
{
_nativeStream.Dispose();
}
}
private void CheckDisposed()
{
if (_isDisposed)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
}
internal void SwitchToOpaqueMode()
{
if (_nativeStream == null)
{
_nativeStream = new RequestStream(RequestContext);
}
_nativeStream.SwitchToOpaqueMode();
}
}
}
| 37.028139 | 166 | 0.572514 | [
"Apache-2.0"
] | ar0311/aspnetcore | src/Servers/HttpSys/src/RequestProcessing/Request.cs | 17,107 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// ------------------------------------------------------------------------------
// Changes to this file must follow the https://aka.ms/api-review process.
// ------------------------------------------------------------------------------
namespace System.Text.Json
{
public enum JsonCommentHandling : byte
{
Disallow = (byte)0,
Skip = (byte)1,
Allow = (byte)2,
}
public sealed partial class JsonDocument : System.IDisposable
{
internal JsonDocument() { }
public System.Text.Json.JsonElement RootElement { get { throw null; } }
public void Dispose() { }
public static System.Text.Json.JsonDocument Parse(System.Buffers.ReadOnlySequence<byte> utf8Json, System.Text.Json.JsonDocumentOptions options = default(System.Text.Json.JsonDocumentOptions)) { throw null; }
public static System.Text.Json.JsonDocument Parse(System.IO.Stream utf8Json, System.Text.Json.JsonDocumentOptions options = default(System.Text.Json.JsonDocumentOptions)) { throw null; }
public static System.Text.Json.JsonDocument Parse(System.ReadOnlyMemory<byte> utf8Json, System.Text.Json.JsonDocumentOptions options = default(System.Text.Json.JsonDocumentOptions)) { throw null; }
public static System.Text.Json.JsonDocument Parse(System.ReadOnlyMemory<char> json, System.Text.Json.JsonDocumentOptions options = default(System.Text.Json.JsonDocumentOptions)) { throw null; }
public static System.Text.Json.JsonDocument Parse(string json, System.Text.Json.JsonDocumentOptions options = default(System.Text.Json.JsonDocumentOptions)) { throw null; }
public static System.Threading.Tasks.Task<System.Text.Json.JsonDocument> ParseAsync(System.IO.Stream utf8Json, System.Text.Json.JsonDocumentOptions options = default(System.Text.Json.JsonDocumentOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public static System.Text.Json.JsonDocument ParseValue(ref System.Text.Json.Utf8JsonReader reader) { throw null; }
public static bool TryParseValue(ref System.Text.Json.Utf8JsonReader reader, [System.Diagnostics.CodeAnalysis.NotNullWhenAttribute(true)] out System.Text.Json.JsonDocument? document) { throw null; }
public void WriteTo(System.Text.Json.Utf8JsonWriter writer) { }
}
public partial struct JsonDocumentOptions
{
private int _dummyPrimitive;
public bool AllowTrailingCommas { readonly get { throw null; } set { } }
public System.Text.Json.JsonCommentHandling CommentHandling { readonly get { throw null; } set { } }
public int MaxDepth { readonly get { throw null; } set { } }
}
public readonly partial struct JsonElement
{
private readonly object _dummy;
private readonly int _dummyPrimitive;
public System.Text.Json.JsonElement this[int index] { get { throw null; } }
public System.Text.Json.JsonValueKind ValueKind { get { throw null; } }
public System.Text.Json.JsonElement Clone() { throw null; }
public System.Text.Json.JsonElement.ArrayEnumerator EnumerateArray() { throw null; }
public System.Text.Json.JsonElement.ObjectEnumerator EnumerateObject() { throw null; }
public int GetArrayLength() { throw null; }
public bool GetBoolean() { throw null; }
public byte GetByte() { throw null; }
public byte[] GetBytesFromBase64() { throw null; }
public System.DateTime GetDateTime() { throw null; }
public System.DateTimeOffset GetDateTimeOffset() { throw null; }
public decimal GetDecimal() { throw null; }
public double GetDouble() { throw null; }
public System.Guid GetGuid() { throw null; }
public short GetInt16() { throw null; }
public int GetInt32() { throw null; }
public long GetInt64() { throw null; }
public System.Text.Json.JsonElement GetProperty(System.ReadOnlySpan<byte> utf8PropertyName) { throw null; }
public System.Text.Json.JsonElement GetProperty(System.ReadOnlySpan<char> propertyName) { throw null; }
public System.Text.Json.JsonElement GetProperty(string propertyName) { throw null; }
public string GetRawText() { throw null; }
[System.CLSCompliantAttribute(false)]
public sbyte GetSByte() { throw null; }
public float GetSingle() { throw null; }
public string? GetString() { throw null; }
[System.CLSCompliantAttribute(false)]
public ushort GetUInt16() { throw null; }
[System.CLSCompliantAttribute(false)]
public uint GetUInt32() { throw null; }
[System.CLSCompliantAttribute(false)]
public ulong GetUInt64() { throw null; }
public static System.Text.Json.JsonElement ParseValue(ref System.Text.Json.Utf8JsonReader reader) { throw null; }
public override string? ToString() { throw null; }
public bool TryGetByte(out byte value) { throw null; }
public bool TryGetBytesFromBase64([System.Diagnostics.CodeAnalysis.NotNullWhenAttribute(true)] out byte[]? value) { throw null; }
public bool TryGetDateTime(out System.DateTime value) { throw null; }
public bool TryGetDateTimeOffset(out System.DateTimeOffset value) { throw null; }
public bool TryGetDecimal(out decimal value) { throw null; }
public bool TryGetDouble(out double value) { throw null; }
public bool TryGetGuid(out System.Guid value) { throw null; }
public bool TryGetInt16(out short value) { throw null; }
public bool TryGetInt32(out int value) { throw null; }
public bool TryGetInt64(out long value) { throw null; }
public bool TryGetProperty(System.ReadOnlySpan<byte> utf8PropertyName, out System.Text.Json.JsonElement value) { throw null; }
public bool TryGetProperty(System.ReadOnlySpan<char> propertyName, out System.Text.Json.JsonElement value) { throw null; }
public bool TryGetProperty(string propertyName, out System.Text.Json.JsonElement value) { throw null; }
[System.CLSCompliantAttribute(false)]
public bool TryGetSByte(out sbyte value) { throw null; }
public bool TryGetSingle(out float value) { throw null; }
[System.CLSCompliantAttribute(false)]
public bool TryGetUInt16(out ushort value) { throw null; }
[System.CLSCompliantAttribute(false)]
public bool TryGetUInt32(out uint value) { throw null; }
[System.CLSCompliantAttribute(false)]
public bool TryGetUInt64(out ulong value) { throw null; }
public static bool TryParseValue(ref System.Text.Json.Utf8JsonReader reader, [System.Diagnostics.CodeAnalysis.NotNullWhenAttribute(true)] out System.Text.Json.JsonElement? element) { throw null; }
public bool ValueEquals(System.ReadOnlySpan<byte> utf8Text) { throw null; }
public bool ValueEquals(System.ReadOnlySpan<char> text) { throw null; }
public bool ValueEquals(string? text) { throw null; }
public void WriteTo(System.Text.Json.Utf8JsonWriter writer) { }
public partial struct ArrayEnumerator : System.Collections.Generic.IEnumerable<System.Text.Json.JsonElement>, System.Collections.Generic.IEnumerator<System.Text.Json.JsonElement>, System.Collections.IEnumerable, System.Collections.IEnumerator, System.IDisposable
{
private object _dummy;
private int _dummyPrimitive;
public System.Text.Json.JsonElement Current { get { throw null; } }
object System.Collections.IEnumerator.Current { get { throw null; } }
public void Dispose() { }
public System.Text.Json.JsonElement.ArrayEnumerator GetEnumerator() { throw null; }
public bool MoveNext() { throw null; }
public void Reset() { }
System.Collections.Generic.IEnumerator<System.Text.Json.JsonElement> System.Collections.Generic.IEnumerable<System.Text.Json.JsonElement>.GetEnumerator() { throw null; }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; }
}
public partial struct ObjectEnumerator : System.Collections.Generic.IEnumerable<System.Text.Json.JsonProperty>, System.Collections.Generic.IEnumerator<System.Text.Json.JsonProperty>, System.Collections.IEnumerable, System.Collections.IEnumerator, System.IDisposable
{
private object _dummy;
private int _dummyPrimitive;
public System.Text.Json.JsonProperty Current { get { throw null; } }
object System.Collections.IEnumerator.Current { get { throw null; } }
public void Dispose() { }
public System.Text.Json.JsonElement.ObjectEnumerator GetEnumerator() { throw null; }
public bool MoveNext() { throw null; }
public void Reset() { }
System.Collections.Generic.IEnumerator<System.Text.Json.JsonProperty> System.Collections.Generic.IEnumerable<System.Text.Json.JsonProperty>.GetEnumerator() { throw null; }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; }
}
}
public readonly partial struct JsonEncodedText : System.IEquatable<System.Text.Json.JsonEncodedText>
{
private readonly object _dummy;
private readonly int _dummyPrimitive;
public System.ReadOnlySpan<byte> EncodedUtf8Bytes { get { throw null; } }
public static System.Text.Json.JsonEncodedText Encode(System.ReadOnlySpan<byte> utf8Value, System.Text.Encodings.Web.JavaScriptEncoder? encoder = null) { throw null; }
public static System.Text.Json.JsonEncodedText Encode(System.ReadOnlySpan<char> value, System.Text.Encodings.Web.JavaScriptEncoder? encoder = null) { throw null; }
public static System.Text.Json.JsonEncodedText Encode(string value, System.Text.Encodings.Web.JavaScriptEncoder? encoder = null) { throw null; }
public override bool Equals([System.Diagnostics.CodeAnalysis.NotNullWhenAttribute(true)] object? obj) { throw null; }
public bool Equals(System.Text.Json.JsonEncodedText other) { throw null; }
public override int GetHashCode() { throw null; }
public override string ToString() { throw null; }
}
public partial class JsonException : System.Exception
{
public JsonException() { }
protected JsonException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
public JsonException(string? message) { }
public JsonException(string? message, System.Exception? innerException) { }
public JsonException(string? message, string? path, long? lineNumber, long? bytePositionInLine) { }
public JsonException(string? message, string? path, long? lineNumber, long? bytePositionInLine, System.Exception? innerException) { }
public long? BytePositionInLine { get { throw null; } }
public long? LineNumber { get { throw null; } }
public override string Message { get { throw null; } }
public string? Path { get { throw null; } }
public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
}
public abstract partial class JsonNamingPolicy
{
protected JsonNamingPolicy() { }
public static System.Text.Json.JsonNamingPolicy CamelCase { get { throw null; } }
public abstract string ConvertName(string name);
}
public readonly partial struct JsonProperty
{
private readonly object _dummy;
private readonly int _dummyPrimitive;
public string Name { get { throw null; } }
public System.Text.Json.JsonElement Value { get { throw null; } }
public bool NameEquals(System.ReadOnlySpan<byte> utf8Text) { throw null; }
public bool NameEquals(System.ReadOnlySpan<char> text) { throw null; }
public bool NameEquals(string? text) { throw null; }
public override string ToString() { throw null; }
public void WriteTo(System.Text.Json.Utf8JsonWriter writer) { }
}
public partial struct JsonReaderOptions
{
private int _dummyPrimitive;
public bool AllowTrailingCommas { readonly get { throw null; } set { } }
public System.Text.Json.JsonCommentHandling CommentHandling { readonly get { throw null; } set { } }
public int MaxDepth { readonly get { throw null; } set { } }
}
public partial struct JsonReaderState
{
private object _dummy;
private int _dummyPrimitive;
public JsonReaderState(System.Text.Json.JsonReaderOptions options = default(System.Text.Json.JsonReaderOptions)) { throw null; }
public System.Text.Json.JsonReaderOptions Options { get { throw null; } }
}
public static partial class JsonSerializer
{
[System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute("JSON serialization and deserialization might require types that cannot be statically analyzed. Use the overload that takes a JsonTypeInfo or JsonSerializerContext, or make sure all of the required types are preserved.")]
public static object? Deserialize(System.ReadOnlySpan<byte> utf8Json, [System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembersAttribute(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicConstructors | System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicFields | System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicProperties)] System.Type returnType, System.Text.Json.JsonSerializerOptions? options = null) { throw null; }
public static object? Deserialize(System.ReadOnlySpan<byte> utf8Json, System.Type returnType, System.Text.Json.Serialization.JsonSerializerContext context) { throw null; }
[System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute("JSON serialization and deserialization might require types that cannot be statically analyzed. Use the overload that takes a JsonTypeInfo or JsonSerializerContext, or make sure all of the required types are preserved.")]
public static object? Deserialize(System.ReadOnlySpan<char> json, [System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembersAttribute(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicConstructors | System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicFields | System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicProperties)] System.Type returnType, System.Text.Json.JsonSerializerOptions? options = null) { throw null; }
public static object? Deserialize(System.ReadOnlySpan<char> json, System.Type returnType, System.Text.Json.Serialization.JsonSerializerContext context) { throw null; }
[System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute("JSON serialization and deserialization might require types that cannot be statically analyzed. Use the overload that takes a JsonTypeInfo or JsonSerializerContext, or make sure all of the required types are preserved.")]
public static object? Deserialize(string json, [System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembersAttribute(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicConstructors | System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicFields | System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicProperties)] System.Type returnType, System.Text.Json.JsonSerializerOptions? options = null) { throw null; }
public static object? Deserialize(string json, System.Type returnType, System.Text.Json.Serialization.JsonSerializerContext context) { throw null; }
[System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute("JSON serialization and deserialization might require types that cannot be statically analyzed. Use the overload that takes a JsonTypeInfo or JsonSerializerContext, or make sure all of the required types are preserved.")]
public static object? Deserialize(ref System.Text.Json.Utf8JsonReader reader, [System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembersAttribute(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicConstructors | System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicFields | System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicProperties)] System.Type returnType, System.Text.Json.JsonSerializerOptions? options = null) { throw null; }
public static object? Deserialize(ref System.Text.Json.Utf8JsonReader reader, System.Type returnType, System.Text.Json.Serialization.JsonSerializerContext context) { throw null; }
[System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute("JSON serialization and deserialization might require types that cannot be statically analyzed. Use the overload that takes a JsonTypeInfo or JsonSerializerContext, or make sure all of the required types are preserved.")]
public static System.Threading.Tasks.ValueTask<object?> DeserializeAsync(System.IO.Stream utf8Json, [System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembersAttribute(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicConstructors | System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicFields | System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicProperties)] System.Type returnType, System.Text.Json.JsonSerializerOptions? options = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public static System.Threading.Tasks.ValueTask<object?> DeserializeAsync(System.IO.Stream utf8Json, System.Type returnType, System.Text.Json.Serialization.JsonSerializerContext context, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
[System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute("JSON serialization and deserialization might require types that cannot be statically analyzed. Use the overload that takes a JsonTypeInfo or JsonSerializerContext, or make sure all of the required types are preserved.")]
public static System.Collections.Generic.IAsyncEnumerable<TValue?> DeserializeAsyncEnumerable<[System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembersAttribute(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicConstructors | System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicFields | System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicProperties)] TValue>(System.IO.Stream utf8Json, System.Text.Json.JsonSerializerOptions? options = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
[System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute("JSON serialization and deserialization might require types that cannot be statically analyzed. Use the overload that takes a JsonTypeInfo or JsonSerializerContext, or make sure all of the required types are preserved.")]
public static System.Threading.Tasks.ValueTask<TValue?> DeserializeAsync<[System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembersAttribute(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicConstructors | System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicFields | System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicProperties)] TValue>(System.IO.Stream utf8Json, System.Text.Json.JsonSerializerOptions? options = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public static System.Threading.Tasks.ValueTask<TValue?> DeserializeAsync<TValue>(System.IO.Stream utf8Json, System.Text.Json.Serialization.Metadata.JsonTypeInfo<TValue> jsonTypeInfo, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
[System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute("JSON serialization and deserialization might require types that cannot be statically analyzed. Use the overload that takes a JsonTypeInfo or JsonSerializerContext, or make sure all of the required types are preserved.")]
public static TValue? Deserialize<[System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembersAttribute(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicConstructors | System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicFields | System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicProperties)] TValue>(System.ReadOnlySpan<byte> utf8Json, System.Text.Json.JsonSerializerOptions? options = null) { throw null; }
public static TValue? Deserialize<TValue>(System.ReadOnlySpan<byte> utf8Json, System.Text.Json.Serialization.Metadata.JsonTypeInfo<TValue> jsonTypeInfo) { throw null; }
[System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute("JSON serialization and deserialization might require types that cannot be statically analyzed. Use the overload that takes a JsonTypeInfo or JsonSerializerContext, or make sure all of the required types are preserved.")]
public static TValue? Deserialize<[System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembersAttribute(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicConstructors | System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicFields | System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicProperties)] TValue>(System.ReadOnlySpan<char> json, System.Text.Json.JsonSerializerOptions? options = null) { throw null; }
public static TValue? Deserialize<TValue>(System.ReadOnlySpan<char> json, System.Text.Json.Serialization.Metadata.JsonTypeInfo<TValue> jsonTypeInfo) { throw null; }
[System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute("JSON serialization and deserialization might require types that cannot be statically analyzed. Use the overload that takes a JsonTypeInfo or JsonSerializerContext, or make sure all of the required types are preserved.")]
public static TValue? Deserialize<[System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembersAttribute(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicConstructors | System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicFields | System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicProperties)] TValue>(string json, System.Text.Json.JsonSerializerOptions? options = null) { throw null; }
public static TValue? Deserialize<TValue>(string json, System.Text.Json.Serialization.Metadata.JsonTypeInfo<TValue> jsonTypeInfo) { throw null; }
[System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute("JSON serialization and deserialization might require types that cannot be statically analyzed. Use the overload that takes a JsonTypeInfo or JsonSerializerContext, or make sure all of the required types are preserved.")]
public static TValue? Deserialize<[System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembersAttribute(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicConstructors | System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicFields | System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicProperties)] TValue>(ref System.Text.Json.Utf8JsonReader reader, System.Text.Json.JsonSerializerOptions? options = null) { throw null; }
public static TValue? Deserialize<TValue>(ref System.Text.Json.Utf8JsonReader reader, System.Text.Json.Serialization.Metadata.JsonTypeInfo<TValue> jsonTypeInfo) { throw null; }
[System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute("JSON serialization and deserialization might require types that cannot be statically analyzed. Use the overload that takes a JsonTypeInfo or JsonSerializerContext, or make sure all of the required types are preserved.")]
public static string Serialize(object? value, [System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembersAttribute(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicFields | System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicProperties)] System.Type inputType, System.Text.Json.JsonSerializerOptions? options = null) { throw null; }
public static string Serialize(object? value, System.Type inputType, System.Text.Json.Serialization.JsonSerializerContext context) { throw null; }
[System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute("JSON serialization and deserialization might require types that cannot be statically analyzed. Use the overload that takes a JsonTypeInfo or JsonSerializerContext, or make sure all of the required types are preserved.")]
public static void Serialize(System.Text.Json.Utf8JsonWriter writer, object? value, [System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembersAttribute(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicFields | System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicProperties)] System.Type inputType, System.Text.Json.JsonSerializerOptions? options = null) { }
public static void Serialize(System.Text.Json.Utf8JsonWriter writer, object? value, System.Type inputType, System.Text.Json.Serialization.JsonSerializerContext context) { }
[System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute("JSON serialization and deserialization might require types that cannot be statically analyzed. Use the overload that takes a JsonTypeInfo or JsonSerializerContext, or make sure all of the required types are preserved.")]
public static System.Threading.Tasks.Task SerializeAsync(System.IO.Stream utf8Json, object? value, [System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembersAttribute(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicFields | System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicProperties)] System.Type inputType, System.Text.Json.JsonSerializerOptions? options = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public static System.Threading.Tasks.Task SerializeAsync(System.IO.Stream utf8Json, object? value, [System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembersAttribute(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicFields | System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicProperties)] System.Type inputType, System.Text.Json.Serialization.JsonSerializerContext context, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
[System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute("JSON serialization and deserialization might require types that cannot be statically analyzed. Use the overload that takes a JsonTypeInfo or JsonSerializerContext, or make sure all of the required types are preserved.")]
public static System.Threading.Tasks.Task SerializeAsync<[System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembersAttribute(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicFields | System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicProperties)] TValue>(System.IO.Stream utf8Json, TValue value, System.Text.Json.JsonSerializerOptions? options = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public static System.Threading.Tasks.Task SerializeAsync<TValue>(System.IO.Stream utf8Json, TValue value, System.Text.Json.Serialization.Metadata.JsonTypeInfo<TValue> jsonTypeInfo, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
[System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute("JSON serialization and deserialization might require types that cannot be statically analyzed. Use the overload that takes a JsonTypeInfo or JsonSerializerContext, or make sure all of the required types are preserved.")]
public static byte[] SerializeToUtf8Bytes(object? value, [System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembersAttribute(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicFields | System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicProperties)] System.Type inputType, System.Text.Json.JsonSerializerOptions? options = null) { throw null; }
public static byte[] SerializeToUtf8Bytes(object? value, System.Type inputType, System.Text.Json.Serialization.JsonSerializerContext context) { throw null; }
[System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute("JSON serialization and deserialization might require types that cannot be statically analyzed. Use the overload that takes a JsonTypeInfo or JsonSerializerContext, or make sure all of the required types are preserved.")]
public static byte[] SerializeToUtf8Bytes<[System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembersAttribute(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicFields | System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicProperties)] TValue>(TValue value, System.Text.Json.JsonSerializerOptions? options = null) { throw null; }
public static byte[] SerializeToUtf8Bytes<TValue>(TValue value, System.Text.Json.Serialization.Metadata.JsonTypeInfo<TValue> jsonTypeInfo) { throw null; }
[System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute("JSON serialization and deserialization might require types that cannot be statically analyzed. Use the overload that takes a JsonTypeInfo or JsonSerializerContext, or make sure all of the required types are preserved.")]
public static void Serialize<[System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembersAttribute(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicFields | System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicProperties)] TValue>(System.Text.Json.Utf8JsonWriter writer, TValue value, System.Text.Json.JsonSerializerOptions? options = null) { }
public static void Serialize<TValue>(System.Text.Json.Utf8JsonWriter writer, TValue value, System.Text.Json.Serialization.Metadata.JsonTypeInfo<TValue> jsonTypeInfo) { }
[System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute("JSON serialization and deserialization might require types that cannot be statically analyzed. Use the overload that takes a JsonTypeInfo or JsonSerializerContext, or make sure all of the required types are preserved.")]
public static string Serialize<[System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembersAttribute(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicFields | System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicProperties)] TValue>(TValue value, System.Text.Json.JsonSerializerOptions? options = null) { throw null; }
public static string Serialize<TValue>(TValue value, System.Text.Json.Serialization.Metadata.JsonTypeInfo<TValue> jsonTypeInfo) { throw null; }
}
public enum JsonSerializerDefaults
{
General = 0,
Web = 1,
}
public sealed partial class JsonSerializerOptions
{
public JsonSerializerOptions() { }
public JsonSerializerOptions(System.Text.Json.JsonSerializerDefaults defaults) { }
public JsonSerializerOptions(System.Text.Json.JsonSerializerOptions options) { }
public bool AllowTrailingCommas { get { throw null; } set { } }
public System.Collections.Generic.IList<System.Text.Json.Serialization.JsonConverter> Converters { get { throw null; } }
public int DefaultBufferSize { get { throw null; } set { } }
public System.Text.Json.Serialization.JsonIgnoreCondition DefaultIgnoreCondition { get { throw null; } set { } }
public System.Text.Json.JsonNamingPolicy? DictionaryKeyPolicy { get { throw null; } set { } }
public System.Text.Encodings.Web.JavaScriptEncoder? Encoder { get { throw null; } set { } }
[System.ObsoleteAttribute("JsonSerializerOptions.IgnoreNullValues is obsolete. To ignore null values when serializing, set DefaultIgnoreCondition to JsonIgnoreCondition.WhenWritingNull.", DiagnosticId = "SYSLIB0020", UrlFormat = "https://aka.ms/dotnet-warnings/{0}")]
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public bool IgnoreNullValues { get { throw null; } set { } }
public bool IgnoreReadOnlyFields { get { throw null; } set { } }
public bool IgnoreReadOnlyProperties { get { throw null; } set { } }
public bool IncludeFields { get { throw null; } set { } }
public int MaxDepth { get { throw null; } set { } }
public System.Text.Json.Serialization.JsonNumberHandling NumberHandling { get { throw null; } set { } }
public bool PropertyNameCaseInsensitive { get { throw null; } set { } }
public System.Text.Json.JsonNamingPolicy? PropertyNamingPolicy { get { throw null; } set { } }
public System.Text.Json.JsonCommentHandling ReadCommentHandling { get { throw null; } set { } }
public System.Text.Json.Serialization.ReferenceHandler? ReferenceHandler { get { throw null; } set { } }
public System.Text.Json.Serialization.JsonUnknownTypeHandling UnknownTypeHandling { get { throw null; } set { } }
public bool WriteIndented { get { throw null; } set { } }
public void AddContext<TContext>() where TContext : System.Text.Json.Serialization.JsonSerializerContext, new() { }
[System.Diagnostics.CodeAnalysis.RequiresUnreferencedCode("Getting a converter for a type may require reflection which depends on unreferenced code.")]
public System.Text.Json.Serialization.JsonConverter GetConverter(System.Type typeToConvert) { throw null; }
}
public enum JsonTokenType : byte
{
None = (byte)0,
StartObject = (byte)1,
EndObject = (byte)2,
StartArray = (byte)3,
EndArray = (byte)4,
PropertyName = (byte)5,
Comment = (byte)6,
String = (byte)7,
Number = (byte)8,
True = (byte)9,
False = (byte)10,
Null = (byte)11,
}
public enum JsonValueKind : byte
{
Undefined = (byte)0,
Object = (byte)1,
Array = (byte)2,
String = (byte)3,
Number = (byte)4,
True = (byte)5,
False = (byte)6,
Null = (byte)7,
}
public partial struct JsonWriterOptions
{
private object _dummy;
private int _dummyPrimitive;
public System.Text.Encodings.Web.JavaScriptEncoder? Encoder { readonly get { throw null; } set { } }
public bool Indented { get { throw null; } set { } }
public bool SkipValidation { get { throw null; } set { } }
}
public ref partial struct Utf8JsonReader
{
private object _dummy;
private int _dummyPrimitive;
public Utf8JsonReader(System.Buffers.ReadOnlySequence<byte> jsonData, bool isFinalBlock, System.Text.Json.JsonReaderState state) { throw null; }
public Utf8JsonReader(System.Buffers.ReadOnlySequence<byte> jsonData, System.Text.Json.JsonReaderOptions options = default(System.Text.Json.JsonReaderOptions)) { throw null; }
public Utf8JsonReader(System.ReadOnlySpan<byte> jsonData, bool isFinalBlock, System.Text.Json.JsonReaderState state) { throw null; }
public Utf8JsonReader(System.ReadOnlySpan<byte> jsonData, System.Text.Json.JsonReaderOptions options = default(System.Text.Json.JsonReaderOptions)) { throw null; }
public long BytesConsumed { get { throw null; } }
public int CurrentDepth { get { throw null; } }
public System.Text.Json.JsonReaderState CurrentState { get { throw null; } }
public readonly bool HasValueSequence { get { throw null; } }
public bool IsFinalBlock { get { throw null; } }
public System.SequencePosition Position { get { throw null; } }
public readonly long TokenStartIndex { get { throw null; } }
public System.Text.Json.JsonTokenType TokenType { get { throw null; } }
public readonly System.Buffers.ReadOnlySequence<byte> ValueSequence { get { throw null; } }
public readonly System.ReadOnlySpan<byte> ValueSpan { get { throw null; } }
public bool GetBoolean() { throw null; }
public byte GetByte() { throw null; }
public byte[] GetBytesFromBase64() { throw null; }
public string GetComment() { throw null; }
public System.DateTime GetDateTime() { throw null; }
public System.DateTimeOffset GetDateTimeOffset() { throw null; }
public decimal GetDecimal() { throw null; }
public double GetDouble() { throw null; }
public System.Guid GetGuid() { throw null; }
public short GetInt16() { throw null; }
public int GetInt32() { throw null; }
public long GetInt64() { throw null; }
[System.CLSCompliantAttribute(false)]
public sbyte GetSByte() { throw null; }
public float GetSingle() { throw null; }
public string? GetString() { throw null; }
[System.CLSCompliantAttribute(false)]
public ushort GetUInt16() { throw null; }
[System.CLSCompliantAttribute(false)]
public uint GetUInt32() { throw null; }
[System.CLSCompliantAttribute(false)]
public ulong GetUInt64() { throw null; }
public bool Read() { throw null; }
public void Skip() { }
public bool TryGetByte(out byte value) { throw null; }
public bool TryGetBytesFromBase64([System.Diagnostics.CodeAnalysis.NotNullWhenAttribute(true)] out byte[]? value) { throw null; }
public bool TryGetDateTime(out System.DateTime value) { throw null; }
public bool TryGetDateTimeOffset(out System.DateTimeOffset value) { throw null; }
public bool TryGetDecimal(out decimal value) { throw null; }
public bool TryGetDouble(out double value) { throw null; }
public bool TryGetGuid(out System.Guid value) { throw null; }
public bool TryGetInt16(out short value) { throw null; }
public bool TryGetInt32(out int value) { throw null; }
public bool TryGetInt64(out long value) { throw null; }
[System.CLSCompliantAttribute(false)]
public bool TryGetSByte(out sbyte value) { throw null; }
public bool TryGetSingle(out float value) { throw null; }
[System.CLSCompliantAttribute(false)]
public bool TryGetUInt16(out ushort value) { throw null; }
[System.CLSCompliantAttribute(false)]
public bool TryGetUInt32(out uint value) { throw null; }
[System.CLSCompliantAttribute(false)]
public bool TryGetUInt64(out ulong value) { throw null; }
public bool TrySkip() { throw null; }
public bool ValueTextEquals(System.ReadOnlySpan<byte> utf8Text) { throw null; }
public bool ValueTextEquals(System.ReadOnlySpan<char> text) { throw null; }
public bool ValueTextEquals(string? text) { throw null; }
}
public sealed partial class Utf8JsonWriter : System.IAsyncDisposable, System.IDisposable
{
public Utf8JsonWriter(System.Buffers.IBufferWriter<byte> bufferWriter, System.Text.Json.JsonWriterOptions options = default(System.Text.Json.JsonWriterOptions)) { }
public Utf8JsonWriter(System.IO.Stream utf8Json, System.Text.Json.JsonWriterOptions options = default(System.Text.Json.JsonWriterOptions)) { }
public long BytesCommitted { get { throw null; } }
public int BytesPending { get { throw null; } }
public int CurrentDepth { get { throw null; } }
public System.Text.Json.JsonWriterOptions Options { get { throw null; } }
public void Dispose() { }
public System.Threading.Tasks.ValueTask DisposeAsync() { throw null; }
public void Flush() { }
public System.Threading.Tasks.Task FlushAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public void Reset() { }
public void Reset(System.Buffers.IBufferWriter<byte> bufferWriter) { }
public void Reset(System.IO.Stream utf8Json) { }
public void WriteBase64String(System.ReadOnlySpan<byte> utf8PropertyName, System.ReadOnlySpan<byte> bytes) { }
public void WriteBase64String(System.ReadOnlySpan<char> propertyName, System.ReadOnlySpan<byte> bytes) { }
public void WriteBase64String(string propertyName, System.ReadOnlySpan<byte> bytes) { }
public void WriteBase64String(System.Text.Json.JsonEncodedText propertyName, System.ReadOnlySpan<byte> bytes) { }
public void WriteBase64StringValue(System.ReadOnlySpan<byte> bytes) { }
public void WriteBoolean(System.ReadOnlySpan<byte> utf8PropertyName, bool value) { }
public void WriteBoolean(System.ReadOnlySpan<char> propertyName, bool value) { }
public void WriteBoolean(string propertyName, bool value) { }
public void WriteBoolean(System.Text.Json.JsonEncodedText propertyName, bool value) { }
public void WriteBooleanValue(bool value) { }
public void WriteCommentValue(System.ReadOnlySpan<byte> utf8Value) { }
public void WriteCommentValue(System.ReadOnlySpan<char> value) { }
public void WriteCommentValue(string value) { }
public void WriteEndArray() { }
public void WriteEndObject() { }
public void WriteNull(System.ReadOnlySpan<byte> utf8PropertyName) { }
public void WriteNull(System.ReadOnlySpan<char> propertyName) { }
public void WriteNull(string propertyName) { }
public void WriteNull(System.Text.Json.JsonEncodedText propertyName) { }
public void WriteNullValue() { }
public void WriteNumber(System.ReadOnlySpan<byte> utf8PropertyName, decimal value) { }
public void WriteNumber(System.ReadOnlySpan<byte> utf8PropertyName, double value) { }
public void WriteNumber(System.ReadOnlySpan<byte> utf8PropertyName, int value) { }
public void WriteNumber(System.ReadOnlySpan<byte> utf8PropertyName, long value) { }
public void WriteNumber(System.ReadOnlySpan<byte> utf8PropertyName, float value) { }
[System.CLSCompliantAttribute(false)]
public void WriteNumber(System.ReadOnlySpan<byte> utf8PropertyName, uint value) { }
[System.CLSCompliantAttribute(false)]
public void WriteNumber(System.ReadOnlySpan<byte> utf8PropertyName, ulong value) { }
public void WriteNumber(System.ReadOnlySpan<char> propertyName, decimal value) { }
public void WriteNumber(System.ReadOnlySpan<char> propertyName, double value) { }
public void WriteNumber(System.ReadOnlySpan<char> propertyName, int value) { }
public void WriteNumber(System.ReadOnlySpan<char> propertyName, long value) { }
public void WriteNumber(System.ReadOnlySpan<char> propertyName, float value) { }
[System.CLSCompliantAttribute(false)]
public void WriteNumber(System.ReadOnlySpan<char> propertyName, uint value) { }
[System.CLSCompliantAttribute(false)]
public void WriteNumber(System.ReadOnlySpan<char> propertyName, ulong value) { }
public void WriteNumber(string propertyName, decimal value) { }
public void WriteNumber(string propertyName, double value) { }
public void WriteNumber(string propertyName, int value) { }
public void WriteNumber(string propertyName, long value) { }
public void WriteNumber(string propertyName, float value) { }
[System.CLSCompliantAttribute(false)]
public void WriteNumber(string propertyName, uint value) { }
[System.CLSCompliantAttribute(false)]
public void WriteNumber(string propertyName, ulong value) { }
public void WriteNumber(System.Text.Json.JsonEncodedText propertyName, decimal value) { }
public void WriteNumber(System.Text.Json.JsonEncodedText propertyName, double value) { }
public void WriteNumber(System.Text.Json.JsonEncodedText propertyName, int value) { }
public void WriteNumber(System.Text.Json.JsonEncodedText propertyName, long value) { }
public void WriteNumber(System.Text.Json.JsonEncodedText propertyName, float value) { }
[System.CLSCompliantAttribute(false)]
public void WriteNumber(System.Text.Json.JsonEncodedText propertyName, uint value) { }
[System.CLSCompliantAttribute(false)]
public void WriteNumber(System.Text.Json.JsonEncodedText propertyName, ulong value) { }
public void WriteNumberValue(decimal value) { }
public void WriteNumberValue(double value) { }
public void WriteNumberValue(int value) { }
public void WriteNumberValue(long value) { }
public void WriteNumberValue(float value) { }
[System.CLSCompliantAttribute(false)]
public void WriteNumberValue(uint value) { }
[System.CLSCompliantAttribute(false)]
public void WriteNumberValue(ulong value) { }
public void WritePropertyName(System.ReadOnlySpan<byte> utf8PropertyName) { }
public void WritePropertyName(System.ReadOnlySpan<char> propertyName) { }
public void WritePropertyName(string propertyName) { }
public void WritePropertyName(System.Text.Json.JsonEncodedText propertyName) { }
public void WriteStartArray() { }
public void WriteStartArray(System.ReadOnlySpan<byte> utf8PropertyName) { }
public void WriteStartArray(System.ReadOnlySpan<char> propertyName) { }
public void WriteStartArray(string propertyName) { }
public void WriteStartArray(System.Text.Json.JsonEncodedText propertyName) { }
public void WriteStartObject() { }
public void WriteStartObject(System.ReadOnlySpan<byte> utf8PropertyName) { }
public void WriteStartObject(System.ReadOnlySpan<char> propertyName) { }
public void WriteStartObject(string propertyName) { }
public void WriteStartObject(System.Text.Json.JsonEncodedText propertyName) { }
public void WriteString(System.ReadOnlySpan<byte> utf8PropertyName, System.DateTime value) { }
public void WriteString(System.ReadOnlySpan<byte> utf8PropertyName, System.DateTimeOffset value) { }
public void WriteString(System.ReadOnlySpan<byte> utf8PropertyName, System.Guid value) { }
public void WriteString(System.ReadOnlySpan<byte> utf8PropertyName, System.ReadOnlySpan<byte> utf8Value) { }
public void WriteString(System.ReadOnlySpan<byte> utf8PropertyName, System.ReadOnlySpan<char> value) { }
public void WriteString(System.ReadOnlySpan<byte> utf8PropertyName, string? value) { }
public void WriteString(System.ReadOnlySpan<byte> utf8PropertyName, System.Text.Json.JsonEncodedText value) { }
public void WriteString(System.ReadOnlySpan<char> propertyName, System.DateTime value) { }
public void WriteString(System.ReadOnlySpan<char> propertyName, System.DateTimeOffset value) { }
public void WriteString(System.ReadOnlySpan<char> propertyName, System.Guid value) { }
public void WriteString(System.ReadOnlySpan<char> propertyName, System.ReadOnlySpan<byte> utf8Value) { }
public void WriteString(System.ReadOnlySpan<char> propertyName, System.ReadOnlySpan<char> value) { }
public void WriteString(System.ReadOnlySpan<char> propertyName, string? value) { }
public void WriteString(System.ReadOnlySpan<char> propertyName, System.Text.Json.JsonEncodedText value) { }
public void WriteString(string propertyName, System.DateTime value) { }
public void WriteString(string propertyName, System.DateTimeOffset value) { }
public void WriteString(string propertyName, System.Guid value) { }
public void WriteString(string propertyName, System.ReadOnlySpan<byte> utf8Value) { }
public void WriteString(string propertyName, System.ReadOnlySpan<char> value) { }
public void WriteString(string propertyName, string? value) { }
public void WriteString(string propertyName, System.Text.Json.JsonEncodedText value) { }
public void WriteString(System.Text.Json.JsonEncodedText propertyName, System.DateTime value) { }
public void WriteString(System.Text.Json.JsonEncodedText propertyName, System.DateTimeOffset value) { }
public void WriteString(System.Text.Json.JsonEncodedText propertyName, System.Guid value) { }
public void WriteString(System.Text.Json.JsonEncodedText propertyName, System.ReadOnlySpan<byte> utf8Value) { }
public void WriteString(System.Text.Json.JsonEncodedText propertyName, System.ReadOnlySpan<char> value) { }
public void WriteString(System.Text.Json.JsonEncodedText propertyName, string? value) { }
public void WriteString(System.Text.Json.JsonEncodedText propertyName, System.Text.Json.JsonEncodedText value) { }
public void WriteStringValue(System.DateTime value) { }
public void WriteStringValue(System.DateTimeOffset value) { }
public void WriteStringValue(System.Guid value) { }
public void WriteStringValue(System.ReadOnlySpan<byte> utf8Value) { }
public void WriteStringValue(System.ReadOnlySpan<char> value) { }
public void WriteStringValue(string? value) { }
public void WriteStringValue(System.Text.Json.JsonEncodedText value) { }
}
}
namespace System.Text.Json.Nodes
{
public sealed partial class JsonArray : System.Text.Json.Nodes.JsonNode, System.Collections.Generic.ICollection<System.Text.Json.Nodes.JsonNode?>, System.Collections.Generic.IEnumerable<System.Text.Json.Nodes.JsonNode?>, System.Collections.Generic.IList<System.Text.Json.Nodes.JsonNode?>, System.Collections.IEnumerable
{
public JsonArray(System.Text.Json.Nodes.JsonNodeOptions? options = default(System.Text.Json.Nodes.JsonNodeOptions?)) { }
public JsonArray(System.Text.Json.Nodes.JsonNodeOptions options, params System.Text.Json.Nodes.JsonNode?[] items) { }
public JsonArray(params System.Text.Json.Nodes.JsonNode?[] items) { }
public int Count { get { throw null; } }
bool System.Collections.Generic.ICollection<System.Text.Json.Nodes.JsonNode?>.IsReadOnly { get { throw null; } }
public void Add(System.Text.Json.Nodes.JsonNode? item) { }
public void Add<T>(T? value) { }
public void Clear() { }
public bool Contains(System.Text.Json.Nodes.JsonNode? item) { throw null; }
public static System.Text.Json.Nodes.JsonArray? Create(System.Text.Json.JsonElement element, System.Text.Json.Nodes.JsonNodeOptions? options = default(System.Text.Json.Nodes.JsonNodeOptions?)) { throw null; }
public System.Collections.Generic.IEnumerator<System.Text.Json.Nodes.JsonNode?> GetEnumerator() { throw null; }
public int IndexOf(System.Text.Json.Nodes.JsonNode? item) { throw null; }
public void Insert(int index, System.Text.Json.Nodes.JsonNode? item) { }
public bool Remove(System.Text.Json.Nodes.JsonNode? item) { throw null; }
public void RemoveAt(int index) { }
void System.Collections.Generic.ICollection<System.Text.Json.Nodes.JsonNode?>.CopyTo(System.Text.Json.Nodes.JsonNode?[]? array, int index) { }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; }
public override void WriteTo(System.Text.Json.Utf8JsonWriter writer, System.Text.Json.JsonSerializerOptions? options = null) { }
}
public abstract partial class JsonNode : System.Dynamic.IDynamicMetaObjectProvider
{
internal JsonNode() { }
public System.Text.Json.Nodes.JsonNode? this[int index] { get { throw null; } set { } }
public System.Text.Json.Nodes.JsonNode? this[string propertyName] { get { throw null; } set { } }
public System.Text.Json.Nodes.JsonNodeOptions? Options { get { throw null; } }
public System.Text.Json.Nodes.JsonNode? Parent { get { throw null; } }
public System.Text.Json.Nodes.JsonNode Root { get { throw null; } }
public System.Text.Json.Nodes.JsonArray AsArray() { throw null; }
public System.Text.Json.Nodes.JsonObject AsObject() { throw null; }
public System.Text.Json.Nodes.JsonValue AsValue() { throw null; }
public string GetPath() { throw null; }
public virtual TValue GetValue<[System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembersAttribute(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicConstructors | System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicFields | System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicProperties)] TValue>() { throw null; }
public static explicit operator bool (System.Text.Json.Nodes.JsonNode value) { throw null; }
public static explicit operator byte (System.Text.Json.Nodes.JsonNode value) { throw null; }
public static explicit operator char (System.Text.Json.Nodes.JsonNode value) { throw null; }
public static explicit operator System.DateTime (System.Text.Json.Nodes.JsonNode value) { throw null; }
public static explicit operator System.DateTimeOffset (System.Text.Json.Nodes.JsonNode value) { throw null; }
public static explicit operator decimal (System.Text.Json.Nodes.JsonNode value) { throw null; }
public static explicit operator double (System.Text.Json.Nodes.JsonNode value) { throw null; }
public static explicit operator System.Guid (System.Text.Json.Nodes.JsonNode value) { throw null; }
public static explicit operator short (System.Text.Json.Nodes.JsonNode value) { throw null; }
public static explicit operator int (System.Text.Json.Nodes.JsonNode value) { throw null; }
public static explicit operator long (System.Text.Json.Nodes.JsonNode value) { throw null; }
public static explicit operator bool? (System.Text.Json.Nodes.JsonNode? value) { throw null; }
public static explicit operator byte? (System.Text.Json.Nodes.JsonNode? value) { throw null; }
public static explicit operator char? (System.Text.Json.Nodes.JsonNode? value) { throw null; }
public static explicit operator System.DateTimeOffset? (System.Text.Json.Nodes.JsonNode? value) { throw null; }
public static explicit operator System.DateTime? (System.Text.Json.Nodes.JsonNode? value) { throw null; }
public static explicit operator decimal? (System.Text.Json.Nodes.JsonNode? value) { throw null; }
public static explicit operator double? (System.Text.Json.Nodes.JsonNode? value) { throw null; }
public static explicit operator System.Guid? (System.Text.Json.Nodes.JsonNode? value) { throw null; }
public static explicit operator short? (System.Text.Json.Nodes.JsonNode? value) { throw null; }
public static explicit operator int? (System.Text.Json.Nodes.JsonNode? value) { throw null; }
public static explicit operator long? (System.Text.Json.Nodes.JsonNode? value) { throw null; }
[System.CLSCompliantAttribute(false)]
public static explicit operator sbyte? (System.Text.Json.Nodes.JsonNode? value) { throw null; }
public static explicit operator float? (System.Text.Json.Nodes.JsonNode? value) { throw null; }
[System.CLSCompliantAttribute(false)]
public static explicit operator ushort? (System.Text.Json.Nodes.JsonNode? value) { throw null; }
[System.CLSCompliantAttribute(false)]
public static explicit operator uint? (System.Text.Json.Nodes.JsonNode? value) { throw null; }
[System.CLSCompliantAttribute(false)]
public static explicit operator ulong? (System.Text.Json.Nodes.JsonNode? value) { throw null; }
[System.CLSCompliantAttribute(false)]
public static explicit operator sbyte (System.Text.Json.Nodes.JsonNode value) { throw null; }
public static explicit operator float (System.Text.Json.Nodes.JsonNode value) { throw null; }
public static explicit operator string? (System.Text.Json.Nodes.JsonNode? value) { throw null; }
[System.CLSCompliantAttribute(false)]
public static explicit operator ushort (System.Text.Json.Nodes.JsonNode value) { throw null; }
[System.CLSCompliantAttribute(false)]
public static explicit operator uint (System.Text.Json.Nodes.JsonNode value) { throw null; }
[System.CLSCompliantAttribute(false)]
public static explicit operator ulong (System.Text.Json.Nodes.JsonNode value) { throw null; }
public static implicit operator System.Text.Json.Nodes.JsonNode (bool value) { throw null; }
public static implicit operator System.Text.Json.Nodes.JsonNode (byte value) { throw null; }
public static implicit operator System.Text.Json.Nodes.JsonNode (char value) { throw null; }
public static implicit operator System.Text.Json.Nodes.JsonNode (System.DateTime value) { throw null; }
public static implicit operator System.Text.Json.Nodes.JsonNode (System.DateTimeOffset value) { throw null; }
public static implicit operator System.Text.Json.Nodes.JsonNode (decimal value) { throw null; }
public static implicit operator System.Text.Json.Nodes.JsonNode (double value) { throw null; }
public static implicit operator System.Text.Json.Nodes.JsonNode (System.Guid value) { throw null; }
public static implicit operator System.Text.Json.Nodes.JsonNode (short value) { throw null; }
public static implicit operator System.Text.Json.Nodes.JsonNode (int value) { throw null; }
public static implicit operator System.Text.Json.Nodes.JsonNode (long value) { throw null; }
public static implicit operator System.Text.Json.Nodes.JsonNode? (bool? value) { throw null; }
public static implicit operator System.Text.Json.Nodes.JsonNode? (byte? value) { throw null; }
public static implicit operator System.Text.Json.Nodes.JsonNode? (char? value) { throw null; }
public static implicit operator System.Text.Json.Nodes.JsonNode? (System.DateTimeOffset? value) { throw null; }
public static implicit operator System.Text.Json.Nodes.JsonNode? (System.DateTime? value) { throw null; }
public static implicit operator System.Text.Json.Nodes.JsonNode? (decimal? value) { throw null; }
public static implicit operator System.Text.Json.Nodes.JsonNode? (double? value) { throw null; }
public static implicit operator System.Text.Json.Nodes.JsonNode? (System.Guid? value) { throw null; }
public static implicit operator System.Text.Json.Nodes.JsonNode? (short? value) { throw null; }
public static implicit operator System.Text.Json.Nodes.JsonNode? (int? value) { throw null; }
public static implicit operator System.Text.Json.Nodes.JsonNode? (long? value) { throw null; }
[System.CLSCompliantAttribute(false)]
public static implicit operator System.Text.Json.Nodes.JsonNode? (sbyte? value) { throw null; }
public static implicit operator System.Text.Json.Nodes.JsonNode? (float? value) { throw null; }
[System.CLSCompliantAttribute(false)]
public static implicit operator System.Text.Json.Nodes.JsonNode? (ushort? value) { throw null; }
[System.CLSCompliantAttribute(false)]
public static implicit operator System.Text.Json.Nodes.JsonNode? (uint? value) { throw null; }
[System.CLSCompliantAttribute(false)]
public static implicit operator System.Text.Json.Nodes.JsonNode? (ulong? value) { throw null; }
[System.CLSCompliantAttribute(false)]
public static implicit operator System.Text.Json.Nodes.JsonNode (sbyte value) { throw null; }
public static implicit operator System.Text.Json.Nodes.JsonNode (float value) { throw null; }
public static implicit operator System.Text.Json.Nodes.JsonNode? (string? value) { throw null; }
[System.CLSCompliantAttribute(false)]
public static implicit operator System.Text.Json.Nodes.JsonNode (ushort value) { throw null; }
[System.CLSCompliantAttribute(false)]
public static implicit operator System.Text.Json.Nodes.JsonNode (uint value) { throw null; }
[System.CLSCompliantAttribute(false)]
public static implicit operator System.Text.Json.Nodes.JsonNode (ulong value) { throw null; }
public static System.Text.Json.Nodes.JsonNode? Parse(System.IO.Stream utf8Json, System.Text.Json.Nodes.JsonNodeOptions? nodeOptions = default(System.Text.Json.Nodes.JsonNodeOptions?), System.Text.Json.JsonDocumentOptions documentOptions = default(System.Text.Json.JsonDocumentOptions)) { throw null; }
public static System.Text.Json.Nodes.JsonNode? Parse(System.ReadOnlySpan<byte> utf8Json, System.Text.Json.Nodes.JsonNodeOptions? nodeOptions = default(System.Text.Json.Nodes.JsonNodeOptions?), System.Text.Json.JsonDocumentOptions documentOptions = default(System.Text.Json.JsonDocumentOptions)) { throw null; }
public static System.Text.Json.Nodes.JsonNode? Parse(string json, System.Text.Json.Nodes.JsonNodeOptions? nodeOptions = default(System.Text.Json.Nodes.JsonNodeOptions?), System.Text.Json.JsonDocumentOptions documentOptions = default(System.Text.Json.JsonDocumentOptions)) { throw null; }
public static System.Text.Json.Nodes.JsonNode? Parse(ref System.Text.Json.Utf8JsonReader reader, System.Text.Json.Nodes.JsonNodeOptions? nodeOptions = default(System.Text.Json.Nodes.JsonNodeOptions?)) { throw null; }
System.Dynamic.DynamicMetaObject System.Dynamic.IDynamicMetaObjectProvider.GetMetaObject(System.Linq.Expressions.Expression parameter) { throw null; }
public string ToJsonString(System.Text.Json.JsonSerializerOptions? options = null) { throw null; }
public override string ToString() { throw null; }
public abstract void WriteTo(System.Text.Json.Utf8JsonWriter writer, System.Text.Json.JsonSerializerOptions? options = null);
}
public partial struct JsonNodeOptions
{
private int _dummyPrimitive;
public bool PropertyNameCaseInsensitive { readonly get { throw null; } set { } }
}
public sealed partial class JsonObject : System.Text.Json.Nodes.JsonNode, System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<string, System.Text.Json.Nodes.JsonNode?>>, System.Collections.Generic.IDictionary<string, System.Text.Json.Nodes.JsonNode?>, System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<string, System.Text.Json.Nodes.JsonNode?>>, System.Collections.IEnumerable
{
public JsonObject(System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<string, System.Text.Json.Nodes.JsonNode?>> properties, System.Text.Json.Nodes.JsonNodeOptions? options = default(System.Text.Json.Nodes.JsonNodeOptions?)) { }
public JsonObject(System.Text.Json.Nodes.JsonNodeOptions? options = default(System.Text.Json.Nodes.JsonNodeOptions?)) { }
public int Count { get { throw null; } }
bool System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<string, System.Text.Json.Nodes.JsonNode?>>.IsReadOnly { get { throw null; } }
System.Collections.Generic.ICollection<string> System.Collections.Generic.IDictionary<string, System.Text.Json.Nodes.JsonNode?>.Keys { get { throw null; } }
System.Collections.Generic.ICollection<System.Text.Json.Nodes.JsonNode?> System.Collections.Generic.IDictionary<string, System.Text.Json.Nodes.JsonNode?>.Values { get { throw null; } }
public void Add(System.Collections.Generic.KeyValuePair<string, System.Text.Json.Nodes.JsonNode?> property) { }
public void Add(string propertyName, System.Text.Json.Nodes.JsonNode? value) { }
public void Clear() { }
public bool ContainsKey(string propertyName) { throw null; }
public static System.Text.Json.Nodes.JsonObject? Create(System.Text.Json.JsonElement element, System.Text.Json.Nodes.JsonNodeOptions? options = default(System.Text.Json.Nodes.JsonNodeOptions?)) { throw null; }
public System.Collections.Generic.IEnumerator<System.Collections.Generic.KeyValuePair<string, System.Text.Json.Nodes.JsonNode?>> GetEnumerator() { throw null; }
public bool Remove(string propertyName) { throw null; }
bool System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<string, System.Text.Json.Nodes.JsonNode?>>.Contains(System.Collections.Generic.KeyValuePair<string, System.Text.Json.Nodes.JsonNode> item) { throw null; }
void System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<string, System.Text.Json.Nodes.JsonNode?>>.CopyTo(System.Collections.Generic.KeyValuePair<string, System.Text.Json.Nodes.JsonNode>[] array, int index) { }
bool System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<string, System.Text.Json.Nodes.JsonNode?>>.Remove(System.Collections.Generic.KeyValuePair<string, System.Text.Json.Nodes.JsonNode> item) { throw null; }
bool System.Collections.Generic.IDictionary<string, System.Text.Json.Nodes.JsonNode?>.TryGetValue(string propertyName, out System.Text.Json.Nodes.JsonNode? jsonNode) { throw null; }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; }
public bool TryGetPropertyValue(string propertyName, out System.Text.Json.Nodes.JsonNode? jsonNode) { throw null; }
public override void WriteTo(System.Text.Json.Utf8JsonWriter writer, System.Text.Json.JsonSerializerOptions? options = null) { }
}
public abstract partial class JsonValue : System.Text.Json.Nodes.JsonNode
{
private protected JsonValue(System.Text.Json.Nodes.JsonNodeOptions? options = default(System.Text.Json.Nodes.JsonNodeOptions?)) { throw null; }
public static System.Text.Json.Nodes.JsonValue? Create<T>(T? value, System.Text.Json.Nodes.JsonNodeOptions? options = default(System.Text.Json.Nodes.JsonNodeOptions?)) { throw null; }
public abstract bool TryGetValue<T>([System.Diagnostics.CodeAnalysis.NotNullWhenAttribute(true)] out T? value);
}
}
namespace System.Text.Json.Serialization
{
public abstract partial class JsonAttribute : System.Attribute
{
protected JsonAttribute() { }
}
[System.AttributeUsageAttribute(System.AttributeTargets.Constructor, AllowMultiple=false)]
public sealed partial class JsonConstructorAttribute : System.Text.Json.Serialization.JsonAttribute
{
public JsonConstructorAttribute() { }
}
public abstract partial class JsonConverter
{
internal JsonConverter() { }
public abstract bool CanConvert(System.Type typeToConvert);
}
[System.AttributeUsageAttribute(System.AttributeTargets.Class | System.AttributeTargets.Enum | System.AttributeTargets.Field | System.AttributeTargets.Property | System.AttributeTargets.Struct, AllowMultiple=false)]
public partial class JsonConverterAttribute : System.Text.Json.Serialization.JsonAttribute
{
protected JsonConverterAttribute() { }
public JsonConverterAttribute([System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembersAttribute(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] System.Type converterType) { }
[System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembersAttribute(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)]
public System.Type? ConverterType { get { throw null; } }
public virtual System.Text.Json.Serialization.JsonConverter? CreateConverter(System.Type typeToConvert) { throw null; }
}
public abstract partial class JsonConverterFactory : System.Text.Json.Serialization.JsonConverter
{
protected JsonConverterFactory() { }
public abstract System.Text.Json.Serialization.JsonConverter? CreateConverter(System.Type typeToConvert, System.Text.Json.JsonSerializerOptions options);
}
public abstract partial class JsonConverter<T> : System.Text.Json.Serialization.JsonConverter
{
protected internal JsonConverter() { }
public virtual bool HandleNull { get { throw null; } }
public override bool CanConvert(System.Type typeToConvert) { throw null; }
public abstract T? Read(ref System.Text.Json.Utf8JsonReader reader, System.Type typeToConvert, System.Text.Json.JsonSerializerOptions options);
public abstract void Write(System.Text.Json.Utf8JsonWriter writer, T value, System.Text.Json.JsonSerializerOptions options);
}
[System.AttributeUsageAttribute(System.AttributeTargets.Field | System.AttributeTargets.Property, AllowMultiple=false)]
public sealed partial class JsonExtensionDataAttribute : System.Text.Json.Serialization.JsonAttribute
{
public JsonExtensionDataAttribute() { }
}
[System.AttributeUsageAttribute(System.AttributeTargets.Field | System.AttributeTargets.Property, AllowMultiple=false)]
public sealed partial class JsonIgnoreAttribute : System.Text.Json.Serialization.JsonAttribute
{
public JsonIgnoreAttribute() { }
public System.Text.Json.Serialization.JsonIgnoreCondition Condition { get { throw null; } set { } }
}
public enum JsonIgnoreCondition
{
Never = 0,
Always = 1,
WhenWritingDefault = 2,
WhenWritingNull = 3,
}
[System.AttributeUsageAttribute(System.AttributeTargets.Field | System.AttributeTargets.Property, AllowMultiple=false)]
public sealed partial class JsonIncludeAttribute : System.Text.Json.Serialization.JsonAttribute
{
public JsonIncludeAttribute() { }
}
[System.FlagsAttribute]
public enum JsonNumberHandling
{
Strict = 0,
AllowReadingFromString = 1,
WriteAsString = 2,
AllowNamedFloatingPointLiterals = 4,
}
[System.AttributeUsageAttribute(System.AttributeTargets.Class | System.AttributeTargets.Field | System.AttributeTargets.Property | System.AttributeTargets.Struct, AllowMultiple=false)]
public sealed partial class JsonNumberHandlingAttribute : System.Text.Json.Serialization.JsonAttribute
{
public JsonNumberHandlingAttribute(System.Text.Json.Serialization.JsonNumberHandling handling) { }
public System.Text.Json.Serialization.JsonNumberHandling Handling { get { throw null; } }
}
[System.AttributeUsageAttribute(System.AttributeTargets.Field | System.AttributeTargets.Property, AllowMultiple=false)]
public sealed partial class JsonPropertyNameAttribute : System.Text.Json.Serialization.JsonAttribute
{
public JsonPropertyNameAttribute(string name) { }
public string Name { get { throw null; } }
}
[System.AttributeUsageAttribute(System.AttributeTargets.Assembly, AllowMultiple=true)]
public sealed partial class JsonSerializableAttribute : System.Text.Json.Serialization.JsonAttribute
{
public JsonSerializableAttribute(System.Type type) { }
public string? TypeInfoPropertyName { get { throw null; } set { } }
}
public abstract partial class JsonSerializerContext
{
protected JsonSerializerContext(System.Text.Json.JsonSerializerOptions? options) { }
public System.Text.Json.JsonSerializerOptions Options { get { throw null; } }
public abstract System.Text.Json.Serialization.Metadata.JsonTypeInfo? GetTypeInfo(System.Type type);
}
public sealed partial class JsonStringEnumConverter : System.Text.Json.Serialization.JsonConverterFactory
{
public JsonStringEnumConverter() { }
public JsonStringEnumConverter(System.Text.Json.JsonNamingPolicy? namingPolicy = null, bool allowIntegerValues = true) { }
public override bool CanConvert(System.Type typeToConvert) { throw null; }
public override System.Text.Json.Serialization.JsonConverter CreateConverter(System.Type typeToConvert, System.Text.Json.JsonSerializerOptions options) { throw null; }
}
public enum JsonUnknownTypeHandling
{
JsonElement = 0,
JsonNode = 1,
}
public abstract partial class ReferenceHandler
{
protected ReferenceHandler() { }
public static System.Text.Json.Serialization.ReferenceHandler IgnoreCycles { get { throw null; } }
public static System.Text.Json.Serialization.ReferenceHandler Preserve { get { throw null; } }
public abstract System.Text.Json.Serialization.ReferenceResolver CreateResolver();
}
public sealed partial class ReferenceHandler<T> : System.Text.Json.Serialization.ReferenceHandler where T : System.Text.Json.Serialization.ReferenceResolver, new()
{
public ReferenceHandler() { }
public override System.Text.Json.Serialization.ReferenceResolver CreateResolver() { throw null; }
}
public abstract partial class ReferenceResolver
{
protected ReferenceResolver() { }
public abstract void AddReference(string referenceId, object value);
public abstract string GetReference(object value, out bool alreadyExists);
public abstract object ResolveReference(string referenceId);
}
}
namespace System.Text.Json.Serialization.Metadata
{
public static partial class JsonMetadataServices
{
public static System.Text.Json.Serialization.JsonConverter<bool> BooleanConverter { get { throw null; } }
public static System.Text.Json.Serialization.JsonConverter<byte[]> ByteArrayConverter { get { throw null; } }
public static System.Text.Json.Serialization.JsonConverter<byte> ByteConverter { get { throw null; } }
public static System.Text.Json.Serialization.JsonConverter<char> CharConverter { get { throw null; } }
public static System.Text.Json.Serialization.JsonConverter<System.DateTime> DateTimeConverter { get { throw null; } }
public static System.Text.Json.Serialization.JsonConverter<System.DateTimeOffset> DateTimeOffsetConverter { get { throw null; } }
public static System.Text.Json.Serialization.JsonConverter<decimal> DecimalConverter { get { throw null; } }
public static System.Text.Json.Serialization.JsonConverter<double> DoubleConverter { get { throw null; } }
public static System.Text.Json.Serialization.JsonConverter<System.Guid> GuidConverter { get { throw null; } }
public static System.Text.Json.Serialization.JsonConverter<short> Int16Converter { get { throw null; } }
public static System.Text.Json.Serialization.JsonConverter<int> Int32Converter { get { throw null; } }
public static System.Text.Json.Serialization.JsonConverter<long> Int64Converter { get { throw null; } }
public static System.Text.Json.Serialization.JsonConverter<object> ObjectConverter { get { throw null; } }
[System.CLSCompliantAttribute(false)]
public static System.Text.Json.Serialization.JsonConverter<sbyte> SByteConverter { get { throw null; } }
public static System.Text.Json.Serialization.JsonConverter<float> SingleConverter { get { throw null; } }
public static System.Text.Json.Serialization.JsonConverter<string> StringConverter { get { throw null; } }
[System.CLSCompliantAttribute(false)]
public static System.Text.Json.Serialization.JsonConverter<ushort> UInt16Converter { get { throw null; } }
[System.CLSCompliantAttribute(false)]
public static System.Text.Json.Serialization.JsonConverter<uint> UInt32Converter { get { throw null; } }
[System.CLSCompliantAttribute(false)]
public static System.Text.Json.Serialization.JsonConverter<ulong> UInt64Converter { get { throw null; } }
public static System.Text.Json.Serialization.JsonConverter<System.Uri> UriConverter { get { throw null; } }
public static System.Text.Json.Serialization.JsonConverter<System.Version> VersionConverter { get { throw null; } }
public static System.Text.Json.Serialization.Metadata.JsonTypeInfo<TElement[]> CreateArrayInfo<TElement>(System.Text.Json.JsonSerializerOptions options, System.Text.Json.Serialization.Metadata.JsonTypeInfo elementInfo, System.Text.Json.Serialization.JsonNumberHandling numberHandling) { throw null; }
public static System.Text.Json.Serialization.Metadata.JsonTypeInfo<TCollection> CreateDictionaryInfo<TCollection, TKey, TValue>(System.Text.Json.JsonSerializerOptions options, System.Func<TCollection> createObjectFunc, System.Text.Json.Serialization.Metadata.JsonTypeInfo keyInfo, System.Text.Json.Serialization.Metadata.JsonTypeInfo valueInfo, System.Text.Json.Serialization.JsonNumberHandling numberHandling) where TCollection : System.Collections.Generic.Dictionary<TKey, TValue> where TKey : notnull { throw null; }
public static System.Text.Json.Serialization.Metadata.JsonTypeInfo<TCollection> CreateListInfo<TCollection, TElement>(System.Text.Json.JsonSerializerOptions options, System.Func<TCollection>? createObjectFunc, System.Text.Json.Serialization.Metadata.JsonTypeInfo elementInfo, System.Text.Json.Serialization.JsonNumberHandling numberHandling) where TCollection : System.Collections.Generic.List<TElement> { throw null; }
public static System.Text.Json.Serialization.Metadata.JsonTypeInfo<T> CreateObjectInfo<T>() where T : notnull { throw null; }
public static System.Text.Json.Serialization.Metadata.JsonPropertyInfo CreatePropertyInfo<T>(System.Text.Json.JsonSerializerOptions options, bool isProperty, System.Type declaringType, System.Text.Json.Serialization.Metadata.JsonTypeInfo propertyTypeInfo, System.Text.Json.Serialization.JsonConverter<T>? converter, System.Func<object, T>? getter, System.Action<object, T>? setter, System.Text.Json.Serialization.JsonIgnoreCondition ignoreCondition, System.Text.Json.Serialization.JsonNumberHandling numberHandling, string propertyName, string? jsonPropertyName) { throw null; }
public static System.Text.Json.Serialization.Metadata.JsonTypeInfo<T> CreateValueInfo<T>(System.Text.Json.JsonSerializerOptions options, System.Text.Json.Serialization.JsonConverter converter) { throw null; }
public static System.Text.Json.Serialization.JsonConverter<T> GetEnumConverter<T>(System.Text.Json.JsonSerializerOptions options) where T : struct { throw null; }
public static System.Text.Json.Serialization.JsonConverter<T?> GetNullableConverter<T>(System.Text.Json.Serialization.Metadata.JsonTypeInfo<T> underlyingTypeInfo) where T : struct { throw null; }
public static void InitializeObjectInfo<T>(System.Text.Json.Serialization.Metadata.JsonTypeInfo<T> info, System.Text.Json.JsonSerializerOptions options, System.Func<T>? createObjectFunc, System.Func<System.Text.Json.Serialization.JsonSerializerContext, System.Text.Json.Serialization.Metadata.JsonPropertyInfo[]> propInitFunc, System.Text.Json.Serialization.JsonNumberHandling numberHandling) where T : notnull { }
}
public abstract partial class JsonPropertyInfo
{
internal JsonPropertyInfo() { }
}
public partial class JsonTypeInfo
{
internal JsonTypeInfo() { }
public static readonly System.Type ObjectType;
}
public abstract partial class JsonTypeInfo<T> : System.Text.Json.Serialization.Metadata.JsonTypeInfo
{
internal JsonTypeInfo() { }
}
}
| 93.974148 | 621 | 0.750013 | [
"MIT"
] | ChristophHornung/runtime | src/libraries/System.Text.Json/ref/System.Text.Json.cs | 79,972 | 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("RafyProjects")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("RafyProjects")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[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("4b0db11c-8cdf-4f43-89b2-a6f151d633a0")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: InternalsVisibleTo("RafySDK, PublicKey=0024000004800000940000000602000000240000525341310004000001000100d3ae8c70610ec4e9ddd1c83c90c9e99c19a4c675e79b0360283797b567ea20e1a6804e1bd5459f5ad6d354a3ee5d1608faafff8d33460116af32c3e9b012c38f5ef334eff3b7f85f1a3db52e4f44ebbbf24429b5650072bb1968ea80dec1b97ab9429db053fc85d89acc0f287516bf367efebecc7ea085808367f978f69fb8c2")] | 47.578947 | 373 | 0.775996 | [
"MIT"
] | zgynhqf/trunk | Rafy/Tools/VSTemplates/Properties/AssemblyInfo.cs | 1,811 | C# |
// SF API version v50.0
// Custom fields included: False
// Relationship objects included: True
using System;
using NetCoreForce.Client.Models;
using NetCoreForce.Client.Attributes;
using Newtonsoft.Json;
namespace NetCoreForce.Models
{
///<summary>
/// Client Browser
///<para>SObject Name: ClientBrowser</para>
///<para>Custom Object: False</para>
///</summary>
public class SfClientBrowser : SObject
{
[JsonIgnore]
public static string SObjectTypeName
{
get { return "ClientBrowser"; }
}
///<summary>
/// Client Browser ID
/// <para>Name: Id</para>
/// <para>SF Type: id</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "id")]
[Updateable(false), Createable(false)]
public string Id { get; set; }
///<summary>
/// User ID
/// <para>Name: UsersId</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "usersId")]
[Updateable(false), Createable(false)]
public string UsersId { get; set; }
///<summary>
/// ReferenceTo: User
/// <para>RelationshipName: Users</para>
///</summary>
[JsonProperty(PropertyName = "users")]
[Updateable(false), Createable(false)]
public SfUser Users { get; set; }
///<summary>
/// Full User Agent
/// <para>Name: FullUserAgent</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "fullUserAgent")]
[Updateable(false), Createable(false)]
public string FullUserAgent { get; set; }
///<summary>
/// Proxy Info
/// <para>Name: ProxyInfo</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "proxyInfo")]
[Updateable(false), Createable(false)]
public string ProxyInfo { get; set; }
///<summary>
/// Last Update
/// <para>Name: LastUpdate</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "lastUpdate")]
[Updateable(false), Createable(false)]
public DateTimeOffset? LastUpdate { get; set; }
///<summary>
/// Created Date
/// <para>Name: CreatedDate</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "createdDate")]
[Updateable(false), Createable(false)]
public DateTimeOffset? CreatedDate { get; set; }
}
}
| 25.663158 | 50 | 0.649303 | [
"MIT"
] | Mintish/NetCoreForce | src/NetCoreForce.Models/SfClientBrowser.cs | 2,438 | C# |
using System.Threading.Tasks;
using Xunit;
namespace Bamboo.Sales.Samples
{
public class SampleManager_Tests : SalesDomainTestBase
{
//private readonly SampleManager _sampleManager;
public SampleManager_Tests()
{
//_sampleManager = GetRequiredService<SampleManager>();
}
[Fact]
public async Task Method1Async()
{
}
}
}
| 18.727273 | 67 | 0.616505 | [
"MIT"
] | BlazorHub/bamboomodules | Bamboo.Sales/test/Bamboo.Sales.Domain.Tests/Samples/SampleManager_Tests.cs | 414 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.