content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2 values |
|---|---|---|---|---|---|---|---|---|
// Copyright (c) 2022 TrakHound Inc., All Rights Reserved.
// This file is subject to the terms and conditions defined in
// file 'LICENSE.txt', which is part of this source code package.
using System.Collections.Generic;
using System.Text.Json.Serialization;
namespace MTConnect.Agents.Configuration
{
public class AdapterConfiguration
{
/// <summary>
/// The name of the device that corresponds to the name of the device in the Devices file. Each adapter can map to one device.
/// Specifying a "*" will map to the default device.
/// </summary>
[JsonPropertyName("device")]
public string Device { get; set; }
/// <summary>
/// The host the adapter is located on.
/// </summary>
[JsonPropertyName("host")]
public string Host { get; set; }
/// <summary>
/// The port to connect to the adapter.
/// </summary>
[JsonPropertyName("port")]
public int Port { get; set; }
/// <summary>
/// Replaces the Manufacturer attribute in the device XML.
/// </summary>
[JsonPropertyName("manufacturer")]
public string Manufacturer { get; set; }
/// <summary>
/// Replaces the Model attribute in the device XML.
/// </summary>
[JsonPropertyName("model")]
public string Model { get; set; }
/// <summary>
/// Replaces the Station attribute in the device XML.
/// </summary>
[JsonPropertyName("station")]
public string Station { get; set; }
/// <summary>
/// Replaces the UUID attribute in the device XML.
/// </summary>
[JsonPropertyName("uuid")]
public string Uuid { get; set; }
/// <summary>
/// For devices that do not have the ability to provide available events, if yes, this sets the Availability to AVAILABLE upon connection.
/// </summary>
[JsonPropertyName("autoAvailable")]
public bool AutoAvailable { get; set; }
/// <summary>
/// Comma separated list of additional devices connected to this adapter. This provides availability support when one adapter feeds multiple devices.
/// </summary>
[JsonPropertyName("additionalDevices")]
public List<string> AdditionalDevices { get; set; }
/// <summary>
/// If value is true, filters all duplicate values for data items. This is to support adapters that are not doing proper duplicate filtering.
/// </summary>
[JsonPropertyName("filterDuplicates")]
public bool FilterDuplicates { get; set; }
/// <summary>
/// The length of time an adapter can be silent before it is disconnected. This is only for legacy adapters that do not support heartbeats.
/// If heartbeats are present, this will be ignored.
/// </summary>
[JsonPropertyName("legacyTimeout")]
public int LegacyTimeout { get; set; }
/// <summary>
/// The amount of time between adapter reconnection attempts.
/// This is useful for implementation of high performance adapters where availability needs to be tracked in near-real-time.
/// Time is specified in milliseconds (ms). Defaults to the top level ReconnectInterval.
/// </summary>
[JsonPropertyName("reconnectInterval")]
public int ReconnectInterval { get; set; }
/// <summary>
/// Overwrite timestamps with the agent time. This will correct clock drift but will not give as accurate relative time since it will not take into consideration network latencies.
/// This can be overridden on a per adapter basis.
/// </summary>
[JsonPropertyName("ignoreTimestamps")]
public bool IgnoreTimestamps { get; set; }
/// <summary>
/// Do not overwrite the UUID with the UUID from the adapter, preserve the UUID in the Devices.xml file. This can be overridden on a per adapter basis.
/// </summary>
[JsonPropertyName("preserveUuid")]
public bool PreserveUuid { get; set; }
/// <summary>
/// Boost the thread priority of this adapter so that events are handled faster.
/// </summary>
[JsonPropertyName("realTime")]
public bool RealTime { get; set; }
/// <summary>
/// The timestamps will be given as relative offsets represented as a floating point number of milliseconds.
/// The offset will be added to the arrival time of the first recorded event.
/// </summary>
[JsonPropertyName("relativeTime")]
public bool RelativeTime { get; set; }
/// <summary>
/// Adapter setting for data item units conversion in the agent. Assumes the adapter has already done unit conversion. Defaults to global.
/// </summary>
[JsonPropertyName("conversionRequired")]
public bool ConversionRequired { get; set; }
/// <summary>
/// Always converts the value of the data items to upper case.
/// </summary>
[JsonPropertyName("upcaseDataItemValue")]
public bool UpcaseDataItemValue { get; set; }
/// <summary>
/// Specifies the SHDR protocol version used by the adapter. When greater than one (1), allows multiple complex observations, like Condition and Message on the same line.
/// If it equials one (1), then any observation requiring more than a key/value pair need to be on separate lines. Applies to only this adapter.
/// </summary>
[JsonPropertyName("shdrVersion")]
public string ShdrVersion { get; set; }
/// <summary>
/// Suppress the Adapter IP Address and port when creating the Agent Device ids and names for 1.7.
/// </summary>
[JsonPropertyName("suppressIpAddress")]
public bool SuppressIpAddress { get; set; }
public AdapterConfiguration()
{
Device = "*";
Host = "localhost";
Port = 7878;
AutoAvailable = false;
AdditionalDevices = null;
FilterDuplicates = false;
LegacyTimeout = 600;
ReconnectInterval = 10000;
IgnoreTimestamps = false;
PreserveUuid = false;
RealTime = false;
RelativeTime = false;
ConversionRequired = true;
UpcaseDataItemValue = true;
ShdrVersion = "1";
SuppressIpAddress = false;
}
}
}
| 40.233129 | 189 | 0.613449 | [
"Apache-2.0"
] | TrakHound/MTConnect | src/MTConnect.NET-Common/Agents/Configuration/AdapterConfiguration.cs | 6,558 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using QFramework.GraphDesigner;
using Invert.Data;
using QFramework;
using QFramework.Json;
using UnityEngine;
namespace QFramework.GraphDesigner
{
public class UndoSystem : DiagramPlugin,
IDataRecordPropertyBeforeChange,
IDataRecordInserted,
IDataRecordRemoved,
IExecuteCommand<UndoCommand>,
IExecuteCommand<RedoCommand>,
IExecuteCommand<TestyCommand>,
IToolbarQuery,
ICommandExecuting,
ICommandExecuted,
IKeyboardEvent
{
public string CurrentUndoGroupId = null;
private List<UndoItem> _undoItems;
public List<UndoItem> UndoItems
{
get { return _undoItems ?? (_undoItems = new List<UndoItem>()); }
set { _undoItems = value; }
}
public void BeforePropertyChanged(IDataRecord record, string name, object previousValue, object nextValue)
{
if (IsUndoRedo) return;
if (CurrentUndoGroupId == null || record is UndoItem || record is RedoItem) return;
try
{
var undoItem = new UndoItem();
undoItem.Time = DateTime.Now;
undoItem.Group = CurrentUndoGroupId;
undoItem.DataRecordId = record.Identifier;
undoItem.Data = InvertJsonExtensions.SerializeObject(record).ToString();
undoItem.RecordType = record.GetType().AssemblyQualifiedName;
undoItem.Type = UndoType.Changed;
undoItem.Name = CurrentName;
UndoItems.Add(undoItem);
}
catch (Exception ex)
{
}
}
public void RecordInserted(IDataRecord record)
{
if (IsUndoRedo) return;
if (CurrentUndoGroupId == null || record is UndoItem || record is RedoItem) return;
var undoItem = new UndoItem();
undoItem.Time = DateTime.Now;
undoItem.Group = CurrentUndoGroupId;
undoItem.DataRecordId = record.Identifier;
undoItem.Data = InvertJsonExtensions.SerializeObject(record).ToString();
undoItem.RecordType = record.GetType().AssemblyQualifiedName;
undoItem.Type = UndoType.Inserted;
undoItem.Name = CurrentName;
UndoItems.Add(undoItem);
}
public void RecordRemoved(IDataRecord record)
{
if (IsUndoRedo) return;
if (CurrentUndoGroupId == null || record is UndoItem || record is RedoItem) return;
var undoItem = new UndoItem();
undoItem.Time = DateTime.Now;
undoItem.Group = CurrentUndoGroupId;
undoItem.DataRecordId = record.Identifier;
undoItem.Data = InvertJsonExtensions.SerializeObject(record).ToString();
undoItem.RecordType = record.GetType().AssemblyQualifiedName;
undoItem.Name = CurrentName;
undoItem.Type = UndoType.Removed;
UndoItems.Add(undoItem);
}
public bool IsUndoRedo { get; set; }
public void Execute(UndoCommand command)
{
Repository = Container.Resolve<IRepository>();
var undoGroup = Repository.All<UndoItem>().GroupBy(p => p.Group).LastOrDefault();
if (undoGroup == null) return;
IsUndoRedo = true;
try
{
foreach (var undoItem in undoGroup)
{
// Create redo item
var redoItem = new RedoItem();
redoItem.Data = undoItem.Data;
redoItem.Group = undoItem.Group;
redoItem.DataRecordId = undoItem.DataRecordId;
redoItem.Name = undoItem.Name;
redoItem.Time = undoItem.Time;
redoItem.Type = undoItem.Type;
redoItem.RecordType = undoItem.RecordType;
redoItem.UndoData = InvertJsonExtensions.SerializeObject(undoItem).ToString();
if (undoItem.Type == UndoType.Inserted)
{
var record = Repository.GetById<IDataRecord>(undoItem.DataRecordId);
redoItem.Data = InvertJsonExtensions.SerializeObject(record).ToString();
Repository.Remove(record);
redoItem.Type = UndoType.Removed;
}
else if (undoItem.Type == UndoType.Removed)
{
var obj =
InvertJsonExtensions.DeserializeObject(Type.GetType(undoItem.RecordType),
JSON.Parse(undoItem.Data).AsObject) as IDataRecord;
Repository.Add(obj);
redoItem.Type = UndoType.Inserted;
redoItem.Data = InvertJsonExtensions.SerializeObject(obj).ToString();
}
else
{
var record = Repository.GetById<IDataRecord>(undoItem.DataRecordId);
// We don't want to signal any events on deserialization
record.Repository = null;
redoItem.Data = InvertJsonExtensions.SerializeObject(record).ToString();
InvertJsonExtensions.DeserializeExistingObject(record, JSON.Parse(undoItem.Data).AsObject);
record.Changed = true;
record.Repository = Repository;
}
Repository.Remove(undoItem);
Repository.Add(redoItem);
}
}
catch (Exception ex)
{
// If we don't catch the exception IsUndoRedo won't be set back to fals causing cascading issues
}
IsUndoRedo = false;
Repository.Commit();
}
public void Execute(RedoCommand command)
{
IsUndoRedo = true;
Repository = Container.Resolve<IRepository>();
var redoGroup = Repository.All<RedoItem>().GroupBy(p => p.Group).LastOrDefault();
if (redoGroup == null) return;
foreach (var redoItem in redoGroup)
{
// Create redo item
var undoItem = InvertJsonExtensions.DeserializeObject(typeof(UndoItem), JSON.Parse(redoItem.UndoData)) as UndoItem;
if (redoItem.Type == UndoType.Inserted)
{
var record = Repository.GetById<IDataRecord>(redoItem.DataRecordId);
Repository.Remove(record);
}
else if (redoItem.Type == UndoType.Removed)
{
var obj = InvertJsonExtensions.DeserializeObject(Type.GetType(redoItem.RecordType), JSON.Parse(redoItem.Data).AsObject) as IDataRecord;
Repository.Add(obj);
}
else
{
var record = Repository.GetById<IDataRecord>(redoItem.DataRecordId);
// We don't want to signal any events on deserialization
record.Repository = null;
InvertJsonExtensions.DeserializeExistingObject(record, JSON.Parse(redoItem.Data).AsObject);
record.Changed = true;
record.Repository = Repository;
}
Repository.Remove(redoItem);
Repository.Add(undoItem);
}
IsUndoRedo = false;
Repository.Commit();
}
public void QueryToolbarCommands(ToolbarUI ui)
{
var repo = Container.Resolve<IRepository>();
if (repo == null) return;
var undoItem = repo.All<UndoItem>().LastOrDefault();
if (undoItem != null)
{
ui.AddCommand(new ToolbarItem()
{
Title = "Undo",
Command = new UndoCommand(),
Position = ToolbarPosition.BottomRight,
Order = -2
});
}
var redoItem = repo.All<RedoItem>().LastOrDefault();
if (redoItem != null)
{
ui.AddCommand(new ToolbarItem()
{
Title = "Redo",
Command = new RedoCommand(),
Position = ToolbarPosition.BottomRight,
Order = -1
});
}
}
public void CommandExecuting(ICommand command)
{
if (command is UndoCommand) return;
CurrentUndoGroupId = DateTime.Now.Hour.ToString() + DateTime.Now.Minute + DateTime.Now.Second.ToString();
CurrentName = command.Title;
UndoItems.Clear();
}
public string CurrentName { get; set; }
public override void Loaded(QFrameworkContainer container)
{
base.Loaded(container);
Repository = container.Resolve<IRepository>();
}
public IRepository Repository { get; set; }
public void CommandExecuted(ICommand command)
{
if (Repository == null) return;
if (command is UndoCommand || command is RedoCommand) return;
CurrentUndoGroupId = null;
if (Repository != null)
{
foreach (var item in UndoItems)
{
Repository.Add(item);
}
Repository.RemoveAll<RedoItem>();
}
var items = Repository.All<UndoItem>().Reverse();
foreach (var item in items.Skip(20))
Repository.Remove(item);
Repository.Commit();
}
public void Execute(TestyCommand command)
{
var sb = new StringBuilder();
foreach (var item in InvertApplication.Plugins.OrderBy(p => p.Title))
{
sb.AppendLine(item.Title);
}
InvertApplication.Log(sb.ToString());
}
public bool KeyEvent(KeyCode keyCode, ModifierKeyState state)
{
if (state.Ctrl && keyCode == KeyCode.Z)
{
InvertApplication.Execute(new UndoCommand());
return true;
}
if (state.Ctrl && keyCode == KeyCode.Y)
{
InvertApplication.Execute(new RedoCommand());
return true;
}
return false;
}
}
}
| 38.302083 | 156 | 0.516363 | [
"MIT"
] | 317392507/QFramework | Assets/QFramework/Framework/0.Core/Editor/0.EditorKit/uFrame.Editor/Systems/UndoSystem.cs | 11,033 | C# |
using System;
using Newtonsoft.Json;
namespace IIIF.Serialisation
{
public abstract class WriteOnlyConverter : JsonConverter
{
public override bool CanConvert(Type objectType) => true;
public override bool CanRead => false;
public override object ReadJson(JsonReader reader, Type objectType, object? existingValue,
JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
public abstract class WriteOnlyConverter<T> : JsonConverter<T>
{
public override bool CanRead => false;
public override T ReadJson(JsonReader reader, Type objectType, T? existingValue, bool hasExistingValue, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
} | 30.730769 | 138 | 0.673342 | [
"MIT"
] | Riksarkivet/iiif-net | src/IIIF/IIIF/Serialisation/WriteOnlyConverter.cs | 799 | C# |
using System;
using LinCms.Entities.Blog;
namespace LinCms.Blog.Notifications
{
public class CreateNotificationDto
{
public const string CreateOrCancelAsync = "CreateNotificationDto.CreateOrCancelAsync";
public NotificationType NotificationType { get; set; }
public Guid? ArticleId { get; set; }
public Guid? CommentId { get; set; }
public long NotificationRespUserId { get; set; }
public long UserInfoId { get; set; }
public bool IsCancel { get; set; }
public DateTime CreateTime { get; set; }
}
}
| 30.421053 | 94 | 0.66782 | [
"MIT"
] | KribKing/lin-cms-dotnetcore | src/LinCms.Application.Contracts/Blog/Notifications/CreateNotificationDto.cs | 580 | 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("Alphora Dataphor - FHIR DSTU2 Core Integration")]
[assembly: AssemblyDescription("FHIR DSTU2 Core Integration assembly for Alphora Dataphor")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Alphora")]
[assembly: AssemblyProduct("Dataphor")]
[assembly: AssemblyCopyright("Copyright © Alphora 2015-2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: Alphora.Dataphor.DAE.Server.DAERegister("Alphora.Dataphor.FHIR2.Core.DAERegister")]
// 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("6114fc36-b844-42d9-a181-273d338162ad")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("3.1.*")]
[assembly: AssemblyFileVersion("3.1.0.0")]
| 42 | 94 | 0.756892 | [
"BSD-3-Clause"
] | DBCG/Dataphor | Libraries/FHIR2.Core/Source/Properties/AssemblyInfo.cs | 1,599 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(MeshFilter), typeof(MeshRenderer))]
public class Test4 : MonoBehaviour
{
public int xGridCount, yGridCount, zGridCount;
private Vector3[] _vertices;
private int[] _triangles;
private int _t = 0, _v = 0;
// Use this for initialization
void Start()
{
Mesh mesh = new Mesh();
MeshFilter filter = GetComponent<MeshFilter>();
filter.mesh = mesh;
mesh.name = "Mesh04";
StartCoroutine(GenerateMesh(mesh));
}
private IEnumerator GenerateMesh(Mesh mesh)
{
yield return StartCoroutine(GenerateVextex());
mesh.vertices = _vertices;
yield return StartCoroutine(GenerateTriange(mesh));
}
private int GetVextexCount()
{
int connerVertexCount = 8;
int edgeVertexCount = (xGridCount + yGridCount + zGridCount - 3) * 4;
int faceVertexCount = (xGridCount - 1) * (yGridCount - 1) * 2
+ (zGridCount - 1) * (yGridCount - 1) * 2
+ (xGridCount - 1) * (zGridCount - 1) * 2;
return connerVertexCount + edgeVertexCount + faceVertexCount;
}
private IEnumerator GenerateVextex()
{
_vertices = new Vector3[GetVextexCount()];
int index = 0;
for (int y = 0; y < yGridCount + 1; y++)
{
for (int x = 0; x < xGridCount + 1; x++, index++)
{
_vertices[index] = new Vector3(x, y, 0);
yield return null;
}
for (int z = 1; z < zGridCount + 1; z++, index++)
{
_vertices[index] = new Vector3(xGridCount, y, z);
yield return null;
}
for (int x = xGridCount - 1; x >= 0; x--, index++)
{
_vertices[index] = new Vector3(x, y, zGridCount);
yield return null;
}
for (int z = zGridCount - 1; z > 0; z--, index++)
{
_vertices[index] = new Vector3(0, y, z);
yield return null;
}
}
for (int z = 1; z < zGridCount; z++)
{
for (int x = 1; x < xGridCount; x++, index++)
{
_vertices[index] = new Vector3(x, yGridCount, z);
yield return null;
}
}
for (int z = 1; z < zGridCount; z++)
{
for (int x = 1; x < xGridCount; x++, index++)
{
_vertices[index] = new Vector3(x, 0, z);
yield return null;
}
}
}
private int GetTriangeCount()
{
return xGridCount * yGridCount * 4 + xGridCount * zGridCount * 4 + yGridCount * zGridCount * 4;
}
private IEnumerator GenerateTriange(Mesh mesh)
{
_triangles = new int[GetTriangeCount() * 3];
int circleVextexCount = 2 * xGridCount + 2 * zGridCount;
yield return StartCoroutine(GenerateSide(mesh, circleVextexCount));
yield return StartCoroutine(GenerateTop(mesh, circleVextexCount));
yield return StartCoroutine(GenerateBottom(mesh, circleVextexCount));
}
private IEnumerator GenerateSide(Mesh mesh,int circleVextexCount)
{
for (int y = 0; y < yGridCount; y++)
{
for (int i = 0; i < circleVextexCount; i++,_v++,_t += 6)
{
SetQuad(_triangles,_t,_v,_v+1,_v+circleVextexCount,_v+1+circleVextexCount,circleVextexCount);
mesh.triangles = _triangles;
yield return null;
}
}
}
private IEnumerator GenerateTop(Mesh mesh,int circleVextexCount)
{
//第一行前三个面
for (int x = 0; x < xGridCount - 1; x++,_v++,_t += 6)
{
SetQuad(_triangles,_t,_v,_v+1,_v+circleVextexCount-1,_v+circleVextexCount);
mesh.triangles = _triangles;
yield return null;
}
//第一行第四个面
SetQuad(_triangles,_t,_v,_v+1,_v+circleVextexCount-1,_v+2);
mesh.triangles = _triangles;
_t += 6;
yield return null;
int vMin = circleVextexCount * (yGridCount + 1) - 1;
int vMid = vMin + 1;
int vMax = _v + 2;
//中间行所有面
for (int z = 0; z < zGridCount - 2; z++,vMin--,vMid++,vMax++)
{
//第一个面
SetQuad(_triangles,_t,vMin,vMid,vMin - 1,vMid + xGridCount);
mesh.triangles = _triangles;
_t += 6;
yield return null;
//中间面片
for (int i = 0; i < xGridCount - 2; i++,_t += 6,vMid++)
{
SetQuad(_triangles,_t,vMid,vMid+1,vMid +xGridCount - 1,vMid +xGridCount);
mesh.triangles = _triangles;
yield return null;
}
//最后一个面
SetQuad(_triangles,_t,vMid,vMax,vMid + xGridCount -1,vMax + 1);
mesh.triangles = _triangles;
_t += 6;
yield return null;
}
int vTop = vMin - 2;
//第一个面
SetQuad(_triangles,_t,vMin,vMid,vMin - 1,vTop);
mesh.triangles = _triangles;
_t += 6;
yield return null;
for (int i = 0; i < xGridCount - 2; i++,vMid++,vTop--)
{
//中间面
SetQuad(_triangles,_t,vMid,vMid + 1,vTop,vTop -1 );
mesh.triangles = _triangles;
_t += 6;
yield return null;
}
//最后一行最后一个面
SetQuad(_triangles,_t,vMid,vTop - 2,vTop,vTop - 1);
mesh.triangles = _triangles;
_t += 6;
yield return null;
}
private IEnumerator GenerateBottom(Mesh mesh, int circleVextexCount)
{
int vMin = circleVextexCount - 1;
int vMid = _vertices.Length - (xGridCount - 1) * (zGridCount - 1);
//第一行,第一面
SetQuad(_triangles,_t,vMin,vMid,0,1);
_t += 6;
mesh.triangles = _triangles;
yield return null;
int vMax = 1;
//第一行,中间面
for (int i = 0; i < xGridCount - 2; i++, _t += 6,vMax++,vMid++)
{
SetQuad(_triangles,_t,vMid,vMid + 1,vMax,vMax + 1);
mesh.triangles = _triangles;
yield return null;
}
//第一行,最后面
SetQuad(_triangles,_t,vMid,vMax + 2,vMax,vMax + 1);
_t += 6;
mesh.triangles = _triangles;
yield return null;
vMid++;
vMax += 2;
for (int z = 0; z < zGridCount - 2; z++,vMin --,vMid++,vMax ++)
{
//第一面
SetQuad(_triangles,_t,vMin - 1,vMid,vMin,vMid - xGridCount + 1);
_t += 6;
mesh.triangles = _triangles;
yield return null;
//中间面
for (int i = 0; i < xGridCount - 2; i++, _t += 6,vMid++)
{
SetQuad(_triangles,_t,vMid,vMid + 1, vMid - xGridCount + 1,vMid - xGridCount + 2);
mesh.triangles = _triangles;
yield return null;
}
//最后面
SetQuad(_triangles,_t,vMid,vMax + 1,vMid - xGridCount + 1,vMax);
_t += 6;
mesh.triangles = _triangles;
yield return null;
}
vMid = vMid - xGridCount + 1;
//最后行,第一面
SetQuad(_triangles,_t,vMin - 1,vMin - 2,vMin,vMid);
_t += 6;
mesh.triangles = _triangles;
yield return null;
int vBottom = vMin - 2;
//最后行,中间面
for (int i = 0; i < xGridCount - 2; i++, _t += 6,vBottom--,vMid++)
{
SetQuad(_triangles,_t,vBottom,vBottom - 1,vMid,vMid + 1);
mesh.triangles = _triangles;
yield return null;
}
//最后行,最后面
SetQuad(_triangles,_t,vBottom,vBottom - 1,vMid,vBottom - 2);
_t += 6;
mesh.triangles = _triangles;
yield return null;
}
private void SetQuad(int[] triangles, int i, int v00, int v10, int v01, int v11,int circleVextexCount)
{
v10 = (v00 / circleVextexCount) * circleVextexCount + v10 % circleVextexCount;
v11 = (v01 / circleVextexCount) * circleVextexCount + v11 % circleVextexCount;
SetQuad(triangles, i, v00, v10, v01, v11);
}
private void SetQuad(int[] triangles, int i, int v00, int v10, int v01, int v11)
{
triangles[i] = v00;
triangles[i + 1] = v01;
triangles[i + 2] = v10;
triangles[i + 3] = v01;
triangles[i + 4] = v11;
triangles[i + 5] = v10;
}
private void OnDrawGizmos()
{
if (_vertices == null)
return;
for (int i = 0; i < _vertices.Length; i++)
{
Gizmos.DrawSphere(transform.TransformPoint(_vertices[i]), 0.1f);
}
}
} | 29.959596 | 109 | 0.50708 | [
"MIT"
] | BlueMonk1107/MeshProgram | Assets/Scripts/Test_4/Test4.cs | 9,100 | C# |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public static class Sound_Manager {
private class MonoBehaviourDummy : MonoBehaviour { }
public enum Sound {
None,
BulletTime_In,
BulletTime_Out,
Dash,
Dash_2,
Dash_3,
Dash_4,
Player_Counter,
Sword_Hit,
Sword_Kill,
Sword_Kill_2,
Sword_Wrong,
Sword_Draw,
Sword_Sheathe,
Sword,
Sword_2,
Sword_3,
Sword_4,
Sword_5,
Sword_6,
Sword_7,
ComboButton,
Footsteps_Hero,
Footstep_Minion,
Footstep_Minion_2,
Footstep_Minion_3,
Footstep_Minion_4,
Footstep_Minion_5,
Footstep_Minion_6,
Combo_Healing,
Combo_Earthshatter,
Countered,
Countered_2,
Menu_Over,
Menu_Click,
Open_Map,
Arrow_Fire,
Arrow_Hit,
Arrow_Deflect,
Minion_Sword,
Minion_Sword_2,
Minion_Sword_3,
Minion_Sword_4,
Minion_Sword_5,
Minion_Sword_6,
Minion_Sword_7,
Minion_Sword_8,
Minion_Sword_9,
Minion_Sword_10,
Minion_Sword_11,
Minion_Dead,
Minion_Dead_2,
Minion_Dead_3,
Player_Hit,
Player_Hit_2,
Player_Hit_3,
Player_Hit_4,
Player_Hit_5,
ExperienceTick,
Ding,
Victory,
Defeat,
Pickup,
Rifle_Fire,
Rifle_Fire_1,
Rifle_Fire_2,
Rifle_Fire_3,
Rifle_Fire_4,
Building,
Demolish,
TimeSwoosh,
Warning,
Axe_1,
Axe_2,
Axe_3,
Axe_4,
Axe_5,
Axe_6,
Pickaxe_1,
Pickaxe_2,
Pickaxe_3,
Pickaxe_4,
Pickaxe_5,
Talking,
Gong,
Coins,
AsianBonus,
}
public enum AudioType {
Master,
Music,
Sound
}
private static bool isInit = false;
private static Dictionary<Sound,AudioClip> dictionary;
private static Dictionary<Sound,float> timers;
private static bool disableAllSounds = false;
private static GameObject globalGameObject;
public delegate float DelGetAudio(AudioType audioType);
private static DelGetAudio GetAudioFunc;
public static void Init() {
Sound_Manager.Init((Sound_Manager.AudioType audioType) => .1f);
}
public static void Init(DelGetAudio GetAudioFunc) {
if (isInit) return;
Debug.Log("Loading Sounds...");
isInit = true;
Sound_Manager.GetAudioFunc = GetAudioFunc;
CreateGlobalObject();
dictionary = new Dictionary<Sound,AudioClip>();
timers = new Dictionary<Sound,float>();
foreach(Sound sound in System.Enum.GetValues(typeof(Sound))) {
if (sound == Sound.None) continue;
Load(sound);
}
PoolObjects();
}
private static void CreateGlobalObject() {
globalGameObject = new GameObject();
Object.DontDestroyOnLoad(globalGameObject);
globalGameObject.AddComponent<MonoBehaviourDummy>();
}
public static void Load(Sound sound, string folder = "") {
if (folder == "") folder = "Sounds/"; //Default sound folder
dictionary[sound] = (AudioClip) Resources.Load(folder+sound);
//if (dictionary[sound] == null) Debug.Log("Couldnt load "+folder+sound);
timers[sound] = 0f;
}
public static float GetSoundLength(Sound sound) {
if (!dictionary.ContainsKey(sound)) {
Debug.Log("Sound not found: "+sound);
return 0f;
}
return dictionary[sound].length;
}
public static void DisableAllSounds() {
disableAllSounds = true;
}
public static void EnableAllSounds() {
disableAllSounds = false;
}
/*
public static AudioClip GetAudioClip(CustomSound.Type unitSound) {
Sound sound = ConvertUnitSoundToSound(unitSound);
//Init();
if (disableAllSounds) return null;
if (!dictionary.ContainsKey(sound)) {
Debug.Log("Sound not found: "+sound);
return null;
}
return dictionary[sound];
}
public static Sound ConvertUnitSoundToSound(CustomSound.Type unitSound) {
switch (unitSound) {
default:
case CustomSound.Type.Sword: return Sound.Minion_Sword;
case CustomSound.Type.Gunshot_Rifle: return Sound.Rifle_Fire;
case CustomSound.Type.Crash: return Sound.Combo_Earthshatter;
}
}*/
public static float GetAudio(AudioType audioType) {
return GetAudioFunc(audioType);
}
/*public static AudioSource PlaySound(CustomSound.Type unitSound, Vector3 pos = default(Vector3), object obj = null) {
return PlaySound(ConvertUnitSoundToSound(unitSound), pos, obj);
}*/
/*public static AudioSource PlaySound(CustomSound unitSound, Vector3 pos) {
return PlaySound(unitSound.audioClip, true, pos);
}*/
public static AudioSource PlaySound(AudioClip audioClip, bool usePosition = false, Vector3 pos = default(Vector3)) {
if (usePosition) {
return PlayClipAtPoint(audioClip, pos);
} else {
return PlayClip(audioClip);
}
}
public static AudioSource PlaySound(Sound sound, Vector3 pos = default(Vector3), object obj = null) {
//Window_DebugMessages.AddMessage(sound);
//Init();
if (disableAllSounds) return null;
if (!dictionary.ContainsKey(sound)) {
Debug.Log("Sound not found: "+sound);
return null;
}
switch (sound) {
default:
return PlayClip(dictionary[sound]);
case Sound.Victory:
return PlayClip(dictionary[sound], 90);
//return PlayClipAtPoint(dictionary[sound], pos);
case Sound.Arrow_Fire:
case Sound.Arrow_Hit:
case Sound.Arrow_Deflect:
case Sound.Sword_Draw:
case Sound.Sword_Sheathe:
//return PlayClipAtPoint(dictionary[sound], pos);
return PlayClip(dictionary[sound]);
case Sound.Sword_Hit:
case Sound.Sword_Wrong:
return PlayClip(dictionary[sound]);
/*if (CanPlay(sound)) {
if (Time.realtimeSinceStartup - timers[sound] > .1f)
timers[sound] = Time.realtimeSinceStartup - .05f;
timers[sound] += .01f;
return PlayClipAtPoint(dictionary[sound], pos, 100);
} return null;*/
case Sound.Dash:
Sound[] sounds = new[] { Sound.Dash, Sound.Dash_2, Sound.Dash_3, Sound.Dash_4 };
return PlayClip(dictionary[sounds[Random.Range(0, sounds.Length)]]);
//return PlayClipAtPoint(dictionary[sounds[Random.Range(0, sounds.Length)]], pos, 100);
case Sound.Sword_Kill:
if (CanPlay(sound)) {
if (Time.realtimeSinceStartup - timers[sound] > .1f)
timers[sound] = Time.realtimeSinceStartup - .03f;
timers[sound] += .01f;
sounds = new[] { Sound.Sword_Kill, Sound.Sword_Kill_2, };
return PlayClipAtPoint(dictionary[sounds[Random.Range(0, sounds.Length)]], pos, 100);
}
return null;
case Sound.Sword:
sounds = new[] { Sound.Sword, Sound.Sword_2, Sound.Sword_3, Sound.Sword_4, Sound.Sword_5, Sound.Sword_6, Sound.Sword_7 };
return PlayClip(dictionary[sounds[Random.Range(0, sounds.Length)]]);
//return PlayClipAtPoint(dictionary[sounds[Random.Range(0, sounds.Length)]], pos, 100);
case Sound.Footsteps_Hero:
return PlayClipAtPoint(dictionary[sound], pos, true);
case Sound.Footstep_Minion:
sounds = new[] { Sound.Footstep_Minion, Sound.Footstep_Minion_2, Sound.Footstep_Minion_3, Sound.Footstep_Minion_4, Sound.Footstep_Minion_5, Sound.Footstep_Minion_6 };
return PlayClipAtPoint(dictionary[sounds[Random.Range(0, sounds.Length)]], pos, 140, .5f * GetAudio(AudioType.Sound));
/*case Sound.Minion_Dead:
if (CanPlay(sound)) {
if (Time.realtimeSinceStartup - timers[sound] > .1f)
timers[sound] = Time.realtimeSinceStartup - .05f;
timers[sound] += .01f;
sounds = new[] { Sound.Minion_Dead, Sound.Minion_Dead_2, Sound.Minion_Dead_3 };
return PlayClipAtPoint(dictionary[sounds[Random.Range(0, sounds.Length)]], pos);
}
return null;*/
case Sound.Countered:
sounds = new[] { Sound.Countered, Sound.Countered_2 };
return PlayClipAtPoint(dictionary[sounds[Random.Range(0, sounds.Length)]], pos);
case Sound.Player_Hit:
sounds = new[] { Sound.Player_Hit, Sound.Player_Hit_2, Sound.Player_Hit_3, Sound.Player_Hit_4, Sound.Player_Hit_5 };
return PlayClipAtPoint(dictionary[sounds[Random.Range(0, sounds.Length)]], pos, 100);
case Sound.Minion_Sword:
if (!CanPlay(sound)) return null;
timers[sound] = Time.realtimeSinceStartup + Random.Range(.05f, .2f);
sounds = new[] { Sound.Minion_Sword, Sound.Minion_Sword_2, Sound.Minion_Sword_3, Sound.Minion_Sword_4, Sound.Minion_Sword_5, Sound.Minion_Sword_6, Sound.Minion_Sword_7, Sound.Minion_Sword_8, Sound.Minion_Sword_9, Sound.Minion_Sword_10, Sound.Minion_Sword_11 };
return PlayClipAtPoint(dictionary[sounds[Random.Range(0, sounds.Length)]], pos);
case Sound.Minion_Dead:
if (!CanPlay(sound)) return null;
timers[sound] = Time.realtimeSinceStartup + Random.Range(.05f, .2f);
sounds = new[] { Sound.Minion_Dead, Sound.Minion_Dead_2, Sound.Minion_Dead_3 };
return PlayClipAtPoint(dictionary[sounds[Random.Range(0, sounds.Length)]], pos);
case Sound.Axe_1:
if (!CanPlay(sound)) return null;
timers[sound] = Time.realtimeSinceStartup + Random.Range(.05f, .2f);
sounds = new[] { Sound.Axe_1, Sound.Axe_2, Sound.Axe_3, Sound.Axe_4, Sound.Axe_5, Sound.Axe_6 };
return PlayClipAtPoint(dictionary[sounds[Random.Range(0, sounds.Length)]], pos, 100, .1f);
case Sound.Pickaxe_1:
if (!CanPlay(sound)) return null;
timers[sound] = Time.realtimeSinceStartup + Random.Range(.05f, .2f);
sounds = new[] { Sound.Pickaxe_1, Sound.Pickaxe_2, Sound.Pickaxe_3, Sound.Pickaxe_4, Sound.Pickaxe_5 };
return PlayClipAtPoint(dictionary[sounds[Random.Range(0, sounds.Length)]], pos, 100, .1f);
case Sound.Rifle_Fire:
if (!CanPlay(sound)) return null;
/*
if (Time.realtimeSinceStartup - timers[sound] > .1f)
timers[sound] = Time.realtimeSinceStartup - .03f;
timers[sound] += .01f;
*/
timers[sound] = Time.realtimeSinceStartup + Random.Range(.02f, .05f);
sounds = new[] { Sound.Rifle_Fire_1, Sound.Rifle_Fire_2, Sound.Rifle_Fire_3, Sound.Rifle_Fire_4 };
return PlayClipAtPoint(dictionary[sounds[Random.Range(0, sounds.Length)]], pos);
case Sound.TimeSwoosh:
if (!CanPlay(sound)) return null;
timers[sound] = Time.realtimeSinceStartup + .1f;
return PlayClip(dictionary[sound]);
case Sound.Building:
return PlayClipAtPoint(dictionary[sound], pos);
case Sound.Talking:
return PlayClip(dictionary[sound], true);
}
}
public static bool CanPlay(Sound sound) {
return Time.realtimeSinceStartup > timers[sound];
}
private static AudioSource PlayClip(AudioClip clip) {
AudioSource src = PlayClipAtPoint(clip, Vector3.zero);
src.spatialBlend = 0f;
return src;
}
private static AudioSource PlayClip(AudioClip clip, bool loop) {
AudioSource src = PlayClipAtPoint(clip, Vector3.zero, 128, GetAudio(AudioType.Sound), loop);
src.spatialBlend = 0f;
return src;
}
private static AudioSource PlayClip(AudioClip clip, int priority) {
AudioSource src = PlayClipAtPoint(clip, Vector3.zero, priority, GetAudio(AudioType.Sound));
src.spatialBlend = 0f;
return src;
}
private static AudioSource PlayClipAtPoint(AudioClip clip, Vector3 pos) {
return PlayClipAtPoint(clip, pos, 128);
}
private static AudioSource PlayClipAtPoint(AudioClip clip, Vector3 pos, bool loop) {
return PlayClipAtPoint(clip, pos, 128, 1f, loop);
}
private static AudioSource PlayClipAtPoint(AudioClip clip, Vector3 pos, int priority) {
return PlayClipAtPoint(clip, pos, priority, GetAudio(AudioType.Sound), false);
}
private static AudioSource PlayClipAtPoint(AudioClip clip, Vector3 pos, int priority, float volMultiplier) {
return PlayClipAtPoint(clip, pos, priority, GetAudio(AudioType.Sound) * volMultiplier, false);
}
private static AudioSource PlayClipAtPoint(AudioClip clip, Vector3 pos, int priority, float vol, bool loop = false) {
GameObject tempGO = GetPooledObject();
AudioSource aSource = tempGO.GetComponent<AudioSource>();
tempGO.transform.position = pos; // set its position
aSource.clip = clip; // define the clip
aSource.priority = priority;
// set other aSource properties here, if desired
aSource.spatialBlend = 1f;//0.5f;
aSource.dopplerLevel = .0f;
aSource.minDistance = 60;
aSource.maxDistance = 400;
aSource.rolloffMode = AudioRolloffMode.Linear;
aSource.volume = vol;
if (!loop) {
aSource.loop = false;
tempGO.SetActive(true);
globalGameObject.GetComponent<MonoBehaviourDummy>().StartCoroutine(DisablePooledObject(tempGO, clip.length));
} else {
aSource.loop = true;
tempGO.SetActive(true);
}
aSource.Play(); // start the sound
return aSource; // return the AudioSource reference
}
public static void StopSound(AudioSource audioSource) {
audioSource.Stop();
audioSource.transform.gameObject.SetActive(false);
}
public static void StopSound(AudioSource audioSource, string clipName) {
if (clipName == audioSource.clip.name)
StopSound(audioSource);
}
public static IEnumerator DisablePooledObject(GameObject obj, float time) {
yield return globalGameObject.GetComponent<MonoBehaviourDummy>().StartCoroutine(WaitForRealSeconds(time)); // waits
if (obj != null) {
obj.SetActive(false);
}
}
public static IEnumerator WaitForRealSeconds(float time) {
float start = Time.realtimeSinceStartup;
while (Time.realtimeSinceStartup < start + time) {
yield return null;
}
}
private static GameObject[] poolArr = null;
private static int poolAmount = 30;
private static int poolAmountMax = 50;
/*public static void Init() {
PoolObjects();
}*/
public static void PoolObjects() {
//Init();
List<GameObject> poolList = new List<GameObject>();
for (int i=0; i<poolAmount; i++) {
GameObject tempGO = new GameObject("Pooled_Audio_"+i, typeof(AudioSource)); // create the temp object
//tempGO.AddComponent<AudioSource>(); // add an audio source
tempGO.SetActive(false);
poolList.Add(tempGO);
}
poolArr = poolList.ToArray();
}
private static GameObject GetPooledObject() {
if (poolArr == null || poolArr.Length < poolAmount || poolArr[0] == null) PoolObjects();
for (int i=0; i<poolAmount; i++) {
if (poolArr[i] != null && !poolArr[i].activeSelf) {
return poolArr[i];
}
}
if (poolAmount >= poolAmountMax) {
// Maximum objects in pool, dont create more!
return poolArr[Random.Range(0, poolArr.Length)];
}
GameObject tempGO = new GameObject("Pooled_Audio_"+poolAmount, typeof(AudioSource)); // create the temp object
//tempGO.AddComponent<AudioSource>(); // add an audio source
tempGO.SetActive(false);
List<GameObject> poolList = new List<GameObject>(poolArr);
poolList.Add(tempGO);
poolAmount++;
poolArr = poolList.ToArray();
return tempGO;
}
}
| 38.130641 | 272 | 0.639382 | [
"MIT"
] | mickeyzzq/UCMEGRSamples | CMK/Assets/_/Stuff/Scripts/Sound_Manager.cs | 16,053 | C# |
using System.Collections.Generic;
using Newtonsoft.Json;
namespace luno_api
{
public class ListTradeResponse
{
[JsonProperty("trades")]
public List<ListTrade> Trades { get; set; }
}
} | 19.363636 | 51 | 0.666667 | [
"MIT"
] | armandvanderwalt/luno-api | luno-api/ListTradeResponse.cs | 215 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace net_mvc_day02
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
}
| 24.208333 | 99 | 0.58864 | [
"MIT"
] | Willson-L/net_mvc_study | net_mvc_day02/net_mvc_day02/net_mvc_day02/App_Start/RouteConfig.cs | 583 | C# |
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.EventSystems;
public class SellHoney : MonoBehaviour, IPointerClickHandler
{
[SerializeField] HoneyManager honeyManager;
[SerializeField] MoneyManager moneyManager;
public void OnPointerClick(PointerEventData eventData)
{
moneyManager.SellHoney(honeyManager.GetHoneyAmount());
honeyManager.ClearHoney();
}
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
}
| 20.9 | 62 | 0.69378 | [
"MIT"
] | AlexYam94/Game_off_2021_Bee_Keeper | Assets/Scripts/Items/SellHoney.cs | 627 | C# |
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace Out_Parameters
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
| 23.047619 | 66 | 0.568182 | [
"MIT"
] | NetOffice/NetOffice | Tests/Concept Tests/Out Parameters/Out Parameters/Program.cs | 486 | C# |
/*
Copyright (C) 2008 Siarhei Novik (snovik@gmail.com)
Copyright (C) 2008, 2009 , 2010, 2011, 2012 Andrea Maggiulli (a.maggiulli@gmail.com)
This file is part of QLNet Project https://github.com/amaggiulli/qlnet
QLNet is free software: you can redistribute it and/or modify it
under the terms of the QLNet license. You should have received a
copy of the license along with this program; if not, license is
available at <https://github.com/amaggiulli/QLNet/blob/develop/LICENSE>.
QLNet is a based on QuantLib, a free-software/open-source library
for financial quantitative analysts and developers - http://quantlib.org/
The QuantLib license is available online at http://quantlib.org/license.shtml.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the license for more details.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
#if NET40 || NET45
using Microsoft.VisualStudio.TestTools.UnitTesting;
#else
using Xunit;
#endif
using QLNet;
using Calendar = QLNet.Calendar;
namespace TestSuite
{
#if NET40 || NET45
[TestClass()]
#endif
public class T_Bonds : IDisposable
{
#region Initialize&Cleanup
private SavedSettings backup;
#if NET40 || NET45
[TestInitialize]
public void testInitialize()
{
#else
public T_Bonds()
{
#endif
backup = new SavedSettings();
}
#if NET40 || NET45
[TestCleanup]
#endif
public void testCleanup()
{
Dispose();
}
public void Dispose()
{
backup.Dispose();
}
#endregion
class CommonVars
{
// common data
public Calendar calendar;
public Date today;
public double faceAmount;
// setup
public CommonVars()
{
calendar = new TARGET();
today = calendar.adjust(Date.Today);
Settings.setEvaluationDate(today);
faceAmount = 1000000.0;
}
}
#if NET40 || NET45
[TestMethod()]
#else
[Fact]
#endif
public void testYield()
{
//"Testing consistency of bond price/yield calculation...");
CommonVars vars = new CommonVars();
double tolerance = 1.0e-7;
int maxEvaluations = 100;
int[] issueMonths = new int[] { -24, -18, -12, -6, 0, 6, 12, 18, 24 };
int[] lengths = new int[] { 3, 5, 10, 15, 20 };
int settlementDays = 3;
double[] coupons = new double[] { 0.02, 0.05, 0.08 };
Frequency[] frequencies = new Frequency[] { Frequency.Semiannual, Frequency.Annual };
DayCounter bondDayCount = new Thirty360();
BusinessDayConvention accrualConvention = BusinessDayConvention.Unadjusted;
BusinessDayConvention paymentConvention = BusinessDayConvention.ModifiedFollowing;
double redemption = 100.0;
double[] yields = new double[] { 0.03, 0.04, 0.05, 0.06, 0.07 };
Compounding[] compounding = new Compounding[] { Compounding.Compounded, Compounding.Continuous };
for (int i = 0; i < issueMonths.Length; i++)
{
for (int j = 0; j < lengths.Length; j++)
{
for (int k = 0; k < coupons.Length; k++)
{
for (int l = 0; l < frequencies.Length; l++)
{
for (int n = 0; n < compounding.Length; n++)
{
Date dated = vars.calendar.advance(vars.today, issueMonths[i], TimeUnit.Months);
Date issue = dated;
Date maturity = vars.calendar.advance(issue, lengths[j], TimeUnit.Years);
Schedule sch = new Schedule(dated, maturity, new Period(frequencies[l]), vars.calendar,
accrualConvention, accrualConvention, DateGeneration.Rule.Backward, false);
FixedRateBond bond = new FixedRateBond(settlementDays, vars.faceAmount, sch,
new List<double>() { coupons[k] },
bondDayCount, paymentConvention,
redemption, issue);
for (int m = 0; m < yields.Length; m++)
{
double price = bond.cleanPrice(yields[m], bondDayCount, compounding[n], frequencies[l]);
double calculated = bond.yield(price, bondDayCount, compounding[n], frequencies[l], null,
tolerance, maxEvaluations);
if (Math.Abs(yields[m] - calculated) > tolerance)
{
// the difference might not matter
double price2 = bond.cleanPrice(calculated, bondDayCount, compounding[n], frequencies[l]);
if (Math.Abs(price - price2) / price > tolerance)
{
QAssert.Fail("yield recalculation failed:\n"
+ " issue: " + issue + "\n"
+ " maturity: " + maturity + "\n"
+ " coupon: " + coupons[k] + "\n"
+ " frequency: " + frequencies[l] + "\n\n"
+ " yield: " + yields[m] + " "
+ (compounding[n] == Compounding.Compounded ? "compounded" : "continuous") + "\n"
+ " price: " + price + "\n"
+ " yield': " + calculated + "\n"
+ " price': " + price2);
}
}
}
}
}
}
}
}
}
#if NET40 || NET45
[TestMethod()]
#else
[Fact]
#endif
public void testTheoretical()
{
// "Testing theoretical bond price/yield calculation...");
CommonVars vars = new CommonVars();
double tolerance = 1.0e-7;
int maxEvaluations = 100;
int[] lengths = new int[] { 3, 5, 10, 15, 20 };
int settlementDays = 3;
double[] coupons = new double[] { 0.02, 0.05, 0.08 };
Frequency[] frequencies = new Frequency[] { Frequency.Semiannual, Frequency.Annual };
DayCounter bondDayCount = new Actual360();
BusinessDayConvention accrualConvention = BusinessDayConvention.Unadjusted;
BusinessDayConvention paymentConvention = BusinessDayConvention.ModifiedFollowing;
double redemption = 100.0;
double[] yields = new double[] { 0.03, 0.04, 0.05, 0.06, 0.07 };
for (int j = 0; j < lengths.Length; j++)
{
for (int k = 0; k < coupons.Length; k++)
{
for (int l = 0; l < frequencies.Length; l++)
{
Date dated = vars.today;
Date issue = dated;
Date maturity = vars.calendar.advance(issue, lengths[j], TimeUnit.Years);
SimpleQuote rate = new SimpleQuote(0.0);
var discountCurve = new Handle<YieldTermStructure>(Utilities.flatRate(vars.today, rate, bondDayCount));
Schedule sch = new Schedule(dated, maturity, new Period(frequencies[l]), vars.calendar,
accrualConvention, accrualConvention, DateGeneration.Rule.Backward, false);
FixedRateBond bond = new FixedRateBond(settlementDays, vars.faceAmount, sch, new List<double>() { coupons[k] },
bondDayCount, paymentConvention, redemption, issue);
IPricingEngine bondEngine = new DiscountingBondEngine(discountCurve);
bond.setPricingEngine(bondEngine);
for (int m = 0; m < yields.Length; m++)
{
rate.setValue(yields[m]);
double price = bond.cleanPrice(yields[m], bondDayCount, Compounding.Continuous, frequencies[l]);
double calculatedPrice = bond.cleanPrice();
if (Math.Abs(price - calculatedPrice) > tolerance)
{
QAssert.Fail("price calculation failed:"
+ "\n issue: " + issue
+ "\n maturity: " + maturity
+ "\n coupon: " + coupons[k]
+ "\n frequency: " + frequencies[l] + "\n"
+ "\n yield: " + yields[m]
+ "\n expected: " + price
+ "\n calculated': " + calculatedPrice
+ "\n error': " + (price - calculatedPrice));
}
double calculatedYield = bond.yield(bondDayCount, Compounding.Continuous, frequencies[l],
tolerance, maxEvaluations);
if (Math.Abs(yields[m] - calculatedYield) > tolerance)
{
QAssert.Fail("yield calculation failed:"
+ "\n issue: " + issue
+ "\n maturity: " + maturity
+ "\n coupon: " + coupons[k]
+ "\n frequency: " + frequencies[l] + "\n"
+ "\n yield: " + yields[m]
+ "\n price: " + price
+ "\n yield': " + calculatedYield);
}
}
}
}
}
}
#if NET40 || NET45
[TestMethod()]
#else
[Fact]
#endif
public void testCached()
{
// ("Testing bond price/yield calculation against cached values...");
CommonVars vars = new CommonVars();
// with implicit settlement calculation:
Date today = new Date(22, Month.November, 2004);
Settings.setEvaluationDate(today);
Calendar bondCalendar = new NullCalendar();
DayCounter bondDayCount = new ActualActual(ActualActual.Convention.ISMA);
int settlementDays = 1;
var discountCurve = new Handle<YieldTermStructure>(Utilities.flatRate(today, new SimpleQuote(0.03), new Actual360()));
// actual market values from the evaluation date
Frequency freq = Frequency.Semiannual;
Schedule sch1 = new Schedule(new Date(31, Month.October, 2004), new Date(31, Month.October, 2006), new Period(freq),
bondCalendar, BusinessDayConvention.Unadjusted, BusinessDayConvention.Unadjusted,
DateGeneration.Rule.Backward, false);
FixedRateBond bond1 = new FixedRateBond(settlementDays, vars.faceAmount, sch1, new List<double>() { 0.025 },
bondDayCount, BusinessDayConvention.ModifiedFollowing, 100.0, new Date(1, Month.November, 2004));
IPricingEngine bondEngine = new DiscountingBondEngine(discountCurve);
bond1.setPricingEngine(bondEngine);
double marketPrice1 = 99.203125;
double marketYield1 = 0.02925;
Schedule sch2 = new Schedule(new Date(15, Month.November, 2004), new Date(15, Month.November, 2009), new Period(freq),
bondCalendar, BusinessDayConvention.Unadjusted, BusinessDayConvention.Unadjusted,
DateGeneration.Rule.Backward, false);
FixedRateBond bond2 = new FixedRateBond(settlementDays, vars.faceAmount, sch2, new List<double>() { 0.035 },
bondDayCount, BusinessDayConvention.ModifiedFollowing,
100.0, new Date(15, Month.November, 2004));
bond2.setPricingEngine(bondEngine);
double marketPrice2 = 99.6875;
double marketYield2 = 0.03569;
// calculated values
double cachedPrice1a = 99.204505, cachedPrice2a = 99.687192;
double cachedPrice1b = 98.943393, cachedPrice2b = 101.986794;
double cachedYield1a = 0.029257, cachedYield2a = 0.035689;
double cachedYield1b = 0.029045, cachedYield2b = 0.035375;
double cachedYield1c = 0.030423, cachedYield2c = 0.030432;
// check
double tolerance = 1.0e-6;
double price, yield;
price = bond1.cleanPrice(marketYield1, bondDayCount, Compounding.Compounded, freq);
if (Math.Abs(price - cachedPrice1a) > tolerance)
{
QAssert.Fail("failed to reproduce cached price:"
+ "\n calculated: " + price
+ "\n expected: " + cachedPrice1a
+ "\n tolerance: " + tolerance
+ "\n error: " + (price - cachedPrice1a));
}
price = bond1.cleanPrice();
if (Math.Abs(price - cachedPrice1b) > tolerance)
{
QAssert.Fail("failed to reproduce cached price:"
+ "\n calculated: " + price
+ "\n expected: " + cachedPrice1b
+ "\n tolerance: " + tolerance
+ "\n error: " + (price - cachedPrice1b));
}
yield = bond1.yield(marketPrice1, bondDayCount, Compounding.Compounded, freq);
if (Math.Abs(yield - cachedYield1a) > tolerance)
{
QAssert.Fail("failed to reproduce cached compounded yield:"
+ "\n calculated: " + yield
+ "\n expected: " + cachedYield1a
+ "\n tolerance: " + tolerance
+ "\n error: " + (yield - cachedYield1a));
}
yield = bond1.yield(marketPrice1, bondDayCount, Compounding.Continuous, freq);
if (Math.Abs(yield - cachedYield1b) > tolerance)
{
QAssert.Fail("failed to reproduce cached continuous yield:"
+ "\n calculated: " + yield
+ "\n expected: " + cachedYield1b
+ "\n tolerance: " + tolerance
+ "\n error: " + (yield - cachedYield1b));
}
yield = bond1.yield(bondDayCount, Compounding.Continuous, freq);
if (Math.Abs(yield - cachedYield1c) > tolerance)
{
QAssert.Fail("failed to reproduce cached continuous yield:"
+ "\n calculated: " + yield
+ "\n expected: " + cachedYield1c
+ "\n tolerance: " + tolerance
+ "\n error: " + (yield - cachedYield1c));
}
price = bond2.cleanPrice(marketYield2, bondDayCount, Compounding.Compounded, freq);
if (Math.Abs(price - cachedPrice2a) > tolerance)
{
QAssert.Fail("failed to reproduce cached price:"
+ "\n calculated: " + price
+ "\n expected: " + cachedPrice2a
+ "\n tolerance: " + tolerance
+ "\n error: " + (price - cachedPrice2a));
}
price = bond2.cleanPrice();
if (Math.Abs(price - cachedPrice2b) > tolerance)
{
QAssert.Fail("failed to reproduce cached price:"
+ "\n calculated: " + price
+ "\n expected: " + cachedPrice2b
+ "\n tolerance: " + tolerance
+ "\n error: " + (price - cachedPrice2b));
}
yield = bond2.yield(marketPrice2, bondDayCount, Compounding.Compounded, freq);
if (Math.Abs(yield - cachedYield2a) > tolerance)
{
QAssert.Fail("failed to reproduce cached compounded yield:"
+ "\n calculated: " + yield
+ "\n expected: " + cachedYield2a
+ "\n tolerance: " + tolerance
+ "\n error: " + (yield - cachedYield2a));
}
yield = bond2.yield(marketPrice2, bondDayCount, Compounding.Continuous, freq);
if (Math.Abs(yield - cachedYield2b) > tolerance)
{
QAssert.Fail("failed to reproduce cached continuous yield:"
+ "\n calculated: " + yield
+ "\n expected: " + cachedYield2b
+ "\n tolerance: " + tolerance
+ "\n error: " + (yield - cachedYield2b));
}
yield = bond2.yield(bondDayCount, Compounding.Continuous, freq);
if (Math.Abs(yield - cachedYield2c) > tolerance)
{
QAssert.Fail("failed to reproduce cached continuous yield:"
+ "\n calculated: " + yield
+ "\n expected: " + cachedYield2c
+ "\n tolerance: " + tolerance
+ "\n error: " + (yield - cachedYield2c));
}
// with explicit settlement date:
Schedule sch3 = new Schedule(new Date(30, Month.November, 2004), new Date(30, Month.November, 2006), new Period(freq),
new UnitedStates(UnitedStates.Market.GovernmentBond), BusinessDayConvention.Unadjusted,
BusinessDayConvention.Unadjusted, DateGeneration.Rule.Backward, false);
FixedRateBond bond3 = new FixedRateBond(settlementDays, vars.faceAmount, sch3, new List<double>() { 0.02875 },
new ActualActual(ActualActual.Convention.ISMA),
BusinessDayConvention.ModifiedFollowing, 100.0, new Date(30, Month.November, 2004));
bond3.setPricingEngine(bondEngine);
double marketYield3 = 0.02997;
Date settlementDate = new Date(30, Month.November, 2004);
double cachedPrice3 = 99.764759;
price = bond3.cleanPrice(marketYield3, bondDayCount, Compounding.Compounded, freq, settlementDate);
if (Math.Abs(price - cachedPrice3) > tolerance)
{
QAssert.Fail("failed to reproduce cached price:"
+ "\n calculated: " + price + ""
+ "\n expected: " + cachedPrice3 + ""
+ "\n error: " + (price - cachedPrice3));
}
// this should give the same result since the issue date is the
// earliest possible settlement date
Settings.setEvaluationDate(new Date(22, Month.November, 2004));
price = bond3.cleanPrice(marketYield3, bondDayCount, Compounding.Compounded, freq);
if (Math.Abs(price - cachedPrice3) > tolerance)
{
QAssert.Fail("failed to reproduce cached price:"
+ "\n calculated: " + price + ""
+ "\n expected: " + cachedPrice3 + ""
+ "\n error: " + (price - cachedPrice3));
}
}
#if NET40 || NET45
[TestMethod()]
#else
[Fact]
#endif
public void testCachedZero()
{
// Testing zero-coupon bond prices against cached values
CommonVars vars = new CommonVars();
Date today = new Date(22, Month.November, 2004);
Settings.setEvaluationDate(today);
int settlementDays = 1;
var discountCurve = new Handle<YieldTermStructure>(Utilities.flatRate(today, 0.03, new Actual360()));
double tolerance = 1.0e-6;
// plain
ZeroCouponBond bond1 = new ZeroCouponBond(settlementDays, new UnitedStates(UnitedStates.Market.GovernmentBond),
vars.faceAmount, new Date(30, Month.November, 2008), BusinessDayConvention.ModifiedFollowing,
100.0, new Date(30, Month.November, 2004));
IPricingEngine bondEngine = new DiscountingBondEngine(discountCurve);
bond1.setPricingEngine(bondEngine);
double cachedPrice1 = 88.551726;
double price = bond1.cleanPrice();
if (Math.Abs(price - cachedPrice1) > tolerance)
{
QAssert.Fail("failed to reproduce cached price:\n"
+ " calculated: " + price + "\n"
+ " expected: " + cachedPrice1 + "\n"
+ " error: " + (price - cachedPrice1));
}
ZeroCouponBond bond2 = new ZeroCouponBond(settlementDays, new UnitedStates(UnitedStates.Market.GovernmentBond),
vars.faceAmount, new Date(30, Month.November, 2007), BusinessDayConvention.ModifiedFollowing,
100.0, new Date(30, Month.November, 2004));
bond2.setPricingEngine(bondEngine);
double cachedPrice2 = 91.278949;
price = bond2.cleanPrice();
if (Math.Abs(price - cachedPrice2) > tolerance)
{
QAssert.Fail("failed to reproduce cached price:\n"
+ " calculated: " + price + "\n"
+ " expected: " + cachedPrice2 + "\n"
+ " error: " + (price - cachedPrice2));
}
ZeroCouponBond bond3 = new ZeroCouponBond(settlementDays, new UnitedStates(UnitedStates.Market.GovernmentBond),
vars.faceAmount, new Date(30, Month.November, 2006), BusinessDayConvention.ModifiedFollowing,
100.0, new Date(30, Month.November, 2004));
bond3.setPricingEngine(bondEngine);
double cachedPrice3 = 94.098006;
price = bond3.cleanPrice();
if (Math.Abs(price - cachedPrice3) > tolerance)
{
QAssert.Fail("failed to reproduce cached price:\n"
+ " calculated: " + price + "\n"
+ " expected: " + cachedPrice3 + "\n"
+ " error: " + (price - cachedPrice3));
}
}
#if NET40 || NET45
[TestMethod()]
#else
[Fact]
#endif
public void testCachedFixed()
{
// "Testing fixed-coupon bond prices against cached values...");
CommonVars vars = new CommonVars();
Date today = new Date(22, Month.November, 2004);
Settings.setEvaluationDate(today);
int settlementDays = 1;
var discountCurve = new Handle<YieldTermStructure>(Utilities.flatRate(today, 0.03, new Actual360()));
double tolerance = 1.0e-6;
// plain
Schedule sch = new Schedule(new Date(30, Month.November, 2004),
new Date(30, Month.November, 2008), new Period(Frequency.Semiannual),
new UnitedStates(UnitedStates.Market.GovernmentBond),
BusinessDayConvention.Unadjusted, BusinessDayConvention.Unadjusted, DateGeneration.Rule.Backward, false);
FixedRateBond bond1 = new FixedRateBond(settlementDays, vars.faceAmount, sch, new List<double>() { 0.02875 },
new ActualActual(ActualActual.Convention.ISMA), BusinessDayConvention.ModifiedFollowing,
100.0, new Date(30, Month.November, 2004));
IPricingEngine bondEngine = new DiscountingBondEngine(discountCurve);
bond1.setPricingEngine(bondEngine);
double cachedPrice1 = 99.298100;
double price = bond1.cleanPrice();
if (Math.Abs(price - cachedPrice1) > tolerance)
{
QAssert.Fail("failed to reproduce cached price:\n"
+ " calculated: " + price + "\n"
+ " expected: " + cachedPrice1 + "\n"
+ " error: " + (price - cachedPrice1));
}
// varying coupons
List<double> couponRates = new InitializedList<double>(4);
couponRates[0] = 0.02875;
couponRates[1] = 0.03;
couponRates[2] = 0.03125;
couponRates[3] = 0.0325;
FixedRateBond bond2 = new FixedRateBond(settlementDays, vars.faceAmount, sch, couponRates,
new ActualActual(ActualActual.Convention.ISMA),
BusinessDayConvention.ModifiedFollowing,
100.0, new Date(30, Month.November, 2004));
bond2.setPricingEngine(bondEngine);
double cachedPrice2 = 100.334149;
price = bond2.cleanPrice();
if (Math.Abs(price - cachedPrice2) > tolerance)
{
QAssert.Fail("failed to reproduce cached price:\n"
+ " calculated: " + price + "\n"
+ " expected: " + cachedPrice2 + "\n"
+ " error: " + (price - cachedPrice2));
}
// stub date
Schedule sch3 = new Schedule(new Date(30, Month.November, 2004),
new Date(30, Month.March, 2009), new Period(Frequency.Semiannual),
new UnitedStates(UnitedStates.Market.GovernmentBond),
BusinessDayConvention.Unadjusted, BusinessDayConvention.Unadjusted, DateGeneration.Rule.Backward, false,
null, new Date(30, Month.November, 2008));
FixedRateBond bond3 = new FixedRateBond(settlementDays, vars.faceAmount, sch3,
couponRates, new ActualActual(ActualActual.Convention.ISMA),
BusinessDayConvention.ModifiedFollowing,
100.0, new Date(30, Month.November, 2004));
bond3.setPricingEngine(bondEngine);
double cachedPrice3 = 100.382794;
price = bond3.cleanPrice();
if (Math.Abs(price - cachedPrice3) > tolerance)
{
QAssert.Fail("failed to reproduce cached price:\n"
+ " calculated: " + price + "\n"
+ " expected: " + cachedPrice3 + "\n"
+ " error: " + (price - cachedPrice3));
}
}
#if NET40 || NET45
[TestMethod()]
#else
[Fact]
#endif
public void testCachedFloating()
{
// "Testing floating-rate bond prices against cached values...");
CommonVars vars = new CommonVars();
Date today = new Date(22, Month.November, 2004);
Settings.setEvaluationDate(today);
int settlementDays = 1;
var riskFreeRate = new Handle<YieldTermStructure>(Utilities.flatRate(today, 0.025, new Actual360()));
var discountCurve = new Handle<YieldTermStructure>(Utilities.flatRate(today, 0.03, new Actual360()));
IborIndex index = new USDLibor(new Period(6, TimeUnit.Months), riskFreeRate);
int fixingDays = 1;
double tolerance = 1.0e-6;
IborCouponPricer pricer = new BlackIborCouponPricer(new Handle<OptionletVolatilityStructure>());
// plain
Schedule sch = new Schedule(new Date(30, Month.November, 2004), new Date(30, Month.November, 2008),
new Period(Frequency.Semiannual), new UnitedStates(UnitedStates.Market.GovernmentBond),
BusinessDayConvention.ModifiedFollowing, BusinessDayConvention.ModifiedFollowing,
DateGeneration.Rule.Backward, false);
FloatingRateBond bond1 = new FloatingRateBond(settlementDays, vars.faceAmount, sch,
index, new ActualActual(ActualActual.Convention.ISMA),
BusinessDayConvention.ModifiedFollowing, fixingDays,
new List<double>(), new List<double>(),
new List < double? >(), new List < double? >(),
false,
100.0, new Date(30, Month.November, 2004));
IPricingEngine bondEngine = new DiscountingBondEngine(riskFreeRate);
bond1.setPricingEngine(bondEngine);
Utils.setCouponPricer(bond1.cashflows(), pricer);
#if QL_USE_INDEXED_COUPON
double cachedPrice1 = 99.874645;
#else
double cachedPrice1 = 99.874646;
#endif
double price = bond1.cleanPrice();
if (Math.Abs(price - cachedPrice1) > tolerance)
{
QAssert.Fail("failed to reproduce cached price:\n"
+ " calculated: " + price + "\n"
+ " expected: " + cachedPrice1 + "\n"
+ " error: " + (price - cachedPrice1));
}
// different risk-free and discount curve
FloatingRateBond bond2 = new FloatingRateBond(settlementDays, vars.faceAmount, sch,
index, new ActualActual(ActualActual.Convention.ISMA),
BusinessDayConvention.ModifiedFollowing, fixingDays,
new List<double>(), new List<double>(),
new List < double? >(), new List < double? >(),
false,
100.0, new Date(30, Month.November, 2004));
IPricingEngine bondEngine2 = new DiscountingBondEngine(discountCurve);
bond2.setPricingEngine(bondEngine2);
Utils.setCouponPricer(bond2.cashflows(), pricer);
#if QL_USE_INDEXED_COUPON
double cachedPrice2 = 97.955904;
#else
double cachedPrice2 = 97.955904;
#endif
price = bond2.cleanPrice();
if (Math.Abs(price - cachedPrice2) > tolerance)
{
QAssert.Fail("failed to reproduce cached price:\n"
+ " calculated: " + price + "\n"
+ " expected: " + cachedPrice2 + "\n"
+ " error: " + (price - cachedPrice2));
}
// varying spread
List<double> spreads = new InitializedList<double>(4);
spreads[0] = 0.001;
spreads[1] = 0.0012;
spreads[2] = 0.0014;
spreads[3] = 0.0016;
FloatingRateBond bond3 = new FloatingRateBond(settlementDays, vars.faceAmount, sch,
index, new ActualActual(ActualActual.Convention.ISMA),
BusinessDayConvention.ModifiedFollowing, fixingDays,
new List<double>(), spreads,
new List < double? >(), new List < double? >(),
false,
100.0, new Date(30, Month.November, 2004));
bond3.setPricingEngine(bondEngine2);
Utils.setCouponPricer(bond3.cashflows(), pricer);
#if QL_USE_INDEXED_COUPON
double cachedPrice3 = 98.495458;
#else
double cachedPrice3 = 98.495459;
#endif
price = bond3.cleanPrice();
if (Math.Abs(price - cachedPrice3) > tolerance)
{
QAssert.Fail("failed to reproduce cached price:\n"
+ " calculated: " + price + "\n"
+ " expected: " + cachedPrice3 + "\n"
+ " error: " + (price - cachedPrice3));
}
}
#if NET40 || NET45
[TestMethod()]
#else
[Fact]
#endif
public void testBrazilianCached()
{
//("Testing Brazilian public bond prices against cached values...");
CommonVars vars = new CommonVars();
double faceAmount = 1000.0;
double redemption = 100.0;
Date issueDate = new Date(1, Month.January, 2007);
Date today = new Date(6, Month.June, 2007);
Settings.setEvaluationDate(today);
// NTN-F maturity dates
List<Date> maturityDates = new InitializedList<Date>(6);
maturityDates[0] = new Date(1, Month.January, 2008);
maturityDates[1] = new Date(1, Month.January, 2010);
maturityDates[2] = new Date(1, Month.July, 2010);
maturityDates[3] = new Date(1, Month.January, 2012);
maturityDates[4] = new Date(1, Month.January, 2014);
maturityDates[5] = new Date(1, Month.January, 2017);
// NTN-F yields
List<double> yields = new InitializedList<double>(6);
yields[0] = 0.114614;
yields[1] = 0.105726;
yields[2] = 0.105328;
yields[3] = 0.104283;
yields[4] = 0.103218;
yields[5] = 0.102948;
// NTN-F prices
List<double> prices = new InitializedList<double>(6);
prices[0] = 1034.63031372;
prices[1] = 1030.09919487;
prices[2] = 1029.98307160;
prices[3] = 1028.13585068;
prices[4] = 1028.33383817;
prices[5] = 1026.19716497;
int settlementDays = 1;
vars.faceAmount = 1000.0;
// The tolerance is high because Andima truncate yields
double tolerance = 1.0e-4;
List<InterestRate> couponRates = new InitializedList<InterestRate>(1);
couponRates[0] = new InterestRate(0.1, new Thirty360(), Compounding.Compounded, Frequency.Annual);
for (int bondIndex = 0; bondIndex < maturityDates.Count; bondIndex++)
{
// plain
InterestRate yield = new InterestRate(yields[bondIndex], new Business252(new Brazil()),
Compounding.Compounded, Frequency.Annual);
Schedule schedule = new Schedule(new Date(1, Month.January, 2007),
maturityDates[bondIndex], new Period(Frequency.Semiannual),
new Brazil(Brazil.Market.Settlement),
BusinessDayConvention.Unadjusted, BusinessDayConvention.Unadjusted,
DateGeneration.Rule.Backward, false);
FixedRateBond bond = new FixedRateBond(settlementDays,
faceAmount,
schedule,
couponRates,
BusinessDayConvention.Following,
redemption,
issueDate);
double cachedPrice = prices[bondIndex];
double price = vars.faceAmount * (bond.cleanPrice(yield.rate(),
yield.dayCounter(),
yield.compounding(),
yield.frequency(),
today) + bond.accruedAmount(today)) / 100;
if (Math.Abs(price - cachedPrice) > tolerance)
{
QAssert.Fail("failed to reproduce cached price:\n"
+ " calculated: " + price + "\n"
+ " expected: " + cachedPrice + "\n"
+ " error: " + (price - cachedPrice) + "\n"
);
}
}
}
#if NET40 || NET45
[TestMethod()]
#else
[Fact]
#endif
public void testAmortizingFixedBond()
{
Date startDate = new Date(2, 1, 2007);
Settings.setEvaluationDate(startDate);
Period bondLength = new Period(12, TimeUnit.Months);
DayCounter dCounter = new Thirty360();
Frequency payFrequency = Frequency.Monthly;
double amount = 400000000;
double rate = 0.06;
var discountCurve = new Handle<YieldTermStructure>(Utilities.flatRate(startDate, new SimpleQuote(rate), new Thirty360()));
AmortizingFixedRateBond bond = BondFactory.makeAmortizingFixedBond(startDate, bondLength, dCounter, payFrequency, amount, rate);
IPricingEngine bondEngine = new DiscountingBondEngine(discountCurve);
bond.setPricingEngine(bondEngine);
// cached values
int totCashflow = 24;
int totNotionals = 13;
double PVDifference = 13118862.59;
double[] notionals = {400000000, 367573428, 334984723, 302233075, 269317669, 236237685, 202992302, 169580691, 136002023,
102255461, 68340166, 34255295, 0
};
// test total cashflow count
QAssert.AreEqual(bond.cashflows().Count, totCashflow, "Cashflow size different");
// test notional cashflow count
QAssert.AreEqual(bond.notionals().Count, totNotionals, "Notionals size different");
// test notional amortization values
for (int i = 0; i < totNotionals; i++)
{
QAssert.AreEqual(bond.notionals()[i], notionals[i], 1, "Notionals " + i + "is different");
}
// test PV difference
double cash = bond.CASH();
QAssert.AreEqual(cash - amount, PVDifference, 0.1, "PV Difference wrong");
}
#if NET40 || NET45
[TestMethod()]
#else
[Fact]
#endif
public void testMBSFixedBondCached()
{
// Test MBS Bond against cached values
// from Fabozzi MBS Products Structuring and Analytical Techniques
// Second Edition - WILEY ISBN 978-1-118-00469-2
// pag 58,61,63
#region Cached Values
double[] OutstandingBalance = {400000000, 399396651, 398724866, 397984841, 397176808, 396301034, 395357823, 394347512, 393270474,
392127117, 390917882, 389643247, 388303720, 386899847, 385432204, 383901402, 382308084, 380652925,
378936631, 377159941, 375323622, 373428474, 371475324, 369465030, 367398478, 365276580, 363100276,
360870534, 358588346, 356317966, 354059336, 351812393, 349577078, 347353331, 345141093, 342940305,
340750907, 338572840, 336406048, 334250471, 332106052, 329972733, 327850458, 325739170, 323638812,
321549327, 319470661, 317402757, 315345560, 313299014, 311263066, 309237660, 307222743, 305218260,
303224158, 301240383, 299266882, 297303602, 295350492, 293407497, 291474567, 289551650, 287638694,
285735647, 283842460, 281959081, 280085459, 278221545, 276367288, 274522640, 272687550, 270861969,
269045848, 267239140, 265441794, 263653764, 261875001, 260105457, 258345086, 256593839, 254851671,
253118533, 251394381, 249679167, 247972846, 246275371, 244586698, 242906782, 241235576, 239573036,
237919118, 236273777, 234636970, 233008651, 231388779, 229777308, 228174197, 226579401, 224992878,
223414586, 221844483, 220282525, 218728672, 217182881, 215645111, 214115321, 212593469, 211079516,
209573419, 208075140, 206584637, 205101871, 203626802, 202159389, 200699595, 199247379, 197802703,
196365528, 194935815, 193513525, 192098622, 190691066, 189290820, 187897846, 186512107, 185133566,
183762186, 182397929, 181040759, 179690640, 178347535, 177011409, 175682225, 174359947, 173044541,
171735971, 170434201, 169139197, 167850924, 166569347, 165294431, 164026143, 162764449, 161509314,
160260704, 159018587, 157782929, 156553696, 155330855, 154114374, 152904220, 151700360, 150502762,
149311394, 148126224, 146947219, 145774348, 144607580, 143446882, 142292225, 141143576, 140000905,
138864182, 137733374, 136608453, 135489388, 134376148, 133268704, 132167026, 131071083, 129980848,
128896290, 127817380, 126744089, 125676388, 124614249, 123557642, 122506539, 121460913, 120420734,
119385975, 118356608, 117332605, 116313939, 115300582, 114292506, 113289685, 112292092, 111299699,
110312480, 109330408, 108353458, 107381601, 106414813, 105453067, 104496337, 103544598, 102597823,
101655987, 100719066, 99787032, 98859862, 97937530, 97020012, 96107282, 95199317, 94296091,
93397579, 92503759, 91614606, 90730095, 89850202, 88974905, 88104180, 87238002, 86376348,
85519196, 84666522, 83818303, 82974516, 82135138, 81300146, 80469519, 79643233, 78821266,
78003597, 77190202, 76381060, 75576149, 74775447, 73978932, 73186584, 72398380, 71614300,
70834321, 70058424, 69286586, 68518787, 67755007, 66995224, 66239418, 65487568, 64739655,
63995657, 63255556, 62519330, 61786959, 61058425, 60333707, 59612785, 58895641, 58182253,
57472605, 56766675, 56064445, 55365895, 54671008, 53979764, 53292143, 52608129, 51927702,
51250843, 50577534, 49907758, 49241495, 48578728, 47919438, 47263609, 46611221, 45962258,
45316701, 44674534, 44035738, 43400297, 42768192, 42139408, 41513926, 40891731, 40272804,
39657129, 39044690, 38435469, 37829450, 37226618, 36626954, 36030443, 35437069, 34846816,
34259667, 33675607, 33094619, 32516689, 31941799, 31369935, 30801080, 30235220, 29672339,
29112422, 28555453, 28001417, 27450300, 26902085, 26356759, 25814305, 25274711, 24737960,
24204038, 23672931, 23144624, 22619103, 22096353, 21576360, 21059110, 20544589, 20032782,
19523677, 19017258, 18513512, 18012425, 17513984, 17018175, 16524985, 16034399, 15546405,
15060989, 14578138, 14097838, 13620077, 13144842, 12672119, 12201896, 11734160, 11268897,
10806096, 10345743, 9887826, 9432332, 8979249, 8528565, 8080267, 7634342, 7190780,
6749566, 6310691, 5874140, 5439903, 5007967, 4578321, 4150953, 3725851, 3303003,
2882398, 2464024, 2047870, 1633925, 1222176, 812614, 405225
};
double[] Prepayments = { 200350, 266975, 333463, 399780, 465892, 531764, 597362, 662652, 727600, 792172, 856336, 920057, 983303,
1046041, 1108239, 1169864, 1230887, 1291274, 1350996, 1410023, 1468325, 1525872, 1582637, 1638590, 1693706, 1747956,
1801315, 1853758, 1842021, 1830345, 1818729, 1807174, 1795678, 1784241, 1772864, 1761546, 1750286, 1739085, 1727941,
1716855, 1705827, 1694856, 1683941, 1673083, 1662281, 1651536, 1640845, 1630210, 1619631, 1609106, 1598635, 1588219,
1577856, 1567548, 1557292, 1547090, 1536941, 1526844, 1516799, 1506807, 1496866, 1486977, 1477139, 1467352, 1457616,
1447930, 1438294, 1428708, 1419172, 1409686, 1400248, 1390859, 1381519, 1372228, 1362985, 1353789, 1344641, 1335541,
1326488, 1317481, 1308522, 1299608, 1290741, 1281920, 1273145, 1264415, 1255731, 1247091, 1238497, 1229947, 1221441,
1212979, 1204562, 1196187, 1187857, 1179569, 1171325, 1163123, 1154964, 1146847, 1138773, 1130740, 1122749, 1114799,
1106891, 1099023, 1091197, 1083411, 1075665, 1067960, 1060295, 1052669, 1045083, 1037537, 1030029, 1022561, 1015131,
1007740, 1000388, 993073, 985797, 978558, 971357, 964193, 957067, 949977, 942924, 935908, 928929, 921985, 915078,
908207, 901371, 894571, 887806, 881077, 874382, 867722, 861097, 854506, 847950, 841427, 834939, 828484, 822063,
815675, 809320, 802998, 796710, 790454, 784230, 778039, 771880, 765753, 759658, 753595, 747563, 741563, 735594,
729656, 723749, 717872, 712026, 706211, 700426, 694671, 688946, 683251, 677585, 671949, 666342, 660765, 655216,
649697, 644206, 638744, 633310, 627904, 622527, 617178, 611856, 606563, 601297, 596058, 590847, 585662, 580505,
575375, 570271, 565194, 560144, 555120, 550122, 545150, 540204, 535284, 530390, 525521, 520677, 515859, 511066,
506298, 501555, 496836, 492142, 487473, 482828, 478207, 473611, 469038, 464490, 459965, 455463, 450986, 446531,
442100, 437692, 433307, 428945, 424606, 420289, 415995, 411724, 407474, 403247, 399042, 394860, 390698, 386559,
382442, 378345, 374271, 370217, 366185, 362174, 358184, 354215, 350266, 346339, 342431, 338545, 334678, 330832,
327006, 323200, 319414, 315648, 311901, 308174, 304467, 300779, 297110, 293461, 289831, 286220, 282627, 279054,
275499, 271963, 268445, 264946, 261466, 258003, 254559, 251133, 247724, 244334, 240961, 237606, 234269, 230949,
227647, 224362, 221094, 217844, 214610, 211394, 208194, 205012, 201845, 198696, 195563, 192447, 189347, 186263,
183195, 180144, 177109, 174089, 171086, 168098, 165126, 162170, 159229, 156304, 153394, 150500, 147620, 144756,
141907, 139073, 136254, 133450, 130660, 127885, 125125, 122380, 119648, 116932, 114229, 111541, 108867, 106207,
103561, 100930, 98312, 95707, 93117, 90540, 87977, 85428, 82891, 80369, 77859, 75363, 72880, 70410, 67954, 65510,
63079, 60661, 58256, 55863, 53483, 51116, 48761, 46419, 44089, 41772, 39466, 37173, 34893, 32624, 30367, 28122,
25889, 23668, 21459, 19261, 17075, 14901, 12738, 10587, 8447, 6318, 4201, 2095, 0
};
double[] NetInterest = { 1833333, 1830568, 1827489, 1824097, 1820394, 1816380, 1812057, 1807426, 1802490, 1797249, 1791707, 1785865,
1779725, 1773291, 1766564, 1759548, 1752245, 1744659, 1736793, 1728650, 1720233, 1711547, 1702595, 1693381,
1683910, 1674184, 1664210, 1653990, 1643530, 1633124, 1622772, 1612473, 1602228, 1592036, 1581897, 1571810,
1561775, 1551792, 1541861, 1531981, 1522153, 1512375, 1502648, 1492971, 1483345, 1473768, 1464241, 1454763,
1445334, 1435954, 1426622, 1417339, 1408104, 1398917, 1389777, 1380685, 1371640, 1362642, 1353690, 1344784,
1335925, 1327112, 1318344, 1309622, 1300945, 1292312, 1283725, 1275182, 1266683, 1258229, 1249818, 1241451,
1233127, 1224846, 1216608, 1208413, 1200260, 1192150, 1184082, 1176055, 1168070, 1160127, 1152224, 1144363,
1136542, 1128762, 1121022, 1113323, 1105663, 1098043, 1090463, 1082921, 1075419, 1067956, 1060532, 1053146,
1045798, 1038489, 1031217, 1023984, 1016787, 1009628, 1002506, 995422, 988373, 981362, 974387, 967448, 960545,
953678, 946846, 940050, 933290, 926564, 919873, 913217, 906596, 900009, 893456, 886937, 880452, 874001, 867583,
861198, 854847, 848529, 842243, 835991, 829770, 823582, 817426, 811302, 805210, 799150, 793121, 787123, 781157,
775221, 769317, 763443, 757599, 751786, 746004, 740251, 734528, 728835, 723172, 717538, 711933, 706358, 700811,
695293, 689804, 684344, 678912, 673508, 668132, 662785, 657465, 652173, 646908, 641671, 636461, 631278, 626122,
620993, 615891, 610815, 605766, 600742, 595746, 590775, 585830, 580910, 576017, 571149, 566306, 561488, 556696,
551928, 547186, 542468, 537774, 533106, 528461, 523841, 519244, 514672, 510124, 505599, 501098, 496620, 492166,
487735, 483327, 478942, 474579, 470240, 465923, 461629, 457357, 453108, 448880, 444675, 440492, 436330, 432190,
428072, 423976, 419900, 415846, 411813, 407802, 403811, 399841, 395892, 391963, 388055, 384167, 380300, 376453,
372626, 368819, 365031, 361264, 357516, 353788, 350080, 346391, 342721, 339070, 335439, 331826, 328232, 324657,
321101, 317564, 314044, 310544, 307061, 303597, 300151, 296723, 293313, 289921, 286547, 283190, 279851, 276529,
273225, 269938, 266669, 263416, 260181, 256962, 253760, 250575, 247407, 244256, 241121, 238002, 234900, 231814,
228744, 225690, 222653, 219631, 216625, 213635, 210660, 207702, 204758, 201830, 198918, 196021, 193139, 190272,
187420, 184584, 181762, 178955, 176163, 173385, 170622, 167874, 165140, 162420, 159715, 157023, 154347, 151684,
149035, 146400, 143779, 141172, 138578, 135998, 133432, 130879, 128340, 125814, 123301, 120802, 118316, 115842,
113382, 110935, 108501, 106080, 103671, 101275, 98892, 96521, 94163, 91817, 89484, 87162, 84854, 82557, 80272,
78000, 75740, 73491, 71254, 69030, 66816, 64615, 62425, 60247, 58081, 55925, 53782, 51649, 49528, 47418, 45319,
43232, 41155, 39089, 37035, 34991, 32958, 30936, 28924, 26923, 24933, 22953, 20984, 19025, 17077, 15139, 13211,
11293, 9386, 7489, 5602, 3724, 1857
};
double[] ScheduledPrincipal = { 402998, 404810, 406562, 408253, 409882, 411447, 412949, 414386, 415758, 417063, 418300, 419470, 420571,
421602, 422563, 423454, 424273, 425020, 425694, 426296, 426824, 427278, 427657, 427962, 428192, 428347,
428427, 428430, 428358, 428286, 428213, 428141, 428069, 427997, 427924, 427852, 427780, 427708, 427636,
427564, 427491, 427419, 427347, 427275, 427203, 427131, 427059, 426987, 426915, 426843, 426771, 426699,
426627, 426555, 426483, 426411, 426339, 426267, 426195, 426123, 426051, 425979, 425907, 425835, 425764,
425692, 425620, 425548, 425476, 425405, 425333, 425261, 425189, 425118, 425046, 424974, 424902, 424831,
424759, 424687, 424616, 424544, 424472, 424401, 424329, 424258, 424186, 424114, 424043, 423971, 423900,
423828, 423757, 423685, 423614, 423542, 423471, 423399, 423328, 423256, 423185, 423114, 423042, 422971,
422900, 422828, 422757, 422685, 422614, 422543, 422472, 422400, 422329, 422258, 422187, 422115, 422044,
421973, 421902, 421830, 421759, 421688, 421617, 421546, 421475, 421404, 421332, 421261, 421190, 421119,
421048, 420977, 420906, 420835, 420764, 420693, 420622, 420551, 420480, 420409, 420338, 420267, 420196,
420126, 420055, 419984, 419913, 419842, 419771, 419700, 419630, 419559, 419488, 419417, 419346, 419276,
419205, 419134, 419064, 418993, 418922, 418851, 418781, 418710, 418639, 418569, 418498, 418428, 418357,
418286, 418216, 418145, 418075, 418004, 417934, 417863, 417793, 417722, 417652, 417581, 417511, 417440,
417370, 417299, 417229, 417159, 417088, 417018, 416947, 416877, 416807, 416736, 416666, 416596, 416526,
416455, 416385, 416315, 416245, 416174, 416104, 416034, 415964, 415893, 415823, 415753, 415683, 415613,
415543, 415473, 415403, 415332, 415262, 415192, 415122, 415052, 414982, 414912, 414842, 414772, 414702,
414632, 414562, 414492, 414422, 414352, 414282, 414213, 414143, 414073, 414003, 413933, 413863, 413793,
413724, 413654, 413584, 413514, 413444, 413375, 413305, 413235, 413165, 413096, 413026, 412956, 412887,
412817, 412747, 412678, 412608, 412538, 412469, 412399, 412330, 412260, 412191, 412121, 412051, 411982,
411912, 411843, 411773, 411704, 411635, 411565, 411496, 411426, 411357, 411287, 411218, 411149, 411079,
411010, 410941, 410871, 410802, 410733, 410663, 410594, 410525, 410455, 410386, 410317, 410248, 410178,
410109, 410040, 409971, 409902, 409833, 409763, 409694, 409625, 409556, 409487, 409418, 409349, 409280,
409211, 409142, 409073, 409003, 408934, 408865, 408796, 408728, 408659, 408590, 408521, 408452, 408383,
408314, 408245, 408176, 408107, 408038, 407970, 407901, 407832, 407763, 407694, 407625, 407557, 407488,
407419, 407350, 407282, 407213, 407144, 407076, 407007, 406938, 406870, 406801, 406732, 406664, 406595,
406526, 406458, 406389, 406321, 406252, 406184, 406115, 406047, 405978, 405910, 405841, 405773, 405704,
405636, 405567, 405499, 405430, 405362, 405294, 405225
};
#endregion
Date startDate = new Date(1, 2, 2007);
Settings.setEvaluationDate(startDate);
Period bondLength = new Period(358, TimeUnit.Months);
Period originalLenght = new Period(360, TimeUnit.Months);
DayCounter dCounter = new Thirty360();
Frequency payFrequency = Frequency.Monthly;
double amount = 400000000;
double WACrate = 0.06;
double PassThroughRate = 0.055;
PSACurve psa100 = new PSACurve(startDate);
var discountCurve = new Handle<YieldTermStructure>(Utilities.flatRate(startDate, new SimpleQuote(WACrate), new Thirty360()));
// 400 Million Pass-Through with a 5.5% Pass-through Rate, a WAC of 6.0%, and a WAM of 358 Months,
// Assuming 100% PSA
MBSFixedRateBond bond = BondFactory.makeMBSFixedBond(startDate,
bondLength,
originalLenght,
dCounter,
payFrequency,
amount,
WACrate,
PassThroughRate,
psa100);
IPricingEngine bondEngine = new DiscountingBondEngine(discountCurve);
bond.setPricingEngine(bondEngine);
// Calculate Monthly Expecting Cashflow
List<CashFlow> cf = bond.expectedCashflows();
// Outstanding Balance
int i = 0;
foreach (CashFlow c in cf)
{
if (c is QLNet.FixedRateCoupon)
{
FixedRateCoupon frc = c as FixedRateCoupon;
QAssert.AreEqual(OutstandingBalance[i], frc.nominal(), 1, "Outstanding Balance " + i++ + "is different");
}
}
// Prepayments
i = 0;
foreach (CashFlow c in cf)
{
if (c is QLNet.VoluntaryPrepay)
{
QAssert.AreEqual(Prepayments[i], c.amount(), 1, "Prepayments " + i++ + "is different");
}
}
// Net Interest
i = 0;
foreach (CashFlow c in cf)
{
if (c is QLNet.FixedRateCoupon)
{
FixedRateCoupon frc = c as FixedRateCoupon;
QAssert.AreEqual(NetInterest[i], frc.amount(), 1, "Net Interest " + i++ + "is different");
}
}
// Scheduled Principal
i = 0;
foreach (CashFlow c in cf)
{
if (c is QLNet.AmortizingPayment)
{
QAssert.AreEqual(ScheduledPrincipal[i], c.amount(), 1, "Scheduled Principal " + i++ + "is different");
}
}
// Monthly Yield
QAssert.AreEqual(0.00458333333333381, bond.MonthlyYield(), 0.000000001, "MonthlyYield is different");
// Bond Equivalent Yield
QAssert.AreEqual(0.0556, bond.BondEquivalentYield(), 0.0001, " Bond Equivalent Yield is different");
}
#if NET40 || NET45
[TestMethod()]
#else
[Fact]
#endif
public void testAmortizingBond1()
{
// Input Values
double faceValue = 40000;
double marketValue = 43412;
double couponRate = 0.06;
Date issueDate = new Date(1, Month.January, 2001);
Date maturirtyDate = new Date(1, Month.January, 2005);
Date tradeDate = new Date(1, Month.January, 2004);
Frequency paymentFrequency = Frequency.Semiannual;
DayCounter dc = new Thirty360(Thirty360.Thirty360Convention.USA);
// Build Bond
AmortizingBond bond = BondFactory.makeAmortizingBond(faceValue, marketValue, couponRate,
issueDate, maturirtyDate, tradeDate, paymentFrequency, dc, AmortizingMethod.EffectiveInterestRate);
// Amortizing Yield ( Effective Rate )
double y1 = bond.Yield();
QAssert.AreEqual(-0.0236402, y1, 0.001, "Amortizing Yield is different");
// Amortized Cost at Date
double Amort1 = bond.AmortizationValue(new Date(31, Month.August, 2004));
QAssert.AreEqual(41126.01, Amort1, 100, "Amortized Cost at 08/31/2004 is different");
double Amort2 = bond.AmortizationValue(new Date(30, Month.September, 2004));
QAssert.AreEqual(40842.83, Amort2, 100, "Amortized Cost at 09/30/2004 is different");
}
#if NET40 || NET45
[TestMethod()]
#else
[Fact]
#endif
public void testAmortizingBond2()
{
// Par – 500,000
// Cost – 471,444
// Coupon Rate - .0520
// Issue Date – March 15 1999
// Maturity Date – May 15 2028
// Trade Date – December 31 2007
// Payment Frequency - Semi-Annual; May/Nov
// Day Count Method - 30/360
// Input Values
double faceValue = 500000;
double marketValue = 471444;
double couponRate = 0.0520;
Date issueDate = new Date(15, Month.March, 1999);
Date maturirtyDate = new Date(15, Month.May, 2028);
Date tradeDate = new Date(31, Month.December, 2007);
Frequency paymentFrequency = Frequency.Semiannual;
DayCounter dc = new Thirty360(Thirty360.Thirty360Convention.USA);
// Build Bond
AmortizingBond bond = BondFactory.makeAmortizingBond(faceValue, marketValue, couponRate,
issueDate, maturirtyDate, tradeDate, paymentFrequency, dc, AmortizingMethod.EffectiveInterestRate);
// Amortizing Yield ( Effective Rate )
double y1 = bond.Yield();
QAssert.AreEqual(0.0575649, y1, 0.001, "Amortizing Yield is different");
// Amortized Cost at Date
double Amort1 = bond.AmortizationValue(new Date(30, Month.November, 2012));
QAssert.AreEqual(475698.12, Amort1, 100, "Amortized Cost at 11/30/2012 is different");
double Amort2 = bond.AmortizationValue(new Date(30, Month.December, 2012));
QAssert.AreEqual(475779.55, Amort1, 100, "Amortized Cost at 12/30/2012 is different");
}
#if NET40 || NET45
[TestMethod()]
#else
[Fact]
#endif
public void testAmortizingFixedRateBond()
{
// Testing amortizing fixed rate bond
/*
* Following data is generated from Excel using function pmt with Nper = 360, PV = 100.0
*/
double[] rates = { 0.0, 0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.09, 0.10, 0.11, 0.12 };
double[] amounts = {0.277777778, 0.321639520, 0.369619473, 0.421604034,
0.477415295, 0.536821623, 0.599550525,
0.665302495, 0.733764574, 0.804622617,
0.877571570, 0.952323396, 1.028612597
};
Frequency freq = Frequency.Monthly;
Date refDate = Date.Today;
double tolerance = 1.0e-6;
for (int i = 0; i < rates.Length; ++i)
{
AmortizingFixedRateBond myBond = new AmortizingFixedRateBond(0,
new NullCalendar(), 100.0, refDate, new Period(30, TimeUnit.Years), freq, rates[i], new ActualActual(ActualActual.Convention.ISMA));
List<CashFlow> cashflows = myBond.cashflows();
List<double> notionals = myBond.notionals();
for (int k = 0; k < cashflows.Count / 2; ++k)
{
double coupon = cashflows[2 * k].amount();
double principal = cashflows[2 * k + 1].amount();
double totalAmount = coupon + principal;
// Check the amount is same as pmt returned
double error = Math.Abs(totalAmount - amounts[i]);
if (error > tolerance)
{
QAssert.Fail(" Rate: " + rates[i] +
" " + k + "th cash flow " +
" Failed!" +
" Expected Amount: " + amounts[i] +
" Calculated Amount: " + totalAmount);
}
// Check the coupon result
double expectedCoupon = notionals[k] * rates[i] / (int)freq;
error = Math.Abs(coupon - expectedCoupon);
if (error > tolerance)
{
QAssert.Fail(" Rate: " + rates[i] +
" " + k + "th cash flow " +
" Failed!" +
" Expected Coupon: " + expectedCoupon +
" Calculated Coupon: " + coupon);
}
}
}
}
/// <summary>
/// Test calculation of South African R2048 bond
/// This requires the use of the Schedule to be constructed
/// with a custom date vector
/// </summary>
#if NET40 || NET45
[TestMethod()]
#else
[Fact]
#endif
public void testBondFromScheduleWithDateVector()
{
// Testing South African R2048 bond price using Schedule constructor with Date vector
//When pricing bond from Yield To Maturity, use NullCalendar()
Calendar calendar = new NullCalendar();
int settlementDays = 3;
Date issueDate = new Date(29, Month.June, 2012);
Date today = new Date(7, Month.September, 2015);
Date evaluationDate = calendar.adjust(today);
Date settlementDate = calendar.advance(evaluationDate, new Period(settlementDays, TimeUnit.Days));
Settings.setEvaluationDate(evaluationDate);
// For the schedule to generate correctly for Feb-28's, make maturity date on Feb 29
Date maturityDate = new Date(29, Month.February, 2048);
double coupon = 0.0875;
Compounding comp = Compounding.Compounded;
Frequency freq = Frequency.Semiannual;
DayCounter dc = new ActualActual(ActualActual.Convention.Bond);
// Yield as quoted in market
InterestRate yield = new InterestRate(0.09185, dc, comp, freq);
Period tenor = new Period(6, TimeUnit.Months);
Period exCouponPeriod = new Period(10, TimeUnit.Days);
// Generate coupon dates for 31 Aug and end of Feb each year
// For leap years, this will generate 29 Feb, but the bond
// actually pays coupons on 28 Feb, regardsless of whether
// it is a leap year or not.
Schedule schedule = new Schedule(issueDate, maturityDate, tenor,
new NullCalendar(), BusinessDayConvention.Unadjusted, BusinessDayConvention.Unadjusted,
DateGeneration.Rule.Backward, true);
// Adjust the 29 Feb's to 28 Feb
List<Date> dates = new List<Date>();
for (int i = 0; i < schedule.Count; ++i)
{
Date d = schedule.date(i);
if (d.Month == 2 && d.Day == 29)
dates.Add(new Date(28, Month.February, d.Year));
else
dates.Add(d);
}
schedule = new Schedule(dates,
schedule.calendar(),
schedule.businessDayConvention(),
schedule.terminationDateBusinessDayConvention(),
schedule.tenor(),
schedule.rule(),
schedule.endOfMonth(),
schedule.isRegular());
FixedRateBond bond = new FixedRateBond(0, 100.0, schedule, new List<double>() {coupon}, dc,
BusinessDayConvention.Following, 100.0, issueDate, calendar, exCouponPeriod, calendar,
BusinessDayConvention.Unadjusted, false);
double calculatedPrice = BondFunctions.dirtyPrice(bond, yield, settlementDate);
double expectedPrice = 95.75706;
double tolerance = 1e-5;
if (Math.Abs(calculatedPrice - expectedPrice) > tolerance)
{
QAssert.Fail(string.Format("failed to reproduce R2048 dirty price\nexpected: {0}\ncalculated: {1}",
expectedPrice, calculatedPrice));
}
}
#if NET40 || NET45
[TestMethod()]
#else
[Fact]
#endif
public void testWeightedAverageLife()
{
// Test against know data
DateTime today = new Date(5, Month.Jun, 2018);
List<double> amounts = new List<double> { 5080, 35255, 8335 };
List < DateTime > schedule = new List<DateTime> { new Date(1, 8, 2035),
new Date(1, 8, 2036), new Date(1, 8, 2037)
};
DateTime wal = BondFunctions.WeightedAverageLife(today, amounts, schedule);
QAssert.IsTrue(wal == new DateTime(2036, 08, 25));
}
public enum CouponType
{
FixedRate,
AdjRate,
OIS,
ZeroCoupon
}
#if NET40 || NET45
[DataTestMethod]
[DataRow(CouponType.FixedRate, 5.25, "2/13/2018", "12/01/2032", "3/23/2018", "", 119.908, 5.833, 3.504)]
[DataRow(CouponType.ZeroCoupon, 0, "3/15/2018", "1/1/2054", "3/26/2018", "", 5.793, 0.00, 8.126)]
[DataRow(CouponType.FixedRate, 2.2, "3/1/2018", "3/1/2021", "3/26/2018", "", 100.530, 1.53, 2.013)]
[DataRow(CouponType.FixedRate, 2.25, "3/1/2018", "3/1/2021", "3/26/2018", "", 100.393, 1.56, 2.111)]
[DataRow(CouponType.FixedRate, 3, "2/15/2018", "2/15/2031", "3/26/2018", "", 98.422, 3.42, 3.150)]
[DataRow(CouponType.FixedRate, 4, "2/1/2018", "2/15/2027", "3/26/2018", "08/15/2018", 111.170, 6.11, 2.585)]
[DataRow(CouponType.FixedRate, 4, "2/20/2018", "10/1/2036", "3/26/2018", "", 104.676, 4.00, 3.650)]
[DataRow(CouponType.FixedRate, 1.85, "2/1/2018", "2/1/2021", "3/26/2018", "", 99.916, 2.83, 1.880)]
[DataRow(CouponType.FixedRate, 2.85, "2/15/2018", "2/15/2031", "3/26/2018", "", 99.525, 3.25, 2.984)]
[DataRow(CouponType.FixedRate, 5.375, "08/26/2010", "03/01/2023", "7/16/2018", "", 103.674, 20.156, 4.490)]
#else
[Theory]
[InlineData(CouponType.FixedRate, 5.25, "2/13/2018", "12/01/2032", "3/23/2018", "", 119.908, 5.833, 3.504)]
[InlineData(CouponType.ZeroCoupon, 0, "3/15/2018", "1/1/2054", "3/26/2018", "", 5.793, 0.00, 8.126)]
[InlineData(CouponType.FixedRate, 2.2, "3/1/2018", "3/1/2021", "3/26/2018", "", 100.530, 1.53, 2.013)]
[InlineData(CouponType.FixedRate, 2.25, "3/1/2018", "3/1/2021", "3/26/2018", "", 100.393, 1.56, 2.111)]
[InlineData(CouponType.FixedRate, 3, "2/15/2018", "2/15/2031", "3/26/2018", "", 98.422, 3.42, 3.150)]
[InlineData(CouponType.FixedRate, 4, "2/1/2018", "2/15/2027", "3/26/2018", "08/15/2018", 111.170, 6.11, 2.585)]
[InlineData(CouponType.FixedRate, 4, "2/20/2018", "10/1/2036", "3/26/2018", "", 104.676, 4.00, 3.650)]
[InlineData(CouponType.FixedRate, 1.85, "2/1/2018", "2/1/2021", "3/26/2018", "", 99.916, 2.83, 1.880)]
[InlineData(CouponType.FixedRate, 2.85, "2/15/2018", "2/15/2031", "3/26/2018", "", 99.525, 3.25, 2.984)]
[InlineData(CouponType.FixedRate, 5.375, "03/01/2018", "03/01/2023", "7/16/2018", "", 103.674, 20.156, 4.490)]
#endif
public void testAccruedInterest(CouponType couponType, double Coupon,
string AccrualDate, string MaturityDate, string SettlementDate, string FirstCouponDate,
double Price, double expectedAccruedInterest, double expectedYtm)
{
// Convert dates
Date maturityDate = Convert.ToDateTime(MaturityDate, new CultureInfo("en-US"));
Date settlementDate = Convert.ToDateTime(SettlementDate, new CultureInfo("en-US"));
Date datedDate = Convert.ToDateTime(AccrualDate, new CultureInfo("en-US"));
Date firstCouponDate = null;
if (FirstCouponDate != String.Empty)
firstCouponDate = Convert.ToDateTime(FirstCouponDate, new CultureInfo("en-US"));
Coupon = Coupon / 100;
Calendar calendar = new TARGET();
int settlementDays = 1;
Period tenor = new Period(6, TimeUnit.Months);
Period exCouponPeriod = new Period(6, TimeUnit.Days);
//Compounding comp = Compounding.Compounded;
//Frequency freq = Frequency.Semiannual;
DayCounter dc = new Thirty360(Thirty360.Thirty360Convention.USA);
Schedule schedule = new Schedule(datedDate, maturityDate, tenor, new NullCalendar(),
BusinessDayConvention.Unadjusted, BusinessDayConvention.Unadjusted, DateGeneration.Rule.Backward, false,
firstCouponDate);
CallableFixedRateBond bond = new CallableFixedRateBond(settlementDays, 1000.0, schedule, new InitializedList<double>(1, Coupon),
dc, BusinessDayConvention.Unadjusted, 100.0, null);
double accruedInterest = CashFlows.accruedAmount(bond.cashflows(), false, settlementDate);
if (Math.Abs(accruedInterest - expectedAccruedInterest) > 1e-2)
QAssert.Fail("Failed to reproduce accrual interest at " + settlementDate
+ "\n calculated: " + accruedInterest
+ "\n expected: " + expectedAccruedInterest);
}
public struct test_case
{
public Date settlementDate;
public double testPrice;
public double accruedAmount;
public double NPV;
public double yield;
public double duration;
public double convexity;
public test_case(Date settlementDate, double testPrice, double accruedAmount, double nPV, double yield, double duration, double convexity)
{
this.settlementDate = settlementDate;
this.testPrice = testPrice;
this.accruedAmount = accruedAmount;
NPV = nPV;
this.yield = yield;
this.duration = duration;
this.convexity = convexity;
}
}
#if NET40 || NET45
[TestMethod()]
#else
[Fact]
#endif
public void testExCouponGilt()
{
// Testing ex-coupon UK Gilt price against market values
/* UK Gilts have an exCouponDate 7 business days before the coupon
is due (see <http://www.dmo.gov.uk/index.aspx?page=Gilts/Gilt_Faq>).
On the exCouponDate the bond still trades cum-coupon so we use
6 days below and UK calendar
Output verified with Bloomberg:
ISIN: GB0009997999
Issue Date: February 29th, 1996
Interest Accrue: February 29th, 1996
First Coupon: June 7th, 1996
Maturity: June 7th, 2021
coupon: 8
period: 6M
Settlement date: May 29th, 2013
Test Price : 103
Accrued : 38021.97802
NPV : 106.8021978
Yield : 7.495180593
Yield->NPV : 106.8021978
Yield->NPV->Price : 103
Mod duration : 5.676044458
Convexity : 0.4215314859
PV 0.01 : 0.0606214023
Settlement date: May 30th, 2013
Test Price : 103
Accrued : -1758.241758
NPV : 102.8241758
Yield : 7.496183543
Yield->NPV : 102.8241758
Yield->NPV->Price : 103
Mod duration : 5.892816328
Convexity : 0.4375621862
PV 0.01 : 0.06059239822
Settlement date: May 31st, 2013
Test Price : 103
Accrued : -1538.461538
NPV : 102.8461538
Yield : 7.495987492
Yield->NPV : 102.8461539
Yield->NPV->Price : 103
Mod duration : 5.890186028
Convexity : 0.4372394381
PV 0.01 : 0.06057829784
*/
Calendar calendar = new UnitedKingdom();
int settlementDays = 3;
Date issueDate = new Date(29, Month.February, 1996);
Date startDate = new Date(29, Month.February, 1996);
Date firstCouponDate = new Date(07, Month.June, 1996);
Date maturityDate = new Date(07, Month.June, 2021);
double coupon = 0.08;
Period tenor = new Period(6, TimeUnit.Months);
Period exCouponPeriod = new Period(6, TimeUnit.Days);
Compounding comp = Compounding.Compounded;
Frequency freq = Frequency.Semiannual;
DayCounter dc = new ActualActual(ActualActual.Convention.ISMA);
FixedRateBond bond = new FixedRateBond(settlementDays, 100.0,
new Schedule(startDate, maturityDate, tenor,
new NullCalendar(), BusinessDayConvention.Unadjusted,
BusinessDayConvention.Unadjusted, DateGeneration.Rule.Forward,
true, firstCouponDate), new InitializedList<double>(1, coupon),
dc, BusinessDayConvention.Unadjusted, 100.0,
issueDate, calendar, exCouponPeriod, calendar);
List<CashFlow> leg = bond.cashflows();
test_case[] cases =
{
new test_case(new Date(29, Month.May, 2013), 103.0, 3.8021978, 106.8021978, 0.0749518, 5.6760445, 42.1531486),
new test_case(new Date(30, Month.May, 2013), 103.0, -0.1758242, 102.8241758, 0.0749618, 5.8928163, 43.7562186),
new test_case(new Date(31, Month.May, 2013), 103.0, -0.1538462, 102.8461538, 0.0749599, 5.8901860, 43.7239438)
};
for (int i = 0; i < cases.Length; ++i)
{
double accrued = bond.accruedAmount(cases[i].settlementDate);
if (Math.Abs(accrued - cases[i].accruedAmount) > 1e-6)
QAssert.Fail("Failed to reproduce accrued amount at " + cases[i].settlementDate
+ "\n calculated: " + accrued
+ "\n expected: " + cases[i].accruedAmount);
double npv = cases[i].testPrice + accrued;
if (Math.Abs(npv - cases[i].NPV) > 1e-6)
QAssert.Fail("Failed to reproduce NPV at " + cases[i].settlementDate
+ "\n calculated: " + npv
+ "\n expected: " + cases[i].NPV);
double yield = CashFlows.yield(leg, npv, dc, comp, freq, false, cases[i].settlementDate);
if (Math.Abs(yield - cases[i].yield) > 1e-6)
QAssert.Fail("Failed to reproduce yield at " + cases[i].settlementDate
+ "\n calculated: " + yield
+ "\n expected: " + cases[i].yield);
double duration = CashFlows.duration(leg, yield, dc, comp, freq, Duration.Type.Modified, false, cases[i].settlementDate);
if (Math.Abs(duration - cases[i].duration) > 1e-6)
QAssert.Fail("Failed to reproduce duration at " + cases[i].settlementDate
+ "\n calculated: " + duration
+ "\n expected: " + cases[i].duration);
double convexity = CashFlows.convexity(leg, yield, dc, comp, freq, false, cases[i].settlementDate);
if (Math.Abs(convexity - cases[i].convexity) > 1e-6)
QAssert.Fail("Failed to reproduce convexity at " + cases[i].settlementDate
+ "\n calculated: " + convexity
+ "\n expected: " + cases[i].convexity);
double calcnpv = CashFlows.npv(leg, yield, dc, comp, freq, false, cases[i].settlementDate);
if (Math.Abs(calcnpv - cases[i].NPV) > 1e-6)
QAssert.Fail("Failed to reproduce NPV from yield at " + cases[i].settlementDate
+ "\n calculated: " + calcnpv
+ "\n expected: " + cases[i].NPV);
double calcprice = calcnpv - accrued;
if (Math.Abs(calcprice - cases[i].testPrice) > 1e-6)
QAssert.Fail("Failed to reproduce price from yield at " + cases[i].settlementDate
+ "\n calculated: " + calcprice
+ "\n expected: " + cases[i].testPrice);
}
}
#if NET40 || NET45
[TestMethod()]
#else
[Fact]
#endif
public void testExCouponAustralianBond()
{
// Testing ex-coupon Australian bond price against market values
/* Australian Government Bonds have an exCouponDate 7 calendar
days before the coupon is due. On the exCouponDate the bond
trades ex-coupon so we use 7 days below and NullCalendar.
AGB accrued interest is rounded to 3dp.
Output verified with Bloomberg:
ISIN: AU300TB01208
Issue Date: June 10th, 2004
Interest Accrue: February 15th, 2004
First Coupon: August 15th, 2004
Maturity: February 15th, 2017
coupon: 6
period: 6M
Settlement date: August 7th, 2014
Test Price : 103
Accrued : 28670
NPV : 105.867
Yield : 4.723814867
Yield->NPV : 105.867
Yield->NPV->Price : 103
Mod duration : 2.262763296
Convexity : 0.0654870275
PV 0.01 : 0.02395519619
Settlement date: August 8th, 2014
Test Price : 103
Accrued : -1160
NPV : 102.884
Yield : 4.72354833
Yield->NPV : 102.884
Yield->NPV->Price : 103
Mod duration : 2.325360055
Convexity : 0.06725307785
PV 0.01 : 0.02392423439
Settlement date: August 11th, 2014
Test Price : 103
Accrued : -660
NPV : 102.934
Yield : 4.719277687
Yield->NPV : 102.934
Yield->NPV->Price : 103
Mod duration : 2.317320093
Convexity : 0.06684074058
PV 0.01 : 0.02385310264
*/
Calendar calendar = new Australia();
int settlementDays = 3;
Date issueDate = new Date(10, Month.June, 2004);
Date startDate = new Date(15, Month.February, 2004);
Date firstCouponDate = new Date(15, Month.August, 2004);
Date maturityDate = new Date(15, Month.February, 2017);
double coupon = 0.06;
Period tenor = new Period(6, TimeUnit.Months);
Period exCouponPeriod = new Period(7, TimeUnit.Days);
Compounding comp = Compounding.Compounded;
Frequency freq = Frequency.Semiannual;
DayCounter dc = new ActualActual(ActualActual.Convention.ISMA);
FixedRateBond bond = new FixedRateBond(settlementDays, 100.0,
new Schedule(startDate, maturityDate, tenor, new NullCalendar(), BusinessDayConvention.Unadjusted, BusinessDayConvention.Unadjusted,
DateGeneration.Rule.Forward, true, firstCouponDate),
new InitializedList<double>(1, coupon), dc, BusinessDayConvention.Unadjusted, 100.0, issueDate, calendar, exCouponPeriod, new NullCalendar());
List<CashFlow> leg = bond.cashflows();
test_case[] cases =
{
new test_case(new Date(7, Month.August, 2014), 103.0, 2.8670, 105.867, 0.04723, 2.26276, 6.54870),
new test_case(new Date(8, Month.August, 2014), 103.0, -0.1160, 102.884, 0.047235, 2.32536, 6.72531),
new test_case(new Date(11, Month.August, 2014), 103.0, -0.0660, 102.934, 0.04719, 2.31732, 6.68407)
};
for (int i = 0; i < cases.Length; ++i)
{
double accrued = bond.accruedAmount(cases[i].settlementDate);
if (Math.Abs(accrued - cases[i].accruedAmount) > 1e-3)
QAssert.Fail("Failed to reproduce accrued amount at " + cases[i].settlementDate
+ "\n calculated: " + accrued
+ "\n expected: " + cases[i].accruedAmount);
double npv = cases[i].testPrice + accrued;
if (Math.Abs(npv - cases[i].NPV) > 1e-3)
QAssert.Fail("Failed to reproduce NPV at " + cases[i].settlementDate
+ "\n calculated: " + npv
+ "\n expected: " + cases[i].NPV);
double yield = CashFlows.yield(leg, npv, dc, comp, freq, false, cases[i].settlementDate);
if (Math.Abs(yield - cases[i].yield) > 1e-3)
QAssert.Fail("Failed to reproduce yield at " + cases[i].settlementDate
+ "\n calculated: " + yield
+ "\n expected: " + cases[i].yield);
double duration = CashFlows.duration(leg, yield, dc, comp, freq, Duration.Type.Modified, false, cases[i].settlementDate);
if (Math.Abs(duration - cases[i].duration) > 1e-5)
QAssert.Fail("Failed to reproduce duration at " + cases[i].settlementDate
+ "\n calculated: " + duration
+ "\n expected: " + cases[i].duration);
double convexity = CashFlows.convexity(leg, yield, dc, comp, freq, false, cases[i].settlementDate);
if (Math.Abs(convexity - cases[i].convexity) > 1e-4)
QAssert.Fail("Failed to reproduce convexity at " + cases[i].settlementDate
+ "\n calculated: " + convexity
+ "\n expected: " + cases[i].convexity);
double calcnpv = CashFlows.npv(leg, yield, dc, comp, freq, false, cases[i].settlementDate);
if (Math.Abs(calcnpv - cases[i].NPV) > 1e-3)
QAssert.Fail("Failed to reproduce NPV from yield at " + cases[i].settlementDate
+ "\n calculated: " + calcnpv
+ "\n expected: " + cases[i].NPV);
double calcprice = calcnpv - accrued;
if (Math.Abs(calcprice - cases[i].testPrice) > 1e-3)
QAssert.Fail("Failed to reproduce price from yield at " + cases[i].settlementDate
+ "\n calculated: " + calcprice
+ "\n expected: " + cases[i].testPrice);
}
}
#if NET40 || NET45
[TestMethod()]
#else
[Fact]
#endif
public void testThirty360BondWithSettlementOn31st()
{
// Testing Thirty/360 bond with settlement on 31st of the month
// cusip 3130A0X70, data is from Bloomberg
Settings.setEvaluationDate(new Date(28, Month.July, 2017));
Date datedDate = new Date(13, Month.February, 2014);
Date settlement = new Date(31, Month.July, 2017);
Date maturity = new Date(13, Month.August, 2018);
DayCounter dayCounter = new Thirty360(Thirty360.Thirty360Convention.USA);
Compounding compounding = Compounding.Compounded;
Schedule fixedBondSchedule = new Schedule(datedDate, maturity, new Period(Frequency.Semiannual), new UnitedStates(UnitedStates.Market.GovernmentBond),
BusinessDayConvention.Unadjusted, BusinessDayConvention.Unadjusted, DateGeneration.Rule.Forward, false);
FixedRateBond fixedRateBond = new FixedRateBond(1, 100, fixedBondSchedule, new InitializedList<double>(1, 0.015), dayCounter,
BusinessDayConvention.Unadjusted, 100.0);
double cleanPrice = 100;
double yield = BondFunctions.yield(fixedRateBond, cleanPrice, dayCounter, compounding, Frequency.Semiannual, settlement);
if (Math.Abs(yield - 0.015) > 1e-4)
QAssert.Fail("Failed to yield at " + settlement
+ "\n calculated: " + yield
+ "\n expected: " + "0.015");
double duration = BondFunctions.duration(fixedRateBond, new InterestRate(yield, dayCounter, compounding, Frequency.Semiannual),
Duration.Type.Macaulay, settlement);
if (Math.Abs(duration - 1.022) > 1e-3)
QAssert.Fail("Failed to reproduce duration at " + settlement
+ "\n calculated: " + duration
+ "\n expected: " + "1.022");
double convexity = BondFunctions.convexity(fixedRateBond, new InterestRate(yield, dayCounter, compounding, Frequency.Semiannual), settlement) / 100;
if (Math.Abs(convexity - 0.015) > 1e-3)
QAssert.Fail("Failed to reproduce convexity at " + settlement
+ "\n calculated: " + convexity
+ "\n expected: " + "0.015");
double accrued = BondFunctions.accruedAmount(fixedRateBond, settlement);
if (Math.Abs(accrued - 0.7) > 1e-6)
QAssert.Fail("Failed to reproduce accrued at " + settlement
+ "\n calculated: " + accrued
+ "\n expected: " + "0.7");
}
#if NET40 || NET45
[DataTestMethod()]
[DataRow("64990C4X6", "07/01/2035", 4, "07/10/2018", 106.599, 12.417, 10.24)]
[DataRow("64990C5B3", "07/01/2047", 4, "07/10/2018", 103.9, 17.296, 12.87)]
[DataRow("546415L40", "05/15/2033", 4, "07/10/2018", 104.239, 11.154, 7.71)]
[DataRow("646140CN1", "01/01/2035", 4, "07/10/2018", 105.262, 12.118, 10.59)]
[DataRow("70024PCW7", "06/15/2028", 4, "07/10/2018", 110.839, 8.257, 7.82)]
//[DataRow("602453HJ4", "06/15/2048", 4, "07/10/2018", 103.753, 17.61, 13.73)] // 17.562 from calculation
//[DataRow("397586QG6", "02/15/2035", 4, "07/17/2018", 103.681, 12.138, 8.3)] // 11.946 from calculation
//[DataRow("544351NT2", "06/27/2019", 4, "07/10/2018", 102.424, 0.951, 0.96)] // 0.947 from calculation
//[DataRow("15147TDU9", "07/15/2035", 4, "07/10/2018", 105.591, 12.405, 10.7)]
//[DataRow("832645JK2", "08/15/2048", 4, "07/10/2018", 103.076, 17.618, 13.35)]
//[DataRow("956622N91", "06/01/2051", 4, "07/11/2018", 100, 18.206, 14.92)]
//[DataRow("397586QF8", "02/15/2034", 4, "07/17/2018", 103.941, 11.612, 7.87)]
#else
[Theory]
[InlineData("64990C4X6", "07/01/2035", 4, "07/10/2018", 106.599, 12.417, 10.24)]
[InlineData("64990C5B3", "07/01/2047", 4, "07/10/2018", 103.9, 17.296, 12.87)]
[InlineData("546415L40", "05/15/2033", 4, "07/10/2018", 104.239, 11.154, 7.71)]
[InlineData("646140CN1", "01/01/2035", 4, "07/10/2018", 105.262, 12.118, 10.59)]
[InlineData("70024PCW7", "06/15/2028", 4, "07/10/2018", 110.839, 8.257, 7.82)]
//[InlineData("602453HJ4", "06/15/2048", 4, "07/10/2018", 103.753, 17.61, 13.73)]
//[InlineData("397586QG6", "02/15/2035", 4, "07/17/2018", 103.681, 12.138, 8.3)]
//[InlineData("544351NT2", "06/27/2019", 4, "07/10/2018", 102.424, 0.951, 0.96)]
//[InlineData("15147TDU9", "07/15/2035", 4, "07/10/2018", 105.591, 12.405, 10.7)]
//[InlineData("832645JK2", "08/15/2048", 4, "07/10/2018", 103.076, 17.618, 13.35)]
//[InlineData("956622N91", "06/01/2051", 4, "07/11/2018", 100, 18.206, 14.92)]
//[InlineData("397586QF8", "02/15/2034", 4, "07/17/2018", 103.941, 11.612, 7.87)]
#endif
public void testDurations(string Cusip, string MaturityDate, double Coupon,
string SettlementDate, double Price, double ExpectedModifiedDuration, double ExpectedOASDuration)
{
// Convert dates
Date maturityDate = Convert.ToDateTime(MaturityDate, new CultureInfo("en-US"));
Date settlementDate = Convert.ToDateTime(SettlementDate, new CultureInfo("en-US"));
// Divide number by 100
Coupon = Coupon / 100;
Calendar calendar = new TARGET();
int settlementDays = 1;
Period tenor = new Period(6, TimeUnit.Months);
Period exCouponPeriod = new Period(6, TimeUnit.Days);
Compounding comp = Compounding.Compounded;
Frequency freq = Frequency.Semiannual;
DayCounter dc = new Thirty360(Thirty360.Thirty360Convention.USA);
Schedule sch = new Schedule(null, maturityDate, tenor,
new NullCalendar(), BusinessDayConvention.Unadjusted,
BusinessDayConvention.Unadjusted, DateGeneration.Rule.Backward, false);
FixedRateBond bond = new FixedRateBond(settlementDays, 100.0, sch,
new InitializedList<double>(1, Coupon), dc, BusinessDayConvention.Unadjusted,
100.0, null, calendar, exCouponPeriod, calendar);
double yield = bond.yield(Price, dc, comp, freq, settlementDate);
double duration = BondFunctions.duration(bond, yield, dc, comp, freq, Duration.Type.Modified, settlementDate);
if (Math.Abs(duration - ExpectedModifiedDuration) > 1e-3)
QAssert.Fail("Failed to reproduce modified duration for cusip " + Cusip + " at " + SettlementDate
+ "\n calculated: " + duration
+ "\n expected: " + ExpectedModifiedDuration);
}
}
}
| 50.949539 | 205 | 0.537039 | [
"BSD-3-Clause"
] | maittaeb/QLNet | tests/QLNet.Tests/T_Bonds.cs | 93,912 | C# |
/*
The MIT License (MIT)
Copyright (c) 2018 Helix Toolkit contributors
*/
#if NETFX_CORE
using Windows.UI.Xaml;
using Media = Windows.UI;
namespace HelixToolkit.UWP
#else
using System.Windows;
using Media = System.Windows.Media;
namespace HelixToolkit.Wpf.SharpDX
#endif
{
using global::SharpDX;
using Model;
using Model.Scene;
/// <summary>
///
/// </summary>
/// <seealso cref="GeometryModel3D" />
public class LineGeometryModel3D : GeometryModel3D
{
#region Dependency Properties
/// <summary>
/// The color property
/// </summary>
public static readonly DependencyProperty ColorProperty =
DependencyProperty.Register("Color", typeof(Media.Color), typeof(LineGeometryModel3D), new PropertyMetadata(Media.Colors.Black, (d, e) =>
{
((d as Element3DCore).SceneNode as LineNode).Color = ((Media.Color)e.NewValue).ToColor4();
}));
/// <summary>
/// The thickness property
/// </summary>
public static readonly DependencyProperty ThicknessProperty =
DependencyProperty.Register("Thickness", typeof(double), typeof(LineGeometryModel3D), new PropertyMetadata(1.0, (d, e) =>
{
((d as Element3DCore).SceneNode as LineNode).Thickness = (float)(double)e.NewValue;
}));
/// <summary>
/// The smoothness property
/// </summary>
public static readonly DependencyProperty SmoothnessProperty =
DependencyProperty.Register("Smoothness", typeof(double), typeof(LineGeometryModel3D), new PropertyMetadata(0.0,
(d, e) =>
{
((d as Element3DCore).SceneNode as LineNode).Smoothness = (float)(double)e.NewValue;
}));
/// <summary>
/// The hit test thickness property
/// </summary>
public static readonly DependencyProperty HitTestThicknessProperty =
DependencyProperty.Register("HitTestThickness", typeof(double), typeof(LineGeometryModel3D), new PropertyMetadata(1.0, (d,e)=>
{ ((d as Element3DCore).SceneNode as LineNode).HitTestThickness = (double)e.NewValue; }));
/// <summary>
/// Gets or sets the color.
/// </summary>
/// <value>
/// The color.
/// </value>
public Media.Color Color
{
get { return (Media.Color)this.GetValue(ColorProperty); }
set { this.SetValue(ColorProperty, value); }
}
/// <summary>
/// Gets or sets the thickness.
/// </summary>
/// <value>
/// The thickness.
/// </value>
public double Thickness
{
get { return (double)this.GetValue(ThicknessProperty); }
set { this.SetValue(ThicknessProperty, value); }
}
/// <summary>
/// Gets or sets the smoothness.
/// </summary>
/// <value>
/// The smoothness.
/// </value>
public double Smoothness
{
get { return (double)this.GetValue(SmoothnessProperty); }
set { this.SetValue(SmoothnessProperty, value); }
}
/// <summary>
/// Used only for point/line hit test
/// </summary>
public double HitTestThickness
{
get { return (double)this.GetValue(HitTestThicknessProperty); }
set { this.SetValue(HitTestThicknessProperty, value); }
}
#endregion
/// <summary>
/// Called when [create scene node].
/// </summary>
/// <returns></returns>
protected override SceneNode OnCreateSceneNode()
{
return new LineNode();
}
/// <summary>
/// Assigns the default values to core.
/// </summary>
/// <param name="core">The core.</param>
protected override void AssignDefaultValuesToSceneNode(SceneNode core)
{
if(core is LineNode n)
{
n.Color = Color.ToColor4();
n.Thickness = (float)Thickness;
n.Smoothness = (float)Smoothness;
}
base.AssignDefaultValuesToSceneNode(core);
}
}
}
| 34.047619 | 149 | 0.561772 | [
"MIT"
] | SiNeumann/helix-toolkit | Source/HelixToolkit.SharpDX.SharedModel/Element3D/LineGeometryModel3D.cs | 4,292 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Bot.Schema;
namespace Microsoft.Bot.Builder.Dialogs.Choices
{
/// <summary>
/// Assists with formatting a message activity that contains a list of choices.
/// </summary>
#pragma warning disable CA1052 // Static holder types should be Static or NotInheritable (we can't change this without breaking binary compat)
public class ChoiceFactory
#pragma warning restore CA1052 // Static holder types should be Static or NotInheritable
{
/// <summary>
/// Creates a message activity that includes a list of choices formatted based on the capabilities of a given channel.
/// </summary>
/// <param name="channelId">A channel ID. The <see cref="Connector.Channels"/> class contains known channel IDs.</param>
/// <param name="list">The list of choices to include.</param>
/// <param name="text">Optional, the text of the message to send.</param>
/// <param name="speak">Optional, the text to be spoken by your bot on a speech-enabled channel.</param>
/// <param name="options">Optional, the formatting options to use when rendering as a list.</param>
/// <returns>The created message activity.</returns>
/// <remarks>The algorithm prefers to format the supplied list of choices as suggested actions but can decide
/// to use a text based list if suggested actions aren't natively supported by the channel, there are too many
/// choices for the channel to display, or the title of any choice is too long.
/// <para>If the algorithm decides to use a list, for 3 or fewer choices with short titles it will use an inline
/// list; otherwise, a numbered list.</para></remarks>
public static IMessageActivity ForChannel(string channelId, IList<Choice> list, string text = null, string speak = null, ChoiceFactoryOptions options = null)
{
channelId ??= string.Empty;
list ??= new List<Choice>();
// Find maximum title length
var maxTitleLength = 0;
foreach (var choice in list)
{
var l = choice.Action != null && !string.IsNullOrEmpty(choice.Action.Title) ? choice.Action.Title.Length : choice.Value.Length;
if (l > maxTitleLength)
{
maxTitleLength = l;
}
}
// Determine list style
var supportsSuggestedActions = Channel.SupportsSuggestedActions(channelId, list.Count);
var supportsCardActions = Channel.SupportsCardActions(channelId, list.Count);
var maxActionTitleLength = Channel.MaxActionTitleLength(channelId);
var hasMessageFeed = Channel.HasMessageFeed(channelId);
var longTitles = maxTitleLength > maxActionTitleLength;
if (!longTitles && !supportsSuggestedActions && supportsCardActions)
{
// SuggestedActions is the preferred approach, but for channels that don't
// support them (e.g. Teams, Cortana) we should use a HeroCard with CardActions
return HeroCard(list, text, speak);
}
if (!longTitles && supportsSuggestedActions)
{
// We always prefer showing choices using suggested actions. If the titles are too long, however,
// we'll have to show them as a text list.
return SuggestedAction(list, text, speak);
}
if (!longTitles && list.Count <= 3)
{
// If the titles are short and there are 3 or less choices we'll use an inline list.
return Inline(list, text, speak, options);
}
// Show a numbered list.
return List(list, text, speak, options);
}
/// <summary>
/// Creates a message activity that includes a list of choices formatted as an inline list.
/// </summary>
/// <param name="choices">The list of choices to include.</param>
/// <param name="text">Optional, the text of the message to send.</param>
/// <param name="speak">Optional, the text to be spoken by your bot on a speech-enabled channel.</param>
/// <param name="options">Optional, the formatting options to use when rendering as a list.</param>
/// <returns>The created message activity.</returns>
public static Activity Inline(IList<Choice> choices, string text = null, string speak = null, ChoiceFactoryOptions options = null)
{
choices ??= new List<Choice>();
options ??= new ChoiceFactoryOptions();
var opt = new ChoiceFactoryOptions
{
InlineSeparator = options.InlineSeparator ?? ", ",
InlineOr = options.InlineOr ?? " or ",
InlineOrMore = options.InlineOrMore ?? ", or ",
IncludeNumbers = options.IncludeNumbers ?? true,
};
// Format list of choices
var connector = string.Empty;
var txtBuilder = new StringBuilder(text)
.Append(' ');
for (var index = 0; index < choices.Count; index++)
{
var choice = choices[index];
var title = choice.Action != null && choice.Action.Title != null ? choice.Action.Title : choice.Value;
txtBuilder.Append(connector);
if (opt.IncludeNumbers.Value)
{
txtBuilder
.Append('(')
.Append(index + 1)
.Append(") ");
}
txtBuilder.Append(title);
if (index == choices.Count - 2)
{
connector = (index == 0 ? opt.InlineOr : opt.InlineOrMore) ?? string.Empty;
}
else
{
connector = opt.InlineSeparator ?? string.Empty;
}
}
// Return activity with choices as an inline list.
return MessageFactory.Text(txtBuilder.ToString(), speak, InputHints.ExpectingInput);
}
/// <summary>
/// Creates a message activity that includes a list of choices formatted as a numbered or bulleted list.
/// </summary>
/// <param name="choices">The list of choices to include.</param>
/// <param name="text">Optional, the text of the message to send.</param>
/// <param name="speak">Optional, the text to be spoken by your bot on a speech-enabled channel.</param>
/// <param name="options">Optional, the formatting options to use when rendering as a list.</param>
/// <returns>The created message activity.</returns>
public static Activity List(IList<string> choices, string text = null, string speak = null, ChoiceFactoryOptions options = null)
{
return List(ToChoices(choices), text, speak, options);
}
public static Activity List(IList<Choice> choices, string text = null, string speak = null, ChoiceFactoryOptions options = null)
{
choices ??= new List<Choice>();
options ??= new ChoiceFactoryOptions();
var includeNumbers = options.IncludeNumbers ?? true;
// Format list of choices
var connector = string.Empty;
var txtBuilder = new StringBuilder(text)
.Append("\n\n ");
for (var index = 0; index < choices.Count; index++)
{
var choice = choices[index];
var title = choice.Action?.Title ?? choice.Value;
txtBuilder.Append(connector);
if (includeNumbers)
{
txtBuilder
.Append(index + 1)
.Append(". ");
}
else
{
txtBuilder.Append("- ");
}
txtBuilder.Append(title);
connector = "\n ";
}
// Return activity with choices as a numbered list.
return MessageFactory.Text(txtBuilder.ToString(), speak, InputHints.ExpectingInput);
}
public static IMessageActivity SuggestedAction(IList<string> choices, string text = null, string speak = null)
{
return SuggestedAction(ToChoices(choices), text, speak);
}
public static IMessageActivity SuggestedAction(IList<Choice> choices, string text = null, string speak = null)
{
// Return activity with choices as suggested actions
return MessageFactory.SuggestedActions(ExtractActions(choices), text, speak, InputHints.ExpectingInput);
}
public static IMessageActivity HeroCard(IList<Choice> choices, string text = null, string speak = null)
{
var attachments = new List<Attachment>
{
new HeroCard(text: text, buttons: ExtractActions(choices)).ToAttachment(),
};
// Return activity with choices as HeroCard with buttons
return MessageFactory.Attachment(attachments, null, speak, InputHints.ExpectingInput);
}
public static IList<Choice> ToChoices(IList<string> choices)
{
return choices == null
? new List<Choice>()
: choices.Select(choice => new Choice { Value = choice }).ToList();
}
private static List<CardAction> ExtractActions(IList<Choice> choices)
{
choices ??= new List<Choice>();
// Map choices to actions
return choices.Select(choice =>
{
if (choice.Action != null)
{
return choice.Action;
}
return new CardAction
{
Type = ActionTypes.ImBack,
Value = choice.Value,
Title = choice.Value,
};
}).ToList();
}
}
}
| 43.893617 | 165 | 0.571789 | [
"MIT"
] | Bhaskers-Blu-Org2/botbuilder-dotnet | libraries/Microsoft.Bot.Builder.Dialogs/Choices/ChoiceFactory.cs | 10,317 | C# |
// Copyright (c) Six Labors and contributors.
// Licensed under the Apache License, Version 2.0.
namespace SixLabors.
ImageSharp.Formats.Tga
{
/// <summary>
/// Defines the tga image type. The TGA File Format can be used to store Pseudo-Color,
/// True-Color and Direct-Color images of various pixel depths.
/// </summary>
public enum TgaImageType : byte
{
/// <summary>
/// No image data included.
/// </summary>
NoImageData = 0,
/// <summary>
/// Uncompressed, color mapped image.
/// </summary>
ColorMapped = 1,
/// <summary>
/// Uncompressed true color image.
/// </summary>
TrueColor = 2,
/// <summary>
/// Uncompressed Black and white (grayscale) image.
/// </summary>
BlackAndWhite = 3,
/// <summary>
/// Run length encoded, color mapped image.
/// </summary>
RleColorMapped = 9,
/// <summary>
/// Run length encoded, true color image.
/// </summary>
RleTrueColor = 10,
/// <summary>
/// Run length encoded, black and white (grayscale) image.
/// </summary>
RleBlackAndWhite = 11,
}
}
| 25.612245 | 90 | 0.537052 | [
"Apache-2.0"
] | Sheyne/ImageSharp | src/ImageSharp/Formats/Tga/TgaImageType.cs | 1,255 | C# |
// ---------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// The MIT License (MIT)
//
// 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 Newtonsoft.Json;
using System;
namespace ContosoModels
{
/// <summary>
/// Represents a line item (product + quantity) on an order.
/// </summary>
public class LineItem : DbObject
{
/// <summary>
/// Gets or sets the id of the order the line item is associated with.
/// </summary>
public Guid OrderId { get; set; }
/// <summary>
/// Gets or sets the order the line item is associated with.
/// </summary>
[JsonIgnore]
public Order Order { get; set; }
/// <summary>
/// Gets or sets the product's id.
/// </summary>
public Guid ProductId { get; set; }
/// <summary>
/// Gets or sets the product.
/// </summary>
public Product Product { get; set; }
/// <summary>
/// Gets or sets the quantity of product.
/// </summary>
public int Quantity { get; set; } = 1;
}
} | 38.114754 | 85 | 0.6 | [
"MIT"
] | GauravGarg118/11 | ContosoModels/LineItem.cs | 2,325 | C# |
/* Copyright 2010-present MongoDB Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Text;
using MongoDB.Bson;
using MongoDB.Bson.Serialization;
using MongoDB.Driver.Core.Misc;
namespace MongoDB.Driver
{
/// <summary>
/// The settings used to access a database.
/// </summary>
public class MongoDatabaseSettings
{
// private fields
private Setting<GuidRepresentation> _guidRepresentation;
private Setting<ReadConcern> _readConcern;
private Setting<UTF8Encoding> _readEncoding;
private Setting<ReadPreference> _readPreference;
private Setting<WriteConcern> _writeConcern;
private Setting<UTF8Encoding> _writeEncoding;
// the following fields are set when Freeze is called
private bool _isFrozen;
private int _frozenHashCode;
private string _frozenStringRepresentation;
// constructors
/// <summary>
/// Creates a new instance of MongoDatabaseSettings.
/// </summary>
public MongoDatabaseSettings()
{
}
// public properties
/// <summary>
/// Gets or sets the representation to use for Guids.
/// </summary>
[Obsolete("Configure serializers instead.")]
public GuidRepresentation GuidRepresentation
{
get
{
if (BsonDefaults.GuidRepresentationMode != GuidRepresentationMode.V2)
{
throw new InvalidOperationException("MongoDatabaseSettings.GuidRepresentation can only be used when BsonDefaults.GuidRepresentationMode is V2.");
}
return _guidRepresentation.Value;
}
set
{
if (_isFrozen) { throw new InvalidOperationException("MongoDatabaseSettings is frozen."); }
if (BsonDefaults.GuidRepresentationMode != GuidRepresentationMode.V2)
{
throw new InvalidOperationException("MongoDatabaseSettings.GuidRepresentation can only be used when BsonDefaults.GuidRepresentationMode is V2.");
}
_guidRepresentation.Value = value;
}
}
/// <summary>
/// Gets a value indicating whether the settings have been frozen to prevent further changes.
/// </summary>
public bool IsFrozen
{
get { return _isFrozen; }
}
/// <summary>
/// Gets or sets the read concern.
/// </summary>
public ReadConcern ReadConcern
{
get { return _readConcern.Value; }
set
{
if (_isFrozen) { throw new InvalidOperationException("MongoDatabaseSettings is frozen."); }
_readConcern.Value = Ensure.IsNotNull(value, nameof(value));
}
}
/// <summary>
/// Gets or sets the Read Encoding.
/// </summary>
public UTF8Encoding ReadEncoding
{
get { return _readEncoding.Value; }
set
{
if (_isFrozen) { throw new InvalidOperationException("MongoDatabaseSettings is frozen."); }
_readEncoding.Value = value;
}
}
/// <summary>
/// Gets or sets the read preference.
/// </summary>
public ReadPreference ReadPreference
{
get { return _readPreference.Value; }
set
{
if (_isFrozen) { throw new InvalidOperationException("MongoDatabaseSettings is frozen."); }
if (value == null)
{
throw new ArgumentNullException("value");
}
_readPreference.Value = value;
}
}
/// <summary>
/// Gets the serializer registry.
/// </summary>
public IBsonSerializerRegistry SerializerRegistry
{
get { return BsonSerializer.SerializerRegistry; }
}
/// <summary>
/// Gets or sets the WriteConcern to use.
/// </summary>
public WriteConcern WriteConcern
{
get { return _writeConcern.Value; }
set
{
if (_isFrozen) { throw new InvalidOperationException("MongoDatabaseSettings is frozen."); }
if (value == null)
{
throw new ArgumentNullException("value");
}
_writeConcern.Value = value;
}
}
/// <summary>
/// Gets or sets the Write Encoding.
/// </summary>
public UTF8Encoding WriteEncoding
{
get { return _writeEncoding.Value; }
set
{
if (_isFrozen) { throw new InvalidOperationException("MongoDatabaseSettings is frozen."); }
_writeEncoding.Value = value;
}
}
// public methods
/// <summary>
/// Creates a clone of the settings.
/// </summary>
/// <returns>A clone of the settings.</returns>
public MongoDatabaseSettings Clone()
{
var clone = new MongoDatabaseSettings();
clone._guidRepresentation = _guidRepresentation.Clone();
clone._readConcern = _readConcern.Clone();
clone._readEncoding = _readEncoding.Clone();
clone._readPreference = _readPreference.Clone();
clone._writeConcern = _writeConcern.Clone();
clone._writeEncoding = _writeEncoding.Clone();
return clone;
}
/// <summary>
/// Compares two MongoDatabaseSettings instances.
/// </summary>
/// <param name="obj">The other instance.</param>
/// <returns>True if the two instances are equal.</returns>
public override bool Equals(object obj)
{
var rhs = obj as MongoDatabaseSettings;
if (rhs == null)
{
return false;
}
else
{
if (_isFrozen && rhs._isFrozen)
{
return _frozenStringRepresentation == rhs._frozenStringRepresentation;
}
else
{
return
_guidRepresentation.Value == rhs._guidRepresentation.Value &&
_readConcern.Value == rhs._readConcern.Value &&
object.Equals(_readEncoding, rhs._readEncoding) &&
object.Equals(_readPreference.Value, rhs._readPreference.Value) &&
_writeConcern.Value == rhs._writeConcern.Value &&
object.Equals(_writeEncoding, rhs._writeEncoding);
}
}
}
/// <summary>
/// Freezes the settings.
/// </summary>
/// <returns>The frozen settings.</returns>
public MongoDatabaseSettings Freeze()
{
if (!_isFrozen)
{
_frozenHashCode = GetHashCode();
_frozenStringRepresentation = ToString();
_isFrozen = true;
}
return this;
}
/// <summary>
/// Returns a frozen copy of the settings.
/// </summary>
/// <returns>A frozen copy of the settings.</returns>
public MongoDatabaseSettings FrozenCopy()
{
if (_isFrozen)
{
return this;
}
else
{
return Clone().Freeze();
}
}
/// <summary>
/// Gets the hash code.
/// </summary>
/// <returns>The hash code.</returns>
public override int GetHashCode()
{
if (_isFrozen)
{
return _frozenHashCode;
}
// see Effective Java by Joshua Bloch
int hash = 17;
hash = 37 * hash + _guidRepresentation.Value.GetHashCode();
hash = 37 * hash + ((_readConcern.Value == null) ? 0 : _readConcern.GetHashCode());
hash = 37 * hash + ((_readEncoding.Value == null) ? 0 : _readEncoding.GetHashCode());
hash = 37 * hash + ((_readPreference.Value == null) ? 0 : _readPreference.Value.GetHashCode());
hash = 37 * hash + ((_writeConcern.Value == null) ? 0 : _writeConcern.Value.GetHashCode());
hash = 37 * hash + ((_writeEncoding.Value == null) ? 0 : _writeEncoding.GetHashCode());
return hash;
}
/// <summary>
/// Returns a string representation of the settings.
/// </summary>
/// <returns>A string representation of the settings.</returns>
public override string ToString()
{
if (_isFrozen)
{
return _frozenStringRepresentation;
}
var parts = new List<string>();
parts.Add(string.Format("GuidRepresentation={0}", _guidRepresentation.Value));
parts.Add(string.Format("ReadConcern={0}", _readConcern.Value));
if (_readEncoding.HasBeenSet)
{
parts.Add(string.Format("ReadEncoding={0}", (_readEncoding.Value == null) ? "null" : "UTF8Encoding"));
}
parts.Add(string.Format("ReadPreference={0}", _readPreference.Value));
parts.Add(string.Format("WriteConcern={0}", _writeConcern.Value));
if (_writeEncoding.HasBeenSet)
{
parts.Add(string.Format("WriteEncoding={0}", (_writeEncoding.Value == null) ? "null" : "UTF8Encoding"));
}
return string.Join(";", parts.ToArray());
}
// internal methods
internal void ApplyDefaultValues(IInheritableMongoClientSettings clientSettings)
{
#pragma warning disable 618
if (BsonDefaults.GuidRepresentationMode == GuidRepresentationMode.V2 && !_guidRepresentation.HasBeenSet)
{
GuidRepresentation = clientSettings.GuidRepresentation;
}
#pragma warning restore 618
if (!_readConcern.HasBeenSet)
{
ReadConcern = clientSettings.ReadConcern;
}
if (!_readEncoding.HasBeenSet)
{
ReadEncoding = clientSettings.ReadEncoding;
}
if (!_readPreference.HasBeenSet)
{
ReadPreference = clientSettings.ReadPreference;
}
if (!_writeConcern.HasBeenSet)
{
WriteConcern = clientSettings.WriteConcern;
}
if (!_writeEncoding.HasBeenSet)
{
WriteEncoding = clientSettings.WriteEncoding;
}
}
}
}
| 35.064417 | 165 | 0.545797 | [
"Apache-2.0"
] | Corniel/mongo-csharp-driver | src/MongoDB.Driver/MongoDatabaseSettings.cs | 11,431 | C# |
using System;
namespace UserInterfaceTemplate.Infrastructure.ExceptionHandling
{
public class DebugExceptionHandler : IExceptionHandler
{
public virtual void HandleException(Exception ex)
{
if (ex.IsFatal())
throw ex; //application crash
System.Diagnostics.Debug.WriteLine(ex.Message + "\n" + ex.StackTrace);
}
}
}
| 25.5625 | 83 | 0.613692 | [
"MIT"
] | OpResCodes/WPF-Template | src/UserInterfaceTemplate/Infrastructure/ExceptionHandling/DebugExceptionHandler.cs | 411 | 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("Sample")]
[assembly: AssemblyDescription("http://aka.ms/template10")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Sample")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("Sample")]
[assembly: AssemblyCulture("")]
// 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: ComVisible(false)] | 36.517241 | 84 | 0.741265 | [
"Apache-2.0"
] | ArtjomP/Template10 | Templates (Project)/Blank/Properties/AssemblyInfo.cs | 1,062 | C# |
/*
Copyright (C) 2019 Alex Watt (alexwatt@hotmail.com)
This file is part of Highlander Project https://github.com/alexanderwatt/Highlander.Net
Highlander is free software: you can redistribute it and/or modify it
under the terms of the Highlander license. You should have received a
copy of the license along with this program; if not, license is
available at <https://github.com/alexanderwatt/Highlander.Net/blob/develop/LICENSE>.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the license for more details.
*/
#region Using Directives
using System;
using System.Collections.Generic;
using System.Linq;
using FpML.V5r3.Reporting.Helpers;
using Orion.CalendarEngine.Helpers;
using FpML.V5r3.Reporting;
using Orion.ModelFramework;
using Orion.CalendarEngine.Dates;
#endregion
namespace Orion.CurveEngine.PricingStructures.Interpolators
{
/// <summary>
/// An interpolator for central bank date steps.
/// </summary>
public class GapStepInterpolator : TermCurveInterpolator//GapStep is always on the zero curve. A time zero instantaneous rate may be required.
{
private static CentralBanks _centralBank;
/// <summary>
/// Gets the days for that central bank.
/// </summary>
public DateTime[] CentralBankDays { get; set; }
//TODO add EOM, EOQ and EOY perturbation: this transfers the step to the specific day.
//Also needs to add EOM swaps to the asset config file.
/// <summary>
/// The main ctor.
/// </summary>
/// <param name="termCurve"></param>
/// <param name="baseDate"></param>
/// <param name="centralBankDateRuleMonths"></param>
/// <param name="centralBank"></param>
/// <param name="dayCounter"></param>
public GapStepInterpolator(TermCurve termCurve, DateTime baseDate, int centralBankDateRuleMonths,
CentralBanks centralBank, IDayCounter dayCounter)
: base(ConvertTermCurve(termCurve, baseDate, centralBankDateRuleMonths, dayCounter), baseDate, dayCounter)
{
CentralBankDateRuleMonths = centralBankDateRuleMonths;
_centralBank = centralBank;//var names = Enum.GetNames(typeof(AssetFactory.Types));
//TODO remove this once working.
var lastDate = (DateTime)termCurve.point[termCurve.point.Length - 1].term.Items[0];
CentralBankDays = CentralBanksHelper.GetCentralBankDays(baseDate, centralBank, centralBankDateRuleMonths, lastDate);
TermCurve = InterpolateGapStepTermPoints(termCurve, CentralBankDays, baseDate, dayCounter);
}
/// <summary>
/// Rules for central bank dates.
/// </summary>
public int CentralBankDateRuleMonths { get; }
/// <summary>
/// The central bank name.
/// </summary>
public string CentralBankName { get; } = _centralBank.ToString();
/// <summary>
/// The term curve.
/// </summary>
public TermCurve TermCurve { get; }
private static TermCurve ConvertTermCurve(TermCurve termCurve, DateTime baseDate, int centralBankDateRuleMonths, IDayCounter dayCounter)
{
var interpolationMethod = new InterpolationMethod
{Value = "PiecewiseConstantRateInterpolation"};
termCurve.interpolationMethod = interpolationMethod;
var lastDate = (DateTime)termCurve.point[termCurve.point.Length-1].term.Items[0];
return InterpolateGapStepTermPoints(termCurve, CentralBanksHelper.GetCentralBankDays(baseDate, _centralBank, centralBankDateRuleMonths, lastDate), baseDate, dayCounter);//Add the extra points..
}
private static TermCurve InterpolateGapStepTermPoints(TermCurve termCurve, IList<DateTime> centralBankDates, DateTime baseDate, IDayCounter dayCounter)
{
//Step 1. Insert the extra points.
//
var resultTermCurve = Load(termCurve, centralBankDates, baseDate, dayCounter);
//Step 2.
//
//Step 3. SortPoints the term curve if necessary.
return SortPoints(resultTermCurve);//TODO add the new points...need to sort the termcurve points...
}
/// <summary>
/// Returns a list of non-interpolated values found in a immediate vicinity of requested point.
/// <remarks>
/// If a GetValue method returns a exact match - this method should be returning null.
/// </remarks>
/// </summary>
/// <param name="termCurve"></param>
/// <param name="dates"></param>
/// <returns></returns>
public static int[] GetPreviousIndices(TermCurve termCurve, DateTime[] dates)
{
var termDates = termCurve.GetListTermDates();//GetDiscreteSpace().GetCoordinateArray(1);
var results = new List<int>();
var temp = new int[dates.Length];
var counter = 0;
foreach (var date in dates) //This handles or is supposed to handle the case of multiple central bank dates between node points.
{
var index = Array.BinarySearch(termDates.ToArray(), date);
if (index >= 0)
{
temp[counter] = index;
}
else
{
var nextIndex = ~index;
var prevIndex = nextIndex - 1;
temp[counter] = prevIndex;
}
counter++;
}
for(var i =1; i <= temp.Length-1;i++)
{
var j = 1;
while(temp[i-1]==temp[i])
{
j++;
}
results.Add(j);
}
return results.ToArray();
}
/// <summary>
/// Returns a list of non-interpolated values found in a immediate vicinity of requested point.
/// <remarks>
/// If a GetValue method returns a exact match - this method should be returning null.
/// </remarks>
/// </summary>
/// <param name="termCurve"></param>
/// <param name="date"></param>
/// <returns></returns>
public static int GetPreviousIndex(TermCurve termCurve, DateTime date)
{
var dates = termCurve.GetListTermDates();//GetDiscreteSpace().GetCoordinateArray(1);
var index = Array.BinarySearch(dates.ToArray(), date);
if (index >= 0)
{
return index;
}
var nextIndex = ~index;
var prevIndex = nextIndex - 1;
return prevIndex;
}
/// <summary>
/// Returns a list of non-interpolated values found in a immediate vicinity of requested point.
/// <remarks>
/// If a GetValue method returns a exact match - this method should be returning null.
/// </remarks>
/// </summary>
/// <param name="termCurve"></param>
/// <param name="date"></param>
/// <returns></returns>
public static TermPoint GetPreviousPoint(TermCurve termCurve, DateTime date)
{
var dates = termCurve.GetListTermDates();//GetDiscreteSpace().GetCoordinateArray(1);
var values = termCurve.GetListMidValues();
var index = Array.BinarySearch(dates.ToArray(), date);
if (index >= 0)
{
return termCurve.point[index];
}
var nextIndex = ~index;
var prevIndex = nextIndex - 1;
//TODO check for DateTime1D point and return the date.
var prevPoint = TermPointFactory.Create(values[prevIndex], dates[prevIndex]);
return prevPoint;
}
/// <summary>
/// Returns a list of non-interpolated values found in a immediate vicinity of requested point.
/// <remarks>
/// If a GetValue method returns a exact match - this method should be returning null.
/// </remarks>
/// </summary>
/// <param name="termCurve"></param>
/// <param name="baseDate"></param>
/// <param name="dayCounter"></param>
/// <param name="date"></param>
/// <returns></returns>
public static Decimal InterpolateRate(TermCurve termCurve, DateTime baseDate, IDayCounter dayCounter, DateTime date)
{
var dates = termCurve.GetListTermDates();
var values = termCurve.GetListMidValues();
var index = Array.BinarySearch(dates.ToArray(), date);
if (index >= 0)
{
var result = termCurve.point[index].mid;
return result;
}
var nextIndex = ~index;
var prevIndex = nextIndex - 1;
var baseIndex = prevIndex - 1;
if (prevIndex == 0)
{
return values[prevIndex];//TODO check this.
}
var time1 = dayCounter.YearFraction(baseDate, dates[baseIndex]);
var time2 = dayCounter.YearFraction(baseDate, dates[prevIndex]);
var timei = dayCounter.YearFraction(baseDate, date);
var i1 = (time2-timei)/(time2-time1);
var i2 = (timei - time1) / (time2 - time1);
var r1 = (double)values[baseIndex];
var r2 = (double)values[prevIndex];
var rate = (i1*r1*time1 + i2*r2*time2)/timei;
//TODO check for DateTime1D point and return the date.
return (decimal)rate;
}
/// <summary>
/// Returns a list of non-interpolated values found in a immediate vicinity of requested point.
/// <remarks>
/// If a GetValue method returns a exact match - this method should be returning null.
/// </remarks>
/// </summary>
/// <param name="termCurve"></param>
/// <param name="baseDate"></param>
/// <param name="dayCounter"></param>
/// <param name="date"></param>
/// <returns></returns>
public static Decimal InterpolateRate2(TermCurve termCurve, DateTime baseDate, IDayCounter dayCounter, DateTime date)
{
var dates = termCurve.GetListTermDates();
var values = termCurve.GetListMidValues();
var index = Array.BinarySearch(dates.ToArray(), date);
if (index >= 0)
{
var result = termCurve.point[index].mid;
return result;
}
var nextIndex = ~index;
var prevIndex = nextIndex - 1;
var baseIndex = prevIndex - 1;
if (prevIndex == 0)
{
return values[prevIndex];//TODO check this.
}
var time1 = dayCounter.YearFraction(baseDate, dates[baseIndex]);
var time2 = dayCounter.YearFraction(baseDate, dates[nextIndex]);
var timei = dayCounter.YearFraction(baseDate, date);
var i1 = (time2 - timei) / (time2 - time1);
var i2 = (timei - time1) / (time2 - time1);
var r1 = (double)values[baseIndex];
var r2 = (double)values[nextIndex];
var rate = (i1 * r1 * time1 + i2 * r2 * time2) / timei;
//TODO check for DateTime1D point and return the date.
return (decimal)rate;
}
private static TermCurve Load(TermCurve termCurve, IList<DateTime> centralBankDates, DateTime baseDate, IDayCounter dayCounter)
{
var points = new List<TermPoint>(termCurve.point);
var counter = 0;
foreach(var point in termCurve.point)
{
var date = (DateTime) point.term.Items[0];
if (centralBankDates != null)
{
//dates are the central bank dates between the term curve node dates specified by the input instruments.
//TODO currently the intermediate central bank dates are forgotten.
//They need to be spliced into the term curve.
//Also, the interpolation routine needs to be set to the appropriate back fill/forward fill logic.
var dates = centralBankDates.Where(t => GetPreviousIndex(termCurve, t) == counter).ToList();
foreach (var centralBankDate in dates)
{
if (date == centralBankDate) continue;
if (dates.IndexOf(centralBankDate) == 1)
{
var termPoint =
TermPointFactory.Create(InterpolateRate(termCurve, baseDate, dayCounter, dates[0]), dates[0]);
points.Insert(GetPreviousIndex(termCurve, date), termPoint);
}
else
{
var termPoint =
TermPointFactory.Create(InterpolateRate2(termCurve, baseDate, dayCounter, centralBankDate), centralBankDate);
points.Insert(GetPreviousIndex(termCurve, date), termPoint);
}
}
}
counter++;
}
//TODO does this fix the problem?
//termCurve.point = points.ToArray();
return termCurve;
}
/// <summary>
/// Sorts a term curve.
/// <remarks>
/// No two dates are to be the same!
/// </remarks>
/// </summary>
/// <param name="termCurve"></param>
/// <returns></returns>
private static TermCurve SortPoints(TermCurve termCurve)
{
var points = new SortedList<DateTime, TermPoint>();
foreach (var point in termCurve.point)
{
points.Add((DateTime)point.term.Items[0], point);
}
points.Values.CopyTo(termCurve.point, 0);
return termCurve;
}
}
} | 43.435976 | 205 | 0.569523 | [
"BSD-3-Clause"
] | mmrath/Highlander.Net | FpML.V5r3.Components/CurveEngine/PricingStructures/Interpolators/GapStepInterpolator.cs | 14,247 | C# |
// cs1656-4.cs: Cannot assign to `i' because it is a `foreach iteration variable'
// Line: 14
using System.Collections;
class Test {
static IEnumerable foo () { return null; }
static void Main ()
{
IEnumerable f = foo ();
if (f != null)
foreach (int i in f)
i = 0;
}
}
| 16.882353 | 81 | 0.623693 | [
"Apache-2.0"
] | Sectoid/debian-mono | mcs/errors/cs1656-4.cs | 287 | C# |
#if !RELEASE_UNITY
using Newtonsoft.Json;
using System;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Nightscout.Net.Http
{
internal class HttpClientService : IHttpService, IDisposable
{
private readonly HttpClient _httpClient;
public HttpClientService(string baseURL, TimeSpan timeout, string userAgent)
{
HttpClientHandler handler = new HttpClientHandler
{
AutomaticDecompression = (DecompressionMethods.GZip | DecompressionMethods.Deflate)
};
_httpClient = new HttpClient(handler)
{
Timeout = timeout,
BaseAddress = new Uri(baseURL)
};
_httpClient.DefaultRequestHeaders.Add("User-Agent", userAgent);
}
public async Task<IHttpResponse> GetAsync(string url, CancellationToken token = default, IProgress<double>? progress = null)
{
// We read starting with the response headers so we can update the IProgress<double> if it exists, as well as stopping the body if necessary.
HttpResponseMessage message = await _httpClient.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, token).ConfigureAwait(false);
if (token.IsCancellationRequested)
throw new TaskCanceledException();
using MemoryStream ms = new MemoryStream();
using Stream streamedBody = await message.Content.ReadAsStreamAsync().ConfigureAwait(false);
long total = 0;
byte[] buffer = new byte[8192];
long? length = message.Content.Headers.ContentLength;
progress?.Report(0);
while (true)
{
int read = await streamedBody.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(false);
if (read <= 0)
break;
if (token.IsCancellationRequested)
throw new TaskCanceledException();
if (length.HasValue)
progress?.Report((double)total / length.Value);
await ms.WriteAsync(buffer, 0, read).ConfigureAwait(false);
total += read;
}
progress?.Report(1);
byte[] body = ms.ToArray();
return new HttpClientResponse(body, message);
}
public async Task<IHttpResponse> PostAsync(string url, object? body = null, CancellationToken token = default)
{
var serializedBody = new StringContent(JsonConvert.SerializeObject(body), Encoding.UTF8, "application/json");
HttpResponseMessage message = await _httpClient.PostAsync(url, serializedBody, token).ConfigureAwait(false);
return new HttpClientResponse(message);
}
public void Dispose()
{
GC.SuppressFinalize(this);
_httpClient.Dispose();
}
}
}
#endif | 37 | 153 | 0.618952 | [
"MIT"
] | legoandmars/Nightscout.Net | Nightscout.Net/Http/HttpClientService.cs | 2,999 | C# |
using System;
using System.Windows.Forms;
namespace Finder2
{
static class Program
{
/// <summary>
/// Главная точка входа для приложения.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
| 20 | 66 | 0.534091 | [
"MIT"
] | IllIgt/FilesFinder | Finder2/Program.cs | 472 | C# |
using NCalc;
using System;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.Windows.Forms;
namespace Transport
{
public partial class Report : Form
{
public Report()
{
InitializeComponent();
}
private void Report_Load(object sender, System.EventArgs e)
{
cmbMPS.SelectedIndex = -1;
txtBegin.Text = null;
txtEnd.Text = null;
txtHoursWorked.Text = null;
cmbDriver.SelectedIndex = -1;
txtNumber_p_list.Text = null;
txtNumber_tovar.Text = null;
cmbObjectBegin.SelectedIndex = -1;
cmbObjectEnd.SelectedIndex = -1;
cmbMaterial1.SelectedIndex = -1;
cmbMaterial2.SelectedIndex = -1;
cmbMaterial3.SelectedIndex = -1;
cmbMaterial4.SelectedIndex = -1;
txtKolichestvo1.Text = null;
txtKolichestvo2.Text = null;
txtKolichestvo3.Text = null;
txtKolichestvo4.Text = null;
cmbMerna_edinitsa1.SelectedIndex = -1;
cmbMerna_edinitsa2.SelectedIndex = -1;
cmbMerna_edinitsa3.SelectedIndex = -1;
cmbMerna_edinitsa4.SelectedIndex = -1;
txtGorivo.Text = null;
grdOtcheti.DataSource = null;
string connectionString = null;
SqlConnection conn;
connectionString = "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=Transport;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";
conn = new SqlConnection(connectionString);
SqlCommand cmd1 = new SqlCommand();
SqlCommand cmd2 = new SqlCommand();
SqlCommand cmd3 = new SqlCommand();
SqlCommand cmd31 = new SqlCommand();
SqlCommand cmd41 = new SqlCommand();
SqlCommand cmd42 = new SqlCommand();
SqlCommand cmd43 = new SqlCommand();
SqlCommand cmd44 = new SqlCommand();
cmd1.Connection = conn;
cmd2.Connection = conn;
cmd3.Connection = conn;
cmd31.Connection = conn;
cmd41.Connection = conn;
cmd42.Connection = conn;
cmd43.Connection = conn;
cmd44.Connection = conn;
cmd1.CommandText = "SELECT ИД, Рег_номер FROM МПС";
cmd2.CommandText = "SELECT ИД, Пълно_име FROM Шофьор";
cmd3.CommandText = "SELECT ИД, Наименование from Обект";
cmd31.CommandText = "SELECT ИД, Наименование from Обект";
cmd41.CommandText = "SELECT ИД, Вид FROM Материал";
cmd42.CommandText = "SELECT ИД, Вид FROM Материал";
cmd43.CommandText = "SELECT ИД, Вид FROM Материал";
cmd44.CommandText = "SELECT ИД, Вид FROM Материал";
SqlDataReader reader1, reader2, reader3, reader31, reader41, reader42, reader43, reader44;
DataTable dt1 = new DataTable();
DataTable dt2 = new DataTable();
DataTable dt3 = new DataTable();
DataTable dt31 = new DataTable();
DataTable dt41 = new DataTable();
DataTable dt42 = new DataTable();
DataTable dt43 = new DataTable();
DataTable dt44 = new DataTable();
conn.Open();
reader1 = cmd1.ExecuteReader();
dt1.Columns.Add("Рег_номер", typeof(string));
dt1.Load(reader1);
cmbMPS.ValueMember = dt1.Columns[1].ToString();
cmbMPS.DisplayMember = dt1.Columns[0].ToString();
cmbMPS.DataSource = dt1;
cmbMPS.SelectedIndex = -1;
conn.Close();
conn.Open();
reader2 = cmd2.ExecuteReader();
dt2.Columns.Add("Пълно_име", typeof(string));
dt2.Load(reader2);
cmbDriver.ValueMember = dt2.Columns[1].ToString();
cmbDriver.DisplayMember = dt2.Columns[0].ToString();
cmbDriver.DataSource = dt2;
cmbDriver.SelectedIndex = -1;
conn.Close();
conn.Open();
reader3 = cmd3.ExecuteReader();
dt3.Columns.Add("Наименование", typeof(string));
dt3.Load(reader3);
cmbObjectBegin.ValueMember = dt3.Columns[1].ToString();
cmbObjectBegin.DisplayMember = dt3.Columns[0].ToString();
cmbObjectBegin.DataSource = dt3;
cmbObjectBegin.SelectedIndex = -1;
conn.Close();
conn.Open();
reader31 = cmd31.ExecuteReader();
dt31.Columns.Add("Наименование", typeof(string));
dt31.Load(reader31);
cmbObjectEnd.ValueMember = dt31.Columns[1].ToString();
cmbObjectEnd.DisplayMember = dt31.Columns[0].ToString();
cmbObjectEnd.DataSource = dt31;
cmbObjectEnd.SelectedIndex = -1;
conn.Close();
conn.Open();
reader41 = cmd41.ExecuteReader();
dt41.Columns.Add("Вид", typeof(string));
dt41.Load(reader41);
cmbMaterial1.ValueMember = dt41.Columns[1].ToString();
cmbMaterial1.DisplayMember = dt41.Columns[0].ToString();
cmbMaterial1.DataSource = dt41;
cmbMaterial1.SelectedIndex = -1;
conn.Close();
conn.Open();
reader42 = cmd42.ExecuteReader();
dt42.Columns.Add("Вид", typeof(string));
dt42.Load(reader42);
cmbMaterial2.ValueMember = dt42.Columns[1].ToString();
cmbMaterial2.DisplayMember = dt42.Columns[0].ToString();
cmbMaterial2.DataSource = dt42;
cmbMaterial2.SelectedIndex = -1;
conn.Close();
conn.Open();
reader43 = cmd43.ExecuteReader();
dt43.Columns.Add("Вид", typeof(string));
dt43.Load(reader43);
cmbMaterial3.ValueMember = dt43.Columns[1].ToString();
cmbMaterial3.DisplayMember = dt43.Columns[0].ToString();
cmbMaterial3.DataSource = dt43;
cmbMaterial3.SelectedIndex = -1;
conn.Close();
conn.Open();
reader44 = cmd44.ExecuteReader();
dt44.Columns.Add("Вид", typeof(string));
dt44.Load(reader44);
cmbMaterial4.ValueMember = dt44.Columns[1].ToString();
cmbMaterial4.DisplayMember = dt44.Columns[0].ToString();
cmbMaterial4.DataSource = dt44;
cmbMaterial4.SelectedIndex = -1;
conn.Close();
}
private void btnAdd_Click(object sender, System.EventArgs e)
{
string dateString, reg_number, full_name, objectBegin, objectEnd;
string[] vid = new string[4];
String[] kolichestvo_text = new String[4];
string[] merna_edinitsa = new string[4];
decimal begin_km, end_km, km_tovaritelnitsa, km, gorivo;
String begin_Km, end_Km, km_Tovaritelnitsa, Km, Gorivo;
decimal[] kolichestvo_sum = new decimal[4];
int nomer_paten_list, nomer_tovaritelnitsa, hours_worked;
bool[] hasError = new bool[4];
CultureInfo culture = new CultureInfo("bg-BG");
string connectionString = null;
SqlConnection conn;
connectionString = "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=Transport;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";
conn = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = "INSERT INTO Отчет values (@Data, @MPS, @Begin_km, @End_km, @Km_tovaritelnitsa, @Hours_worked, @Shofior, @Number_paten_list, @Number_tovaritelnitsa, @ObjectBegin, @ObjectEnd, @Material_1, @Material_2, @Material_3, @Material_4, @Kolichestvo_text_1, @Kolichestvo_text_2, @Kolichestvo_text_3, @Kolichestvo_text_4, @Kolichestvo_suma_1, @Kolichestvo_suma_2, @Kolichestvo_suma_3, @Kolichestvo_suma_4, @Merna_edinitsa_1, @Merna_edinitsa_2, @Merna_edinitsa_3, @Merna_edinitsa_4, @Km, @Gorivo)";
dateString = dtpDateFrom.Value.ToShortDateString();
DateTime date = DateTime.Parse(dateString, culture);
reg_number = cmbMPS.Text;
if (txtBegin.Text == "")
{
begin_km = 0;
}
else
{
begin_Km = txtBegin.Text;
begin_Km = begin_Km.Replace(",", ".");
begin_km = decimal.Parse(begin_Km, new CultureInfo("en-US"));
}
if (txtEnd.Text == "")
{
end_km = 0;
}
else
{
end_Km = txtEnd.Text;
end_Km = end_Km.Replace(",", ".");
end_km = decimal.Parse(end_Km, new CultureInfo("en-US"));
}
if (txtKmTovaritelnitsa.Text == "")
{
km_tovaritelnitsa = 0;
}
else
{
km_Tovaritelnitsa = txtKmTovaritelnitsa.Text;
km_Tovaritelnitsa = km_Tovaritelnitsa.Replace(",", ".");
km_tovaritelnitsa = decimal.Parse(km_Tovaritelnitsa, new CultureInfo("en-US"));
}
if (txtHoursWorked.Text == "")
{
hours_worked = 0;
}
else
{
hours_worked = int.Parse(txtHoursWorked.Text);
}
full_name = cmbDriver.Text;
nomer_paten_list = int.Parse(txtNumber_p_list.Text);
nomer_tovaritelnitsa = int.Parse(txtNumber_tovar.Text);
objectBegin = cmbObjectBegin.Text;
objectEnd = cmbObjectEnd.Text;
vid[0] = cmbMaterial1.Text;
vid[1] = cmbMaterial2.Text;
vid[2] = cmbMaterial3.Text;
vid[3] = cmbMaterial4.Text;
kolichestvo_text[0] = txtKolichestvo1.Text;
kolichestvo_text[1] = txtKolichestvo2.Text;
kolichestvo_text[2] = txtKolichestvo3.Text;
kolichestvo_text[3] = txtKolichestvo4.Text;
Expression[] expr = new Expression[4];
for (int i = 0; i < 4; i++)
{
if (kolichestvo_text[i] == "")
{
kolichestvo_sum[i] = 0;
kolichestvo_text[i] = "0";
expr[i] = new Expression(kolichestvo_text[i]);
hasError[i] = expr[i].HasErrors();
}
else
{
kolichestvo_text[i] = kolichestvo_text[i].Replace(",", ".");
expr[i] = new Expression(kolichestvo_text[i]);
hasError[i] = expr[i].HasErrors();
if (hasError[i] == true)
{
MessageBox.Show("Въведеният израз е НЕВАЛИДЕН!");
kolichestvo_sum[i] = 0;
}
else
{
kolichestvo_sum[i] = Convert.ToDecimal(expr[i].Evaluate());
}
}
}
merna_edinitsa[0] = cmbMerna_edinitsa1.Text;
merna_edinitsa[1] = cmbMerna_edinitsa2.Text;
merna_edinitsa[2] = cmbMerna_edinitsa3.Text;
merna_edinitsa[3] = cmbMerna_edinitsa4.Text;
km = end_km - begin_km;
if (txtGorivo.Text == "")
{
gorivo = 0;
}
else
{
Gorivo = txtGorivo.Text;
Gorivo = Gorivo.Replace(",", ".");
gorivo = decimal.Parse(Gorivo, new CultureInfo("en-US"));
}
cmd.Parameters.AddWithValue("@Data", date);
cmd.Parameters.AddWithValue("@MPS", reg_number);
cmd.Parameters.AddWithValue("@Begin_km", begin_km);
cmd.Parameters.AddWithValue("@End_km", end_km);
cmd.Parameters.AddWithValue("@Km_tovaritelnitsa", km_tovaritelnitsa);
cmd.Parameters.AddWithValue("@Hours_worked", hours_worked);
cmd.Parameters.AddWithValue("@Shofior", full_name);
cmd.Parameters.AddWithValue("@Number_paten_list", nomer_paten_list);
cmd.Parameters.AddWithValue("@Number_tovaritelnitsa", nomer_tovaritelnitsa);
cmd.Parameters.AddWithValue("@ObjectBegin", objectBegin);
cmd.Parameters.AddWithValue("@ObjectEnd", objectEnd);
cmd.Parameters.AddWithValue("@Material_1", vid[0]);
cmd.Parameters.AddWithValue("@Material_2", vid[1]);
cmd.Parameters.AddWithValue("@Material_3", vid[2]);
cmd.Parameters.AddWithValue("@Material_4", vid[3]);
cmd.Parameters.AddWithValue("@Kolichestvo_text_1", kolichestvo_text[0]);
cmd.Parameters.AddWithValue("@Kolichestvo_text_2", kolichestvo_text[1]);
cmd.Parameters.AddWithValue("@Kolichestvo_text_3", kolichestvo_text[2]);
cmd.Parameters.AddWithValue("@Kolichestvo_text_4", kolichestvo_text[3]);
cmd.Parameters.AddWithValue("@Kolichestvo_suma_1", kolichestvo_sum[0]);
cmd.Parameters.AddWithValue("@Kolichestvo_suma_2", kolichestvo_sum[1]);
cmd.Parameters.AddWithValue("@Kolichestvo_suma_3", kolichestvo_sum[2]);
cmd.Parameters.AddWithValue("@Kolichestvo_suma_4", kolichestvo_sum[3]);
cmd.Parameters.AddWithValue("@Merna_edinitsa_1", merna_edinitsa[0]);
cmd.Parameters.AddWithValue("@Merna_edinitsa_2", merna_edinitsa[1]);
cmd.Parameters.AddWithValue("@Merna_edinitsa_3", merna_edinitsa[2]);
cmd.Parameters.AddWithValue("@Merna_edinitsa_4", merna_edinitsa[3]);
cmd.Parameters.AddWithValue("@Km", km);
cmd.Parameters.AddWithValue("@Gorivo", gorivo);
try
{
conn.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("Данните са въведени успешно!!!");
cmbMPS.SelectedIndex = -1;
txtBegin.Text = null;
txtEnd.Text = null;
txtKmTovaritelnitsa.Text = null;
txtHoursWorked.Text = null;
cmbDriver.SelectedIndex = -1;
txtNumber_p_list.Text = null;
txtNumber_tovar.Text = null;
cmbObjectBegin.SelectedIndex = -1;
cmbObjectEnd.SelectedIndex = -1;
cmbMaterial1.SelectedIndex = -1;
cmbMaterial2.SelectedIndex = -1;
cmbMaterial3.SelectedIndex = -1;
cmbMaterial4.SelectedIndex = -1;
txtKolichestvo1.Text = null;
txtKolichestvo2.Text = null;
txtKolichestvo3.Text = null;
txtKolichestvo4.Text = null;
cmbMerna_edinitsa1.SelectedIndex = -1;
cmbMerna_edinitsa2.SelectedIndex = -1;
cmbMerna_edinitsa3.SelectedIndex = -1;
cmbMerna_edinitsa4.SelectedIndex = -1;
txtGorivo.Text = null;
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Базата данни не се отваря, защото въведените данни съществуват в нея!");
}
}
private void btnClose_Click(object sender, EventArgs e)
{
this.Close();
}
private void btnShow_Click(object sender, EventArgs e)
{
string dateString1, dateString2, reg_number, full_name, object_begin, object_end;
string[] vid = new string[4];
int day1, day2, month1, month2, year1, year2;
string dateStr1, dateStr2;
reg_number = cmbMPS.Text;
full_name = cmbDriver.Text;
object_begin = cmbObjectBegin.Text;
object_end = cmbObjectEnd.Text;
vid[0] = cmbMaterial1.Text;
vid[1] = cmbMaterial2.Text;
vid[2] = cmbMaterial3.Text;
vid[3] = cmbMaterial4.Text;
CultureInfo culture = new CultureInfo("bg-BG");
string connectionString = null;
SqlConnection conn;
connectionString = "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=Transport;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";
conn = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
dateString1 = dtpDateFrom.Value.ToShortDateString();
dateString2 = dtpDateTo.Value.ToShortDateString();
DateTime date1 = DateTime.Parse(dateString1, culture);
DateTime date2 = DateTime.Parse(dateString2, culture);
day1 = date1.Day;
day2 = date2.Day;
month1 = date1.Month;
month2 = date2.Month;
year1 = date1.Year;
year2 = date2.Year;
if (month1 >= 1 && month1 <= 9)
{
if (day1 >= 1 && day1 <= 9)
{
dateStr1 = year1 + "-0" + month1 + "-0" + day1;
}
else
{
dateStr1 = year1 + "-0" + month1 + "-" + day1;
}
}
else
{
if (day1 >= 1 && day1 <= 9)
{
dateStr1 = year1 + "-" + month1 + "-0" + day1;
}
else
{
dateStr1 = year1 + "-" + month1 + "-" + day1;
}
}
if (month2 >= 1 && month2 <= 9)
{
if (day2 >= 1 && day2 <= 9)
{
dateStr2 = year2 + "-0" + month2 + "-0" + day2;
}
else
{
dateStr2 = year2 + "-0" + month2 + "-" + day2;
}
}
else
{
if (day2 >= 1 && day2 <= 9)
{
dateStr2 = year2 + "-" + month2 + "-0" + day2;
}
else
{
dateStr2 = year2 + "-" + month2 + "-" + day2;
}
}
if (cmbMPS.SelectedIndex != -1)
{
cmd.CommandText = "SELECT ИД, Дата, МПС, Начало_км, Край_км, Км_товарителница, Отработени_часове, Шофьор, Номер_пътен_лист, Номер_товарителница, Обект_начало, Обект_край, Материал_1, Материал_2, Материал_3, Материал_4, Количество_сума_1, Количество_сума_2, Количество_сума_3, Количество_сума_4, Мерна_единица_1, Мерна_единица_2, Мерна_единица_3, Мерна_единица_4, Км, Гориво FROM Отчет WHERE (Дата between '" + dateStr1 + "' AND '" + dateStr2 + "') AND МПС = N'" + reg_number + "'";
//MessageBox.Show(cmd.CommandText);
}
else if(cmbDriver.SelectedIndex != -1)
{
cmd.CommandText = "SELECT ИД, Дата, МПС, Начало_км, Край_км, Км_товарителница, Отработени_часове, Шофьор, Номер_пътен_лист, Номер_товарителница, Обект_начало, Обект_край, Материал_1, Материал_2, Материал_3, Материал_4, Количество_сума_1, Количество_сума_2, Количество_сума_3, Количество_сума_4, Мерна_единица_1, Мерна_единица_2, Мерна_единица_3, Мерна_единица_4, Км, Гориво FROM Отчет WHERE (Дата between '" + dateStr1 + "' AND '" + dateStr2 + "') AND Шофьор = N'" + full_name + "'";
}
else if(cmbObjectBegin.SelectedIndex != -1)
{
cmd.CommandText = "SELECT ИД, Дата, МПС, Начало_км, Край_км, Км_товарителница, Отработени_часове, Шофьор, Номер_пътен_лист, Номер_товарителница, Обект_начало, Обект_край, Материал_1, Материал_2, Материал_3, Материал_4, Количество_сума_1, Количество_сума_2, Количество_сума_3, Количество_сума_4, Мерна_единица_1, Мерна_единица_2, Мерна_единица_3, Мерна_единица_4, Км, Гориво FROM Отчет WHERE (Дата between '" + dateStr1 + "' AND '" + dateStr2 + "') AND Обект_начало = N'" + object_begin + "'";
}
else if(cmbMaterial1.SelectedIndex != -1)
{
cmd.CommandText = "SELECT ИД, Дата, МПС, Начало_км, Край_км, Км_товарителница, Отработени_часове, Шофьор, Номер_пътен_лист, Номер_товарителница, Обект_начало, Обект_край, Материал_1, Материал_2, Материал_3, Материал_4, Количество_сума_1, Количество_сума_2, Количество_сума_3, Количество_сума_4, Мерна_единица_1, Мерна_единица_2, Мерна_единица_3, Мерна_единица_4, Км, Гориво FROM Отчет WHERE (Дата between '" + dateStr1 + "' AND '" + dateStr2 + "') AND Материал_1 = N'" + vid[0] + "'";
}
else if(cmbMaterial2.SelectedIndex != -1)
{
cmd.CommandText = "SELECT ИД, Дата, МПС, Начало_км, Край_км, Км_товарителница, Отработени_часове, Шофьор, Номер_пътен_лист, Номер_товарителница, Обект_начало, Обект_край, Материал_1, Материал_2, Материал_3, Материал_4, Количество_сума_1, Количество_сума_2, Количество_сума_3, Количество_сума_4, Мерна_единица_1, Мерна_единица_2, Мерна_единица_3, Мерна_единица_4, Км, Гориво FROM Отчет WHERE (Дата between '" + dateStr1 + "' AND '" + dateStr2 + "') AND Материал_2 = N'" + vid[1] + "'";
}
else if(cmbMaterial3.SelectedIndex != -1)
{
cmd.CommandText = "SELECT ИД, Дата, МПС, Начало_км, Край_км, Км_товарителница, Отработени_часове, Шофьор, Номер_пътен_лист, Номер_товарителница, Обект_начало, Обект_край, Материал_1, Материал_2, Материал_3, Материал_4, Количество_сума_1, Количество_сума_2, Количество_сума_3, Количество_сума_4, Мерна_единица_1, Мерна_единица_2, Мерна_единица_3, Мерна_единица_4, Км, Гориво FROM Отчет WHERE (Дата between '" + dateStr1 + "' AND '" + dateStr2 + "') AND Материал_3 = N'" + vid[2] + "'";
}
else if(cmbMaterial4.SelectedIndex != -1)
{
cmd.CommandText = "SELECT ИД, Дата, МПС, Начало_км, Край_км, Км_товарителница, Отработени_часове, Шофьор, Номер_пътен_лист, Номер_товарителница, Обект_начало, Обект_край, Материал_1, Материал_2, Материал_3, Материал_4, Количество_сума_1, Количество_сума_2, Количество_сума_3, Количество_сума_4, Мерна_единица_1, Мерна_единица_2, Мерна_единица_3, Мерна_единица_4, Км, Гориво FROM Отчет WHERE (Дата between '" + dateStr1 + "' AND '" + dateStr2 + "') AND Материал_4 = N'" + vid[3] + "'";
}
else if (cmbMPS.SelectedIndex == -1 && cmbDriver.SelectedIndex == -1 && cmbObjectBegin.SelectedIndex == -1 && cmbObjectEnd.SelectedIndex == -1 && cmbMaterial1.SelectedIndex == -1)
{
cmd.CommandText = "SELECT ИД, Дата, МПС, Начало_км, Край_км, Км_товарителница, Отработени_часове, Шофьор, Номер_пътен_лист, Номер_товарителница, Обект_начало, Обект_край, Материал_1, Материал_2, Материал_3, Материал_4, Количество_сума_1, Количество_сума_2, Количество_сума_3, Количество_сума_4, Мерна_единица_1, Мерна_единица_2, Мерна_единица_3, Мерна_единица_4, Км, Гориво FROM Отчет WHERE (Дата between '" + dateStr1 + "' AND '" + dateStr2 + "')";
}
SqlDataAdapter dAdapter = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
dAdapter.Fill(ds);
grdOtcheti.ReadOnly = true;
grdOtcheti.DataSource = ds.Tables[0];
grdOtcheti.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
conn.Close();
}
private void txtClean_Click(object sender, EventArgs e)
{
cmbMPS.SelectedIndex = -1; ;
txtBegin.Text = null;
txtEnd.Text = null;
txtHoursWorked.Text = null;
cmbDriver.SelectedIndex = -1;
txtNumber_p_list.Text = null;
txtNumber_tovar.Text = null;
cmbObjectBegin.SelectedIndex = -1;
cmbObjectEnd.SelectedIndex = -1;
cmbMaterial1.SelectedIndex = -1;
cmbMaterial2.SelectedIndex = -1;
cmbMaterial3.SelectedIndex = -1;
cmbMaterial4.SelectedIndex = -1;
txtKolichestvo1.Text = null;
txtKolichestvo2.Text = null;
txtKolichestvo3.Text = null;
txtKolichestvo4.Text = null;
cmbMerna_edinitsa1.SelectedIndex = -1;
cmbMerna_edinitsa2.SelectedIndex = -1;
cmbMerna_edinitsa3.SelectedIndex = -1;
cmbMerna_edinitsa4.SelectedIndex = -1;
txtGorivo.Text = null;
grdOtcheti.DataSource = null;
}
private void btnLoad_Click(object sender, EventArgs e)
{
int nomer_paten_list, nomer_tovaritelnitsa;
string dateString;
String MPS, full_name, objekt_begin, object_end;
String[] material = new String[4];
String[] merna_edinitsa = new String[4];
nomer_paten_list = 0;
nomer_tovaritelnitsa = 0;
dateString = null;
MPS = null;
full_name = null;
objekt_begin = null;
object_end = null;
material[0] = null;
material[1] = null;
material[2] = null;
material[3] = null;
merna_edinitsa[0] = null;
merna_edinitsa[1] = null;
merna_edinitsa[2] = null;
merna_edinitsa[3] = null;
CultureInfo culture = new CultureInfo("bg-BG");
string connectionString = null;
SqlConnection conn;
connectionString = "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=Transport;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";
conn = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = "SELECT ИД, Дата, МПС, Начало_км, Край_км, Км_товарителница, Отработени_часове, Шофьор, Номер_пътен_лист, Номер_товарителница, Обект_начало, Обект_край, Материал_1, Материал_2, Материал_3, Материал_4, Количество_текст_1, Количество_текст_2, Количество_текст_3, Количество_текст_4, Мерна_единица_1, Мерна_единица_2, Мерна_единица_3, Мерна_единица_4, Км, Гориво FROM Отчет WHERE (Номер_пътен_лист=@Number_paten_list AND Номер_товарителница=@Number_tovaritelnitsa)";
nomer_paten_list = int.Parse(txtNumber_p_list.Text);
nomer_tovaritelnitsa = int.Parse(txtNumber_tovar.Text);
cmd.Parameters.AddWithValue("@Number_paten_list", nomer_paten_list);
cmd.Parameters.AddWithValue("@Number_tovaritelnitsa", nomer_tovaritelnitsa);
dateString = dtpDateFrom.Value.ToShortDateString();
cmbMPS.SelectedIndex = -1;
cmbDriver.SelectedIndex = -1;
cmbMerna_edinitsa1.SelectedIndex = -1;
cmbMerna_edinitsa2.SelectedIndex = -1;
cmbMerna_edinitsa3.SelectedIndex = -1;
cmbMerna_edinitsa4.SelectedIndex = -1;
if (nomer_paten_list != 0 && nomer_tovaritelnitsa != 0)
{
conn.Open();
SqlDataReader sdr = cmd.ExecuteReader();
sdr.Read();
dtpDateFrom.CustomFormat = "dd-MM-yyyy";
dtpDateFrom.Value = Convert.ToDateTime(sdr["Дата"].ToString());
MPS = sdr["МПС"].ToString();
MPS = MPS.Trim();
cmbMPS.SelectedText = MPS;
txtBegin.Text = sdr["Начало_км"].ToString();
txtEnd.Text = sdr["Край_км"].ToString();
txtKmTovaritelnitsa.Text = sdr["Км_товарителница"].ToString();
txtHoursWorked.Text = sdr["Отработени_часове"].ToString();
full_name = sdr["Шофьор"].ToString();
full_name = full_name.Trim();
cmbDriver.SelectedText = full_name;
txtNumber_p_list.Text = sdr["Номер_пътен_лист"].ToString();
txtNumber_tovar.Text = sdr["Номер_товарителница"].ToString();
objekt_begin = sdr["Обект_начало"].ToString();
objekt_begin = objekt_begin.Trim();
cmbObjectBegin.SelectedText = objekt_begin;
object_end = sdr["Обект_край"].ToString();
object_end = object_end.Trim();
cmbObjectEnd.SelectedText = object_end;
material[0] = sdr["Материал_1"].ToString();
material[0] = material[0].Trim();
cmbMaterial1.SelectedText = material[0];
material[1] = sdr["Материал_2"].ToString();
material[1] = material[1].Trim();
cmbMaterial2.SelectedText = material[1];
material[2] = sdr["Материал_3"].ToString();
material[2] = material[2].Trim();
cmbMaterial3.SelectedText = material[2];
material[3] = sdr["Материал_4"].ToString();
material[3] = material[3].Trim();
cmbMaterial4.SelectedText = material[3];
txtKolichestvo1.Text = sdr["Количество_текст_1"].ToString();
txtKolichestvo2.Text = sdr["Количество_текст_2"].ToString();
txtKolichestvo3.Text = sdr["Количество_текст_3"].ToString();
txtKolichestvo4.Text = sdr["Количество_текст_4"].ToString();
merna_edinitsa[0] = sdr["Мерна_единица_1"].ToString();
merna_edinitsa[0] = merna_edinitsa[0].Trim();
cmbMerna_edinitsa1.SelectedText = merna_edinitsa[0];
merna_edinitsa[1] = sdr["Мерна_единица_2"].ToString();
merna_edinitsa[1] = merna_edinitsa[1].Trim();
cmbMerna_edinitsa2.SelectedText = merna_edinitsa[1];
merna_edinitsa[2] = sdr["Мерна_единица_3"].ToString();
merna_edinitsa[2] = merna_edinitsa[2].Trim();
cmbMerna_edinitsa3.SelectedText = merna_edinitsa[2];
merna_edinitsa[3] = sdr["Мерна_единица_4"].ToString();
merna_edinitsa[3] = merna_edinitsa[3].Trim();
cmbMerna_edinitsa4.SelectedText = merna_edinitsa[3];
txtGorivo.Text = sdr["Гориво"].ToString();
conn.Close();
}
}
private void btnEdit_Click(object sender, EventArgs e)
{
string dateString, model, full_name, objekt_begin, object_end;
string[] vid = new string[4];
String[] kolichestvo_text = new String[4];
string[] merna_edinitsa = new string[4];
decimal begin_km, end_km, km_tovaritelnitsa, km, gorivo;
String begin_Km, end_Km, km_Tovaritelnitsa, Km, Gorivo;
decimal[] kolichestvo_sum = new decimal[4];
int nomer_paten_list, nomer_tovaritelnitsa, hours_worked;
bool[] hasError=new bool[4];
CultureInfo culture = new CultureInfo("bg-BG");
string connectionString = null;
SqlConnection conn;
connectionString = "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=Transport;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";
conn = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = "UPDATE Отчет SET Дата=@Data, МПС=@MPS, Начало_км=@Begin_km, Край_км=@End_km, Км_товарителница=@Km_tovaritelnitsa, Отработени_часове=@Hours_worked, Шофьор=@Shofior, Обект_начало=@Object_begin, Обект_край=@Object_end, Материал_1=@Material_1, Материал_2=@Material_2, Материал_3=@Material_3, Материал_4=@Material_4, Количество_текст_1=@Kolichestvo_text_1, Количество_текст_2=@Kolichestvo_text_2, Количество_текст_3=@Kolichestvo_text_3, Количество_текст_4=@Kolichestvo_text_4, Количество_сума_1=@Kolichestvo_suma_1, Количество_сума_2=@Kolichestvo_suma_2, Количество_сума_3=@Kolichestvo_suma_3, Количество_сума_4=@Kolichestvo_suma_4, Мерна_единица_1=@Merna_edinitsa_1, Мерна_единица_2=@Merna_edinitsa_2, Мерна_единица_3=@Merna_edinitsa_3, Мерна_единица_4=@Merna_edinitsa_4, Км=@Km, Гориво=@Gorivo WHERE (Номер_пътен_лист=@Number_paten_list AND Номер_товарителница=@Number_tovaritelnitsa)";
dateString = dtpDateFrom.Value.ToShortDateString();
DateTime date = DateTime.Parse(dateString, culture);
model = cmbMPS.Text;
begin_Km = txtBegin.Text;
begin_Km = begin_Km.Replace(",", ".");
begin_km = decimal.Parse(begin_Km, new CultureInfo("en-US"));
end_Km = txtEnd.Text;
end_Km = end_Km.Replace(",", ".");
end_km = decimal.Parse(end_Km, new CultureInfo("en-US"));
km_Tovaritelnitsa = txtKmTovaritelnitsa.Text;
km_Tovaritelnitsa = km_Tovaritelnitsa.Replace(",", ".");
km_tovaritelnitsa = decimal.Parse(km_Tovaritelnitsa, new CultureInfo("en-US"));
hours_worked = int.Parse(txtHoursWorked.Text);
full_name = cmbDriver.Text;
nomer_paten_list = int.Parse(txtNumber_p_list.Text);
nomer_tovaritelnitsa = int.Parse(txtNumber_tovar.Text);
objekt_begin = cmbObjectBegin.Text;
object_end = cmbObjectEnd.Text;
vid[0] = cmbMaterial1.Text;
vid[1] = cmbMaterial2.Text;
vid[2] = cmbMaterial3.Text;
vid[3] = cmbMaterial4.Text;
kolichestvo_text[0] = txtKolichestvo1.Text;
kolichestvo_text[0] = kolichestvo_text[0].Replace(",", ".");
kolichestvo_text[1] = txtKolichestvo2.Text;
kolichestvo_text[1] = kolichestvo_text[1].Replace(",", ".");
kolichestvo_text[2] = txtKolichestvo3.Text;
kolichestvo_text[2] = kolichestvo_text[2].Replace(",", ".");
kolichestvo_text[3] = txtKolichestvo4.Text;
kolichestvo_text[3] = kolichestvo_text[3].Replace(",", ".");
Expression[] expr = new Expression[4];
for (int i = 0; i < 4; i++)
{
if (kolichestvo_text[i] == "")
{
kolichestvo_sum[i] = 0;
kolichestvo_text[i] = "0";
expr[i] = new Expression(kolichestvo_text[i]);
hasError[i] = expr[i].HasErrors();
}
else
{
expr[i] = new Expression(kolichestvo_text[i]);
hasError[i] = expr[i].HasErrors();
if (hasError[i] == true)
{
MessageBox.Show("Въведеният израз е НЕВАЛИДЕН!");
kolichestvo_sum[i] = 0;
}
else
{
kolichestvo_sum[i] = Convert.ToDecimal(expr[i].Evaluate());
}
}
}
merna_edinitsa[0] = cmbMerna_edinitsa1.Text;
merna_edinitsa[1] = cmbMerna_edinitsa2.Text;
merna_edinitsa[2] = cmbMerna_edinitsa3.Text;
merna_edinitsa[3] = cmbMerna_edinitsa4.Text;
km = end_km - begin_km;
Gorivo = txtGorivo.Text;
Gorivo = Gorivo.Replace(",", ".");
gorivo = decimal.Parse(Gorivo, new CultureInfo("en-US"));
cmd.Parameters.AddWithValue("@Data", date);
cmd.Parameters.AddWithValue("@MPS", model);
cmd.Parameters.AddWithValue("@Begin_km", begin_km);
cmd.Parameters.AddWithValue("@End_km", end_km);
cmd.Parameters.AddWithValue("@Km_tovaritelnitsa", km_tovaritelnitsa);
cmd.Parameters.AddWithValue("@Hours_worked", hours_worked);
cmd.Parameters.AddWithValue("@Shofior", full_name);
cmd.Parameters.AddWithValue("@Number_paten_list", nomer_paten_list);
cmd.Parameters.AddWithValue("@Number_tovaritelnitsa", nomer_tovaritelnitsa);
cmd.Parameters.AddWithValue("@Object_begin", objekt_begin);
cmd.Parameters.AddWithValue("@Object_end", object_end);
cmd.Parameters.AddWithValue("@Material_1", vid[0]);
cmd.Parameters.AddWithValue("@Material_2", vid[1]);
cmd.Parameters.AddWithValue("@Material_3", vid[2]);
cmd.Parameters.AddWithValue("@Material_4", vid[3]);
cmd.Parameters.AddWithValue("@Kolichestvo_text_1", kolichestvo_text[0]);
cmd.Parameters.AddWithValue("@Kolichestvo_text_2", kolichestvo_text[1]);
cmd.Parameters.AddWithValue("@Kolichestvo_text_3", kolichestvo_text[2]);
cmd.Parameters.AddWithValue("@Kolichestvo_text_4", kolichestvo_text[3]);
cmd.Parameters.AddWithValue("@Kolichestvo_suma_1", kolichestvo_sum[0]);
cmd.Parameters.AddWithValue("@Kolichestvo_suma_2", kolichestvo_sum[1]);
cmd.Parameters.AddWithValue("@Kolichestvo_suma_3", kolichestvo_sum[2]);
cmd.Parameters.AddWithValue("@Kolichestvo_suma_4", kolichestvo_sum[3]);
cmd.Parameters.AddWithValue("@Merna_edinitsa_1", merna_edinitsa[0]);
cmd.Parameters.AddWithValue("@Merna_edinitsa_2", merna_edinitsa[1]);
cmd.Parameters.AddWithValue("@Merna_edinitsa_3", merna_edinitsa[2]);
cmd.Parameters.AddWithValue("@Merna_edinitsa_4", merna_edinitsa[3]);
cmd.Parameters.AddWithValue("@Km", km);
cmd.Parameters.AddWithValue("@Gorivo", gorivo);
try
{
conn.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("Данните са обновени успешно!!!");
cmbMPS.SelectedIndex = -1;
txtBegin.Text = null;
txtEnd.Text = null;
txtKmTovaritelnitsa.Text = null;
txtHoursWorked.Text = null;
cmbDriver.SelectedIndex = -1;
txtNumber_p_list.Text = null;
txtNumber_tovar.Text = null;
cmbObjectBegin.SelectedIndex = -1;
cmbObjectEnd.SelectedIndex = -1;
cmbMaterial1.SelectedIndex = -1;
cmbMaterial2.SelectedIndex = -1;
cmbMaterial3.SelectedIndex = -1;
cmbMaterial4.SelectedIndex = -1;
txtKolichestvo1.Text = null;
txtKolichestvo2.Text = null;
txtKolichestvo3.Text = null;
txtKolichestvo4.Text = null;
cmbMerna_edinitsa1.SelectedIndex = -1;
cmbMerna_edinitsa2.SelectedIndex = -1;
cmbMerna_edinitsa3.SelectedIndex = -1;
cmbMerna_edinitsa4.SelectedIndex = -1;
txtGorivo.Text = null;
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Базата данни не се отваря, защото се опитвате да обновите несъщестуващи данни!");
}
}
private void btnDelete_Click(object sender, EventArgs e)
{
int nomer_paten_list, nomer_tovaritelnitsa;
nomer_paten_list = 0;
nomer_tovaritelnitsa = 0;
string connectionString = null;
SqlConnection conn;
connectionString = "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=Transport;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";
conn = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = "DELETE FROM Отчет WHERE (Номер_пътен_лист=@Number_paten_list AND Номер_товарителница=@Number_tovaritelnitsa)";
nomer_paten_list = int.Parse(txtNumber_p_list.Text);
nomer_tovaritelnitsa = int.Parse(txtNumber_tovar.Text);
cmd.Parameters.AddWithValue("@Number_paten_list", nomer_paten_list);
cmd.Parameters.AddWithValue("@Number_tovaritelnitsa", nomer_tovaritelnitsa);
DialogResult deleteDb = MessageBox.Show("Искате ли да изтриете тези данни?", "Изтриване", MessageBoxButtons.YesNo);
if (deleteDb == DialogResult.Yes)
{
try
{
conn.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("Данните са изтрити успешно!!!");
cmbMPS.SelectedIndex = -1;
txtBegin.Text = null;
txtEnd.Text = null;
txtHoursWorked.Text = null;
cmbDriver.SelectedIndex = -1;
txtNumber_p_list.Text = null;
txtNumber_tovar.Text = null;
cmbObjectBegin.SelectedIndex = -1;
cmbMaterial1.SelectedIndex = -1;
cmbMaterial2.SelectedIndex = -1;
cmbMaterial3.SelectedIndex = -1;
cmbMaterial4.SelectedIndex = -1;
txtKolichestvo1.Text = null;
txtKolichestvo2.Text = null;
txtKolichestvo3.Text = null;
txtKolichestvo4.Text = null;
cmbMerna_edinitsa1.SelectedIndex = -1;
cmbMerna_edinitsa2.SelectedIndex = -1;
cmbMerna_edinitsa3.SelectedIndex = -1;
cmbMerna_edinitsa4.SelectedIndex = -1;
txtGorivo.Text = null;
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Базата данни не се отваря, защото се опитвате да изтриете несъщестуващи данни!");
}
}
else if (deleteDb == DialogResult.No)
{
}
}
private void btnExport_Click(object sender, EventArgs e)
{
Microsoft.Office.Interop.Excel._Application app = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel._Workbook workbook = app.Workbooks.Add(Type.Missing);
Microsoft.Office.Interop.Excel._Worksheet worksheet = null;
try
{
worksheet = workbook.ActiveSheet;
worksheet.Name = "Exported From DataGrid";
int cellRowIndex = 1;
int cellColumnIndex = 1;
for (int i = -1; i < grdOtcheti.Rows.Count - 1; i++)
{
for (int j = 0; j < grdOtcheti.Columns.Count; j++)
{
if (cellRowIndex == 1)
{
worksheet.Cells[cellRowIndex, cellColumnIndex] = grdOtcheti.Columns[j].HeaderText;
}
else
{
worksheet.Cells[cellRowIndex, cellColumnIndex] = grdOtcheti.Rows[i].Cells[j].Value.ToString();
}
cellColumnIndex++;
}
cellColumnIndex = 1;
cellRowIndex++;
}
SaveFileDialog saveDialog = new SaveFileDialog();
saveDialog.Filter = "Excel files (*.xlsx)|*.xlsx";
saveDialog.FilterIndex = 1;
if (saveDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
workbook.SaveAs(saveDialog.FileName);
MessageBox.Show("Експортирането на данните е успешно!!!");
}
}
catch (System.Exception ex)
{
MessageBox.Show("Данните не могат да се експортират! ");
}
finally
{
app.Quit();
workbook = null;
app = null;
}
}
}
}
| 51.326136 | 915 | 0.564394 | [
"MIT"
] | ivailo333/Transport | Transport/Report.cs | 48,830 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GasMaskSpawner : MonoBehaviour {
public GameObject gasMask;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
public void SpawnGasMask() {
Instantiate(gasMask, transform.position, transform.rotation);
}
}
| 16.954545 | 63 | 0.726542 | [
"MIT"
] | cmnvb/GGJ18-Team-Snack-Cupboard | Assets/Scripts/GasMaskSpawner.cs | 375 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// アセンブリに関する一般情報は以下の属性セットをとおして制御されます。
// アセンブリに関連付けられている情報を変更するには、
// これらの属性値を変更してください。
[assembly: AssemblyTitle("ConsoleApp1")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ConsoleApp1")]
[assembly: AssemblyCopyright("Copyright © 2018")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// ComVisible を false に設定すると、このアセンブリ内の型は COM コンポーネントから
// 参照できなくなります。COM からこのアセンブリ内の型にアクセスする必要がある場合は、
// その型の ComVisible 属性を true に設定してください。
[assembly: ComVisible(false)]
// このプロジェクトが COM に公開される場合、次の GUID が typelib の ID になります
[assembly: Guid("98670b35-86d6-4e69-bf81-c8276424919f")]
// アセンブリのバージョン情報は次の 4 つの値で構成されています:
//
// メジャー バージョン
// マイナー バージョン
// ビルド番号
// Revision
//
// すべての値を指定するか、次を使用してビルド番号とリビジョン番号を既定に設定できます
// 既定値にすることができます:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: log4net.Config.XmlConfigurator(ConfigFile = @"log4net.config", Watch = true)] | 30.789474 | 88 | 0.752137 | [
"MIT"
] | guitarrapc/CSharpPracticesLab | logger/log4net/DotNetFrameworkConsole/Properties/AssemblyInfo.cs | 1,757 | C# |
using Newtonsoft.Json;
namespace Domain.Entities
{
public class Product
{
public int Id { get; set; }
public string ProductName { get; set; }
public int CategorieId { get; set; }
public double Prijs { get; set; }
public bool Actief { get; set; }
[JsonIgnore]
public Categorie Categorie { get; set; }
}
} | 23.375 | 48 | 0.580214 | [
"MIT"
] | Kimo-sudo/Maccie | Domain/Entities/Product.cs | 376 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Threading.Tasks;
namespace idp.Responses
{
[DataContract]
public class BaseResponse
{
[DataMember(Name = "Error")]
public string ErrorCode { get; set; }
[DataMember(Name = "ErrorDesc")]
public string ErrorDescription { get; set; }
}
}
| 21.157895 | 52 | 0.671642 | [
"MIT"
] | apemon/ndid-examples-dotnet | idp/Responses/BaseResponse.cs | 404 | C# |
using GBCLV3.Models.Launch;
using Stylet;
namespace GBCLV3.ViewModels
{
public class LaunchStatusViewModel : Screen
{
#region Bindings
public bool IsInLaunchProcess =>
Status == LaunchStatus.LoggingIn ||
Status == LaunchStatus.ProcessingDependencies ||
Status == LaunchStatus.StartingProcess;
public bool IsSucceeded =>
Status == LaunchStatus.Running;
public bool IsFailed =>
Status == LaunchStatus.Failed;
public LaunchStatus Status { get; set; }
public string GameOutputLog { get; set; }
public void OnAnimationCompleted()
{
if (this.IsActive) this.RequestClose();
}
#endregion
}
}
| 22.939394 | 60 | 0.602378 | [
"MIT"
] | Lolle2000la/GBCLV3 | GBCLV3/ViewModels/LaunchStatusViewModel.cs | 759 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.0
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Documentation.Analyser
{
using System;
using System.Reflection;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources
{
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources()
{
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager
{
get
{
if (object.ReferenceEquals(resourceMan, null))
{
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Documentation.Analyser.Resources", typeof(Resources).GetTypeInfo().Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture
{
get
{
return resourceCulture;
}
set
{
resourceCulture = value;
}
}
/// <summary>
/// Looks up a localized string similar to Type names should be all uppercase..
/// </summary>
internal static string AnalyzerDescription
{
get
{
return ResourceManager.GetString("AnalyzerDescription", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Type name '{0}' contains lowercase letters.
/// </summary>
internal static string AnalyzerMessageFormat
{
get
{
return ResourceManager.GetString("AnalyzerMessageFormat", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Type name contains lowercase letters.
/// </summary>
internal static string AnalyzerTitle
{
get
{
return ResourceManager.GetString("AnalyzerTitle", resourceCulture);
}
}
}
}
| 36.336449 | 191 | 0.587963 | [
"Apache-2.0"
] | jimmymain/Documentation.Analyzers | Documentation.Analyser/Resources.Designer.cs | 3,888 | 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 datapipeline-2012-10-29.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.DataPipeline.Model
{
/// <summary>
/// Contains information about a pipeline task that is assigned to a task runner.
/// </summary>
public partial class TaskObject
{
private string _attemptId;
private Dictionary<string, PipelineObject> _objects = new Dictionary<string, PipelineObject>();
private string _pipelineId;
private string _taskId;
/// <summary>
/// Gets and sets the property AttemptId.
/// <para>
/// The ID of the pipeline task attempt object. AWS Data Pipeline uses this value to track
/// how many times a task is attempted.
/// </para>
/// </summary>
[AWSProperty(Min=1, Max=1024)]
public string AttemptId
{
get { return this._attemptId; }
set { this._attemptId = value; }
}
// Check to see if AttemptId property is set
internal bool IsSetAttemptId()
{
return this._attemptId != null;
}
/// <summary>
/// Gets and sets the property Objects.
/// <para>
/// Connection information for the location where the task runner will publish the output
/// of the task.
/// </para>
/// </summary>
public Dictionary<string, PipelineObject> Objects
{
get { return this._objects; }
set { this._objects = value; }
}
// Check to see if Objects property is set
internal bool IsSetObjects()
{
return this._objects != null && this._objects.Count > 0;
}
/// <summary>
/// Gets and sets the property PipelineId.
/// <para>
/// The ID of the pipeline that provided the task.
/// </para>
/// </summary>
[AWSProperty(Min=1, Max=1024)]
public string PipelineId
{
get { return this._pipelineId; }
set { this._pipelineId = value; }
}
// Check to see if PipelineId property is set
internal bool IsSetPipelineId()
{
return this._pipelineId != null;
}
/// <summary>
/// Gets and sets the property TaskId.
/// <para>
/// An internal identifier for the task. This ID is passed to the <a>SetTaskStatus</a>
/// and <a>ReportTaskProgress</a> actions.
/// </para>
/// </summary>
[AWSProperty(Min=1, Max=2048)]
public string TaskId
{
get { return this._taskId; }
set { this._taskId = value; }
}
// Check to see if TaskId property is set
internal bool IsSetTaskId()
{
return this._taskId != null;
}
}
} | 30.689076 | 110 | 0.586254 | [
"Apache-2.0"
] | FoxBearBear/aws-sdk-net | sdk/src/Services/DataPipeline/Generated/Model/TaskObject.cs | 3,652 | C# |
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Transactions;
using TransactionScopeExample.Models;
namespace TransactionScopeExample.DbLayer
{
public class DbQuiz
{
private static string CONNECTION_STRING = ConfigurationManager.ConnectionStrings["Default"].ConnectionString;
//Returns the correct answerId
public static int Create(Quiz quiz)
{
int correctAnswerId = -1;
TransactionOptions options = new TransactionOptions { IsolationLevel = IsolationLevel.ReadCommitted };//her kan i sætte isolation om nødvendigt
using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, options))
{
SqlConnection connection = new SqlConnection(CONNECTION_STRING);
connection.Open();
int quizId = InserQuizCommand(connection, quiz);
foreach (var answer in quiz.Answers)
{
answer.QuizId = quizId;
DbAnswer.InsertAnswerCommand(connection, answer);
if (answer.IsCorrectAnswer)
correctAnswerId = answer.AnswerId; //Den beskytter dog ikke imod at i har flere korrekte svar (kan ikke huske om det var muligt)
}
scope.Complete();
connection.Dispose();
}
return correctAnswerId;
}
public static int InserQuizCommand(SqlConnection con, Quiz quiz)
{
SqlCommand cmd = con.CreateCommand();
cmd.CommandText = "INSERT INTO Quiz (Title) OUTPUT Inserted.QuizId VALUES (@title)";
cmd.Parameters.AddWithValue("title", quiz.Title);
return (int)cmd.ExecuteScalar(); //returner det netop indsatte id
}
}
}
| 35.053571 | 155 | 0.631177 | [
"MIT"
] | rohansen/Code-Examples | Database/TransactionScopeExample/TransactionScopeExample/DbLayer/DbQuiz.cs | 1,967 | C# |
using AirplaneProject.Core.Interfaces;
using AirplaneProject.Core.Messages;
using AirplaneProject.Core.Models.Results;
using AirplaneProject.Domain.Bases;
using System;
using System.Threading.Tasks;
namespace AirplaneProject.Core.Models.Validations
{
public class EntityValidation<TEntity> : IEntityValidation<TEntity>
where TEntity : Entity
{
private readonly IRepository<TEntity> repository;
public EntityValidation(IRepository<TEntity> repository)
{
this.repository = repository;
}
public async Task<ISingleResult<TEntity>> RegistroExiste(int id, params string[] includes)
{
var entity = await repository.GetById(id, includes);
if (entity == null)
{
return new SingleResult<TEntity>(MensagensNegocio.MSG04);
}
return new SingleResult<TEntity>(entity);
}
public async Task<ISingleResult<TEntity>> RegistroComMesmoCodigo(int id, string codigo)
{
var result = await repository.ValueExists(id, codigo);
if (result)
{
return new SingleResult<TEntity>(MensagensNegocio.MSG08);
}
return new SingleResult<TEntity>();
}
}
}
| 25.511628 | 92 | 0.747493 | [
"MIT"
] | yakkumo/AirplaneApi | src/AirplaneProject.Core/Models/Validations/EntityValidation.cs | 1,099 | C# |
/*
MIT License
Copyright (c) 2021 Gregor Mohorko
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.
Project: GM.WPF
Created: 2018-4-17
Author: Gregor Mohorko
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
namespace GM.WPF.Utility
{
/// <summary>
/// Utilities for <see cref="TreeView"/>.
/// </summary>
public static class TreeViewUtility
{
/// <summary>
/// Selects this <see cref="TreeViewItem"/>. It also expands the <see cref="TreeView"/> items to this item.
/// </summary>
/// <param name="treeViewItem">The item to select and expand to.</param>
public static void Select(this TreeViewItem treeViewItem)
{
// expand all parents
TreeViewItem parent = treeViewItem.GetParent() as TreeViewItem;
while(parent != null) {
parent.IsExpanded = true;
parent = parent.GetParent() as TreeViewItem;
}
// select the item
treeViewItem.IsSelected = true;
}
}
}
| 32.966667 | 109 | 0.754803 | [
"MIT"
] | GregaMohorko/GM.WPF | src/GM.WPF/GM.WPF/Utility/TreeViewUtility.cs | 1,980 | C# |
using System.Collections.Generic;
namespace Graph.QuadTree
{
/// <typeparam name="TValue">Type of values which stores in tree</typeparam>
public class QuadTreeNode<TValue> where TValue : IQuadObject
{
/// <summary>
/// Maxium values which can be stored in one node
/// </summary>
public static int valCapacity = 4;
public Rectangle Bound { get; private set; }
internal QuadTreeNode<TValue> leftTop = null;
internal QuadTreeNode<TValue> rightTop = null;
internal QuadTreeNode<TValue> leftDown = null;
internal QuadTreeNode<TValue> rightDown = null;
// Collection of values
List<TValue> objects = new List<TValue>();
public QuadTreeNode(Rectangle _bound)
{
Bound = _bound;
}
internal void Subdivide()
{
Rectangle northWestBound = new Rectangle(Bound.X1, Bound.Y1,
(Bound.X1 + Bound.X2) / 2.0f,
(Bound.Y1 + Bound.Y2) / 2.0f);
Rectangle northEastBound = new Rectangle(Bound.X2, Bound.Y2,
(Bound.X1 + Bound.X2) / 2.0f,
(Bound.Y1 + Bound.Y2) / 2.0f);
Rectangle southWestBound = new Rectangle(Bound.X3, Bound.Y3,
(Bound.X1 + Bound.X2) / 2.0f,
(Bound.Y1 + Bound.Y2) / 2.0f);
Rectangle southEastBound = new Rectangle(Bound.X4, Bound.Y4,
(Bound.X1 + Bound.X2) / 2.0f,
(Bound.Y1 + Bound.Y2) / 2.0f);
leftTop = new QuadTreeNode<TValue>(northWestBound);
rightTop = new QuadTreeNode<TValue>(northEastBound);
leftDown = new QuadTreeNode<TValue>(southWestBound);
rightDown = new QuadTreeNode<TValue>(southEastBound);
}
/// <summary>
/// Insert value
/// </summary>
/// <param name="x">X coord to insert</param>
/// <param name="y">Y coord to insert</param>
/// <param name="obj"></param>
public bool Insert(TValue obj)
{
if (!Bound.ContainsPoint(obj.X, obj.Y))
{
return false;
}
// If space is enough, add val
if (objects.Count <= valCapacity)
{
objects.Add(obj);
return true;
}
// Divide bound and insert val in one of created nodes
if (leftTop == null)
Subdivide();
if (leftTop.Insert(obj)) return true;
if (rightTop.Insert(obj)) return true;
if (leftDown.Insert(obj)) return true;
if (rightDown.Insert(obj)) return true;
return false;
}
/// <summary>
/// Remove object from tree
/// </summary>
public bool Remove(TValue obj)
{
if (!Bound.ContainsPoint(obj.X, obj.Y))
return false;
if (objects.Remove(obj))
{
return true;
}
else
{
if (leftTop.Remove(obj)) return true;
if (rightTop.Remove(obj)) return true;
if (leftDown.Remove(obj)) return true;
if (rightDown.Remove(obj)) return true;
}
return false;
}
/// <summary>
/// Get points which are in range
/// </summary>
public List<TValue> QueryRange(Rectangle range)
{
List<TValue> res = new List<TValue>();
if (!Bound.Intersects(range))
return res;
foreach (TValue z in objects)
{
if (range.ContainsPoint(z.X, z.Y))
res.Add(z);
}
if (leftTop == null)
return res;
res.AddRange(leftTop.QueryRange(range));
res.AddRange(rightTop.QueryRange(range));
res.AddRange(leftDown.QueryRange(range));
res.AddRange(rightDown.QueryRange(range));
return res;
}
}
}
| 34.68595 | 81 | 0.494639 | [
"Apache-2.0"
] | DMokhnatkin/GraphLib | GraphLib/GraphLib/QuadTree/QuadTreeNode.cs | 4,199 | C# |
//
// Copyright 2020 Google LLC
//
// 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 System.IO;
using System.Net;
using System.Net.Http.Headers;
using System.Net.Sockets;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
namespace Google.Solutions.Common.Test.Net
{
/// <summary>
/// Simple implementation of a HTTP proxy that can be used in tests.
/// </summary>
public class InProcessHttpProxy : IDisposable
{
private static readonly Regex ConnectRequestPattern
= new Regex(@"^CONNECT ([a-zA-Z0-9\.*]+):(\d+) HTTP/1.1");
private static readonly Regex GetRequestPattern
= new Regex(@"^GET (.*) HTTP/1.1");
// NB. Avoid reusing the same port twice in the same process.
private static ushort nextProxyPort = 3128;
private readonly CancellationTokenSource cancellation = new CancellationTokenSource();
private readonly LinkedList<string> connectionTargets = new LinkedList<string>();
private readonly TcpListener listener;
private readonly IDictionary<string, string> staticFiles =
new Dictionary<string, string>();
public IEnumerable<string> ConnectionTargets => this.connectionTargets;
public ushort Port { get; }
private void DispatchRequests()
{
while (!this.cancellation.IsCancellationRequested)
{
var socket = new NetworkStream(this.listener.AcceptSocket(), true);
var _ = DispatchRequestAsync(socket).ConfigureAwait(false);
}
}
private string ReadLine(Stream stream)
{
var buffer = new StringBuilder();
while (true)
{
int b = stream.ReadByte();
if (b == -1 || b == (byte)'\n')
{
return buffer.ToString();
}
else if (b == (byte)'\r')
{ }
else
{
buffer.Append((char)b);
}
}
}
private async Task DispatchRequestAsync(NetworkStream clientStream)
{
using (clientStream)
{
var firstLine = ReadLine(clientStream);
if (ConnectRequestPattern.Match(firstLine) is Match matchConnect && matchConnect.Success)
{
//
// Read headers.
//
var headers = new Dictionary<string, string>();
string line;
while (!string.IsNullOrEmpty((line = ReadLine(clientStream))))
{
var parts = line.Split(':');
headers.Add(parts[0].ToLower(), parts[1].Trim());
}
this.connectionTargets.AddLast(matchConnect.Groups[1].Value);
await DispatchRequestAsync(
matchConnect.Groups[1].Value,
ushort.Parse(matchConnect.Groups[2].Value),
headers,
clientStream);
}
else if (GetRequestPattern.Match(firstLine) is Match getMatch &&
getMatch.Success &&
this.staticFiles.TryGetValue(getMatch.Groups[1].Value, out var responseBody))
{
var response = Encoding.ASCII.GetBytes(
"HTTP/1.1 200 OK\r\n" +
$"Content-Length: {responseBody.Length}\r\n" +
$"Content-Type: application/x-ns-proxy-autoconfig\r\n" +
"\r\n" +
responseBody);
clientStream.Write(response, 0, response.Length);
}
else
{
var error = Encoding.ASCII.GetBytes($"HTTP /1.1 400 Bad Request");
clientStream.Write(error, 0, error.Length);
}
}
}
protected virtual async Task DispatchRequestAsync(
string server,
ushort serverPort,
IDictionary<string, string> headers,
NetworkStream clientStream)
{
//
// Send response.
//
var response = Encoding.ASCII.GetBytes($"HTTP/1.1 200 OK\r\n\r\n");
clientStream.Write(response, 0, response.Length);
clientStream.Flush();
//
// Relay streams.
//
using (var client = new TcpClient(server, serverPort))
{
var serverStream = client.GetStream();
await Task.WhenAll(
clientStream.CopyToAsync(serverStream),
serverStream.CopyToAsync(clientStream));
}
}
public InProcessHttpProxy(ushort port)
{
this.Port = port;
this.listener = new TcpListener(new IPEndPoint(IPAddress.Loopback, port));
this.listener.Start();
Task.Run(() => DispatchRequests());
}
public InProcessHttpProxy() : this(nextProxyPort++)
{
}
public void AddStaticFile(string path, string body)
{
this.staticFiles.Add(path, body);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
this.cancellation.Cancel();
this.listener.Stop();
}
}
}
public class InProcessAuthenticatingHttpProxy : InProcessHttpProxy
{
public string Realm { get; set; } = "default";
public NetworkCredential Credential { get; set; }
public InProcessAuthenticatingHttpProxy(
ushort port,
NetworkCredential credential)
: base(port)
{
this.Credential = credential;
}
public InProcessAuthenticatingHttpProxy(
NetworkCredential credential)
: base()
{
this.Credential = credential;
}
protected override async Task DispatchRequestAsync(
string server,
ushort serverPort,
IDictionary<string, string> headers,
NetworkStream clientStream)
{
if (headers.TryGetValue("proxy-authorization", out var proxyAuthHeader))
{
var proxyAuth = AuthenticationHeaderValue.Parse(proxyAuthHeader);
if (proxyAuth.Scheme.ToLower() != "basic")
{
SendUnauthenticatedError(clientStream);
return;
}
var credentials = Encoding.ASCII.GetString(
Convert.FromBase64String(proxyAuth.Parameter)).Split(':');
if (credentials.Length != 2 ||
credentials[0] != this.Credential.UserName ||
credentials[1] != this.Credential.Password)
{
SendUnauthenticatedError(clientStream);
}
else
{
await base.DispatchRequestAsync(server, serverPort, headers, clientStream);
}
}
else
{
SendUnauthenticatedError(clientStream);
}
}
private void SendUnauthenticatedError(NetworkStream clientStream)
{
var response = Encoding.ASCII.GetBytes(
"HTTP/1.1 407 Proxy Authentication Required\r\n" +
$"Proxy-Authenticate: Basic realm={this.Realm}\r\n" +
"\r\n");
clientStream.Write(response, 0, response.Length);
clientStream.Flush();
}
}
}
| 34.111969 | 105 | 0.535144 | [
"Apache-2.0"
] | CertifiedWebMaster/iap-desktop | sources/Google.Solutions.Common.Test/Net/InprocHttpProxy.cs | 8,837 | C# |
using System;
using System.Runtime.Serialization;
namespace Elders.Cronus.Projections.Versioning
{
[DataContract(Name = "d661a3e9-f6d0-4ea7-9bd9-435d3c3b8712")]
public class TimeoutProjectionVersionRequest : ISystemCommand
{
TimeoutProjectionVersionRequest() { }
public TimeoutProjectionVersionRequest(ProjectionVersionManagerId id, ProjectionVersion version, VersionRequestTimebox timebox)
{
Id = id;
Version = version;
Timebox = timebox;
}
[DataMember(Order = 1)]
public ProjectionVersionManagerId Id { get; private set; }
[DataMember(Order = 2)]
public ProjectionVersion Version { get; private set; }
[DataMember(Order = 3)]
public VersionRequestTimebox Timebox { get; private set; }
public override string ToString()
{
return $"Timeout projection rebuilding for version `{Version}`. {Environment.NewLine}{nameof(ProjectionVersionManagerId)}: `{Id}`. {Environment.NewLine}Timebox: `{Timebox}`.";
}
}
}
| 32.727273 | 187 | 0.662037 | [
"Apache-2.0"
] | Elders/Cronus | src/Elders.Cronus/Projections/Versioning/Commands/TimeoutProjectionVersionRequest.cs | 1,082 | C# |
using Windows.Foundation;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
namespace BinaryDataSerializer.Editor.Controls
{
public sealed partial class FieldControl : UserControl
{
public static readonly DependencyProperty AnchorPointProperty = DependencyProperty.Register(
"AnchorPoint", typeof(Point), typeof(FieldControl), new PropertyMetadata(default(Point)));
public Point AnchorPoint
{
get => (Point) GetValue(AnchorPointProperty);
set => SetValue(AnchorPointProperty, value);
}
public FieldControl()
{
InitializeComponent();
LayoutUpdated += OnLayoutUpdated;
}
private void OnLayoutUpdated(object sender, object o)
{
var page = GetPage();
AnchorPoint = TransformToVisual(page).TransformPoint(new Point(ActualWidth, ActualHeight / 2));
}
private Page _page;
private Page GetPage()
{
return _page ?? (_page = this.FindVisualParent<Page>());
}
}
}
| 27.846154 | 107 | 0.624309 | [
"MIT"
] | jackwakefield/BinaryDataSerializer | BinaryDataSerializer.Editor/Controls/FieldControl.xaml.cs | 1,088 | C# |
using System.Collections.Generic;
using System;
using scopely.msgpacksharp;
using Neutrino.Core.Messages;
using System.Reflection;
namespace Neutrino.Core
{
public class NetworkMessageFactory
{
private Dictionary<byte, NetworkMessage> messages = new Dictionary<byte, NetworkMessage>();
private Dictionary<Type, NetworkMessage> messagesByType = new Dictionary<Type, NetworkMessage>();
internal NetworkMessageFactory()
{
}
public void Init(params Assembly[] messageAssemblies)
{
BuildInstances(messageAssemblies);
}
public T Get<T>() where T : NetworkMessage
{
NetworkMessage result = null;
if (!messagesByType.TryGetValue(typeof(T), out result))
throw new ApplicationException("Attempt to get network message of type " + typeof(T) + " failed because that message type hasn't been registered");
return (T)result;
}
internal IEnumerable<NetworkMessage> Read(byte[] buffer, int length)
{
int overallOffset = 0;
while (overallOffset < length)
{
int offset = 1;
var result = messages[buffer[overallOffset]];
if (result.IsGuaranteed)
{
result.SequenceNumber = (ushort)((buffer[overallOffset + 1]) + (buffer[overallOffset + 2] << 8));
offset = 3;
}
overallOffset = MsgPackSerializer.DeserializeObject(result, buffer, overallOffset + offset);
yield return result;
}
}
internal NetworkMessage Read(byte[] buffer)
{
int offset = 1;
var result = messages[buffer[0]];
if (result.IsGuaranteed)
{
result.SequenceNumber = (ushort)(buffer[1] + (buffer[2] << 8));
offset = 3;
}
MsgPackSerializer.DeserializeObject(result, buffer, offset);
return result;
}
private void BuildInstances(params Assembly[] messageAssemblies)
{
BuildInstances(typeof(NetworkMessage).Assembly);
foreach (Assembly a in messageAssemblies)
BuildInstances(a);
NeutrinoConfig.Log("Built " + messages.Count + " registered network messages");
}
private void BuildInstances(Assembly messageAssembly)
{
Type networkMsgType = typeof(NetworkMessage);
foreach(Type t in messageAssembly.GetTypes())
{
if (t.IsSubclassOf(networkMsgType) && !messagesByType.ContainsKey(t))
{
if (messages.Count == Byte.MaxValue)
throw new ApplicationException("The maximum number of network messages has been reached - you need to use fewer message types in this project");
var msg = (NetworkMessage)t.GetConstructor(Type.EmptyTypes).Invoke(Utility.emptyArgs);
MsgPackSerializer.SerializeObject(msg, NetworkMessage.cloneBuffer, 0);
MsgPackSerializer.DeserializeObject(msg, NetworkMessage.cloneBuffer, 0);
msg.Id = (byte)messages.Count;
messages[msg.Id] = msg;
messagesByType[msg.GetType()] = msg;
NeutrinoConfig.Log("Registered message type " + msg.GetType() + " as Id " + msg.Id);
}
}
}
}
}
| 32.055556 | 151 | 0.702946 | [
"MIT"
] | electroball09/Neutrino | NeutrinoCore/NetworkMessageFactory.cs | 2,887 | C# |
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
// Could make it take in two generic types.
public class Binding
{
public readonly ViewBlock vb;
public readonly ModelBlock mb;
readonly UnityEvent environmentChanged;
public Binding(ViewBlock vb, ModelBlock mb, UnityEvent viewModelEvent)
{
this.vb = vb;
this.mb = mb;
environmentChanged = viewModelEvent;
}
public void PropagateChange()
{
mb.Position = new Vector3(vb.Position.x, vb.Position.y, vb.Position.z);
this.environmentChanged.Invoke();
}
public void DeleteFromViewAndModel(ModelEnvironment me)
{
vb.Delete();
mb.Delete();
me.RemoveBlock(this.mb);
}
}
| 21.90625 | 75 | 0.717546 | [
"MIT"
] | jtorre39/nebula | NebulaVR/Assets/Scripts/NebulaVR/ViewModel/Binding.cs | 703 | C# |
using System;
using System.Collections.Generic;
namespace JsonSubTypes
{
public class NullableDictionary<TKey, TValue>
{
private bool _hasNullKey;
private TValue _nullKeyValue;
private readonly Dictionary<TKey, TValue> _dictionary = new Dictionary<TKey, TValue>();
public bool TryGetValue(TKey key, out TValue value)
{
if (Equals(key, default(TKey)))
{
if (!_hasNullKey)
{
value = default(TValue);
return false;
}
value = _nullKeyValue;
return true;
}
return _dictionary.TryGetValue(key, out value);
}
public void Add(TKey key, TValue value)
{
if (Equals(key, default(TKey)))
{
if (_hasNullKey)
{
throw new ArgumentException();
}
_hasNullKey = true;
_nullKeyValue = value;
}
else
{
_dictionary.Add(key, value);
}
}
public IEnumerable<TKey> NotNullKeys()
{
return _dictionary.Keys;
}
public IEnumerable<KeyValuePair<TKey, TValue>> Entries()
{
if (_hasNullKey)
{
yield return new KeyValuePair<TKey, TValue>(default(TKey), _nullKeyValue);
}
foreach (var value in _dictionary)
{
yield return value;
}
}
}
}
| 24.5 | 95 | 0.467532 | [
"MIT"
] | AkshaySharmaDEV/CovIt | Assets/unity-sdk-core-1.2.3/ThirdParty/JsonSubTypes/NullableDictionary.cs | 1,619 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class EnableShooting : MonoBehaviour
{
public float ammoCount;
//public AudioSource source1;
public void OnTriggerEnter2D(Collider2D other)
{
PlayerShoot player = other.gameObject.GetComponent<PlayerShoot>();
if (player)
{
print("gun hit");
//source1.Play();
if (player.canShoot)
{
player.ammo += ammoCount;
if(player.ammo > player.maxAmmo)
{
player.maxAmmo = player.ammo;
}
}
else
{
player.ammo += ammoCount;
player.canShoot = true;
}
this.gameObject.SetActive(false);
}
}
}
| 23.666667 | 74 | 0.5223 | [
"MIT"
] | cbrown146/ISTA-415 | src/Scripts/EnableShooting.cs | 854 | C# |
using System;
using System.Threading;
using System.Threading.Tasks;
namespace Example_1_Asynchronous_Data_Calculation
{
class Program
{
static void Main(string[] args)
{
Thread.CurrentThread.Name = "MainThread";
Console.WriteLine("Creating new task, that returns a string value.");
// start new Task
var task = Task<string>.Factory.StartNew(() =>
{
Thread.Sleep(2000);
return "Robert";
});
// user result
Console.WriteLine($"Your name is: {task.Result}");
Console.WriteLine("Press any key to show next example.");
Console.ReadKey();
Console.WriteLine("Creating new task, that returns nothing.");
// start new Task
var voidTask = Task.Factory.StartNew(() =>
{
Thread.CurrentThread.Name = "VoidTask";
#region thread information
Console.WriteLine($"Task thread name: {Thread.CurrentThread.Name}");
Console.WriteLine($"Is background thread: {Thread.CurrentThread.IsBackground}");
Console.WriteLine($"Is threadpool thread: {Thread.CurrentThread.IsThreadPoolThread}");
#endregion
#region throw exception
throw new InvalidOperationException("Something went wrong!");
#endregion
Thread.Sleep(5000);
Console.WriteLine("VoidTask => Hello World!");
}, TaskCreationOptions.LongRunning);
voidTask.Wait();
Console.WriteLine($"Main thread: {Thread.CurrentThread.Name}");
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}
}
}
| 35.490196 | 102 | 0.559116 | [
"MIT"
] | robson081192/ParallelDotNet | MultithreadingPlayground/Example_1_Asynchronous_Data_Calculation/Program.cs | 1,812 | C# |
using System;
using System.Diagnostics;
using System.Linq;
using System.Security.Cryptography;
using static AEZ.AEZConstants;
namespace AEZ
{
/// <summary>
/// Based on https://github.com/Yawning/aez/blob/ec7426b4492636b9b39cb6e173e7423500107163/aez.go
/// </summary>
public class AEZ
{
internal static void Extract(ReadOnlySpan<byte> k, Span<byte> extractedKey)
{
if (extractedKey.Length != ExtractedKeySize)
throw new ArgumentException($"{nameof(extractedKey)} length must be {ExtractedKeySize}. It was {extractedKey.Length}", nameof(extractedKey));
if (k.Length == ExtractedKeySize)
{
k.CopyTo(extractedKey);
}
else
{
_blake2B.Hash(k, extractedKey);
}
}
private static IBlake2B _blake2B =
#if BouncyCastle
new BouncyCastleBlake2B(ExtractedKeySize);
#else
new NSecBlake2B(ExtractedKeySize);
#endif
/// <summary>
/// Encrypts and authenticates the plaintext, authenticates the additional data, and appends the result to ciphertext,
/// returning the updated slice.
/// </summary>
/// <param name="key"></param>
/// <param name="nonce"></param>
/// <param name="ad"></param>
/// <param name="tau"></param>
/// <param name="plainText"></param>
/// <param name="dst"></param>
/// <returns></returns>
public static Span<byte> Encrypt(ReadOnlySpan<byte> key, ReadOnlySpan<byte> nonce, byte[][] ad, int tau,
ReadOnlySpan<byte> plainText, Span<byte> dst)
{
Span<byte> delta = new byte[BlockSize];
Span<byte> x;
var (dstSz, xSz) = (dst.Length, plainText.Length + tau);
if (dst.Length >= dstSz + xSz)
{
dst = dst.Slice(0, dstSz + xSz);
}
else
{
x = new byte[dstSz + xSz];
dst.CopyTo(x);
dst = x;
}
x = dst.Slice(dstSz);
var e = new EState(key);
e.AEZHash(nonce, ad, tau * 8, delta);
if (plainText.Length == 0)
{
e.AEZ_PRF(delta, tau, x);
}
else
{
x.Slice(plainText.Length).Clear();
plainText.CopyTo(x);
e.Encipher(delta, x, x);
}
return dst;
}
/// <summary>
/// Decrypts and authenticates the ciphertext, authenticates additionalData (ad), and if successful appends the
/// resulting plaintext to the provided slice and returns the updated slice. The length of the expected
/// authentication tag in bytes is specified by tau. The ciphertext and dst slices MUST NOT overlap.
/// </summary>
/// <param name="key"></param>
/// <param name="ad"></param>
/// <param name="tau"></param>
/// <param name="cipherText"></param>
/// <param name="dst"></param>
/// <returns></returns>
/// <exception cref="ArgumentException"></exception>
public static Span<byte> Decrypt(ReadOnlySpan<byte> key, ReadOnlySpan<byte> nonce, byte[][] ad, int tau, ReadOnlySpan<byte> cipherText,
Span<byte> dst)
{
if (ad == null) throw new ArgumentNullException(nameof(ad));
if (cipherText.Length < tau)
{
throw new ArgumentException($"{nameof(cipherText)} ({cipherText.Length}) must be longer than {nameof(tau)} ({tau})! ", nameof(cipherText));
}
Span<byte> delta = new byte[BlockSize];
Span<byte> x;
var (dstSz, xSz) = (dst.Length, cipherText.Length);
if (dst.Length >= dstSz + xSz)
{
dst = dst.Slice(0, dstSz + xSz);
}
else
{
x = new byte[dstSz + xSz];
dst.CopyTo(x);
dst = x;
}
x = dst.Slice(dstSz);
var e = new EState(key);
var sum = (byte) 0;
e.AEZHash(nonce, ad, tau * 8, delta);
if (cipherText.Length == tau)
{
e.AEZ_PRF(delta, tau, x);
for (int i = 0; i < tau; i++)
{
sum |= (byte)(x[i] ^ cipherText[i]);
}
dst = dst.Slice(0, dstSz);
}
else
{
e.Decipher(delta, cipherText, x);
for (int i = 0; i < tau; i++)
{
sum |= x[(cipherText.Length - tau + i)];
}
if (sum == 0)
{
dst = dst.Slice(0, dstSz + cipherText.Length - tau);
}
}
if (sum != 0)
{
throw new CryptographicException($"Invalid parameters for decryption!");
}
return dst;
}
}
}
| 34.2 | 157 | 0.484795 | [
"MIT"
] | joemphilips/DotNetLightning | src/AEZ/AEZ.cs | 5,132 | C# |
using ExtendedMap.Forms.Plugin.Abstractions;
using PluginSampleApp.ViewModels;
using Xamarin.Forms;
using Xamarin.Forms.Maps;
namespace PluginSampleApp.Pages
{
public class ExtendedMapPage : ContentPage
{
public ExtendedMapPage()
{
BindingContext = new ExtendedViewModel();
var grid = new Grid
{
RowDefinitions = new RowDefinitionCollection
{
new RowDefinition {Height = new GridLength(1, GridUnitType.Star)}
},
ColumnDefinitions = new ColumnDefinitionCollection
{
new ColumnDefinition {Width = new GridLength(1, GridUnitType.Star)}
}
};
grid.Children.Add(CreateMapContentView(), 0, 0);
Content = grid;
}
View CreateMapContentView()
{
//Coordinates for the starting point of the map
const double latitude = 41.788081;
const double longitude = -87.831573;
var location = new Position(latitude, longitude);
var _map = new global::ExtendedMap.Forms.Plugin.Abstractions.ExtendedMap(MapSpan.FromCenterAndRadius(location, Distance.FromMiles(15))) { IsShowingUser = true };
_map.StyleId = "CustomMap";
_map.BindingContext = BindingContext;
_map.SetBinding<ExtendedViewModel>(global::ExtendedMap.Forms.Plugin.Abstractions.ExtendedMap.CustomPinsProperty, x => x.SamplePins);
var createMapContentView = new CustomMapContentView(_map);
return createMapContentView;
}
}
} | 31.773585 | 173 | 0.599169 | [
"MIT"
] | Kimmax/Xamarin.Forms.Plugins | SampleApp/PluginSampleApp/PluginSampleApp/PluginSampleApp/Pages/ExtendedMapPage.cs | 1,686 | C# |
namespace ExampleProject
{
public class HotelRoom
{
public int Id { get; set; }
public string Name { get; set; }
public int MaxGuests { get; set; }
public bool IsActive { get; set; }
public HotelRoom(HotelRoom source)
{
this.Id = source.Id;
this.Name = source.Name;
this.MaxGuests = source.MaxGuests;
this.IsActive = source.IsActive;
}
public HotelRoom()
{
}
}
} | 20.038462 | 46 | 0.50096 | [
"Apache-2.0"
] | dev-someuser/ReSharper.T4CodeGenerator | Examples/ExampleProject/HotelRoom.cs | 523 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TP_Bibliotheque.Models;
using TP_Bibliotheque.Models.DAL;
using TP_Bibliotheque.Models.Data;
using TP_Bibliotheque.Models.ViewModel;
namespace TP_Bibliotheque.Controllers
{
public class AuthorController : Controller
{
public AuthorController()
{
// TODO Find a way to instanciate this, because it's easier to use than instanciate on the fly in methods
//dal = new AuthorDAL((List<Author>)Session["Authors"]);
}
// GET: Author
public ActionResult Index() // Pour afficher la liste de tous les auteurs
{
AuthorModelView modelView = new AuthorModelView((List<Author>)Session["Authors"]);
return View(modelView);
}
public ActionResult Details(int id) // Pour afficher toutes les infos d'un auteur en particulier
{
AuthorDAL authorDAL = new AuthorDAL((List<Author>)Session["Authors"]); // Récupération des auteurs (général)
BookDAL bookDAL = new BookDAL((List<Book>)Session["Books"]); // Récupération des livres (général)
Author author = authorDAL.Read(id); // Récupération de l'auteur en particulier
//Création d'une modelView avec l'auteur + ses livres
ShowAuthorModelView model = new ShowAuthorModelView(author, bookDAL.FindByAuthor(author));
return View(model);
}
public ActionResult Edit(int id) // Edition des informations d'un auteur
{
// Récupération des auteurs
AuthorDAL authorDAL = new AuthorDAL((List<Author>)Session["Authors"]);
Author author = authorDAL.Read(id); // Lecture des datas de l'auteur en question
var model = new EditAuthorModelView(); // Création de la modelView de l'edition de l'auteur
model.author = author; // Ajout de l'auteur a la modelView
return View(model);
}
public ActionResult Delete(int id) // Suppression d'un auteur
{
AuthorDAL authorDAL = new AuthorDAL((List<Author>)Session["Authors"]);
Author author = authorDAL.Read(id); // R2cupération des infos d'un livre pour un id donné
authorDAL.Delete(id);
AuthorModelView model = new AuthorModelView((List<Author>)Session["Authors"]);
return View(model);
}
public ActionResult Add() // Ajout d'un nouvel auteur
{
Author author = new Author();
return View(author);
}
[HttpPost]
[ValidateAntiForgeryToken] // Création d'un nouvel auteur
public ActionResult Create([Bind(Include = "Name, Firstname")]Author author)
{
AuthorDAL dal = new AuthorDAL((List<Author>)Session["Authors"]);
if (ModelState.IsValid)
{
dal.Add(author);
return RedirectToAction("Index");
}
return View(author);
}
[HttpPost]
[ValidateAntiForgeryToken] // Edition d'un auteur existant
public ActionResult Edition([Bind(Include = "author")]EditAuthorModelView model) // On récupére l'entity Autheur spécial EditAuthorModelView
{
// Récupération des datas d'auteurs
AuthorDAL dal = new AuthorDAL((List<Author>)Session["Authors"]);
if (ModelState.IsValid)
{
dal.Update(model.author.Id, model.author); // Mise à jour des datas de l'auteur
return RedirectToAction("Index"); // Retourner à la liste des auteurs si OK
}
return View("Edit", model); // Rester sur le formulaire d'edition
}
}
} | 37.098039 | 149 | 0.617072 | [
"MIT"
] | sylvainmetayer/TP_Bibliotheque | TP_Bibliotheque/Controllers/AuthorController.cs | 3,810 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class FieldInitializerBindingTests : CompilingTestBase
{
[Fact]
public void NoInitializers()
{
var source = @"
class C
{
static int s1;
int i1;
}";
IEnumerable<ExpectedInitializer> expectedStaticInitializers = null;
IEnumerable<ExpectedInitializer> expectedInstanceInitializers = null;
CompileAndCheckInitializers(source, expectedInstanceInitializers, expectedStaticInitializers);
}
[Fact]
public void ConstantInstanceInitializer()
{
var source = @"
class C
{
static int s1;
int i1 = 1;
}";
IEnumerable<ExpectedInitializer> expectedStaticInitializers = null;
IEnumerable<ExpectedInitializer> expectedInstanceInitializers = new ExpectedInitializer[]
{
new ExpectedInitializer("i1", "1", lineNumber: 4),
};
CompileAndCheckInitializers(source, expectedInstanceInitializers, expectedStaticInitializers);
}
[Fact]
public void ConstantStaticInitializer()
{
var source = @"
class C
{
static int s1 = 1;
int i1;
}";
IEnumerable<ExpectedInitializer> expectedStaticInitializers = new ExpectedInitializer[]
{
new ExpectedInitializer("s1", "1", lineNumber: 3),
};
IEnumerable<ExpectedInitializer> expectedInstanceInitializers = null;
CompileAndCheckInitializers(source, expectedInstanceInitializers, expectedStaticInitializers);
}
[Fact]
public void ExpressionInstanceInitializer()
{
var source = @"
class C
{
static int s1;
int i1 = 1 + Goo();
static int Goo() { return 1; }
}";
IEnumerable<ExpectedInitializer> expectedStaticInitializers = null;
IEnumerable<ExpectedInitializer> expectedInstanceInitializers = new ExpectedInitializer[]
{
new ExpectedInitializer("i1", "1 + Goo()", lineNumber: 4),
};
CompileAndCheckInitializers(source, expectedInstanceInitializers, expectedStaticInitializers);
}
[Fact]
public void ExpressionStaticInitializer()
{
var source = @"
class C
{
static int s1 = 1 + Goo();
int i1;
static int Goo() { return 1; }
}";
IEnumerable<ExpectedInitializer> expectedStaticInitializers = new ExpectedInitializer[]
{
new ExpectedInitializer("s1", "1 + Goo()", lineNumber: 3),
};
IEnumerable<ExpectedInitializer> expectedInstanceInitializers = null;
CompileAndCheckInitializers(source, expectedInstanceInitializers, expectedStaticInitializers);
}
[Fact]
public void InitializerOrder()
{
var source = @"
class C
{
static int s1 = 1;
static int s2 = 2;
static int s3 = 3;
int i1 = 1;
int i2 = 2;
int i3 = 3;
}";
IEnumerable<ExpectedInitializer> expectedStaticInitializers = new ExpectedInitializer[]
{
new ExpectedInitializer("s1", "1", lineNumber: 3),
new ExpectedInitializer("s2", "2", lineNumber: 4),
new ExpectedInitializer("s3", "3", lineNumber: 5),
};
IEnumerable<ExpectedInitializer> expectedInstanceInitializers = new ExpectedInitializer[]
{
new ExpectedInitializer("i1", "1", lineNumber: 6),
new ExpectedInitializer("i2", "2", lineNumber: 7),
new ExpectedInitializer("i3", "3", lineNumber: 8),
};
CompileAndCheckInitializers(source, expectedInstanceInitializers, expectedStaticInitializers);
}
[Fact]
public void AllPartialClasses()
{
var source = @"
partial class C
{
static int s1 = 1;
int i1 = 1;
}
partial class C
{
static int s2 = 2;
int i2 = 2;
}";
IEnumerable<ExpectedInitializer> expectedStaticInitializers = new ExpectedInitializer[]
{
new ExpectedInitializer("s1", "1", lineNumber: 3),
new ExpectedInitializer("s2", "2", lineNumber: 8),
};
IEnumerable<ExpectedInitializer> expectedInstanceInitializers = new ExpectedInitializer[]
{
new ExpectedInitializer("i1", "1", lineNumber: 4),
new ExpectedInitializer("i2", "2", lineNumber: 9),
};
CompileAndCheckInitializers(source, expectedInstanceInitializers, expectedStaticInitializers);
}
[Fact]
public void SomePartialClasses()
{
var source = @"
partial class C
{
static int s1 = 1;
int i1 = 1;
}
partial class C
{
static int s2 = 2;
int i2 = 2;
}
partial class C
{
static int s3;
int i3;
}";
IEnumerable<ExpectedInitializer> expectedStaticInitializers = new ExpectedInitializer[]
{
new ExpectedInitializer("s1", "1", lineNumber: 3),
new ExpectedInitializer("s2", "2", lineNumber: 8),
};
IEnumerable<ExpectedInitializer> expectedInstanceInitializers = new ExpectedInitializer[]
{
new ExpectedInitializer("i1", "1", lineNumber: 4),
new ExpectedInitializer("i2", "2", lineNumber: 9),
};
CompileAndCheckInitializers(source, expectedInstanceInitializers, expectedStaticInitializers);
}
[Fact]
public void Events()
{
var source = @"
class C
{
static event System.Action e = MakeAction(1);
event System.Action f = MakeAction(2);
static System.Action MakeAction(int x) { return null; }
}}";
IEnumerable<ExpectedInitializer> expectedStaticInitializers = new ExpectedInitializer[]
{
new ExpectedInitializer("e", "MakeAction(1)", lineNumber: 3),
};
IEnumerable<ExpectedInitializer> expectedInstanceInitializers = new ExpectedInitializer[]
{
new ExpectedInitializer("f", "MakeAction(2)", lineNumber: 4),
};
CompileAndCheckInitializers(source, expectedInstanceInitializers, expectedStaticInitializers);
}
private static void CompileAndCheckInitializers(string source, IEnumerable<ExpectedInitializer> expectedInstanceInitializers, IEnumerable<ExpectedInitializer> expectedStaticInitializers)
{
var compilation = CreateCompilation(source);
var syntaxTree = compilation.SyntaxTrees.First();
var typeSymbol = (SourceNamedTypeSymbol)compilation.GlobalNamespace.GetMembers("C").Single();
var boundInstanceInitializers = BindInitializersWithoutDiagnostics(typeSymbol, typeSymbol.InstanceInitializers);
CheckBoundInitializers(expectedInstanceInitializers, syntaxTree, boundInstanceInitializers, isStatic: false);
var boundStaticInitializers = BindInitializersWithoutDiagnostics(typeSymbol, typeSymbol.StaticInitializers);
CheckBoundInitializers(expectedStaticInitializers, syntaxTree, boundStaticInitializers, isStatic: true);
}
private static void CheckBoundInitializers(IEnumerable<ExpectedInitializer> expectedInitializers, SyntaxTree syntaxTree, ImmutableArray<BoundInitializer> boundInitializers, bool isStatic)
{
if (expectedInitializers == null)
{
Assert.Equal(0, boundInitializers.Length);
}
else
{
Assert.True(!boundInitializers.IsEmpty, "Expected non-null non-empty bound initializers");
int numInitializers = expectedInitializers.Count();
Assert.Equal(numInitializers, boundInitializers.Length);
int i = 0;
foreach (var expectedInitializer in expectedInitializers)
{
var boundInit = boundInitializers[i++];
Assert.Equal(BoundKind.FieldEqualsValue, boundInit.Kind);
var boundFieldInit = (BoundFieldEqualsValue)boundInit;
var initValueSyntax = boundFieldInit.Value.Syntax;
Assert.Same(initValueSyntax.Parent, boundInit.Syntax);
Assert.Equal(expectedInitializer.InitialValue, initValueSyntax.ToFullString());
var initValueLineNumber = syntaxTree.GetLineSpan(initValueSyntax.Span).StartLinePosition.Line;
Assert.Equal(expectedInitializer.LineNumber, initValueLineNumber);
Assert.Equal(expectedInitializer.FieldName, boundFieldInit.Field.Name);
}
}
}
private static ImmutableArray<BoundInitializer> BindInitializersWithoutDiagnostics(SourceNamedTypeSymbol typeSymbol, ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> initializers)
{
DiagnosticBag diagnostics = DiagnosticBag.GetInstance();
ImportChain unused;
var boundInitializers = ArrayBuilder<BoundInitializer>.GetInstance();
Binder.BindRegularCSharpFieldInitializers(
typeSymbol.DeclaringCompilation,
initializers,
boundInitializers,
diagnostics,
firstDebugImports: out unused);
diagnostics.Verify();
diagnostics.Free();
return boundInitializers.ToImmutableAndFree();
}
private class ExpectedInitializer
{
public string FieldName { get; }
public string InitialValue { get; }
public int LineNumber { get; } //0-indexed
public ExpectedInitializer(string fieldName, string initialValue, int lineNumber)
{
this.FieldName = fieldName;
this.InitialValue = initialValue;
this.LineNumber = lineNumber;
}
}
}
}
| 33.401254 | 197 | 0.624214 | [
"MIT"
] | 06needhamt/roslyn | src/Compilers/CSharp/Test/Semantic/Semantics/FieldInitializerBindingTests.cs | 10,657 | C# |
//Copyright © 2014 Sony Computer Entertainment America LLC. See License.txt.
using System;
using System.Globalization;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
namespace Sce.Atf.Wpf.Controls
{
/// <summary>
/// A TextBox with a bindable StringFormat property</summary>
public class FormattingTextBox : TextBox
{
#region public IFormatProvider FormatProvider
/// <summary>
/// Gets or sets IFormatProvider that controls formatting</summary>
public IFormatProvider FormatProvider
{
get { return (IFormatProvider)GetValue(FormatProviderProperty); }
set { SetValue(FormatProviderProperty, value); }
}
/// <summary>
/// Format provider dependency property</summary>
public static readonly DependencyProperty FormatProviderProperty =
DependencyProperty.Register("FormatProvider",
typeof(IFormatProvider), typeof(FormattingTextBox), new UIPropertyMetadata(CultureInfo.InvariantCulture));
#endregion
#region public string StringFormat
/// <summary>
/// Gets or sets formatting string</summary>
public string StringFormat
{
get { return (string)GetValue(StringFormatProperty); }
set { SetValue(StringFormatProperty, value); }
}
/// <summary>
/// Formatting string dependency property</summary>
public static readonly DependencyProperty StringFormatProperty =
DependencyProperty.Register("StringFormat",
typeof(string), typeof(FormattingTextBox), new UIPropertyMetadata(null, StringFormatChanged));
#endregion
#region public object Value
/// <summary>
/// Gets or sets text in TextBox</summary>
public object Value
{
get { return GetValue(ValueProperty); }
set { SetValue(ValueProperty, value); }
}
/// <summary>
/// Text in TextBox dependency property</summary>
public static readonly DependencyProperty ValueProperty =
DependencyProperty.Register("Value",
typeof(object), typeof(FormattingTextBox),
new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, ValueChangedCallback));
#endregion
#region Ctors
/// <summary>
/// Constructor</summary>
static FormattingTextBox()
{
TextProperty.OverrideMetadata(typeof(FormattingTextBox), new FrameworkPropertyMetadata(TextChangedCallback));
}
#endregion
#region Events
private static void StringFormatChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
((FormattingTextBox)d).UpdateText();
}
#endregion
#region Private Methods
private void UpdateText()
{
userIsChanging = false;
string f = StringFormat;
if (f != null)
{
if (!f.Contains("{0"))
f = string.Format("{{0:{0}}}", f);
Text = String.Format(FormatProvider, f, Value);
}
else
{
Text = Value != null ? String.Format(FormatProvider, "{0}", Value) : null;
}
userIsChanging = true;
}
private string UnFormat(string s)
{
if (StringFormat == null)
return s;
var r = new Regex(@"(.*)(\{0.*\})(.*)");
var match = r.Match(StringFormat);
if (!match.Success)
return s;
if (match.Groups.Count > 1 && !String.IsNullOrEmpty(match.Groups[1].Value))
s = s.Replace(match.Groups[1].Value, "");
if (match.Groups.Count > 3 && !String.IsNullOrEmpty(match.Groups[3].Value))
s = s.Replace(match.Groups[3].Value, "");
return s;
}
private void UpdateValue()
{
if (userIsChanging)
Value = UnFormat(Text);
}
private static void ValueChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var ftb = (FormattingTextBox)d;
if (ftb.userIsChanging)
ftb.UpdateText();
}
private static void TextChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var ftb = (FormattingTextBox)d;
ftb.UpdateValue();
}
private bool userIsChanging = true;
#endregion
}
}
| 32.557047 | 135 | 0.5671 | [
"Apache-2.0"
] | gamebytes/ATF | Framework/Atf.Gui.Wpf/Controls/FormattingTextBox.cs | 4,706 | C# |
public static class RenderQueues
{
public static int WorldOpaque = 2000;
public static int Backwall = 2499;
public static int Stars = 2501;
public static int Gas = 3500;
public static int WorldTransparent = 3500;
public static int Liquid = 3500;
public static int BlockTiles = 4500;
}
| 17.529412 | 43 | 0.741611 | [
"MIT"
] | undancer/oni-data | Managed/main/RenderQueues.cs | 298 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using Leap;
using Leap.Unity;
// this file is intended to be used with a leapmotion controller, developed with ultraleap motion software version v5.3.1-0d83c9b8
// and with unity 2020.3.30f1, to contact and send requests to a custom webpage to command a Double Robotics v3 robot.
public class ControllMove : MonoBehaviour
{
Controller controller; // leapmotion instant
Leap.Vector HandPalmPosition; // get and track the position of the handpalm
float time = 0.0f;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame in unity, to continously track the position of the hand.
// can track two hands but will prioritize the left one if multiple on screen.
// will only use one hands position to call functions
// the tracking is every frame but calls are only sent every 200 ms since that is recommended for DRv3
// x and y coordinates are equivalent of the positions of the user interface in unity, if those are moved these values need to be updated
void Update()
{
controller = new Controller();
Frame frame = controller.Frame();
List<Hand> hands = frame.Hands;
if (frame.Hands.Count > 0)
{
HandPalmPosition = hands[0].PalmPosition;
if (time >= 0.2f)
{
time = 0.0f;
Debug.Log(HandPalmPosition);
Debug.Log("test x :" + (HandPalmPosition[0]));
Debug.Log("text y :" + (HandPalmPosition[1]));
if (HandPalmPosition[2] < 35)
{
Debug.Log("close enough");
if (-70 < HandPalmPosition[0] && HandPalmPosition[0] < 70 && 120 < HandPalmPosition[1] && HandPalmPosition[1] < 250)
{
Debug.Log("back");
StartCoroutine(SendRequest("http://130.240.114.93:3000/driveBackward"));
}
else if (-70 < HandPalmPosition[0] && HandPalmPosition[0] < 70 && 480 < HandPalmPosition[1] && HandPalmPosition[1] < 615)
{
Debug.Log("forward");
StartCoroutine(SendRequest("http://130.240.114.93:3000/driveForward"));
}
else if (120 < HandPalmPosition[0] && HandPalmPosition[0] < 230 && 120 < HandPalmPosition[1] && HandPalmPosition[1] < 250)
{
Debug.Log("up");
StartCoroutine(SendRequest("http://130.240.114.93:3000/poleStand"));
}
else if (120 < HandPalmPosition[0] && HandPalmPosition[0] < 230 && 280 < HandPalmPosition[1] && HandPalmPosition[1] < 430)
{
Debug.Log("right");
StartCoroutine(SendRequest("http://130.240.114.93:3000/turnRight"));
}
else if (-230 < HandPalmPosition[0] && HandPalmPosition[0] < -110 && 120 < HandPalmPosition[1] && HandPalmPosition[1] < 250)
{
Debug.Log("down");
StartCoroutine(SendRequest("http://130.240.114.93:3000/poleSit"));
}
else if (-230 < HandPalmPosition[0] && HandPalmPosition[0] < -110 && 280 < HandPalmPosition[1] && HandPalmPosition[1] < 430)
{
Debug.Log("left");
StartCoroutine(SendRequest("http://130.240.114.93:3000/turnLeft"));
}
else if (-230 < HandPalmPosition[0] && HandPalmPosition[0] < -110 && 480 < HandPalmPosition[1] && HandPalmPosition[1] < 615)
{
Debug.Log("enable nav");
StartCoroutine(SendRequest("http://130.240.114.93:3000/enableNavigation"));
}
else if (120 < HandPalmPosition[0] && HandPalmPosition[0] < 230 && 480 < HandPalmPosition[1] && HandPalmPosition[1] < 615)
{
Debug.Log("stop pole");
StartCoroutine(SendRequest("http://130.240.114.93:3000/poleStop"));
}
}
}
}
time += UnityEngine.Time.deltaTime;
}
// used to connect to and send request to a webpage to control the robot
IEnumerator SendRequest(string url)
{
UnityWebRequest request = UnityWebRequest.Get(url);
yield return request.SendWebRequest();
if (request.isNetworkError || request.isHttpError)
{
Debug.LogError(string.Format("Error: {0}",request.error));
}
else
{
// Response can be accessed through: request.downloadHandler.text
Debug.Log(request.downloadHandler.text);
}
}
}
| 47.575472 | 144 | 0.541543 | [
"MIT"
] | Gustav-Rixon/M7012E-DRv3 | Remote control/Assets/ControllMove.cs | 5,043 | C# |
namespace KryptonDateTimePickerExamples
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1));
this.groupBoxPalette = new System.Windows.Forms.GroupBox();
this.rbOffice2010Black = new System.Windows.Forms.RadioButton();
this.rbOffice2010Silver = new System.Windows.Forms.RadioButton();
this.rbOffice2010Blue = new System.Windows.Forms.RadioButton();
this.rbSparklePurple = new System.Windows.Forms.RadioButton();
this.rbSparkleOrange = new System.Windows.Forms.RadioButton();
this.rbSparkleBlue = new System.Windows.Forms.RadioButton();
this.rbSystem = new System.Windows.Forms.RadioButton();
this.rbOffice2003 = new System.Windows.Forms.RadioButton();
this.rbOffice2007Black = new System.Windows.Forms.RadioButton();
this.rbOffice2007Silver = new System.Windows.Forms.RadioButton();
this.rbOffice2007Blue = new System.Windows.Forms.RadioButton();
this.groupBox4 = new System.Windows.Forms.GroupBox();
this.propertyGrid = new System.Windows.Forms.PropertyGrid();
this.buttonClose = new System.Windows.Forms.Button();
this.kryptonPalette = new Krypton.Toolkit.KryptonPalette();
this.groupBoxRibbon = new System.Windows.Forms.GroupBox();
this.dtpRibbonTime = new Krypton.Toolkit.KryptonDateTimePicker();
this.buttonSpecAny2 = new Krypton.Toolkit.ButtonSpecAny();
this.dtpRibbonShort = new Krypton.Toolkit.KryptonDateTimePicker();
this.dtpRibbonLong = new Krypton.Toolkit.KryptonDateTimePicker();
this.groupBoxNormal = new System.Windows.Forms.GroupBox();
this.dtpNormalTime = new Krypton.Toolkit.KryptonDateTimePicker();
this.buttonSpecAny1 = new Krypton.Toolkit.ButtonSpecAny();
this.dtpNormalShort = new Krypton.Toolkit.KryptonDateTimePicker();
this.dtpNormalLong = new Krypton.Toolkit.KryptonDateTimePicker();
this.groupBoxPalette.SuspendLayout();
this.groupBox4.SuspendLayout();
this.groupBoxRibbon.SuspendLayout();
this.groupBoxNormal.SuspendLayout();
this.SuspendLayout();
//
// groupBoxPalette
//
this.groupBoxPalette.Controls.Add(this.rbOffice2010Black);
this.groupBoxPalette.Controls.Add(this.rbOffice2010Silver);
this.groupBoxPalette.Controls.Add(this.rbOffice2010Blue);
this.groupBoxPalette.Controls.Add(this.rbSparklePurple);
this.groupBoxPalette.Controls.Add(this.rbSparkleOrange);
this.groupBoxPalette.Controls.Add(this.rbSparkleBlue);
this.groupBoxPalette.Controls.Add(this.rbSystem);
this.groupBoxPalette.Controls.Add(this.rbOffice2003);
this.groupBoxPalette.Controls.Add(this.rbOffice2007Black);
this.groupBoxPalette.Controls.Add(this.rbOffice2007Silver);
this.groupBoxPalette.Controls.Add(this.rbOffice2007Blue);
this.groupBoxPalette.Location = new System.Drawing.Point(12, 309);
this.groupBoxPalette.Name = "groupBoxPalette";
this.groupBoxPalette.Size = new System.Drawing.Size(382, 181);
this.groupBoxPalette.TabIndex = 3;
this.groupBoxPalette.TabStop = false;
this.groupBoxPalette.Text = "Palette";
//
// rbOffice2010Black
//
this.rbOffice2010Black.AutoSize = true;
this.rbOffice2010Black.Location = new System.Drawing.Point(24, 72);
this.rbOffice2010Black.Name = "rbOffice2010Black";
this.rbOffice2010Black.Size = new System.Drawing.Size(115, 17);
this.rbOffice2010Black.TabIndex = 2;
this.rbOffice2010Black.Text = "Office 2010 - Black";
this.rbOffice2010Black.UseVisualStyleBackColor = true;
this.rbOffice2010Black.CheckedChanged += new System.EventHandler(this.rbOffice2010Black_CheckedChanged);
//
// rbOffice2010Silver
//
this.rbOffice2010Silver.AutoSize = true;
this.rbOffice2010Silver.Location = new System.Drawing.Point(24, 49);
this.rbOffice2010Silver.Name = "rbOffice2010Silver";
this.rbOffice2010Silver.Size = new System.Drawing.Size(117, 17);
this.rbOffice2010Silver.TabIndex = 1;
this.rbOffice2010Silver.Text = "Office 2010 - Silver";
this.rbOffice2010Silver.UseVisualStyleBackColor = true;
this.rbOffice2010Silver.CheckedChanged += new System.EventHandler(this.rbOffice2010Silver_CheckedChanged);
//
// rbOffice2010Blue
//
this.rbOffice2010Blue.AutoSize = true;
this.rbOffice2010Blue.Checked = true;
this.rbOffice2010Blue.Location = new System.Drawing.Point(24, 26);
this.rbOffice2010Blue.Name = "rbOffice2010Blue";
this.rbOffice2010Blue.Size = new System.Drawing.Size(111, 17);
this.rbOffice2010Blue.TabIndex = 0;
this.rbOffice2010Blue.TabStop = true;
this.rbOffice2010Blue.Text = "Office 2010 - Blue";
this.rbOffice2010Blue.UseVisualStyleBackColor = true;
this.rbOffice2010Blue.CheckedChanged += new System.EventHandler(this.rbOffice2010Blue_CheckedChanged);
//
// rbSparklePurple
//
this.rbSparklePurple.AutoSize = true;
this.rbSparklePurple.Location = new System.Drawing.Point(163, 72);
this.rbSparklePurple.Name = "rbSparklePurple";
this.rbSparklePurple.Size = new System.Drawing.Size(100, 17);
this.rbSparklePurple.TabIndex = 8;
this.rbSparklePurple.Text = "Sparkle - Purple";
this.rbSparklePurple.UseVisualStyleBackColor = true;
this.rbSparklePurple.CheckedChanged += new System.EventHandler(this.rbSparklePurple_CheckedChanged);
//
// rbSparkleOrange
//
this.rbSparkleOrange.AutoSize = true;
this.rbSparkleOrange.Location = new System.Drawing.Point(163, 49);
this.rbSparkleOrange.Name = "rbSparkleOrange";
this.rbSparkleOrange.Size = new System.Drawing.Size(106, 17);
this.rbSparkleOrange.TabIndex = 7;
this.rbSparkleOrange.Text = "Sparkle - Orange";
this.rbSparkleOrange.UseVisualStyleBackColor = true;
this.rbSparkleOrange.CheckedChanged += new System.EventHandler(this.rbSparkleOrange_CheckedChanged);
//
// rbSparkleBlue
//
this.rbSparkleBlue.AutoSize = true;
this.rbSparkleBlue.Location = new System.Drawing.Point(163, 26);
this.rbSparkleBlue.Name = "rbSparkleBlue";
this.rbSparkleBlue.Size = new System.Drawing.Size(90, 17);
this.rbSparkleBlue.TabIndex = 6;
this.rbSparkleBlue.Text = "Sparkle - Blue";
this.rbSparkleBlue.UseVisualStyleBackColor = true;
this.rbSparkleBlue.CheckedChanged += new System.EventHandler(this.rbSparkleBlue_CheckedChanged);
//
// rbSystem
//
this.rbSystem.AutoSize = true;
this.rbSystem.Location = new System.Drawing.Point(163, 127);
this.rbSystem.Name = "rbSystem";
this.rbSystem.Size = new System.Drawing.Size(60, 17);
this.rbSystem.TabIndex = 10;
this.rbSystem.Text = "System";
this.rbSystem.UseVisualStyleBackColor = true;
this.rbSystem.CheckedChanged += new System.EventHandler(this.rbSystem_CheckedChanged);
//
// rbOffice2003
//
this.rbOffice2003.AutoSize = true;
this.rbOffice2003.Location = new System.Drawing.Point(163, 104);
this.rbOffice2003.Name = "rbOffice2003";
this.rbOffice2003.Size = new System.Drawing.Size(81, 17);
this.rbOffice2003.TabIndex = 9;
this.rbOffice2003.Text = "Office 2003";
this.rbOffice2003.UseVisualStyleBackColor = true;
this.rbOffice2003.CheckedChanged += new System.EventHandler(this.rbOffice2003_CheckedChanged);
//
// rbOffice2007Black
//
this.rbOffice2007Black.AutoSize = true;
this.rbOffice2007Black.Location = new System.Drawing.Point(24, 150);
this.rbOffice2007Black.Name = "rbOffice2007Black";
this.rbOffice2007Black.Size = new System.Drawing.Size(115, 17);
this.rbOffice2007Black.TabIndex = 5;
this.rbOffice2007Black.Text = "Office 2007 - Black";
this.rbOffice2007Black.UseVisualStyleBackColor = true;
this.rbOffice2007Black.CheckedChanged += new System.EventHandler(this.rbOffice2007Black_CheckedChanged);
//
// rbOffice2007Silver
//
this.rbOffice2007Silver.AutoSize = true;
this.rbOffice2007Silver.Location = new System.Drawing.Point(24, 127);
this.rbOffice2007Silver.Name = "rbOffice2007Silver";
this.rbOffice2007Silver.Size = new System.Drawing.Size(117, 17);
this.rbOffice2007Silver.TabIndex = 4;
this.rbOffice2007Silver.Text = "Office 2007 - Silver";
this.rbOffice2007Silver.UseVisualStyleBackColor = true;
this.rbOffice2007Silver.CheckedChanged += new System.EventHandler(this.rbOffice2007Silver_CheckedChanged);
//
// rbOffice2007Blue
//
this.rbOffice2007Blue.AutoSize = true;
this.rbOffice2007Blue.Location = new System.Drawing.Point(24, 104);
this.rbOffice2007Blue.Name = "rbOffice2007Blue";
this.rbOffice2007Blue.Size = new System.Drawing.Size(111, 17);
this.rbOffice2007Blue.TabIndex = 3;
this.rbOffice2007Blue.Text = "Office 2007 - Blue";
this.rbOffice2007Blue.UseVisualStyleBackColor = true;
this.rbOffice2007Blue.CheckedChanged += new System.EventHandler(this.rbOffice2007Blue_CheckedChanged);
//
// groupBox4
//
this.groupBox4.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.groupBox4.Controls.Add(this.propertyGrid);
this.groupBox4.Location = new System.Drawing.Point(400, 12);
this.groupBox4.Name = "groupBox4";
this.groupBox4.Size = new System.Drawing.Size(319, 478);
this.groupBox4.TabIndex = 4;
this.groupBox4.TabStop = false;
this.groupBox4.Text = "Properties for KryptonDateTimePicker";
//
// propertyGrid
//
this.propertyGrid.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.propertyGrid.Location = new System.Drawing.Point(6, 19);
this.propertyGrid.Name = "propertyGrid";
this.propertyGrid.Size = new System.Drawing.Size(307, 453);
this.propertyGrid.TabIndex = 0;
this.propertyGrid.ToolbarVisible = false;
//
// buttonClose
//
this.buttonClose.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonClose.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.buttonClose.Location = new System.Drawing.Point(644, 500);
this.buttonClose.Name = "buttonClose";
this.buttonClose.Size = new System.Drawing.Size(75, 23);
this.buttonClose.TabIndex = 5;
this.buttonClose.Text = "&Close";
this.buttonClose.UseVisualStyleBackColor = true;
this.buttonClose.Click += new System.EventHandler(this.buttonClose_Click);
//
// kryptonPalette
//
this.kryptonPalette.BaseRenderMode = Krypton.Toolkit.RendererMode.Inherit;
//
// groupBoxRibbon
//
this.groupBoxRibbon.Controls.Add(this.dtpRibbonTime);
this.groupBoxRibbon.Controls.Add(this.dtpRibbonShort);
this.groupBoxRibbon.Controls.Add(this.dtpRibbonLong);
this.groupBoxRibbon.Location = new System.Drawing.Point(12, 162);
this.groupBoxRibbon.Name = "groupBoxRibbon";
this.groupBoxRibbon.Size = new System.Drawing.Size(382, 140);
this.groupBoxRibbon.TabIndex = 1;
this.groupBoxRibbon.TabStop = false;
this.groupBoxRibbon.Text = "Ribbon Style";
//
// dtpRibbonTime
//
this.dtpRibbonTime.AlwaysActive = false;
this.dtpRibbonTime.ButtonSpecs.AddRange(new Krypton.Toolkit.ButtonSpecAny[] {
this.buttonSpecAny2});
this.dtpRibbonTime.CalendarDimensions = new System.Drawing.Size(1, 1);
this.dtpRibbonTime.CalendarFirstDayOfWeek = System.Windows.Forms.Day.Default;
this.dtpRibbonTime.DropDownAlign = System.Windows.Forms.LeftRightAlignment.Left;
this.dtpRibbonTime.Format = System.Windows.Forms.DateTimePickerFormat.Time;
this.dtpRibbonTime.InputControlStyle = Krypton.Toolkit.InputControlStyle.Ribbon;
this.dtpRibbonTime.Location = new System.Drawing.Point(24, 92);
this.dtpRibbonTime.Name = "dtpRibbonTime";
this.dtpRibbonTime.Palette = this.kryptonPalette;
this.dtpRibbonTime.PaletteMode = Krypton.Toolkit.PaletteMode.Custom;
this.dtpRibbonTime.ShowUpDown = true;
this.dtpRibbonTime.Size = new System.Drawing.Size(204, 21);
this.dtpRibbonTime.TabIndex = 2;
this.dtpRibbonTime.Enter += new System.EventHandler(this.dtp_Enter);
//
// buttonSpecAny2
//
this.buttonSpecAny2.Style = Krypton.Toolkit.PaletteButtonStyle.Standalone;
this.buttonSpecAny2.Type = Krypton.Toolkit.PaletteButtonSpecStyle.Close;
this.buttonSpecAny2.UniqueName = "711F5E5D57D243B7711F5E5D57D243B7";
this.buttonSpecAny2.Click += new System.EventHandler(this.buttonSpecAny2_Click);
//
// dtpRibbonShort
//
this.dtpRibbonShort.AlwaysActive = false;
this.dtpRibbonShort.CalendarDimensions = new System.Drawing.Size(1, 1);
this.dtpRibbonShort.CalendarFirstDayOfWeek = System.Windows.Forms.Day.Default;
this.dtpRibbonShort.DropDownAlign = System.Windows.Forms.LeftRightAlignment.Left;
this.dtpRibbonShort.Format = System.Windows.Forms.DateTimePickerFormat.Short;
this.dtpRibbonShort.InputControlStyle = Krypton.Toolkit.InputControlStyle.Ribbon;
this.dtpRibbonShort.Location = new System.Drawing.Point(24, 63);
this.dtpRibbonShort.Name = "dtpRibbonShort";
this.dtpRibbonShort.Palette = this.kryptonPalette;
this.dtpRibbonShort.PaletteMode = Krypton.Toolkit.PaletteMode.Custom;
this.dtpRibbonShort.Size = new System.Drawing.Size(204, 21);
this.dtpRibbonShort.TabIndex = 1;
this.dtpRibbonShort.Enter += new System.EventHandler(this.dtp_Enter);
//
// dtpRibbonLong
//
this.dtpRibbonLong.AlwaysActive = false;
this.dtpRibbonLong.CalendarDimensions = new System.Drawing.Size(1, 1);
this.dtpRibbonLong.CalendarFirstDayOfWeek = System.Windows.Forms.Day.Default;
this.dtpRibbonLong.CustomNullText = "<Custom Text When Null>";
this.dtpRibbonLong.DropDownAlign = System.Windows.Forms.LeftRightAlignment.Left;
this.dtpRibbonLong.Format = System.Windows.Forms.DateTimePickerFormat.Long;
this.dtpRibbonLong.InputControlStyle = Krypton.Toolkit.InputControlStyle.Ribbon;
this.dtpRibbonLong.Location = new System.Drawing.Point(24, 34);
this.dtpRibbonLong.Name = "dtpRibbonLong";
this.dtpRibbonLong.Palette = this.kryptonPalette;
this.dtpRibbonLong.PaletteMode = Krypton.Toolkit.PaletteMode.Custom;
this.dtpRibbonLong.ShowCheckBox = true;
this.dtpRibbonLong.Size = new System.Drawing.Size(204, 21);
this.dtpRibbonLong.TabIndex = 0;
this.dtpRibbonLong.Enter += new System.EventHandler(this.dtp_Enter);
//
// groupBoxNormal
//
this.groupBoxNormal.Controls.Add(this.dtpNormalTime);
this.groupBoxNormal.Controls.Add(this.dtpNormalShort);
this.groupBoxNormal.Controls.Add(this.dtpNormalLong);
this.groupBoxNormal.Location = new System.Drawing.Point(12, 12);
this.groupBoxNormal.Name = "groupBoxNormal";
this.groupBoxNormal.Size = new System.Drawing.Size(382, 140);
this.groupBoxNormal.TabIndex = 0;
this.groupBoxNormal.TabStop = false;
this.groupBoxNormal.Text = "Normal Style";
//
// dtpNormalTime
//
this.dtpNormalTime.ButtonSpecs.AddRange(new Krypton.Toolkit.ButtonSpecAny[] {
this.buttonSpecAny1});
this.dtpNormalTime.CalendarDimensions = new System.Drawing.Size(1, 1);
this.dtpNormalTime.CalendarFirstDayOfWeek = System.Windows.Forms.Day.Default;
this.dtpNormalTime.DropDownAlign = System.Windows.Forms.LeftRightAlignment.Left;
this.dtpNormalTime.Format = System.Windows.Forms.DateTimePickerFormat.Time;
this.dtpNormalTime.Location = new System.Drawing.Point(24, 93);
this.dtpNormalTime.Name = "dtpNormalTime";
this.dtpNormalTime.Palette = this.kryptonPalette;
this.dtpNormalTime.PaletteMode = Krypton.Toolkit.PaletteMode.Custom;
this.dtpNormalTime.ShowUpDown = true;
this.dtpNormalTime.Size = new System.Drawing.Size(204, 21);
this.dtpNormalTime.TabIndex = 2;
this.dtpNormalTime.Enter += new System.EventHandler(this.dtp_Enter);
//
// buttonSpecAny1
//
this.buttonSpecAny1.Style = Krypton.Toolkit.PaletteButtonStyle.Standalone;
this.buttonSpecAny1.Type = Krypton.Toolkit.PaletteButtonSpecStyle.Close;
this.buttonSpecAny1.UniqueName = "529C8C7BCFA94ED8529C8C7BCFA94ED8";
this.buttonSpecAny1.Click += new System.EventHandler(this.buttonSpecAny1_Click);
//
// dtpNormalShort
//
this.dtpNormalShort.CalendarDimensions = new System.Drawing.Size(1, 1);
this.dtpNormalShort.CalendarFirstDayOfWeek = System.Windows.Forms.Day.Default;
this.dtpNormalShort.DropDownAlign = System.Windows.Forms.LeftRightAlignment.Left;
this.dtpNormalShort.Format = System.Windows.Forms.DateTimePickerFormat.Short;
this.dtpNormalShort.Location = new System.Drawing.Point(24, 64);
this.dtpNormalShort.Name = "dtpNormalShort";
this.dtpNormalShort.Palette = this.kryptonPalette;
this.dtpNormalShort.PaletteMode = Krypton.Toolkit.PaletteMode.Custom;
this.dtpNormalShort.Size = new System.Drawing.Size(204, 21);
this.dtpNormalShort.TabIndex = 1;
this.dtpNormalShort.Enter += new System.EventHandler(this.dtp_Enter);
//
// dtpNormalLong
//
this.dtpNormalLong.CalendarDimensions = new System.Drawing.Size(1, 1);
this.dtpNormalLong.CalendarFirstDayOfWeek = System.Windows.Forms.Day.Default;
this.dtpNormalLong.CustomNullText = "<Custom Text When Null>";
this.dtpNormalLong.DropDownAlign = System.Windows.Forms.LeftRightAlignment.Left;
this.dtpNormalLong.Format = System.Windows.Forms.DateTimePickerFormat.Long;
this.dtpNormalLong.Location = new System.Drawing.Point(24, 35);
this.dtpNormalLong.Name = "dtpNormalLong";
this.dtpNormalLong.Palette = this.kryptonPalette;
this.dtpNormalLong.PaletteMode = Krypton.Toolkit.PaletteMode.Custom;
this.dtpNormalLong.ShowCheckBox = true;
this.dtpNormalLong.Size = new System.Drawing.Size(204, 21);
this.dtpNormalLong.TabIndex = 0;
this.dtpNormalLong.Enter += new System.EventHandler(this.dtp_Enter);
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(729, 535);
this.Controls.Add(this.groupBoxRibbon);
this.Controls.Add(this.groupBoxNormal);
this.Controls.Add(this.buttonClose);
this.Controls.Add(this.groupBox4);
this.Controls.Add(this.groupBoxPalette);
this.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MaximizeBox = false;
this.MinimizeBox = false;
this.MinimumSize = new System.Drawing.Size(745, 573);
this.Name = "Form1";
this.Text = "KryptonDateTimePicker Examples";
this.Load += new System.EventHandler(this.Form1_Load);
this.groupBoxPalette.ResumeLayout(false);
this.groupBoxPalette.PerformLayout();
this.groupBox4.ResumeLayout(false);
this.groupBoxRibbon.ResumeLayout(false);
this.groupBoxNormal.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.GroupBox groupBoxPalette;
private System.Windows.Forms.RadioButton rbSparklePurple;
private System.Windows.Forms.RadioButton rbSparkleOrange;
private System.Windows.Forms.RadioButton rbSparkleBlue;
private System.Windows.Forms.RadioButton rbSystem;
private System.Windows.Forms.RadioButton rbOffice2003;
private System.Windows.Forms.RadioButton rbOffice2007Black;
private System.Windows.Forms.RadioButton rbOffice2007Silver;
private System.Windows.Forms.RadioButton rbOffice2007Blue;
private System.Windows.Forms.GroupBox groupBox4;
private System.Windows.Forms.PropertyGrid propertyGrid;
private System.Windows.Forms.Button buttonClose;
private Krypton.Toolkit.KryptonPalette kryptonPalette;
private System.Windows.Forms.GroupBox groupBoxRibbon;
private System.Windows.Forms.GroupBox groupBoxNormal;
private Krypton.Toolkit.KryptonDateTimePicker dtpRibbonTime;
private Krypton.Toolkit.KryptonDateTimePicker dtpRibbonShort;
private Krypton.Toolkit.KryptonDateTimePicker dtpRibbonLong;
private Krypton.Toolkit.KryptonDateTimePicker dtpNormalTime;
private Krypton.Toolkit.KryptonDateTimePicker dtpNormalShort;
private Krypton.Toolkit.KryptonDateTimePicker dtpNormalLong;
private Krypton.Toolkit.ButtonSpecAny buttonSpecAny2;
private Krypton.Toolkit.ButtonSpecAny buttonSpecAny1;
private System.Windows.Forms.RadioButton rbOffice2010Black;
private System.Windows.Forms.RadioButton rbOffice2010Silver;
private System.Windows.Forms.RadioButton rbOffice2010Blue;
}
}
| 56.455982 | 162 | 0.648581 | [
"BSD-3-Clause"
] | Krypton-Suite/Standard-Toolkit-Demos | Source/Krypton Toolkit Examples/KryptonDateTimePicker Examples/Form1.Designer.cs | 25,012 | C# |
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.Aws.WafV2.Outputs
{
[OutputType]
public sealed class RuleGroupRuleStatementByteMatchStatementFieldToMatchQueryString
{
[OutputConstructor]
private RuleGroupRuleStatementByteMatchStatementFieldToMatchQueryString()
{
}
}
}
| 27.363636 | 88 | 0.737542 | [
"ECL-2.0",
"Apache-2.0"
] | Otanikotani/pulumi-aws | sdk/dotnet/WafV2/Outputs/RuleGroupRuleStatementByteMatchStatementFieldToMatchQueryString.cs | 602 | C# |
using System;
using CBS.Data;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.UI;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
[assembly: HostingStartup(typeof(CBS.Areas.Identity.IdentityHostingStartup))]
namespace CBS.Areas.Identity
{
public class IdentityHostingStartup : IHostingStartup
{
public void Configure(IWebHostBuilder builder)
{
builder.ConfigureServices((context, services) => {
});
}
}
} | 28.857143 | 77 | 0.745875 | [
"MIT"
] | masonclarke24/CBS | src/ClubBAISTSystem/CBS/Areas/Identity/IdentityHostingStartup.cs | 608 | C# |
using Android.App;
using Android.Content;
using Android.Content.PM;
using Android.OS;
using Android.Widget;
namespace MWC.Android.Screens {
[Activity(Label = "Home", ScreenOrientation = ScreenOrientation.Portrait)]
public class HomeScreen : BaseScreen {
protected MWC.Adapters.DaysListAdapter dayList;
protected ListView dayListView = null;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// set our layout to be the home screen
SetContentView(Resource.Layout.HomeScreen);
//Find our controls
dayListView = FindViewById<ListView>(Resource.Id.DayList);
// wire up task click handler
if (dayListView != null) {
dayListView.ItemClick += (object sender, AdapterView.ItemClickEventArgs e) => {
var sessionDetails = new Intent(this, typeof(SessionsScreen));
sessionDetails.PutExtra("DayID", e.Position + 1);
StartActivity(sessionDetails);
};
}
}
protected override void OnResume()
{
base.OnResume();
// create our adapter
dayList = new MWC.Adapters.DaysListAdapter(this);
//Hook up our adapter to our ListView
dayListView.Adapter = this.dayList;
}
}
}
| 32.177778 | 96 | 0.577348 | [
"Apache-2.0"
] | Eg-Virus/mobile-samples | MWC/MWC.Droid/Screens/Home/HomeScreen.cs | 1,450 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace CaseAPI.PegaClasses
{
public partial class Pega
{
public string pyLabel { get; set; }
public string pyNote { get; set; }
public string pxCreateDateTime { get; set; }
public string pzInsKey { get; set; }
public string pyTemplateDisplayText { get; set; }
public override string ToString()
{
return JsonSerializer.Serialize(this);
}
}
}
| 25.590909 | 57 | 0.646536 | [
"MIT"
] | microsoft/GBB-Business-Applications | demos/migration-pega-to-d365/src/AzureFunctions/CaseAPI/PegaClasses/Pega.cs | 565 | C# |
using System;
using System.Windows.Input;
namespace AupRename
{
public class DelegateCommand : ICommand
{
private readonly Action _execute;
private readonly Func<bool> _canExecute;
public event EventHandler CanExecuteChanged;
public DelegateCommand(Action execute)
: this(execute, null)
{
}
public DelegateCommand(Action execute, Func<bool> canExecute)
{
_execute = execute ?? throw new ArgumentException(null, nameof(execute));
_canExecute = canExecute;
}
public bool CanExecute(object parameter)
{
return _canExecute == null || _canExecute();
}
public void Execute(object parameter)
{
_execute();
}
public void RaiseCanExecuteChanged()
{
CanExecuteChanged?.Invoke(this, EventArgs.Empty);
}
}
}
| 23.3 | 85 | 0.587983 | [
"MIT"
] | karoterra/AupRename | AupRename/DelegateCommand.cs | 934 | C# |
/*
* Copyright (c) 2018 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
namespace TencentCloud.Tdcpg.V20211118.Models
{
using Newtonsoft.Json;
using System.Collections.Generic;
using TencentCloud.Common;
public class DescribeResourcesByDealNameRequest : AbstractModel
{
/// <summary>
/// 计费订单id(如果计费还没回调业务发货,可能出现错误码InvalidParameterValue.DealNameNotFound,这种情况需要业务重试DescribeResourcesByDealName接口直到成功)
/// </summary>
[JsonProperty("DealName")]
public string DealName{ get; set; }
/// <summary>
/// For internal usage only. DO NOT USE IT.
/// </summary>
public override void ToMap(Dictionary<string, string> map, string prefix)
{
this.SetParamSimple(map, prefix + "DealName", this.DealName);
}
}
}
| 32 | 122 | 0.682528 | [
"Apache-2.0"
] | tencentcloudapi-test/tencentcloud-sdk-dotnet | TencentCloud/Tdcpg/V20211118/Models/DescribeResourcesByDealNameRequest.cs | 1,494 | C# |
using System;
namespace GenericScale
{
class Program
{
static void Main(string[] args)
{
int left = 1;
int right = 2;
EqualityScale<int> equalityScale = new EqualityScale<int>(left, right);
Console.WriteLine(equalityScale.AreEqual()); // false
int leftTwo = 5;
int rightTwo = 5;
EqualityScale<int> eqs2 = new EqualityScale<int>(leftTwo, rightTwo);
Console.WriteLine(eqs2.AreEqual()); // true
}
}
}
| 23.26087 | 83 | 0.547664 | [
"MIT"
] | kristiyanivanovx/SoftUni-Programming-Basics-March-2020 | 03 - CSharp-Advanced/08 - Generics - Lab & Exercise/GenericScale/Program.cs | 537 | C# |
using NBatch.Main.Readers.SqlReader;
using NUnit.Framework;
namespace NBatch.Main.UnitTests.Readers.SqlReader
{
[TestFixture]
class SqlDbItemReaderTests
{
[Test]
public void DbIsCalledForActualExecution()
{
var fakeDb = new FakeDb();
var sqlReader = new SqlDbItemReader<string>(fakeDb)
.Query("query")
.OrderBy("foo");
sqlReader.Read(0, 10);
Assert.That(fakeDb.ExecuteCalled, Is.True);
}
[Test]
public void OrderByClauseMustBeSet()
{
var sqlReader = new SqlDbItemReader<string>(new FakeDb());
Assert.That(() => sqlReader.Read(0, 10), Throws.Exception.Message.Contains("order by clause"));
}
}
} | 26.1 | 107 | 0.578544 | [
"MIT"
] | tenzinkabsang/NBatch | src/NBatch.Main.UnitTests/Readers/SqlReader/SqlDbItemReaderTests.cs | 783 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Security.Principal;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Data.ProviderBase;
using Microsoft.Data.SqlClient.Server;
[assembly: InternalsVisibleTo("System.Data.DataSetExtensions, PublicKey=" + Microsoft.Data.SqlClient.AssemblyRef.EcmaPublicKeyFull)] // DevDiv Bugs 92166
namespace Microsoft.Data.SqlClient
{
using System.Diagnostics.Tracing;
using Microsoft.Data.Common;
/// <include file='..\..\..\..\..\..\..\doc\snippets\Microsoft.Data.SqlClient\SqlConnection.xml' path='docs/members[@name="SqlConnection"]/SqlConnection/*' />
[DefaultEvent("InfoMessage")]
public sealed partial class SqlConnection : DbConnection, ICloneable
{
internal bool ForceNewConnection
{
get;
set;
}
internal bool _suppressStateChangeForReconnection = false; // Do not use for anything else ! Value will be overwritten by CR process
static private readonly object EventInfoMessage = new object();
// System column encryption key store providers are added by default
static private readonly Dictionary<string, SqlColumnEncryptionKeyStoreProvider> _SystemColumnEncryptionKeyStoreProviders
= new Dictionary<string, SqlColumnEncryptionKeyStoreProvider>(capacity: 1, comparer: StringComparer.OrdinalIgnoreCase)
{
{SqlColumnEncryptionCertificateStoreProvider.ProviderName, new SqlColumnEncryptionCertificateStoreProvider()},
{SqlColumnEncryptionCngProvider.ProviderName, new SqlColumnEncryptionCngProvider()},
{SqlColumnEncryptionCspProvider.ProviderName, new SqlColumnEncryptionCspProvider()}
};
/// <summary>
/// Custom provider list should be provided by the user. We shallow copy the user supplied dictionary into a ReadOnlyDictionary.
/// Custom provider list can only supplied once per application.
/// </summary>
static private ReadOnlyDictionary<string, SqlColumnEncryptionKeyStoreProvider> _CustomColumnEncryptionKeyStoreProviders;
// Lock to control setting of _CustomColumnEncryptionKeyStoreProviders
static private readonly Object _CustomColumnEncryptionKeyProvidersLock = new Object();
/// <summary>
/// Dictionary object holding trusted key paths for various SQL Servers.
/// Key to the dictionary is a SQL Server Name
/// IList contains a list of trusted key paths.
/// </summary>
static private readonly ConcurrentDictionary<string, IList<string>> _ColumnEncryptionTrustedMasterKeyPaths
= new ConcurrentDictionary<string, IList<string>>(concurrencyLevel: 4 * Environment.ProcessorCount /* default value in ConcurrentDictionary*/,
capacity: 1,
comparer: StringComparer.OrdinalIgnoreCase);
/// <include file='..\..\..\..\..\..\..\doc\snippets\Microsoft.Data.SqlClient\SqlConnection.xml' path='docs/members[@name="SqlConnection"]/ColumnEncryptionTrustedMasterKeyPaths/*' />
[
DefaultValue(null),
ResCategoryAttribute(StringsHelper.ResourceNames.DataCategory_Data),
ResDescriptionAttribute(StringsHelper.ResourceNames.TCE_SqlConnection_TrustedColumnMasterKeyPaths),
]
static public IDictionary<string, IList<string>> ColumnEncryptionTrustedMasterKeyPaths
{
get
{
return _ColumnEncryptionTrustedMasterKeyPaths;
}
}
/// <summary>
/// Defines whether query metadata caching is enabled.
/// </summary>
static private bool _ColumnEncryptionQueryMetadataCacheEnabled = true;
/// <include file='..\..\..\..\..\..\..\doc\snippets\Microsoft.Data.SqlClient\SqlConnection.xml' path='docs/members[@name="SqlConnection"]/ColumnEncryptionQueryMetadataCacheEnabled/*' />
[
DefaultValue(null),
ResCategoryAttribute(StringsHelper.ResourceNames.DataCategory_Data),
ResDescriptionAttribute(StringsHelper.ResourceNames.TCE_SqlConnection_ColumnEncryptionQueryMetadataCacheEnabled),
]
static public bool ColumnEncryptionQueryMetadataCacheEnabled
{
get
{
return _ColumnEncryptionQueryMetadataCacheEnabled;
}
set
{
_ColumnEncryptionQueryMetadataCacheEnabled = value;
}
}
/// <summary>
/// Defines whether query metadata caching is enabled.
/// </summary>
static private TimeSpan _ColumnEncryptionKeyCacheTtl = TimeSpan.FromHours(2);
/// <include file='..\..\..\..\..\..\..\doc\snippets\Microsoft.Data.SqlClient\SqlConnection.xml' path='docs/members[@name="SqlConnection"]/ColumnEncryptionKeyCacheTtl/*' />
[
DefaultValue(null),
ResCategoryAttribute(StringsHelper.ResourceNames.DataCategory_Data),
ResDescriptionAttribute(StringsHelper.ResourceNames.TCE_SqlConnection_ColumnEncryptionKeyCacheTtl),
]
static public TimeSpan ColumnEncryptionKeyCacheTtl
{
get
{
return _ColumnEncryptionKeyCacheTtl;
}
set
{
_ColumnEncryptionKeyCacheTtl = value;
}
}
/// <include file='..\..\..\..\..\..\..\doc\snippets\Microsoft.Data.SqlClient\SqlConnection.xml' path='docs/members[@name="SqlConnection"]/RegisterColumnEncryptionKeyStoreProviders/*' />
static public void RegisterColumnEncryptionKeyStoreProviders(IDictionary<string, SqlColumnEncryptionKeyStoreProvider> customProviders)
{
// Return when the provided dictionary is null.
if (customProviders == null)
{
throw SQL.NullCustomKeyStoreProviderDictionary();
}
// Validate that custom provider list doesn't contain any of system provider list
foreach (string key in customProviders.Keys)
{
// Validate the provider name
//
// Check for null or empty
if (string.IsNullOrWhiteSpace(key))
{
throw SQL.EmptyProviderName();
}
// Check if the name starts with MSSQL_, since this is reserved namespace for system providers.
if (key.StartsWith(ADP.ColumnEncryptionSystemProviderNamePrefix, StringComparison.InvariantCultureIgnoreCase))
{
throw SQL.InvalidCustomKeyStoreProviderName(key, ADP.ColumnEncryptionSystemProviderNamePrefix);
}
// Validate the provider value
if (customProviders[key] == null)
{
throw SQL.NullProviderValue(key);
}
}
lock (_CustomColumnEncryptionKeyProvidersLock)
{
// Provider list can only be set once
if (_CustomColumnEncryptionKeyStoreProviders != null)
{
throw SQL.CanOnlyCallOnce();
}
// Create a temporary dictionary and then add items from the provided dictionary.
// Dictionary constructor does shallow copying by simply copying the provider name and provider reference pairs
// in the provided customerProviders dictionary.
Dictionary<string, SqlColumnEncryptionKeyStoreProvider> customColumnEncryptionKeyStoreProviders =
new Dictionary<string, SqlColumnEncryptionKeyStoreProvider>(customProviders, StringComparer.OrdinalIgnoreCase);
// Set the dictionary to the ReadOnly dictionary.
_CustomColumnEncryptionKeyStoreProviders = new ReadOnlyDictionary<string, SqlColumnEncryptionKeyStoreProvider>(customColumnEncryptionKeyStoreProviders);
}
}
/// <summary>
/// This function walks through both system and custom column encryption key store providers and returns an object if found.
/// </summary>
/// <param name="providerName">Provider Name to be searched in System Provider diction and Custom provider dictionary.</param>
/// <param name="columnKeyStoreProvider">If the provider is found, returns the corresponding SqlColumnEncryptionKeyStoreProvider instance.</param>
/// <returns>true if the provider is found, else returns false</returns>
static internal bool TryGetColumnEncryptionKeyStoreProvider(string providerName, out SqlColumnEncryptionKeyStoreProvider columnKeyStoreProvider)
{
Debug.Assert(!string.IsNullOrWhiteSpace(providerName), "Provider name is invalid");
// Initialize the out parameter
columnKeyStoreProvider = null;
// Search in the sytem provider list.
if (_SystemColumnEncryptionKeyStoreProviders.TryGetValue(providerName, out columnKeyStoreProvider))
{
return true;
}
lock (_CustomColumnEncryptionKeyProvidersLock)
{
// If custom provider is not set, then return false
if (_CustomColumnEncryptionKeyStoreProviders == null)
{
return false;
}
// Search in the custom provider list
return _CustomColumnEncryptionKeyStoreProviders.TryGetValue(providerName, out columnKeyStoreProvider);
}
}
/// <summary>
/// This function returns a list of system provider dictionary currently supported by this driver.
/// </summary>
/// <returns>Combined list of provider names</returns>
static internal List<string> GetColumnEncryptionSystemKeyStoreProviders()
{
HashSet<string> providerNames = new HashSet<string>(_SystemColumnEncryptionKeyStoreProviders.Keys);
return providerNames.ToList();
}
/// <summary>
/// This function returns a list of custom provider dictionary currently registered.
/// </summary>
/// <returns>Combined list of provider names</returns>
static internal List<string> GetColumnEncryptionCustomKeyStoreProviders()
{
if (_CustomColumnEncryptionKeyStoreProviders != null)
{
HashSet<string> providerNames = new HashSet<string>(_CustomColumnEncryptionKeyStoreProviders.Keys);
return providerNames.ToList();
}
return new List<string>();
}
private SqlDebugContext _sdc; // SQL Debugging support
private bool _AsyncCommandInProgress;
// SQLStatistics support
internal SqlStatistics _statistics;
private bool _collectstats;
private bool _fireInfoMessageEventOnUserErrors; // False by default
// root task associated with current async invocation
Tuple<TaskCompletionSource<DbConnectionInternal>, Task> _currentCompletion;
private SqlCredential _credential; // SQL authentication password stored in SecureString
private string _connectionString;
private int _connectRetryCount;
private string _accessToken; // Access Token to be used for token based authententication
// connection resiliency
private object _reconnectLock = new object();
internal Task _currentReconnectionTask;
private Task _asyncWaitingForReconnection; // current async task waiting for reconnection in non-MARS connections
private Guid _originalConnectionId = Guid.Empty;
private CancellationTokenSource _reconnectionCancellationSource;
internal SessionData _recoverySessionData;
internal WindowsIdentity _lastIdentity;
internal WindowsIdentity _impersonateIdentity;
private int _reconnectCount;
private ServerCertificateValidationCallback _serverCertificateValidationCallback;
private ClientCertificateRetrievalCallback _clientCertificateRetrievalCallback;
private SqlClientOriginalNetworkAddressInfo _originalNetworkAddressInfo;
// Transient Fault handling flag. This is needed to convey to the downstream mechanism of connection establishment, if Transient Fault handling should be used or not
// The downstream handling of Connection open is the same for idle connection resiliency. Currently we want to apply transient fault handling only to the connections opened
// using SqlConnection.Open() method.
internal bool _applyTransientFaultHandling = false;
/// <include file='..\..\..\..\..\..\..\doc\snippets\Microsoft.Data.SqlClient\SqlConnection.xml' path='docs/members[@name="SqlConnection"]/ctorConnectionString/*' />
public SqlConnection(string connectionString) : this(connectionString, null)
{
}
/// <include file='..\..\..\..\..\..\..\doc\snippets\Microsoft.Data.SqlClient\SqlConnection.xml' path='docs/members[@name="SqlConnection"]/ctorConnectionStringCredential/*' />
public SqlConnection(string connectionString, SqlCredential credential) : this()
{
ConnectionString = connectionString; // setting connection string first so that ConnectionOption is available
if (credential != null)
{
// The following checks are necessary as setting Credential property will call CheckAndThrowOnInvalidCombinationOfConnectionStringAndSqlCredential
// CheckAndThrowOnInvalidCombinationOfConnectionStringAndSqlCredential it will throw InvalidOperationException rather than Arguemtn exception
// Need to call setter on Credential property rather than setting _credential directly as pool groups need to be checked
SqlConnectionString connectionOptions = (SqlConnectionString)ConnectionOptions;
if (UsesClearUserIdOrPassword(connectionOptions))
{
throw ADP.InvalidMixedArgumentOfSecureAndClearCredential();
}
if (UsesIntegratedSecurity(connectionOptions))
{
throw ADP.InvalidMixedArgumentOfSecureCredentialAndIntegratedSecurity();
}
if (UsesContextConnection(connectionOptions))
{
throw ADP.InvalidMixedArgumentOfSecureCredentialAndContextConnection();
}
if (UsesActiveDirectoryIntegrated(connectionOptions))
{
throw SQL.SettingCredentialWithIntegratedArgument();
}
if (UsesActiveDirectoryInteractive(connectionOptions))
{
throw SQL.SettingCredentialWithInteractiveArgument();
}
if (UsesActiveDirectoryDeviceCodeFlow(connectionOptions))
{
throw SQL.SettingCredentialWithDeviceFlowArgument();
}
Credential = credential;
}
// else
// credential == null: we should not set "Credential" as this will do additional validation check and
// checking pool groups which is not necessary. All necessary operation is already done by calling "ConnectionString = connectionString"
}
private SqlConnection(SqlConnection connection)
{ // Clone
GC.SuppressFinalize(this);
CopyFrom(connection);
_connectionString = connection._connectionString;
if (connection._credential != null)
{
SecureString password = connection._credential.Password.Copy();
password.MakeReadOnly();
_credential = new SqlCredential(connection._credential.UserId, password);
}
_accessToken = connection._accessToken;
_serverCertificateValidationCallback = connection._serverCertificateValidationCallback;
_clientCertificateRetrievalCallback = connection._clientCertificateRetrievalCallback;
_originalNetworkAddressInfo = connection._originalNetworkAddressInfo;
CacheConnectionStringProperties();
}
// This method will be called once connection string is set or changed.
private void CacheConnectionStringProperties()
{
SqlConnectionString connString = ConnectionOptions as SqlConnectionString;
if (connString != null)
{
_connectRetryCount = connString.ConnectRetryCount;
// For Azure SQL connection, set _connectRetryCount to 2 instead of 1 will greatly improve recovery
// success rate
if (_connectRetryCount == 1 && ADP.IsAzureSqlServerEndpoint(connString.DataSource))
{
_connectRetryCount = 2;
}
}
}
//
// PUBLIC PROPERTIES
//
/// <include file='..\..\..\..\..\..\..\doc\snippets\Microsoft.Data.SqlClient\SqlConnection.xml' path='docs/members[@name="SqlConnection"]/StatisticsEnabled/*' />
// used to start/stop collection of statistics data and do verify the current state
//
// devnote: start/stop should not performed using a property since it requires execution of code
//
// start statistics
// set the internal flag (_statisticsEnabled) to true.
// Create a new SqlStatistics object if not already there.
// connect the parser to the object.
// if there is no parser at this time we need to connect it after creation.
[
DefaultValue(false),
ResCategoryAttribute(StringsHelper.ResourceNames.DataCategory_Data),
ResDescriptionAttribute(StringsHelper.ResourceNames.SqlConnection_StatisticsEnabled),
]
public bool StatisticsEnabled
{
get
{
return (_collectstats);
}
set
{
if (IsContextConnection)
{
if (value)
{
throw SQL.NotAvailableOnContextConnection();
}
}
else
{
if (value)
{
// start
if (ConnectionState.Open == State)
{
if (null == _statistics)
{
_statistics = new SqlStatistics();
ADP.TimerCurrent(out _statistics._openTimestamp);
}
// set statistics on the parser
// update timestamp;
Debug.Assert(Parser != null, "Where's the parser?");
Parser.Statistics = _statistics;
}
}
else
{
// stop
if (null != _statistics)
{
if (ConnectionState.Open == State)
{
// remove statistics from parser
// update timestamp;
TdsParser parser = Parser;
Debug.Assert(parser != null, "Where's the parser?");
parser.Statistics = null;
ADP.TimerCurrent(out _statistics._closeTimestamp);
}
}
}
this._collectstats = value;
}
}
}
internal bool AsyncCommandInProgress
{
get
{
return (_AsyncCommandInProgress);
}
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
set
{
_AsyncCommandInProgress = value;
}
}
internal bool IsContextConnection
{
get
{
SqlConnectionString opt = (SqlConnectionString)ConnectionOptions;
return UsesContextConnection(opt);
}
}
/// <summary>
/// Is this connection using column encryption ?
/// </summary>
internal bool IsColumnEncryptionSettingEnabled
{
get
{
SqlConnectionString opt = (SqlConnectionString)ConnectionOptions;
return opt != null ? opt.ColumnEncryptionSetting == SqlConnectionColumnEncryptionSetting.Enabled : false;
}
}
/// <summary>
/// Get enclave attestation url to be used with enclave based Always Encrypted
/// </summary>
internal string EnclaveAttestationUrl
{
get
{
SqlConnectionString opt = (SqlConnectionString)ConnectionOptions;
return opt.EnclaveAttestationUrl;
}
}
/// <summary>
/// Get attestation protocol
/// </summary>
internal SqlConnectionAttestationProtocol AttestationProtocol
{
get
{
SqlConnectionString opt = (SqlConnectionString)ConnectionOptions;
return opt.AttestationProtocol;
}
}
// Is this connection is a Context Connection?
private bool UsesContextConnection(SqlConnectionString opt)
{
return opt != null ? opt.ContextConnection : false;
}
private bool UsesActiveDirectoryIntegrated(SqlConnectionString opt)
{
return opt != null ? opt.Authentication == SqlAuthenticationMethod.ActiveDirectoryIntegrated : false;
}
private bool UsesActiveDirectoryInteractive(SqlConnectionString opt)
{
return opt != null ? opt.Authentication == SqlAuthenticationMethod.ActiveDirectoryInteractive : false;
}
private bool UsesActiveDirectoryDeviceCodeFlow(SqlConnectionString opt)
{
return opt != null ? opt.Authentication == SqlAuthenticationMethod.ActiveDirectoryDeviceCodeFlow : false;
}
private bool UsesAuthentication(SqlConnectionString opt)
{
return opt != null ? opt.Authentication != SqlAuthenticationMethod.NotSpecified : false;
}
// Does this connection uses Integrated Security?
private bool UsesIntegratedSecurity(SqlConnectionString opt)
{
return opt != null ? opt.IntegratedSecurity : false;
}
// Does this connection uses old style of clear userID or Password in connection string?
private bool UsesClearUserIdOrPassword(SqlConnectionString opt)
{
bool result = false;
if (null != opt)
{
result = (!ADP.IsEmpty(opt.UserID) || !ADP.IsEmpty(opt.Password));
}
return result;
}
private bool UsesCertificate(SqlConnectionString opt)
{
return opt != null ? opt.UsesCertificate : false;
}
internal SqlConnectionString.TransactionBindingEnum TransactionBinding
{
get
{
return ((SqlConnectionString)ConnectionOptions).TransactionBinding;
}
}
internal SqlConnectionString.TypeSystem TypeSystem
{
get
{
return ((SqlConnectionString)ConnectionOptions).TypeSystemVersion;
}
}
internal Version TypeSystemAssemblyVersion
{
get
{
return ((SqlConnectionString)ConnectionOptions).TypeSystemAssemblyVersion;
}
}
internal PoolBlockingPeriod PoolBlockingPeriod
{
get
{
return ((SqlConnectionString)ConnectionOptions).PoolBlockingPeriod;
}
}
internal int ConnectRetryInterval
{
get
{
return ((SqlConnectionString)ConnectionOptions).ConnectRetryInterval;
}
}
/// <include file='..\..\..\..\..\..\..\doc\snippets\Microsoft.Data.SqlClient\SqlConnection.xml' path='docs/members[@name="SqlConnection"]/DbProviderFactory/*' />
override protected DbProviderFactory DbProviderFactory
{
get
{
return SqlClientFactory.Instance;
}
}
// AccessToken: To be used for token based authentication
/// <include file='..\..\..\..\..\..\..\doc\snippets\Microsoft.Data.SqlClient\SqlConnection.xml' path='docs/members[@name="SqlConnection"]/AccessToken/*' />
[
Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
ResDescriptionAttribute(StringsHelper.ResourceNames.SqlConnection_AccessToken),
]
public string AccessToken
{
get
{
string result = _accessToken;
// When a connection is connecting or is ever opened, make AccessToken available only if "Persist Security Info" is set to true
// otherwise, return null
SqlConnectionString connectionOptions = (SqlConnectionString)UserConnectionOptions;
if (InnerConnection.ShouldHidePassword && connectionOptions != null && !connectionOptions.PersistSecurityInfo)
{
result = null;
}
return result;
}
set
{
// If a connection is connecting or is ever opened, AccessToken cannot be set
if (!InnerConnection.AllowSetConnectionString)
{
throw ADP.OpenConnectionPropertySet("AccessToken", InnerConnection.State);
}
if (value != null)
{
// Check if the usage of AccessToken has any conflict with the keys used in connection string and credential
CheckAndThrowOnInvalidCombinationOfConnectionOptionAndAccessToken((SqlConnectionString)ConnectionOptions);
}
_accessToken = value;
// Need to call ConnectionString_Set to do proper pool group check
ConnectionString_Set(new SqlConnectionPoolKey(_connectionString, _credential, _accessToken, _serverCertificateValidationCallback, _clientCertificateRetrievalCallback, _originalNetworkAddressInfo));
}
}
/// <include file='..\..\..\..\..\..\..\doc\snippets\Microsoft.Data.SqlClient\SqlConnection.xml' path='docs/members[@name="SqlConnection"]/ConnectionString/*' />
[
DefaultValue(""),
#pragma warning disable 618 // ignore obsolete warning about RecommendedAsConfigurable to use SettingsBindableAttribute
RecommendedAsConfigurable(true),
#pragma warning restore 618
SettingsBindableAttribute(true),
RefreshProperties(RefreshProperties.All),
ResCategoryAttribute(StringsHelper.ResourceNames.DataCategory_Data),
Editor("Microsoft.VSDesigner.Data.SQL.Design.SqlConnectionStringEditor, " + AssemblyRef.MicrosoftVSDesigner, "System.Drawing.Design.UITypeEditor, " + AssemblyRef.SystemDrawing),
ResDescriptionAttribute(StringsHelper.ResourceNames.SqlConnection_ConnectionString),
]
override public string ConnectionString
{
get
{
return ConnectionString_Get();
}
set
{
if (_credential != null || _accessToken != null)
{
SqlConnectionString connectionOptions = new SqlConnectionString(value);
if (_credential != null)
{
// Check for Credential being used with Authentication=ActiveDirectoryIntegrated/ActiveDirectoryInteractive/ActiveDirectoryDeviceCodeFlow. Since a different error string is used
// for this case in ConnectionString setter vs in Credential setter, check for this error case before calling
// CheckAndThrowOnInvalidCombinationOfConnectionStringAndSqlCredential, which is common to both setters.
if (UsesActiveDirectoryIntegrated(connectionOptions))
{
throw SQL.SettingIntegratedWithCredential();
}
else if (UsesActiveDirectoryInteractive(connectionOptions))
{
throw SQL.SettingInteractiveWithCredential();
}
else if (UsesActiveDirectoryDeviceCodeFlow(connectionOptions))
{
throw SQL.SettingDeviceFlowWithCredential();
}
CheckAndThrowOnInvalidCombinationOfConnectionStringAndSqlCredential(connectionOptions);
}
else if (_accessToken != null)
{
CheckAndThrowOnInvalidCombinationOfConnectionOptionAndAccessToken(connectionOptions);
}
}
ConnectionString_Set(new SqlConnectionPoolKey(value, _credential, _accessToken, _serverCertificateValidationCallback, _clientCertificateRetrievalCallback, _originalNetworkAddressInfo));
_connectionString = value; // Change _connectionString value only after value is validated
CacheConnectionStringProperties();
}
}
/// <include file='..\..\..\..\..\..\..\doc\snippets\Microsoft.Data.SqlClient\SqlConnection.xml' path='docs/members[@name="SqlConnection"]/ConnectionTimeout/*' />
[
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
ResDescriptionAttribute(StringsHelper.ResourceNames.SqlConnection_ConnectionTimeout),
]
override public int ConnectionTimeout
{
get
{
SqlConnectionString constr = (SqlConnectionString)ConnectionOptions;
return ((null != constr) ? constr.ConnectTimeout : SqlConnectionString.DEFAULT.Connect_Timeout);
}
}
/// <include file='..\..\..\..\..\..\..\doc\snippets\Microsoft.Data.SqlClient\SqlConnection.xml' path='docs/members[@name="SqlConnection"]/Database/*' />
[
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
ResDescriptionAttribute(StringsHelper.ResourceNames.SqlConnection_Database),
]
override public string Database
{
// if the connection is open, we need to ask the inner connection what it's
// current catalog is because it may have gotten changed, otherwise we can
// just return what the connection string had.
get
{
SqlInternalConnection innerConnection = (InnerConnection as SqlInternalConnection);
string result;
if (null != innerConnection)
{
result = innerConnection.CurrentDatabase;
}
else
{
SqlConnectionString constr = (SqlConnectionString)ConnectionOptions;
result = ((null != constr) ? constr.InitialCatalog : SqlConnectionString.DEFAULT.Initial_Catalog);
}
return result;
}
}
///
/// To indicate the IsSupported flag sent by the server for DNS Caching. This property is for internal testing only.
///
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
internal string SQLDNSCachingSupportedState
{
get
{
SqlInternalConnectionTds innerConnection = (InnerConnection as SqlInternalConnectionTds);
string result;
if (null != innerConnection)
{
result = innerConnection.IsSQLDNSCachingSupported ? "true" : "false";
}
else
{
result = "innerConnection is null!";
}
return result;
}
}
///
/// To indicate the IsSupported flag sent by the server for DNS Caching before redirection. This property is for internal testing only.
///
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
internal string SQLDNSCachingSupportedStateBeforeRedirect
{
get
{
SqlInternalConnectionTds innerConnection = (InnerConnection as SqlInternalConnectionTds);
string result;
if (null != innerConnection)
{
result = innerConnection.IsDNSCachingBeforeRedirectSupported ? "true" : "false";
}
else
{
result = "innerConnection is null!";
}
return result;
}
}
/// <include file='..\..\..\..\..\..\..\doc\snippets\Microsoft.Data.SqlClient\SqlConnection.xml' path='docs/members[@name="SqlConnection"]/DataSource/*' />
[
Browsable(true),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
ResDescriptionAttribute(StringsHelper.ResourceNames.SqlConnection_DataSource),
]
override public string DataSource
{
get
{
SqlInternalConnection innerConnection = (InnerConnection as SqlInternalConnection);
string result;
if (null != innerConnection)
{
result = innerConnection.CurrentDataSource;
}
else
{
SqlConnectionString constr = (SqlConnectionString)ConnectionOptions;
result = ((null != constr) ? constr.DataSource : SqlConnectionString.DEFAULT.Data_Source);
}
return result;
}
}
/// <include file='..\..\..\..\..\..\..\doc\snippets\Microsoft.Data.SqlClient\SqlConnection.xml' path='docs/members[@name="SqlConnection"]/PacketSize/*' />
[
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
ResCategoryAttribute(StringsHelper.ResourceNames.DataCategory_Data),
ResDescriptionAttribute(StringsHelper.ResourceNames.SqlConnection_PacketSize),
]
public int PacketSize
{
// if the connection is open, we need to ask the inner connection what it's
// current packet size is because it may have gotten changed, otherwise we
// can just return what the connection string had.
get
{
if (IsContextConnection)
{
throw SQL.NotAvailableOnContextConnection();
}
SqlInternalConnectionTds innerConnection = (InnerConnection as SqlInternalConnectionTds);
int result;
if (null != innerConnection)
{
result = innerConnection.PacketSize;
}
else
{
SqlConnectionString constr = (SqlConnectionString)ConnectionOptions;
result = ((null != constr) ? constr.PacketSize : SqlConnectionString.DEFAULT.Packet_Size);
}
return result;
}
}
/// <include file='..\..\..\..\..\..\..\doc\snippets\Microsoft.Data.SqlClient\SqlConnection.xml' path='docs/members[@name="SqlConnection"]/ClientConnectionId/*' />
[
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
ResCategoryAttribute(StringsHelper.ResourceNames.DataCategory_Data),
ResDescriptionAttribute(StringsHelper.ResourceNames.SqlConnection_ClientConnectionId),
]
public Guid ClientConnectionId
{
get
{
SqlInternalConnectionTds innerConnection = (InnerConnection as SqlInternalConnectionTds);
if (null != innerConnection)
{
return innerConnection.ClientConnectionId;
}
else
{
Task reconnectTask = _currentReconnectionTask;
// Connection closed but previously open should return the correct ClientConnectionId
DbConnectionClosedPreviouslyOpened innerConnectionClosed = (InnerConnection as DbConnectionClosedPreviouslyOpened);
if ((reconnectTask != null && !reconnectTask.IsCompleted) || null != innerConnectionClosed)
{
return _originalConnectionId;
}
return Guid.Empty;
}
}
}
/// <include file='..\..\..\..\..\..\..\doc\snippets\Microsoft.Data.SqlClient\SqlConnection.xml' path='docs/members[@name="SqlConnection"]/ServerVersion/*' />
[
Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
ResDescriptionAttribute(StringsHelper.ResourceNames.SqlConnection_ServerVersion),
]
override public string ServerVersion
{
get
{
return GetOpenConnection().ServerVersion;
}
}
/// <include file='../../../../../../../doc/snippets/Microsoft.Data.SqlClient/SqlConnection.xml' path='docs/members[@name="SqlConnection"]/ServerProcessId/*' />
[
Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
ResDescription(StringsHelper.ResourceNames.SqlConnection_ServerProcessId),
]
public int ServerProcessId
{
get => State.Equals(ConnectionState.Open) | State.Equals(ConnectionState.Executing) | State.Equals(ConnectionState.Fetching) ?
GetOpenTdsConnection().ServerProcessId : 0;
}
/// <include file='..\..\..\..\..\..\..\doc\snippets\Microsoft.Data.SqlClient\SqlConnection.xml' path='docs/members[@name="SqlConnection"]/State/*' />
[
Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
ResDescriptionAttribute(StringsHelper.ResourceNames.DbConnection_State),
]
override public ConnectionState State
{
get
{
Task reconnectTask = _currentReconnectionTask;
if (reconnectTask != null && !reconnectTask.IsCompleted)
{
return ConnectionState.Open;
}
return InnerConnection.State;
}
}
internal SqlStatistics Statistics
{
get
{
return _statistics;
}
}
/// <include file='..\..\..\..\..\..\..\doc\snippets\Microsoft.Data.SqlClient\SqlConnection.xml' path='docs/members[@name="SqlConnection"]/WorkstationId/*' />
[
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
ResCategoryAttribute(StringsHelper.ResourceNames.DataCategory_Data),
ResDescriptionAttribute(StringsHelper.ResourceNames.SqlConnection_WorkstationId),
]
public string WorkstationId
{
get
{
if (IsContextConnection)
{
throw SQL.NotAvailableOnContextConnection();
}
// If not supplied by the user, the default value is the MachineName
// Note: In Longhorn you'll be able to rename a machine without
// rebooting. Therefore, don't cache this machine name.
SqlConnectionString constr = (SqlConnectionString)ConnectionOptions;
string result = ((null != constr) ? constr.WorkstationId : null);
if (null == result)
{
// getting machine name requires Environment.Permission
// user must have that permission in order to retrieve this
result = Environment.MachineName;
}
return result;
}
}
/// <include file='..\..\..\..\..\..\..\doc\snippets\Microsoft.Data.SqlClient\SqlConnection.xml' path='docs/members[@name="SqlConnection"]/Credential/*' />
// SqlCredential: Pair User Id and password in SecureString which are to be used for SQL authentication
[
Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
ResDescriptionAttribute(StringsHelper.ResourceNames.SqlConnection_Credential),
]
public SqlCredential Credential
{
get
{
SqlCredential result = _credential;
// When a connection is connecting or is ever opened, make credential available only if "Persist Security Info" is set to true
// otherwise, return null
SqlConnectionString connectionOptions = (SqlConnectionString)UserConnectionOptions;
if (InnerConnection.ShouldHidePassword && connectionOptions != null && !connectionOptions.PersistSecurityInfo)
{
result = null;
}
return result;
}
set
{
// If a connection is connecting or is ever opened, user id/password cannot be set
if (!InnerConnection.AllowSetConnectionString)
{
throw ADP.OpenConnectionPropertySet("Credential", InnerConnection.State);
}
// check if the usage of credential has any conflict with the keys used in connection string
if (value != null)
{
// Check for Credential being used with Authentication=ActiveDirectoryIntegrated/ActiveDirectoryInteractive/ActiveDirectoryDeviceCodeFlow. Since a different error string is used
// for this case in ConnectionString setter vs in Credential setter, check for this error case before calling
// CheckAndThrowOnInvalidCombinationOfConnectionStringAndSqlCredential, which is common to both setters.
if (UsesActiveDirectoryIntegrated((SqlConnectionString)ConnectionOptions))
{
throw SQL.SettingCredentialWithIntegratedInvalid();
}
else if (UsesActiveDirectoryInteractive((SqlConnectionString)ConnectionOptions))
{
throw SQL.SettingCredentialWithInteractiveInvalid();
}
else if (UsesActiveDirectoryDeviceCodeFlow((SqlConnectionString)ConnectionOptions))
{
throw SQL.SettingCredentialWithDeviceFlowInvalid();
}
CheckAndThrowOnInvalidCombinationOfConnectionStringAndSqlCredential((SqlConnectionString)ConnectionOptions);
if (_accessToken != null)
{
throw ADP.InvalidMixedUsageOfCredentialAndAccessToken();
}
}
_credential = value;
// Need to call ConnectionString_Set to do proper pool group check
ConnectionString_Set(new SqlConnectionPoolKey(_connectionString, _credential, _accessToken, _serverCertificateValidationCallback, _clientCertificateRetrievalCallback, _originalNetworkAddressInfo));
}
}
// CheckAndThrowOnInvalidCombinationOfConnectionStringAndSqlCredential: check if the usage of credential has any conflict
// with the keys used in connection string
// If there is any conflict, it throws InvalidOperationException
// This is to be used setter of ConnectionString and Credential properties
private void CheckAndThrowOnInvalidCombinationOfConnectionStringAndSqlCredential(SqlConnectionString connectionOptions)
{
if (UsesClearUserIdOrPassword(connectionOptions))
{
throw ADP.InvalidMixedUsageOfSecureAndClearCredential();
}
if (UsesIntegratedSecurity(connectionOptions))
{
throw ADP.InvalidMixedUsageOfSecureCredentialAndIntegratedSecurity();
}
if (UsesContextConnection(connectionOptions))
{
throw ADP.InvalidMixedArgumentOfSecureCredentialAndContextConnection();
}
}
// CheckAndThrowOnInvalidCombinationOfConnectionOptionAndAccessToken: check if the usage of AccessToken has any conflict
// with the keys used in connection string and credential
// If there is any conflict, it throws InvalidOperationException
// This is to be used setter of ConnectionString and AccessToken properties
private void CheckAndThrowOnInvalidCombinationOfConnectionOptionAndAccessToken(SqlConnectionString connectionOptions)
{
if (UsesClearUserIdOrPassword(connectionOptions))
{
throw ADP.InvalidMixedUsageOfAccessTokenAndUserIDPassword();
}
if (UsesIntegratedSecurity(connectionOptions))
{
throw ADP.InvalidMixedUsageOfAccessTokenAndIntegratedSecurity();
}
if (UsesContextConnection(connectionOptions))
{
throw ADP.InvalidMixedUsageOfAccessTokenAndContextConnection();
}
if (UsesAuthentication(connectionOptions))
{
throw ADP.InvalidMixedUsageOfAccessTokenAndAuthentication();
}
// Check if the usage of AccessToken has the conflict with credential
if (_credential != null)
{
throw ADP.InvalidMixedUsageOfAccessTokenAndCredential();
}
}
//
// PUBLIC EVENTS
//
/// <include file='..\..\..\..\..\..\..\doc\snippets\Microsoft.Data.SqlClient\SqlConnection.xml' path='docs/members[@name="SqlConnection"]/InfoMessage/*' />
[
ResCategoryAttribute(StringsHelper.ResourceNames.DataCategory_InfoMessage),
ResDescriptionAttribute(StringsHelper.ResourceNames.DbConnection_InfoMessage),
]
public event SqlInfoMessageEventHandler InfoMessage
{
add
{
Events.AddHandler(EventInfoMessage, value);
}
remove
{
Events.RemoveHandler(EventInfoMessage, value);
}
}
/// <include file='..\..\..\..\..\..\..\doc\snippets\Microsoft.Data.SqlClient\SqlConnection.xml' path='docs/members[@name="SqlConnection"]/FireInfoMessageEventOnUserErrors/*' />
public bool FireInfoMessageEventOnUserErrors
{
get
{
return _fireInfoMessageEventOnUserErrors;
}
set
{
_fireInfoMessageEventOnUserErrors = value;
}
}
#if ADONET_CERT_AUTH
public ServerCertificateValidationCallback ServerCertificateValidationCallback {
get {
return _serverCertificateValidationCallback;
}
set {
_serverCertificateValidationCallback = value;
ConnectionString_Set(new SqlConnectionPoolKey(_connectionString, _credential, _accessToken, _serverCertificateValidationCallback, _clientCertificateRetrievalCallback, _originalNetworkAddressInfo));
}
}
// The exceptions from client certificate callback are not rethrown and instead an SSL
// exchange fails with CRYPT_E_NOT_FOUND = 0x80092004
public ClientCertificateRetrievalCallback ClientCertificateRetrievalCallback {
get {
return _clientCertificateRetrievalCallback;
}
set {
_clientCertificateRetrievalCallback = value;
ConnectionString_Set(new SqlConnectionPoolKey(_connectionString, _credential, _accessToken, _serverCertificateValidationCallback, _clientCertificateRetrievalCallback, _originalNetworkAddressInfo));
}
}
#endif
#if ADONET_ORIGINAL_CLIENT_ADDRESS
public SqlClientOriginalNetworkAddressInfo OriginalNetworkAddressInfo {
get {
return _originalNetworkAddressInfo;
}
set {
_originalNetworkAddressInfo = value;
ConnectionString_Set(new SqlConnectionPoolKey(_connectionString, _credential, _accessToken, _serverCertificateValidationCallback, _clientCertificateRetrievalCallback, _originalNetworkAddressInfo));
}
}
#endif
// Approx. number of times that the internal connection has been reconnected
internal int ReconnectCount
{
get
{
return _reconnectCount;
}
}
//
// PUBLIC METHODS
//
/// <include file='..\..\..\..\..\..\..\doc\snippets\Microsoft.Data.SqlClient\SqlConnection.xml' path='docs/members[@name="SqlConnection"]/BeginTransaction2/*' />
new public SqlTransaction BeginTransaction()
{
// this is just a delegate. The actual method tracks executiontime
return BeginTransaction(IsolationLevel.Unspecified, null);
}
/// <include file='..\..\..\..\..\..\..\doc\snippets\Microsoft.Data.SqlClient\SqlConnection.xml' path='docs/members[@name="SqlConnection"]/BeginTransactionIso/*' />
new public SqlTransaction BeginTransaction(IsolationLevel iso)
{
// this is just a delegate. The actual method tracks executiontime
return BeginTransaction(iso, null);
}
/// <include file='..\..\..\..\..\..\..\doc\snippets\Microsoft.Data.SqlClient\SqlConnection.xml' path='docs/members[@name="SqlConnection"]/BeginTransactionTransactionName/*' />
public SqlTransaction BeginTransaction(string transactionName)
{
// Use transaction names only on the outermost pair of nested
// BEGIN...COMMIT or BEGIN...ROLLBACK statements. Transaction names
// are ignored for nested BEGIN's. The only way to rollback a nested
// transaction is to have a save point from a SAVE TRANSACTION call.
return BeginTransaction(IsolationLevel.Unspecified, transactionName);
}
/// <include file='..\..\..\..\..\..\..\doc\snippets\Microsoft.Data.SqlClient\SqlConnection.xml' path='docs/members[@name="SqlConnection"]/BeginDbTransaction/*' />
// suppress this message - we cannot use SafeHandle here. Also, see notes in the code (VSTFDEVDIV# 560355)
[SuppressMessage("Microsoft.Reliability", "CA2004:RemoveCallsToGCKeepAlive")]
override protected DbTransaction BeginDbTransaction(IsolationLevel isolationLevel)
{
long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent("<prov.SqlConnection.BeginDbTransaction|API> {0}, isolationLevel={1}", ObjectID, (int)isolationLevel);
try
{
DbTransaction transaction = BeginTransaction(isolationLevel);
// VSTFDEVDIV# 560355 - InnerConnection doesn't maintain a ref on the outer connection (this) and
// subsequently leaves open the possibility that the outer connection could be GC'ed before the SqlTransaction
// is fully hooked up (leaving a DbTransaction with a null connection property). Ensure that this is reachable
// until the completion of BeginTransaction with KeepAlive
GC.KeepAlive(this);
return transaction;
}
finally
{
SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID);
}
}
/// <include file='..\..\..\..\..\..\..\doc\snippets\Microsoft.Data.SqlClient\SqlConnection.xml' path='docs/members[@name="SqlConnection"]/BeginTransactionIsoTransactionName/*' />
public SqlTransaction BeginTransaction(IsolationLevel iso, string transactionName)
{
WaitForPendingReconnection();
SqlStatistics statistics = null;
long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent("<sc.SqlConnection.BeginTransaction|API> {0}, iso={1}, transactionName='{2}'", ObjectID, (int)iso, transactionName);
try
{
statistics = SqlStatistics.StartTimer(Statistics);
// NOTE: we used to throw an exception if the transaction name was empty
// (see MDAC 50292) but that was incorrect because we have a BeginTransaction
// method that doesn't have a transactionName argument.
SqlTransaction transaction;
bool isFirstAttempt = true;
do
{
transaction = GetOpenConnection().BeginSqlTransaction(iso, transactionName, isFirstAttempt); // do not reconnect twice
Debug.Assert(isFirstAttempt || !transaction.InternalTransaction.ConnectionHasBeenRestored, "Restored connection on non-first attempt");
isFirstAttempt = false;
} while (transaction.InternalTransaction.ConnectionHasBeenRestored);
// SQLBU 503873 The GetOpenConnection line above doesn't keep a ref on the outer connection (this),
// and it could be collected before the inner connection can hook it to the transaction, resulting in
// a transaction with a null connection property. Use GC.KeepAlive to ensure this doesn't happen.
GC.KeepAlive(this);
return transaction;
}
finally
{
SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID);
SqlStatistics.StopTimer(statistics);
}
}
/// <include file='..\..\..\..\..\..\..\doc\snippets\Microsoft.Data.SqlClient\SqlConnection.xml' path='docs/members[@name="SqlConnection"]/ChangeDatabase/*' />
override public void ChangeDatabase(string database)
{
SqlStatistics statistics = null;
RepairInnerConnection();
SqlClientEventSource.Log.TryCorrelationTraceEvent("<sc.SqlConnection.ChangeDatabase|API|Correlation> ObjectID{0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current);
TdsParser bestEffortCleanupTarget = null;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
#if DEBUG
TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection();
RuntimeHelpers.PrepareConstrainedRegions();
try
{
tdsReliabilitySection.Start();
#else
{
#endif //DEBUG
bestEffortCleanupTarget = SqlInternalConnection.GetBestEffortCleanupTarget(this);
statistics = SqlStatistics.StartTimer(Statistics);
InnerConnection.ChangeDatabase(database);
}
#if DEBUG
finally
{
tdsReliabilitySection.Stop();
}
#endif //DEBUG
}
catch (System.OutOfMemoryException e)
{
Abort(e);
throw;
}
catch (System.StackOverflowException e)
{
Abort(e);
throw;
}
catch (System.Threading.ThreadAbortException e)
{
Abort(e);
SqlInternalConnection.BestEffortCleanup(bestEffortCleanupTarget);
throw;
}
finally
{
SqlStatistics.StopTimer(statistics);
}
}
/// <include file='..\..\..\..\..\..\..\doc\snippets\Microsoft.Data.SqlClient\SqlConnection.xml' path='docs/members[@name="SqlConnection"]/ClearAllPools/*' />
static public void ClearAllPools()
{
(new SqlClientPermission(PermissionState.Unrestricted)).Demand();
SqlConnectionFactory.SingletonInstance.ClearAllPools();
}
/// <include file='..\..\..\..\..\..\..\doc\snippets\Microsoft.Data.SqlClient\SqlConnection.xml' path='docs/members[@name="SqlConnection"]/ClearPool/*' />
static public void ClearPool(SqlConnection connection)
{
ADP.CheckArgumentNull(connection, "connection");
DbConnectionOptions connectionOptions = connection.UserConnectionOptions;
if (null != connectionOptions)
{
connectionOptions.DemandPermission();
if (connection.IsContextConnection)
{
throw SQL.NotAvailableOnContextConnection();
}
SqlConnectionFactory.SingletonInstance.ClearPool(connection);
}
}
/// <include file='..\..\..\..\..\..\..\doc\snippets\Microsoft.Data.SqlClient\SqlConnection.xml' path='docs/members[@name="SqlConnection"]/System.ICloneable.Clone/*' />
object ICloneable.Clone()
{
SqlConnection clone = new SqlConnection(this);
return clone;
}
void CloseInnerConnection()
{
// CloseConnection() now handles the lock
// The SqlInternalConnectionTds is set to OpenBusy during close, once this happens the cast below will fail and
// the command will no longer be cancelable. It might be desirable to be able to cancel the close opperation, but this is
// outside of the scope of Whidbey RTM. See (SqlCommand::Cancel) for other lock.
_originalConnectionId = ClientConnectionId;
InnerConnection.CloseConnection(this, ConnectionFactory);
}
/// <include file='..\..\..\..\..\..\..\doc\snippets\Microsoft.Data.SqlClient\SqlConnection.xml' path='docs/members[@name="SqlConnection"]/Close/*' />
override public void Close()
{
long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent("<sc.SqlConnection.Close|API> {0}", ObjectID);
SqlClientEventSource.Log.TryCorrelationTraceEvent("<sc.SqlConnection.Close|API|Correlation> ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current);
try
{
SqlStatistics statistics = null;
TdsParser bestEffortCleanupTarget = null;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
#if DEBUG
TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection();
RuntimeHelpers.PrepareConstrainedRegions();
try
{
tdsReliabilitySection.Start();
#else
{
#endif //DEBUG
bestEffortCleanupTarget = SqlInternalConnection.GetBestEffortCleanupTarget(this);
statistics = SqlStatistics.StartTimer(Statistics);
Task reconnectTask = _currentReconnectionTask;
if (reconnectTask != null && !reconnectTask.IsCompleted)
{
CancellationTokenSource cts = _reconnectionCancellationSource;
if (cts != null)
{
cts.Cancel();
}
AsyncHelper.WaitForCompletion(reconnectTask, 0, null, rethrowExceptions: false); // we do not need to deal with possible exceptions in reconnection
if (State != ConnectionState.Open)
{// if we cancelled before the connection was opened
OnStateChange(DbConnectionInternal.StateChangeClosed);
}
}
CancelOpenAndWait();
CloseInnerConnection();
GC.SuppressFinalize(this);
if (null != Statistics)
{
ADP.TimerCurrent(out _statistics._closeTimestamp);
}
}
#if DEBUG
finally
{
tdsReliabilitySection.Stop();
}
#endif //DEBUG
}
catch (System.OutOfMemoryException e)
{
Abort(e);
throw;
}
catch (System.StackOverflowException e)
{
Abort(e);
throw;
}
catch (System.Threading.ThreadAbortException e)
{
Abort(e);
SqlInternalConnection.BestEffortCleanup(bestEffortCleanupTarget);
throw;
}
finally
{
SqlStatistics.StopTimer(statistics);
//dispose windows identity once connection is closed.
if (_lastIdentity != null)
{
_lastIdentity.Dispose();
}
}
}
finally
{
SqlDebugContext sdc = _sdc;
_sdc = null;
SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID);
if (sdc != null)
{
sdc.Dispose();
}
}
}
/// <include file='..\..\..\..\..\..\..\doc\snippets\Microsoft.Data.SqlClient\SqlConnection.xml' path='docs/members[@name="SqlConnection"]/CreateCommand/*' />
new public SqlCommand CreateCommand()
{
return new SqlCommand(null, this);
}
private void DisposeMe(bool disposing)
{ // MDAC 65459
// clear credential and AccessToken here rather than in IDisposable.Dispose as these are specific to SqlConnection only
// IDisposable.Dispose is generated code from a template and used by other providers as well
_credential = null;
_accessToken = null;
if (!disposing)
{
// DevDiv2 Bug 457934:SQLConnection leaks when not disposed
// http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/457934
// For non-pooled connections we need to make sure that if the SqlConnection was not closed, then we release the GCHandle on the stateObject to allow it to be GCed
// For pooled connections, we will rely on the pool reclaiming the connection
var innerConnection = (InnerConnection as SqlInternalConnectionTds);
if ((innerConnection != null) && (!innerConnection.ConnectionOptions.Pooling))
{
var parser = innerConnection.Parser;
if ((parser != null) && (parser._physicalStateObj != null))
{
parser._physicalStateObj.DecrementPendingCallbacks(release: false);
}
}
}
}
/// <include file='..\..\..\..\..\..\..\doc\snippets\Microsoft.Data.SqlClient\SqlConnection.xml' path='docs/members[@name="SqlConnection"]/EnlistDistributedTransaction/*' />
public void EnlistDistributedTransaction(System.EnterpriseServices.ITransaction transaction)
{
if (IsContextConnection)
{
throw SQL.NotAvailableOnContextConnection();
}
EnlistDistributedTransactionHelper(transaction);
}
/// <include file='..\..\..\..\..\..\..\doc\snippets\Microsoft.Data.SqlClient\SqlConnection.xml' path='docs/members[@name="SqlConnection"]/Open/*' />
override public void Open()
{
Open(SqlConnectionOverrides.None);
}
/// <include file='../../../../../../../doc/snippets/Microsoft.Data.SqlClient/SqlConnection.xml' path='docs/members[@name="SqlConnection"]/OpenWithOverrides/*' />
public void Open(SqlConnectionOverrides overrides)
{
long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent("<sc.SqlConnection.Open|API|Correlation> ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current);
SqlClientEventSource.Log.TryCorrelationTraceEvent("<sc.SqlConnection.Open|API|Correlation> ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current);
try
{
if (StatisticsEnabled)
{
if (null == _statistics)
{
_statistics = new SqlStatistics();
}
else
{
_statistics.ContinueOnNewConnection();
}
}
SqlStatistics statistics = null;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
statistics = SqlStatistics.StartTimer(Statistics);
if (!TryOpen(null, overrides))
{
throw ADP.InternalError(ADP.InternalErrorCode.SynchronousConnectReturnedPending);
}
}
finally
{
SqlStatistics.StopTimer(statistics);
}
}
finally
{
SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID);
}
}
internal void RegisterWaitingForReconnect(Task waitingTask)
{
if (((SqlConnectionString)ConnectionOptions).MARS)
{
return;
}
Interlocked.CompareExchange(ref _asyncWaitingForReconnection, waitingTask, null);
if (_asyncWaitingForReconnection != waitingTask)
{ // somebody else managed to register
throw SQL.MARSUnsupportedOnConnection();
}
}
private async Task ReconnectAsync(int timeout)
{
try
{
long commandTimeoutExpiration = 0;
if (timeout > 0)
{
commandTimeoutExpiration = ADP.TimerCurrent() + ADP.TimerFromSeconds(timeout);
}
CancellationTokenSource cts = new CancellationTokenSource();
_reconnectionCancellationSource = cts;
CancellationToken ctoken = cts.Token;
int retryCount = _connectRetryCount; // take a snapshot: could be changed by modifying the connection string
for (int attempt = 0; attempt < retryCount; attempt++)
{
if (ctoken.IsCancellationRequested)
{
SqlClientEventSource.Log.TryTraceEvent("<sc.SqlConnection.ReconnectAsync|INFO> Original ClientConnectionID: {0} - reconnection cancelled.", _originalConnectionId);
return;
}
try
{
_impersonateIdentity = _lastIdentity;
try
{
ForceNewConnection = true;
await OpenAsync(ctoken).ConfigureAwait(false);
// On success, increment the reconnect count - we don't really care if it rolls over since it is approx.
_reconnectCount = unchecked(_reconnectCount + 1);
#if DEBUG
Debug.Assert(_recoverySessionData._debugReconnectDataApplied, "Reconnect data was not applied !");
#endif
}
finally
{
_impersonateIdentity = null;
ForceNewConnection = false;
}
SqlClientEventSource.Log.TryTraceEvent("<sc.SqlConnection.ReconnectIfNeeded|INFO> Reconnection succeeded. ClientConnectionID {0} -> {1}", _originalConnectionId, ClientConnectionId);
return;
}
catch (SqlException e)
{
SqlClientEventSource.Log.TryTraceEvent("<sc.SqlConnection.ReconnectAsyncINFO> Original ClientConnectionID {0} - reconnection attempt failed error {1}", _originalConnectionId, e.Message);
if (attempt == retryCount - 1)
{
SqlClientEventSource.Log.TryTraceEvent("<sc.SqlConnection.ReconnectAsync|INFO> Original ClientConnectionID {0} - give up reconnection", _originalConnectionId);
throw SQL.CR_AllAttemptsFailed(e, _originalConnectionId);
}
if (timeout > 0 && ADP.TimerRemaining(commandTimeoutExpiration) < ADP.TimerFromSeconds(ConnectRetryInterval))
{
throw SQL.CR_NextAttemptWillExceedQueryTimeout(e, _originalConnectionId);
}
}
await Task.Delay(1000 * ConnectRetryInterval, ctoken).ConfigureAwait(false);
}
}
finally
{
_recoverySessionData = null;
_suppressStateChangeForReconnection = false;
}
Debug.Fail("Should not reach this point");
}
internal Task ValidateAndReconnect(Action beforeDisconnect, int timeout)
{
Task runningReconnect = _currentReconnectionTask;
// This loop in the end will return not completed reconnect task or null
while (runningReconnect != null && runningReconnect.IsCompleted)
{
// clean current reconnect task (if it is the same one we checked
Interlocked.CompareExchange<Task>(ref _currentReconnectionTask, null, runningReconnect);
// make sure nobody started new task (if which case we did not clean it)
runningReconnect = _currentReconnectionTask;
}
if (runningReconnect == null)
{
if (_connectRetryCount > 0)
{
SqlInternalConnectionTds tdsConn = GetOpenTdsConnection();
if (tdsConn._sessionRecoveryAcknowledged)
{
TdsParserStateObject stateObj = tdsConn.Parser._physicalStateObj;
if (!stateObj.ValidateSNIConnection())
{
if (tdsConn.Parser._sessionPool != null)
{
if (tdsConn.Parser._sessionPool.ActiveSessionsCount > 0)
{
// >1 MARS session
if (beforeDisconnect != null)
{
beforeDisconnect();
}
OnError(SQL.CR_UnrecoverableClient(ClientConnectionId), true, null);
}
}
SessionData cData = tdsConn.CurrentSessionData;
cData.AssertUnrecoverableStateCountIsCorrect();
if (cData._unrecoverableStatesCount == 0)
{
bool callDisconnect = false;
lock (_reconnectLock)
{
tdsConn.CheckEnlistedTransactionBinding();
runningReconnect = _currentReconnectionTask; // double check after obtaining the lock
if (runningReconnect == null)
{
if (cData._unrecoverableStatesCount == 0)
{
// could change since the first check, but now is stable since connection is know to be broken
_originalConnectionId = ClientConnectionId;
SqlClientEventSource.Log.TryTraceEvent("<sc.SqlConnection.ReconnectIfNeeded|INFO> Connection ClientConnectionID {0} is invalid, reconnecting", _originalConnectionId);
_recoverySessionData = cData;
if (beforeDisconnect != null)
{
beforeDisconnect();
}
try
{
_suppressStateChangeForReconnection = true;
tdsConn.DoomThisConnection();
}
catch (SqlException)
{
}
runningReconnect = Task.Run(() => ReconnectAsync(timeout));
// if current reconnect is not null, somebody already started reconnection task - some kind of race condition
Debug.Assert(_currentReconnectionTask == null, "Duplicate reconnection tasks detected");
_currentReconnectionTask = runningReconnect;
}
}
else
{
callDisconnect = true;
}
}
if (callDisconnect && beforeDisconnect != null)
{
beforeDisconnect();
}
}
else
{
if (beforeDisconnect != null)
{
beforeDisconnect();
}
OnError(SQL.CR_UnrecoverableServer(ClientConnectionId), true, null);
}
} // ValidateSNIConnection
} // sessionRecoverySupported
} // connectRetryCount>0
}
else
{ // runningReconnect = null
if (beforeDisconnect != null)
{
beforeDisconnect();
}
}
return runningReconnect;
}
// this is straightforward, but expensive method to do connection resiliency - it take locks and all prepartions as for TDS request
partial void RepairInnerConnection()
{
WaitForPendingReconnection();
if (_connectRetryCount == 0)
{
return;
}
SqlInternalConnectionTds tdsConn = InnerConnection as SqlInternalConnectionTds;
if (tdsConn != null)
{
tdsConn.ValidateConnectionForExecute(null);
tdsConn.GetSessionAndReconnectIfNeeded((SqlConnection)this);
}
}
private void WaitForPendingReconnection()
{
Task reconnectTask = _currentReconnectionTask;
if (reconnectTask != null && !reconnectTask.IsCompleted)
{
AsyncHelper.WaitForCompletion(reconnectTask, 0, null, rethrowExceptions: false);
}
}
void CancelOpenAndWait()
{
// copy from member to avoid changes by background thread
var completion = _currentCompletion;
if (completion != null)
{
completion.Item1.TrySetCanceled();
((IAsyncResult)completion.Item2).AsyncWaitHandle.WaitOne();
}
Debug.Assert(_currentCompletion == null, "After waiting for an async call to complete, there should be no completion source");
}
/// <include file='..\..\..\..\..\..\..\doc\snippets\Microsoft.Data.SqlClient\SqlConnection.xml' path='docs/members[@name="SqlConnection"]/OpenAsync/*' />
public override Task OpenAsync(CancellationToken cancellationToken)
{
long scopeID = SqlClientEventSource.Log.TryPoolerScopeEnterEvent("<sc.SqlConnection.OpenAsync|API> {0}", ObjectID);
SqlClientEventSource.Log.TryCorrelationTraceEvent("<sc.SqlConnection.OpenAsync|API|Correlation> ObjectID {0}, ActivityID {1}", ObjectID, ActivityCorrelator.Current);
try
{
if (StatisticsEnabled)
{
if (null == _statistics)
{
_statistics = new SqlStatistics();
}
else
{
_statistics.ContinueOnNewConnection();
}
}
SqlStatistics statistics = null;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
statistics = SqlStatistics.StartTimer(Statistics);
System.Transactions.Transaction transaction = ADP.GetCurrentTransaction();
TaskCompletionSource<DbConnectionInternal> completion = new TaskCompletionSource<DbConnectionInternal>(transaction);
TaskCompletionSource<object> result = new TaskCompletionSource<object>();
if (cancellationToken.IsCancellationRequested)
{
result.SetCanceled();
return result.Task;
}
if (IsContextConnection)
{
// Async not supported on Context Connections
result.SetException(ADP.ExceptionWithStackTrace(SQL.NotAvailableOnContextConnection()));
return result.Task;
}
bool completed;
try
{
completed = TryOpen(completion);
}
catch (Exception e)
{
result.SetException(e);
return result.Task;
}
if (completed)
{
result.SetResult(null);
}
else
{
CancellationTokenRegistration registration = new CancellationTokenRegistration();
if (cancellationToken.CanBeCanceled)
{
registration = cancellationToken.Register(() => completion.TrySetCanceled());
}
OpenAsyncRetry retry = new OpenAsyncRetry(this, completion, result, registration);
_currentCompletion = new Tuple<TaskCompletionSource<DbConnectionInternal>, Task>(completion, result.Task);
completion.Task.ContinueWith(retry.Retry, TaskScheduler.Default);
return result.Task;
}
return result.Task;
}
finally
{
SqlStatistics.StopTimer(statistics);
}
}
finally
{
SqlClientEventSource.Log.TryPoolerScopeLeaveEvent(scopeID);
}
}
private class OpenAsyncRetry
{
SqlConnection _parent;
TaskCompletionSource<DbConnectionInternal> _retry;
TaskCompletionSource<object> _result;
CancellationTokenRegistration _registration;
public OpenAsyncRetry(SqlConnection parent, TaskCompletionSource<DbConnectionInternal> retry, TaskCompletionSource<object> result, CancellationTokenRegistration registration)
{
_parent = parent;
_retry = retry;
_result = result;
_registration = registration;
}
internal void Retry(Task<DbConnectionInternal> retryTask)
{
SqlClientEventSource.Log.TryTraceEvent("<sc.SqlConnection.OpenAsyncRetry|Info> {0}", _parent.ObjectID);
_registration.Dispose();
try
{
SqlStatistics statistics = null;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
statistics = SqlStatistics.StartTimer(_parent.Statistics);
if (retryTask.IsFaulted)
{
Exception e = retryTask.Exception.InnerException;
_parent.CloseInnerConnection();
_parent._currentCompletion = null;
_result.SetException(retryTask.Exception.InnerException);
}
else if (retryTask.IsCanceled)
{
_parent.CloseInnerConnection();
_parent._currentCompletion = null;
_result.SetCanceled();
}
else
{
bool result;
// protect continuation from races with close and cancel
lock (_parent.InnerConnection)
{
result = _parent.TryOpen(_retry);
}
if (result)
{
_parent._currentCompletion = null;
_result.SetResult(null);
}
else
{
_parent.CloseInnerConnection();
_parent._currentCompletion = null;
_result.SetException(ADP.ExceptionWithStackTrace(ADP.InternalError(ADP.InternalErrorCode.CompletedConnectReturnedPending)));
}
}
}
finally
{
SqlStatistics.StopTimer(statistics);
}
}
catch (Exception e)
{
_parent.CloseInnerConnection();
_parent._currentCompletion = null;
_result.SetException(e);
}
}
}
private bool TryOpen(TaskCompletionSource<DbConnectionInternal> retry, SqlConnectionOverrides overrides = SqlConnectionOverrides.None)
{
SqlConnectionString connectionOptions = (SqlConnectionString)ConnectionOptions;
bool result = false;
_applyTransientFaultHandling = (!overrides.HasFlag(SqlConnectionOverrides.OpenWithoutRetry) && retry == null && connectionOptions != null && connectionOptions.ConnectRetryCount > 0);
if (connectionOptions != null &&
(connectionOptions.Authentication == SqlAuthenticationMethod.SqlPassword ||
connectionOptions.Authentication == SqlAuthenticationMethod.ActiveDirectoryPassword ||
connectionOptions.Authentication == SqlAuthenticationMethod.ActiveDirectoryServicePrincipal) &&
(!connectionOptions.HasUserIdKeyword || !connectionOptions.HasPasswordKeyword) &&
_credential == null)
{
throw SQL.CredentialsNotProvided(connectionOptions.Authentication);
}
if (_impersonateIdentity != null)
{
using (WindowsIdentity identity = DbConnectionPoolIdentity.GetCurrentWindowsIdentity())
{
if (_impersonateIdentity.User == identity.User)
{
result = TryOpenInner(retry);
}
else
{
using (WindowsImpersonationContext context = _impersonateIdentity.Impersonate())
{
result = TryOpenInner(retry);
}
}
}
}
else
{
if (this.UsesIntegratedSecurity(connectionOptions) || this.UsesCertificate(connectionOptions) || this.UsesActiveDirectoryIntegrated(connectionOptions))
{
_lastIdentity = DbConnectionPoolIdentity.GetCurrentWindowsIdentity();
}
else
{
_lastIdentity = null;
}
result = TryOpenInner(retry);
}
// Set future transient fault handling based on connection options
_applyTransientFaultHandling = (retry == null && connectionOptions != null && connectionOptions.ConnectRetryCount > 0);
return result;
}
private bool TryOpenInner(TaskCompletionSource<DbConnectionInternal> retry)
{
TdsParser bestEffortCleanupTarget = null;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
#if DEBUG
TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection();
RuntimeHelpers.PrepareConstrainedRegions();
try
{
tdsReliabilitySection.Start();
#else
{
#endif //DEBUG
if (ForceNewConnection)
{
if (!InnerConnection.TryReplaceConnection(this, ConnectionFactory, retry, UserConnectionOptions))
{
return false;
}
}
else
{
if (!InnerConnection.TryOpenConnection(this, ConnectionFactory, retry, UserConnectionOptions))
{
return false;
}
}
// does not require GC.KeepAlive(this) because of OnStateChange
// GetBestEffortCleanup must happen AFTER OpenConnection to get the correct target.
bestEffortCleanupTarget = SqlInternalConnection.GetBestEffortCleanupTarget(this);
var tdsInnerConnection = (InnerConnection as SqlInternalConnectionTds);
if (tdsInnerConnection == null)
{
SqlInternalConnectionSmi innerConnection = (InnerConnection as SqlInternalConnectionSmi);
innerConnection.AutomaticEnlistment();
}
else
{
Debug.Assert(tdsInnerConnection.Parser != null, "Where's the parser?");
if (!tdsInnerConnection.ConnectionOptions.Pooling)
{
// For non-pooled connections, we need to make sure that the finalizer does actually run to avoid leaking SNI handles
GC.ReRegisterForFinalize(this);
}
if (StatisticsEnabled)
{
ADP.TimerCurrent(out _statistics._openTimestamp);
tdsInnerConnection.Parser.Statistics = _statistics;
}
else
{
tdsInnerConnection.Parser.Statistics = null;
_statistics = null; // in case of previous Open/Close/reset_CollectStats sequence
}
CompleteOpen();
}
}
#if DEBUG
finally
{
tdsReliabilitySection.Stop();
}
#endif //DEBUG
}
catch (System.OutOfMemoryException e)
{
Abort(e);
throw;
}
catch (System.StackOverflowException e)
{
Abort(e);
throw;
}
catch (System.Threading.ThreadAbortException e)
{
Abort(e);
SqlInternalConnection.BestEffortCleanup(bestEffortCleanupTarget);
throw;
}
return true;
}
//
// INTERNAL PROPERTIES
//
internal bool HasLocalTransaction
{
get
{
return GetOpenConnection().HasLocalTransaction;
}
}
internal bool HasLocalTransactionFromAPI
{
get
{
Task reconnectTask = _currentReconnectionTask;
if (reconnectTask != null && !reconnectTask.IsCompleted)
{
return false; //we will not go into reconnection if we are inside the transaction
}
return GetOpenConnection().HasLocalTransactionFromAPI;
}
}
internal bool IsShiloh
{
get
{
if (_currentReconnectionTask != null)
{ // holds true even if task is completed
return true; // if CR is enabled, connection, if established, will be Katmai+
}
return GetOpenConnection().IsShiloh;
}
}
internal bool IsYukonOrNewer
{
get
{
if (_currentReconnectionTask != null)
{ // holds true even if task is completed
return true; // if CR is enabled, connection, if established, will be Katmai+
}
return GetOpenConnection().IsYukonOrNewer;
}
}
internal bool IsKatmaiOrNewer
{
get
{
if (_currentReconnectionTask != null)
{ // holds true even if task is completed
return true; // if CR is enabled, connection, if established, will be Katmai+
}
return GetOpenConnection().IsKatmaiOrNewer;
}
}
internal TdsParser Parser
{
get
{
SqlInternalConnectionTds tdsConnection = (GetOpenConnection() as SqlInternalConnectionTds);
if (null == tdsConnection)
{
throw SQL.NotAvailableOnContextConnection();
}
return tdsConnection.Parser;
}
}
internal bool Asynchronous
{
get
{
SqlConnectionString constr = (SqlConnectionString)ConnectionOptions;
return ((null != constr) ? constr.Asynchronous : SqlConnectionString.DEFAULT.Asynchronous);
}
}
//
// INTERNAL METHODS
//
internal void ValidateConnectionForExecute(string method, SqlCommand command)
{
Task asyncWaitingForReconnection = _asyncWaitingForReconnection;
if (asyncWaitingForReconnection != null)
{
if (!asyncWaitingForReconnection.IsCompleted)
{
throw SQL.MARSUnsupportedOnConnection();
}
else
{
Interlocked.CompareExchange(ref _asyncWaitingForReconnection, null, asyncWaitingForReconnection);
}
}
if (_currentReconnectionTask != null)
{
Task currentReconnectionTask = _currentReconnectionTask;
if (currentReconnectionTask != null && !currentReconnectionTask.IsCompleted)
{
return; // execution will wait for this task later
}
}
SqlInternalConnection innerConnection = GetOpenConnection(method);
innerConnection.ValidateConnectionForExecute(command);
}
// Surround name in brackets and then escape any end bracket to protect against SQL Injection.
// NOTE: if the user escapes it themselves it will not work, but this was the case in V1 as well
// as native OleDb and Odbc.
static internal string FixupDatabaseTransactionName(string name)
{
if (!ADP.IsEmpty(name))
{
return SqlServerEscapeHelper.EscapeIdentifier(name);
}
else
{
return name;
}
}
// If wrapCloseInAction is defined, then the action it defines will be run with the connection close action passed in as a parameter
// The close action also supports being run asynchronously
internal void OnError(SqlException exception, bool breakConnection, Action<Action> wrapCloseInAction)
{
Debug.Assert(exception != null && exception.Errors.Count != 0, "SqlConnection: OnError called with null or empty exception!");
// Bug fix - MDAC 49022 - connection open after failure... Problem was parser was passing
// Open as a state - because the parser's connection to the netlib was open. We would
// then set the connection state to the parser's state - which is not correct. The only
// time the connection state should change to what is passed in to this function is if
// the parser is broken, then we should be closed. Changed to passing in
// TdsParserState, not ConnectionState.
if (breakConnection && (ConnectionState.Open == State))
{
if (wrapCloseInAction != null)
{
int capturedCloseCount = _closeCount;
Action closeAction = () =>
{
if (capturedCloseCount == _closeCount)
{
SqlClientEventSource.Log.TryTraceEvent("<sc.SqlConnection.OnError|INFO> {0}, Connection broken.", ObjectID);
Close();
}
};
wrapCloseInAction(closeAction);
}
else
{
SqlClientEventSource.Log.TryTraceEvent("<sc.SqlConnection.OnError|INFO> {0}, Connection broken.", ObjectID);
Close();
}
}
if (exception.Class >= TdsEnums.MIN_ERROR_CLASS)
{
// It is an error, and should be thrown. Class of TdsEnums.MIN_ERROR_CLASS or above is an error,
// below TdsEnums.MIN_ERROR_CLASS denotes an info message.
throw exception;
}
else
{
// If it is a class < TdsEnums.MIN_ERROR_CLASS, it is a warning collection - so pass to handler
this.OnInfoMessage(new SqlInfoMessageEventArgs(exception));
}
}
//
// PRIVATE METHODS
//
// SxS: using Debugger.IsAttached
// TODO: review this code for SxS issues (VSDD 540765)
[ResourceExposure(ResourceScope.None)]
[ResourceConsumption(ResourceScope.Process, ResourceScope.Process)]
private void CompleteOpen()
{
Debug.Assert(ConnectionState.Open == State, "CompleteOpen not open");
// be sure to mark as open so SqlDebugCheck can issue Query
// check to see if we need to hook up sql-debugging if a debugger is attached
// We only need this check for Shiloh and earlier servers.
if (!GetOpenConnection().IsYukonOrNewer &&
System.Diagnostics.Debugger.IsAttached)
{
bool debugCheck = false;
try
{
new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand(); // MDAC 66682, 69017
debugCheck = true;
}
catch (SecurityException e)
{
ADP.TraceExceptionWithoutRethrow(e);
}
if (debugCheck)
{
// if we don't have Unmanaged code permission, don't check for debugging
// but let the connection be opened while under the debugger
CheckSQLDebugOnConnect();
}
}
}
internal SqlInternalConnection GetOpenConnection()
{
SqlInternalConnection innerConnection = (InnerConnection as SqlInternalConnection);
if (null == innerConnection)
{
throw ADP.ClosedConnectionError();
}
return innerConnection;
}
internal SqlInternalConnection GetOpenConnection(string method)
{
DbConnectionInternal innerConnection = InnerConnection;
SqlInternalConnection innerSqlConnection = (innerConnection as SqlInternalConnection);
if (null == innerSqlConnection)
{
throw ADP.OpenConnectionRequired(method, innerConnection.State);
}
return innerSqlConnection;
}
internal SqlInternalConnectionTds GetOpenTdsConnection()
{
SqlInternalConnectionTds innerConnection = (InnerConnection as SqlInternalConnectionTds);
if (null == innerConnection)
{
throw ADP.ClosedConnectionError();
}
return innerConnection;
}
internal SqlInternalConnectionTds GetOpenTdsConnection(string method)
{
SqlInternalConnectionTds innerConnection = (InnerConnection as SqlInternalConnectionTds);
if (null == innerConnection)
{
throw ADP.OpenConnectionRequired(method, InnerConnection.State);
}
return innerConnection;
}
internal void OnInfoMessage(SqlInfoMessageEventArgs imevent)
{
bool notified;
OnInfoMessage(imevent, out notified);
}
internal void OnInfoMessage(SqlInfoMessageEventArgs imevent, out bool notified)
{
Debug.Assert(null != imevent, "null SqlInfoMessageEventArgs");
var imeventValue = (null != imevent) ? imevent.Message : "";
SqlClientEventSource.Log.TryTraceEvent("<sc.SqlConnection.OnInfoMessage|API|INFO> {0}, Message='{1}'", ObjectID, imeventValue);
SqlInfoMessageEventHandler handler = (SqlInfoMessageEventHandler)Events[EventInfoMessage];
if (null != handler)
{
notified = true;
try
{
handler(this, imevent);
}
catch (Exception e)
{ // MDAC 53175
if (!ADP.IsCatchableOrSecurityExceptionType(e))
{
throw;
}
ADP.TraceExceptionWithoutRethrow(e);
}
}
else
{
notified = false;
}
}
//
// SQL DEBUGGING SUPPORT
//
// this only happens once per connection
// SxS: using named file mapping APIs
// TODO: review this code for SxS issues (VSDD 540765)
[ResourceExposure(ResourceScope.None)]
[ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
private void CheckSQLDebugOnConnect()
{
IntPtr hFileMap;
uint pid = (uint)SafeNativeMethods.GetCurrentProcessId();
string mapFileName;
// If Win2k or later, prepend "Global\\" to enable this to work through TerminalServices.
if (ADP.IsPlatformNT5)
{
mapFileName = "Global\\" + TdsEnums.SDCI_MAPFILENAME;
}
else
{
mapFileName = TdsEnums.SDCI_MAPFILENAME;
}
mapFileName = mapFileName + pid.ToString(CultureInfo.InvariantCulture);
hFileMap = NativeMethods.OpenFileMappingA(0x4/*FILE_MAP_READ*/, false, mapFileName);
if (ADP.PtrZero != hFileMap)
{
IntPtr pMemMap = NativeMethods.MapViewOfFile(hFileMap, 0x4/*FILE_MAP_READ*/, 0, 0, IntPtr.Zero);
if (ADP.PtrZero != pMemMap)
{
SqlDebugContext sdc = new SqlDebugContext();
sdc.hMemMap = hFileMap;
sdc.pMemMap = pMemMap;
sdc.pid = pid;
// optimization: if we only have to refresh memory-mapped data at connection open time
// optimization: then call here instead of in CheckSQLDebug() which gets called
// optimization: at command execution time
// RefreshMemoryMappedData(sdc);
// delaying setting out global state until after we issue this first SQLDebug command so that
// we don't reentrantly call into CheckSQLDebug
CheckSQLDebug(sdc);
// now set our global state
_sdc = sdc;
}
}
}
// This overload is called by the Command object when executing stored procedures. Note that
// if SQLDebug has never been called, it is a noop.
internal void CheckSQLDebug()
{
if (null != _sdc)
CheckSQLDebug(_sdc);
}
// SxS: using GetCurrentThreadId
[ResourceExposure(ResourceScope.None)]
[ResourceConsumption(ResourceScope.Process, ResourceScope.Process)]
[SecurityPermissionAttribute(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)] // MDAC 66682, 69017
private void CheckSQLDebug(SqlDebugContext sdc)
{
// check to see if debugging has been activated
Debug.Assert(null != sdc, "SQL Debug: invalid null debugging context!");
#pragma warning disable 618
uint tid = (uint)AppDomain.GetCurrentThreadId(); // Sql Debugging doesn't need fiber support;
#pragma warning restore 618
RefreshMemoryMappedData(sdc);
// UNDONE: do I need to remap the contents of pMemMap each time I call into here?
// UNDONE: current behavior is to only marshal the contents of the memory-mapped file
// UNDONE: at connection open time.
// If we get here, the debugger must be hooked up.
if (!sdc.active)
{
if (sdc.fOption/*TdsEnums.SQLDEBUG_ON*/)
{
// turn on
sdc.active = true;
sdc.tid = tid;
try
{
IssueSQLDebug(TdsEnums.SQLDEBUG_ON, sdc.machineName, sdc.pid, sdc.dbgpid, sdc.sdiDllName, sdc.data);
sdc.tid = 0; // reset so that the first successful time through, we notify the server of the context switch
}
catch
{
sdc.active = false;
throw;
}
}
}
// be sure to pick up thread context switch, especially the first time through
if (sdc.active)
{
if (!sdc.fOption/*TdsEnums.SQLDEBUG_OFF*/)
{
// turn off and free the memory
sdc.Dispose();
// okay if we throw out here, no state to clean up
IssueSQLDebug(TdsEnums.SQLDEBUG_OFF, null, 0, 0, null, null);
}
else
{
// notify server of context change
if (sdc.tid != tid)
{
sdc.tid = tid;
try
{
IssueSQLDebug(TdsEnums.SQLDEBUG_CONTEXT, null, sdc.pid, sdc.tid, null, null);
}
catch
{
sdc.tid = 0;
throw;
}
}
}
}
}
private void IssueSQLDebug(uint option, string machineName, uint pid, uint id, string sdiDllName, byte[] data)
{
if (GetOpenConnection().IsYukonOrNewer)
{
// TODO: When Yukon actually supports debugging, we need to modify this method to do the right thing(tm)
return;
}
// CONSIDER: we could cache three commands, one for each mode {on, off, context switch}
// CONSIDER: but debugging is not the performant case so save space instead amd rebuild each time
SqlCommand c = new SqlCommand(TdsEnums.SP_SDIDEBUG, this);
c.CommandType = CommandType.StoredProcedure;
// context param
SqlParameter p = new SqlParameter(null, SqlDbType.VarChar, TdsEnums.SQLDEBUG_MODE_NAMES[option].Length);
p.Value = TdsEnums.SQLDEBUG_MODE_NAMES[option];
c.Parameters.Add(p);
if (option == TdsEnums.SQLDEBUG_ON)
{
// debug dll name
p = new SqlParameter(null, SqlDbType.VarChar, sdiDllName.Length);
p.Value = sdiDllName;
c.Parameters.Add(p);
// debug machine name
p = new SqlParameter(null, SqlDbType.VarChar, machineName.Length);
p.Value = machineName;
c.Parameters.Add(p);
}
if (option != TdsEnums.SQLDEBUG_OFF)
{
// client pid
p = new SqlParameter(null, SqlDbType.Int);
p.Value = pid;
c.Parameters.Add(p);
// dbgpid or tid
p = new SqlParameter(null, SqlDbType.Int);
p.Value = id;
c.Parameters.Add(p);
}
if (option == TdsEnums.SQLDEBUG_ON)
{
// debug data
p = new SqlParameter(null, SqlDbType.VarBinary, (null != data) ? data.Length : 0);
p.Value = data;
c.Parameters.Add(p);
}
c.ExecuteNonQuery();
}
/// <include file='..\..\..\..\..\..\..\doc\snippets\Microsoft.Data.SqlClient\SqlConnection.xml' path='docs/members[@name="SqlConnection"]/ChangePasswordConnectionStringNewPassword/*' />
public static void ChangePassword(string connectionString, string newPassword)
{
long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent("<sc.SqlConnection.ChangePassword|API>");
SqlClientEventSource.Log.TryCorrelationTraceEvent("<sc.SqlConnection.ChangePassword|API|Correlation> ActivityID {0}", ActivityCorrelator.Current);
try
{
if (ADP.IsEmpty(connectionString))
{
throw SQL.ChangePasswordArgumentMissing("connectionString");
}
if (ADP.IsEmpty(newPassword))
{
throw SQL.ChangePasswordArgumentMissing("newPassword");
}
if (TdsEnums.MAXLEN_NEWPASSWORD < newPassword.Length)
{
throw ADP.InvalidArgumentLength("newPassword", TdsEnums.MAXLEN_NEWPASSWORD);
}
SqlConnectionPoolKey key = new SqlConnectionPoolKey(connectionString, credential: null, accessToken: null, serverCertificateValidationCallback: null, clientCertificateRetrievalCallback: null, originalNetworkAddressInfo: null);
SqlConnectionString connectionOptions = SqlConnectionFactory.FindSqlConnectionOptions(key);
if (connectionOptions.IntegratedSecurity || connectionOptions.Authentication == SqlAuthenticationMethod.ActiveDirectoryIntegrated)
{
throw SQL.ChangePasswordConflictsWithSSPI();
}
if (!ADP.IsEmpty(connectionOptions.AttachDBFilename))
{
throw SQL.ChangePasswordUseOfUnallowedKey(SqlConnectionString.KEY.AttachDBFilename);
}
if (connectionOptions.ContextConnection)
{
throw SQL.ChangePasswordUseOfUnallowedKey(SqlConnectionString.KEY.Context_Connection);
}
System.Security.PermissionSet permissionSet = connectionOptions.CreatePermissionSet();
permissionSet.Demand();
ChangePassword(connectionString, connectionOptions, null, newPassword, null);
}
finally
{
SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID);
}
}
/// <include file='..\..\..\..\..\..\..\doc\snippets\Microsoft.Data.SqlClient\SqlConnection.xml' path='/docs/members[@name="SqlConnection"]/ChangePasswordConnectionStringCredentialNewSecurePassword/*' />
public static void ChangePassword(string connectionString, SqlCredential credential, SecureString newSecurePassword)
{
long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent("<sc.SqlConnection.ChangePassword|API>");
SqlClientEventSource.Log.TryCorrelationTraceEvent("<sc.SqlConnection.ChangePassword|API|Correlation> ActivityID {0}", ActivityCorrelator.Current);
try
{
if (ADP.IsEmpty(connectionString))
{
throw SQL.ChangePasswordArgumentMissing("connectionString");
}
// check credential; not necessary to check the length of password in credential as the check is done by SqlCredential class
if (credential == null)
{
throw SQL.ChangePasswordArgumentMissing("credential");
}
if (newSecurePassword == null || newSecurePassword.Length == 0)
{
throw SQL.ChangePasswordArgumentMissing("newSecurePassword");
}
if (!newSecurePassword.IsReadOnly())
{
throw ADP.MustBeReadOnly("newSecurePassword");
}
if (TdsEnums.MAXLEN_NEWPASSWORD < newSecurePassword.Length)
{
throw ADP.InvalidArgumentLength("newSecurePassword", TdsEnums.MAXLEN_NEWPASSWORD);
}
SqlConnectionPoolKey key = new SqlConnectionPoolKey(connectionString, credential, accessToken: null, serverCertificateValidationCallback: null, clientCertificateRetrievalCallback: null, originalNetworkAddressInfo: null);
SqlConnectionString connectionOptions = SqlConnectionFactory.FindSqlConnectionOptions(key);
// Check for incompatible connection string value with SqlCredential
if (!ADP.IsEmpty(connectionOptions.UserID) || !ADP.IsEmpty(connectionOptions.Password))
{
throw ADP.InvalidMixedArgumentOfSecureAndClearCredential();
}
if (connectionOptions.IntegratedSecurity || connectionOptions.Authentication == SqlAuthenticationMethod.ActiveDirectoryIntegrated)
{
throw SQL.ChangePasswordConflictsWithSSPI();
}
if (!ADP.IsEmpty(connectionOptions.AttachDBFilename))
{
throw SQL.ChangePasswordUseOfUnallowedKey(SqlConnectionString.KEY.AttachDBFilename);
}
if (connectionOptions.ContextConnection)
{
throw SQL.ChangePasswordUseOfUnallowedKey(SqlConnectionString.KEY.Context_Connection);
}
System.Security.PermissionSet permissionSet = connectionOptions.CreatePermissionSet();
permissionSet.Demand();
ChangePassword(connectionString, connectionOptions, credential, null, newSecurePassword);
}
finally
{
SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID);
}
}
private static void ChangePassword(string connectionString, SqlConnectionString connectionOptions, SqlCredential credential, string newPassword, SecureString newSecurePassword)
{
// note: This is the only case where we directly construt the internal connection, passing in the new password.
// Normally we would simply create a regular connectoin and open it but there is no other way to pass the
// new password down to the constructor. Also it would have an unwanted impact on the connection pool
//
using (SqlInternalConnectionTds con = new SqlInternalConnectionTds(null, connectionOptions, credential, null, newPassword, newSecurePassword, false, null, null, null, null))
{
if (!con.IsYukonOrNewer)
{
throw SQL.ChangePasswordRequiresYukon();
}
}
SqlConnectionPoolKey key = new SqlConnectionPoolKey(connectionString, credential, accessToken: null, serverCertificateValidationCallback: null, clientCertificateRetrievalCallback: null, originalNetworkAddressInfo: null);
SqlConnectionFactory.SingletonInstance.ClearPool(key);
}
internal void RegisterForConnectionCloseNotification<T>(ref Task<T> outerTask, object value, int tag)
{
// Connection exists, schedule removal, will be added to ref collection after calling ValidateAndReconnect
outerTask = outerTask.ContinueWith(task =>
{
RemoveWeakReference(value);
return task;
}, TaskScheduler.Default).Unwrap();
}
// updates our context with any changes made to the memory-mapped data by an external process
static private void RefreshMemoryMappedData(SqlDebugContext sdc)
{
Debug.Assert(ADP.PtrZero != sdc.pMemMap, "SQL Debug: invalid null value for pMemMap!");
// copy memory mapped file contents into managed types
MEMMAP memMap = (MEMMAP)Marshal.PtrToStructure(sdc.pMemMap, typeof(MEMMAP));
sdc.dbgpid = memMap.dbgpid;
sdc.fOption = (memMap.fOption == 1) ? true : false;
// xlate ansi byte[] -> managed strings
Encoding cp = System.Text.Encoding.GetEncoding(TdsEnums.DEFAULT_ENGLISH_CODE_PAGE_VALUE);
sdc.machineName = cp.GetString(memMap.rgbMachineName, 0, memMap.rgbMachineName.Length);
sdc.sdiDllName = cp.GetString(memMap.rgbDllName, 0, memMap.rgbDllName.Length);
// just get data reference
sdc.data = memMap.rgbData;
}
/// <include file='..\..\..\..\..\..\..\doc\snippets\Microsoft.Data.SqlClient\SqlConnection.xml' path='docs/members[@name="SqlConnection"]/ResetStatistics/*' />
public void ResetStatistics()
{
if (IsContextConnection)
{
throw SQL.NotAvailableOnContextConnection();
}
if (null != Statistics)
{
Statistics.Reset();
if (ConnectionState.Open == State)
{
// update timestamp;
ADP.TimerCurrent(out _statistics._openTimestamp);
}
}
}
/// <include file='..\..\..\..\..\..\..\doc\snippets\Microsoft.Data.SqlClient\SqlConnection.xml' path='docs/members[@name="SqlConnection"]/RetrieveStatistics/*' />
public IDictionary RetrieveStatistics()
{
if (IsContextConnection)
{
throw SQL.NotAvailableOnContextConnection();
}
if (null != Statistics)
{
UpdateStatistics();
return Statistics.GetHashtable();
}
else
{
return new SqlStatistics().GetHashtable();
}
}
private void UpdateStatistics()
{
if (ConnectionState.Open == State)
{
// update timestamp
ADP.TimerCurrent(out _statistics._closeTimestamp);
}
// delegate the rest of the work to the SqlStatistics class
Statistics.UpdateStatistics();
}
/// <include file='..\..\..\..\..\..\..\doc\snippets\Microsoft.Data.SqlClient\SqlConnection.xml' path='docs/members[@name="SqlConnection"]/RetrieveInternalInfo/*' />
public IDictionary<string, object> RetrieveInternalInfo()
{
IDictionary<string, object> internalDictionary = new Dictionary<string, object>();
internalDictionary.Add("SQLDNSCachingSupportedState", SQLDNSCachingSupportedState);
internalDictionary.Add("SQLDNSCachingSupportedStateBeforeRedirect", SQLDNSCachingSupportedStateBeforeRedirect);
return internalDictionary;
}
//
// UDT SUPPORT
//
private Assembly ResolveTypeAssembly(AssemblyName asmRef, bool throwOnError)
{
Debug.Assert(TypeSystemAssemblyVersion != null, "TypeSystemAssembly should be set !");
if (string.Compare(asmRef.Name, "Microsoft.SqlServer.Types", StringComparison.OrdinalIgnoreCase) == 0)
{
if (asmRef.Version != TypeSystemAssemblyVersion && SqlClientEventSource.Log.IsTraceEnabled())
{
SqlClientEventSource.Log.TryTraceEvent("<sc.SqlConnection.ResolveTypeAssembly> SQL CLR type version change: Server sent {0}, client will instantiate {1}", asmRef.Version, TypeSystemAssemblyVersion);
}
asmRef.Version = TypeSystemAssemblyVersion;
}
try
{
return Assembly.Load(asmRef);
}
catch (Exception e)
{
if (throwOnError || !ADP.IsCatchableExceptionType(e))
{
throw;
}
else
{
return null;
};
}
}
// TODO - move UDT code to separate file.
internal void CheckGetExtendedUDTInfo(SqlMetaDataPriv metaData, bool fThrow)
{
if (metaData.udt?.Type == null)
{ // If null, we have not obtained extended info.
Debug.Assert(!ADP.IsEmpty(metaData.udt?.AssemblyQualifiedName), "Unexpected state on GetUDTInfo");
// Parameter throwOnError determines whether exception from Assembly.Load is thrown.
metaData.udt.Type =
Type.GetType(typeName: metaData.udt.AssemblyQualifiedName, assemblyResolver: asmRef => ResolveTypeAssembly(asmRef, fThrow), typeResolver: null, throwOnError: fThrow);
if (fThrow && metaData.udt.Type == null)
{
// TODO - BUG - UNDONE - Fix before Whidbey RTM - better message!
throw SQL.UDTUnexpectedResult(metaData.udt.AssemblyQualifiedName);
}
}
}
internal object GetUdtValue(object value, SqlMetaDataPriv metaData, bool returnDBNull)
{
if (returnDBNull && ADP.IsNull(value))
{
return DBNull.Value;
}
object o = null;
// Since the serializer doesn't handle nulls...
if (ADP.IsNull(value))
{
Type t = metaData.udt?.Type;
Debug.Assert(t != null, "Unexpected null of udtType on GetUdtValue!");
o = t.InvokeMember("Null", BindingFlags.Public | BindingFlags.GetProperty | BindingFlags.Static, null, null, new Object[] { }, CultureInfo.InvariantCulture);
Debug.Assert(o != null);
return o;
}
else
{
MemoryStream stm = new MemoryStream((byte[])value);
o = SerializationHelperSql9.Deserialize(stm, metaData.udt?.Type);
Debug.Assert(o != null, "object could NOT be created");
return o;
}
}
internal byte[] GetBytes(object o)
{
Format format = Format.Native;
int maxSize = 0;
return GetBytes(o, out format, out maxSize);
}
internal byte[] GetBytes(object o, out Format format, out int maxSize)
{
SqlUdtInfo attr = AssemblyCache.GetInfoFromType(o.GetType());
maxSize = attr.MaxByteSize;
format = attr.SerializationFormat;
if (maxSize < -1 || maxSize >= UInt16.MaxValue)
{ // Do we need this? Is this the right place?
throw new InvalidOperationException(o.GetType() + ": invalid Size");
}
byte[] retval;
using (MemoryStream stm = new MemoryStream(maxSize < 0 ? 0 : maxSize))
{
SerializationHelperSql9.Serialize(stm, o);
retval = stm.ToArray();
}
return retval;
}
} // SqlConnection
// TODO: This really belongs in it's own source file...
//
// This is a private interface for the SQL Debugger
// You must not change the guid for this coclass
// or the iid for the ISQLDebug interface
//
/// <include file='../../../../../../../doc/snippets/Microsoft.Data.SqlClient/SqlDebugging.xml' path='docs/members[@name="SQLDebugging"]/SQLDebugging/*'/>
[
ComVisible(true),
ClassInterface(ClassInterfaceType.None),
Guid("afef65ad-4577-447a-a148-83acadd3d4b9"),
]
[System.Security.Permissions.PermissionSetAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Name = "FullTrust")]
public sealed class SQLDebugging : ISQLDebug
{
// Security stuff
const int STANDARD_RIGHTS_REQUIRED = (0x000F0000);
const int DELETE = (0x00010000);
const int READ_CONTROL = (0x00020000);
const int WRITE_DAC = (0x00040000);
const int WRITE_OWNER = (0x00080000);
const int SYNCHRONIZE = (0x00100000);
const int FILE_ALL_ACCESS = (STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE | 0x000001FF);
const uint GENERIC_READ = (0x80000000);
const uint GENERIC_WRITE = (0x40000000);
const uint GENERIC_EXECUTE = (0x20000000);
const uint GENERIC_ALL = (0x10000000);
const int SECURITY_DESCRIPTOR_REVISION = (1);
const int ACL_REVISION = (2);
const int SECURITY_AUTHENTICATED_USER_RID = (0x0000000B);
const int SECURITY_LOCAL_SYSTEM_RID = (0x00000012);
const int SECURITY_BUILTIN_DOMAIN_RID = (0x00000020);
const int SECURITY_WORLD_RID = (0x00000000);
const byte SECURITY_NT_AUTHORITY = 5;
const int DOMAIN_GROUP_RID_ADMINS = (0x00000200);
const int DOMAIN_ALIAS_RID_ADMINS = (0x00000220);
const int sizeofSECURITY_ATTRIBUTES = 12; // sizeof(SECURITY_ATTRIBUTES);
const int sizeofSECURITY_DESCRIPTOR = 20; // sizeof(SECURITY_DESCRIPTOR);
const int sizeofACCESS_ALLOWED_ACE = 12; // sizeof(ACCESS_ALLOWED_ACE);
const int sizeofACCESS_DENIED_ACE = 12; // sizeof(ACCESS_DENIED_ACE);
const int sizeofSID_IDENTIFIER_AUTHORITY = 6; // sizeof(SID_IDENTIFIER_AUTHORITY)
const int sizeofACL = 8; // sizeof(ACL);
private IntPtr CreateSD(ref IntPtr pDacl)
{
IntPtr pSecurityDescriptor = IntPtr.Zero;
IntPtr pUserSid = IntPtr.Zero;
IntPtr pAdminSid = IntPtr.Zero;
IntPtr pNtAuthority = IntPtr.Zero;
int cbAcl = 0;
bool status = false;
pNtAuthority = Marshal.AllocHGlobal(sizeofSID_IDENTIFIER_AUTHORITY);
if (pNtAuthority == IntPtr.Zero)
goto cleanup;
Marshal.WriteInt32(pNtAuthority, 0, 0);
Marshal.WriteByte(pNtAuthority, 4, 0);
Marshal.WriteByte(pNtAuthority, 5, SECURITY_NT_AUTHORITY);
status =
NativeMethods.AllocateAndInitializeSid(
pNtAuthority,
(byte)1,
SECURITY_AUTHENTICATED_USER_RID,
0,
0,
0,
0,
0,
0,
0,
ref pUserSid);
if (!status || pUserSid == IntPtr.Zero)
{
goto cleanup;
}
status =
NativeMethods.AllocateAndInitializeSid(
pNtAuthority,
(byte)2,
SECURITY_BUILTIN_DOMAIN_RID,
DOMAIN_ALIAS_RID_ADMINS,
0,
0,
0,
0,
0,
0,
ref pAdminSid);
if (!status || pAdminSid == IntPtr.Zero)
{
goto cleanup;
}
status = false;
pSecurityDescriptor = Marshal.AllocHGlobal(sizeofSECURITY_DESCRIPTOR);
if (pSecurityDescriptor == IntPtr.Zero)
{
goto cleanup;
}
for (int i = 0; i < sizeofSECURITY_DESCRIPTOR; i++)
Marshal.WriteByte(pSecurityDescriptor, i, (byte)0);
cbAcl = sizeofACL
+ (2 * (sizeofACCESS_ALLOWED_ACE))
+ sizeofACCESS_DENIED_ACE
+ NativeMethods.GetLengthSid(pUserSid)
+ NativeMethods.GetLengthSid(pAdminSid);
pDacl = Marshal.AllocHGlobal(cbAcl);
if (pDacl == IntPtr.Zero)
{
goto cleanup;
}
// rights must be added in a certain order. Namely, deny access first, then add access
if (NativeMethods.InitializeAcl(pDacl, cbAcl, ACL_REVISION))
if (NativeMethods.AddAccessDeniedAce(pDacl, ACL_REVISION, WRITE_DAC, pUserSid))
if (NativeMethods.AddAccessAllowedAce(pDacl, ACL_REVISION, GENERIC_READ, pUserSid))
if (NativeMethods.AddAccessAllowedAce(pDacl, ACL_REVISION, GENERIC_ALL, pAdminSid))
if (NativeMethods.InitializeSecurityDescriptor(pSecurityDescriptor, SECURITY_DESCRIPTOR_REVISION))
if (NativeMethods.SetSecurityDescriptorDacl(pSecurityDescriptor, true, pDacl, false))
{
status = true;
}
cleanup:
if (pNtAuthority != IntPtr.Zero)
{
Marshal.FreeHGlobal(pNtAuthority);
}
if (pAdminSid != IntPtr.Zero)
NativeMethods.FreeSid(pAdminSid);
if (pUserSid != IntPtr.Zero)
NativeMethods.FreeSid(pUserSid);
if (status)
return pSecurityDescriptor;
else
{
if (pSecurityDescriptor != IntPtr.Zero)
{
Marshal.FreeHGlobal(pSecurityDescriptor);
}
}
return IntPtr.Zero;
}
// SxS: using file mapping API (CreateFileMapping)
// TODO: review this code for SxS issues (VSDD 540765)
[ResourceExposure(ResourceScope.None)]
[ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
bool ISQLDebug.SQLDebug(int dwpidDebugger, int dwpidDebuggee, [MarshalAs(UnmanagedType.LPStr)] string pszMachineName,
[MarshalAs(UnmanagedType.LPStr)] string pszSDIDLLName, int dwOption, int cbData, byte[] rgbData)
{
bool result = false;
IntPtr hFileMap = IntPtr.Zero;
IntPtr pMemMap = IntPtr.Zero;
IntPtr pSecurityDescriptor = IntPtr.Zero;
IntPtr pSecurityAttributes = IntPtr.Zero;
IntPtr pDacl = IntPtr.Zero;
// validate the structure
if (null == pszMachineName || null == pszSDIDLLName)
return false;
if (pszMachineName.Length > TdsEnums.SDCI_MAX_MACHINENAME ||
pszSDIDLLName.Length > TdsEnums.SDCI_MAX_DLLNAME)
return false;
// note that these are ansi strings
Encoding cp = System.Text.Encoding.GetEncoding(TdsEnums.DEFAULT_ENGLISH_CODE_PAGE_VALUE);
byte[] rgbMachineName = cp.GetBytes(pszMachineName);
byte[] rgbSDIDLLName = cp.GetBytes(pszSDIDLLName);
if (null != rgbData && cbData > TdsEnums.SDCI_MAX_DATA)
return false;
string mapFileName;
// If Win2k or later, prepend "Global\\" to enable this to work through TerminalServices.
if (ADP.IsPlatformNT5)
{
mapFileName = "Global\\" + TdsEnums.SDCI_MAPFILENAME;
}
else
{
mapFileName = TdsEnums.SDCI_MAPFILENAME;
}
mapFileName = mapFileName + dwpidDebuggee.ToString(CultureInfo.InvariantCulture);
// Create Security Descriptor
pSecurityDescriptor = CreateSD(ref pDacl);
pSecurityAttributes = Marshal.AllocHGlobal(sizeofSECURITY_ATTRIBUTES);
if ((pSecurityDescriptor == IntPtr.Zero) || (pSecurityAttributes == IntPtr.Zero))
return false;
Marshal.WriteInt32(pSecurityAttributes, 0, sizeofSECURITY_ATTRIBUTES); // nLength = sizeof(SECURITY_ATTRIBUTES)
Marshal.WriteIntPtr(pSecurityAttributes, 4, pSecurityDescriptor); // lpSecurityDescriptor = pSecurityDescriptor
Marshal.WriteInt32(pSecurityAttributes, 8, 0); // bInheritHandle = FALSE
hFileMap = NativeMethods.CreateFileMappingA(
ADP.InvalidPtr/*INVALID_HANDLE_VALUE*/,
pSecurityAttributes,
0x4/*PAGE_READWRITE*/,
0,
Marshal.SizeOf(typeof(MEMMAP)),
mapFileName);
if (IntPtr.Zero == hFileMap)
{
goto cleanup;
}
pMemMap = NativeMethods.MapViewOfFile(hFileMap, 0x6/*FILE_MAP_READ|FILE_MAP_WRITE*/, 0, 0, IntPtr.Zero);
if (IntPtr.Zero == pMemMap)
{
goto cleanup;
}
// copy data to memory-mapped file
// layout of MEMMAP structure is:
// uint dbgpid
// uint fOption
// byte[32] machineName
// byte[16] sdiDllName
// uint dbData
// byte[255] vData
int offset = 0;
Marshal.WriteInt32(pMemMap, offset, (int)dwpidDebugger);
offset += 4;
Marshal.WriteInt32(pMemMap, offset, (int)dwOption);
offset += 4;
Marshal.Copy(rgbMachineName, 0, ADP.IntPtrOffset(pMemMap, offset), rgbMachineName.Length);
offset += TdsEnums.SDCI_MAX_MACHINENAME;
Marshal.Copy(rgbSDIDLLName, 0, ADP.IntPtrOffset(pMemMap, offset), rgbSDIDLLName.Length);
offset += TdsEnums.SDCI_MAX_DLLNAME;
Marshal.WriteInt32(pMemMap, offset, (int)cbData);
offset += 4;
if (null != rgbData)
{
Marshal.Copy(rgbData, 0, ADP.IntPtrOffset(pMemMap, offset), (int)cbData);
}
NativeMethods.UnmapViewOfFile(pMemMap);
result = true;
cleanup:
if (result == false)
{
if (hFileMap != IntPtr.Zero)
NativeMethods.CloseHandle(hFileMap);
}
if (pSecurityAttributes != IntPtr.Zero)
Marshal.FreeHGlobal(pSecurityAttributes);
if (pSecurityDescriptor != IntPtr.Zero)
Marshal.FreeHGlobal(pSecurityDescriptor);
if (pDacl != IntPtr.Zero)
Marshal.FreeHGlobal(pDacl);
return result;
}
}
// this is a private interface to com+ users
// do not change this guid
[
ComImport,
ComVisible(true),
Guid("6cb925bf-c3c0-45b3-9f44-5dd67c7b7fe8"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown),
BestFitMapping(false, ThrowOnUnmappableChar = true),
]
interface ISQLDebug
{
[System.Security.Permissions.PermissionSetAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Name = "FullTrust")]
bool SQLDebug(
int dwpidDebugger,
int dwpidDebuggee,
[MarshalAs(UnmanagedType.LPStr)] string pszMachineName,
[MarshalAs(UnmanagedType.LPStr)] string pszSDIDLLName,
int dwOption,
int cbData,
byte[] rgbData);
}
sealed class SqlDebugContext : IDisposable
{
// context data
internal uint pid = 0;
internal uint tid = 0;
internal bool active = false;
// memory-mapped data
internal IntPtr pMemMap = ADP.PtrZero;
internal IntPtr hMemMap = ADP.PtrZero;
internal uint dbgpid = 0;
internal bool fOption = false;
internal string machineName = null;
internal string sdiDllName = null;
internal byte[] data = null;
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
// using CloseHandle and UnmapViewOfFile - no exposure
[ResourceExposure(ResourceScope.None)]
[ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
private void Dispose(bool disposing)
{
if (disposing)
{
// Nothing to do here
;
}
if (pMemMap != IntPtr.Zero)
{
NativeMethods.UnmapViewOfFile(pMemMap);
pMemMap = IntPtr.Zero;
}
if (hMemMap != IntPtr.Zero)
{
NativeMethods.CloseHandle(hMemMap);
hMemMap = IntPtr.Zero;
}
active = false;
}
~SqlDebugContext()
{
Dispose(false);
}
}
// native interop memory mapped structure for sdi debugging
[StructLayoutAttribute(LayoutKind.Sequential, Pack = 1)]
internal struct MEMMAP
{
[MarshalAs(UnmanagedType.U4)]
internal uint dbgpid; // id of debugger
[MarshalAs(UnmanagedType.U4)]
internal uint fOption; // 1 - start debugging, 0 - stop debugging
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)]
internal byte[] rgbMachineName;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
internal byte[] rgbDllName;
[MarshalAs(UnmanagedType.U4)]
internal uint cbData;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 255)]
internal byte[] rgbData;
}
} // Microsoft.Data.SqlClient namespace
| 42.83421 | 242 | 0.561888 | [
"MIT"
] | cmeyertons/SqlClient | src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlConnection.cs | 138,483 | C# |
using System;
using System.Collections.Generic;
using KuehneNagel.WeatherForecast.Application.Interfaces;
using KuehneNagel.WeatherForecast.Application.Services;
using KuehneNagel.WeatherForecast.Domain.Interfaces.Services;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace KuehneNagel.WeatherForecast.Application.Tests
{
[TestClass]
public class AppServiceTests
{
private class weatherAggregateServiceMock : IWeatherForecastAggregateService
{
public bool CurrentTemperatureMatchForecast(DateTime dateTime)
{
return true;
}
public double GetCurrentDayForecastAccuracy()
{
return 50;
}
public double GetCurrentTemperature()
{
return 55.55;
}
public IEnumerable<double> GetMaxDayTemperatures()
{
return new List<double>() { 1, 2, 3 };
}
public IEnumerable<double> GetMaxNightTemperatures()
{
return new List<double>() { 4, 5, 6 };
}
public IEnumerable<double> GetMinDayTemperatures()
{
return new List<double>() { 7, 8, 9 };
}
public IEnumerable<double> GetMinNightTemperatures()
{
return new List<double>() { 10, 11, 12 };
}
public string UpdateDataFromOnlineServices()
{
return "Message";
}
}
[TestMethod]
public void GetWeatherData()
{
var mock = new weatherAggregateServiceMock();
IWeatherForecastAppService appService = new WeatherForecastAppService(mock);
var viewModel = appService.GetWeatherData();
Assert.IsTrue(mock.CurrentTemperatureMatchForecast(DateTime.Now) == viewModel.CurrentTemperatureMatchForecast,
"Current Temperature Match Forecast Not Valid!");
Assert.IsTrue(mock.GetCurrentDayForecastAccuracy() == viewModel.CurrentDayForecastAccuracy,
"Current Day Forecast Accuracy Not Valid!");
Assert.IsTrue(mock.GetCurrentTemperature() == viewModel.CurrentTemperature,
"Current Temperature Not Valid!");
var maxDay = viewModel.MaxDayTemperatures.GetEnumerator();
maxDay.MoveNext();
Assert.IsTrue(maxDay.Current == 1,
"Get Max Day Temperatures Not Valid!");
var maxNight = viewModel.MaxNightTemperatures.GetEnumerator();
maxNight.MoveNext();
Assert.IsTrue(maxNight.Current == 4,
"Get Max Night Temperatures Not Valid!");
var minDay = viewModel.MinDayTemperatures.GetEnumerator();
minDay.MoveNext();
Assert.IsTrue(minDay.Current == 7,
"Get Min Day Temperatures Not Valid!");
var minNight = viewModel.MinNightTemperatures.GetEnumerator();
minNight.MoveNext();
Assert.IsTrue(minNight.Current == 10,
"Get Min Night Temperatures Not Valid!");
}
}
}
| 34.387097 | 122 | 0.59162 | [
"MIT"
] | viniciusmiguel/KuehneNagel.WeatherForecast | KuehneNagel.WeatherForecast/KuehneNagel.WeatherForecast.Application.Tests/AppServiceTests.cs | 3,198 | C# |
namespace Example_003_JsonSerialization
{
public class TemperatureRange
{
public Temperature? Min { get; set; }
public Temperature? Max { get; set; }
}
}
| 20.333333 | 45 | 0.639344 | [
"MIT"
] | anton-ivanchenko/Sharp.ValueObject | Examples/Example_003_JsonSerialization/TemperatureRange.cs | 185 | C# |
namespace GenericScriptableArchitecture.Editor
{
using System.Collections.Generic;
using SolidUtilities.Editor.Helpers;
using UnityEditor;
using UnityEngine;
public static class SettingsDrawer
{
private const string EnabledInProjectLabel = "Enable stack traces in all assets";
private static readonly GUIContent _enabledInProjectContent = new GUIContent(EnabledInProjectLabel,
"This has higher priority than the disabled stack trace option on individual assets.");
[SettingsProvider]
public static SettingsProvider CreateSettingsProvider()
{
return new SettingsProvider("Project/Packages/Generic ScriptableObject Architecture", SettingsScope.Project)
{
guiHandler = OnGUI,
keywords = GetKeywords()
};
}
private static void OnGUI(string searchContext)
{
if (StackTraceSettings.EnabledInProject)
{
EditorGUILayoutHelper.DrawInfoMessage(
"Stack traces may affect performance of the game in editor. If possible, enable it on individual assets when they require debugging.");
}
using (EditorGUIUtilityHelper.LabelWidthBlock(220f))
{
StackTraceSettings.EnabledInProject = EditorGUILayout.Toggle(_enabledInProjectContent, StackTraceSettings.EnabledInProject);
}
}
private static HashSet<string> GetKeywords()
{
var keywords = new HashSet<string>();
keywords.AddWords(EnabledInProjectLabel);
return keywords;
}
private static readonly char[] _separators = { ' ' };
private static void AddWords(this HashSet<string> set, string phrase)
{
foreach (string word in phrase.Split(_separators))
{
set.Add(word);
}
}
}
} | 35.017857 | 155 | 0.626211 | [
"MIT"
] | SolidAlloy/GenericScriptableArchitecture | Editor/StackTrace/SettingsDrawer.cs | 1,963 | C# |
/*
* Copyright 2018 JDCLOUD.COM
*
* 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.
*
* Quota
* 集群配额相关接口
*
* OpenAPI spec version: v1
* Contact:
*
* NOTE: This class is auto generated by the jdcloud code generator program.
*/
using System;
using System.Collections.Generic;
using System.Text;
using JDCloudSDK.Core.Service;
using JDCloudSDK.Core.Annotation;
using Newtonsoft.Json;
namespace JDCloudSDK.Kubernetes.Apis
{
/// <summary>
/// 修改 kubernetes 集群配额,内部接口
/// </summary>
public class ModifyQuotaRequest : JdcloudRequest
{
///<summary>
/// 资源类型[kubernetes]
///Required:true
///</summary>
[Required]
public string ResourceType{ get; set; }
///<summary>
/// 配额上限
///Required:true
///</summary>
[Required]
public int Limit{ get; set; }
///<summary>
/// Region ID
///Required:true
///</summary>
[Required]
[JsonProperty("regionId")]
public string RegionIdValue{ get; set; }
}
} | 25.516129 | 76 | 0.636536 | [
"Apache-2.0"
] | jdcloud-api/jdcloud-sdk-net | sdk/src/Service/Kubernetes/Apis/ModifyQuotaRequest.cs | 1,636 | C# |
using Newtonsoft.Json.Linq;
namespace MiControl.Devices
{
public abstract class MiHomeDevice
{
public string Sid { get; }
public string Name { get; set; }
public string CustomName { get; set; }
public string Type { get; }
public float? Voltage { get; private set; }
protected MiHomeDevice(string sid, string type)
{
Sid = sid;
Type = type;
}
public virtual void ParseData(string command)
{
var jObject = JObject.Parse(command);
if (jObject["voltage"] != null && float.TryParse(jObject["voltage"].ToString(), out float v))
{
Voltage = v / 1000;
}
ParseData(jObject);
}
public abstract void ParseData(JObject data);
}
} | 24.5 | 105 | 0.539016 | [
"MIT"
] | ermac0/mi-home | MiControl/MiControl/Devices/MiHomeDevice.cs | 835 | C# |
// (c) 2012-2016 Nick Hodge mailto:nhodge@mungr.com & Brendan Forster
// License: MS-PL
using System.Collections.Generic;
using Newtonsoft.Json;
namespace BoxKite.Twitter.Models
{
public class FriendshipLookupResponse : TwitterControlBase
{
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("screen_name")]
public string ScreenName { get; set; }
[JsonProperty("id")]
public long UserId { get; set; }
[JsonProperty("connections")]
public IEnumerable<string> Connections { get; set; }
}
}
| 25.608696 | 70 | 0.646859 | [
"MIT"
] | nickhodge/BoxKite.Twitter | src/BoxKite.Twitter/Platforms/shared/Models/Service/FriendshipLookupResponse.cs | 591 | C# |
// Copyright (c) 2014 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.Windows;
using System.Windows.Input;
using System.Windows.Threading;
namespace WinIO.AvalonEdit.Rendering
{
/// <summary>
/// Encapsulates and adds MouseHover support to UIElements.
/// </summary>
public class MouseHoverLogic : IDisposable
{
UIElement target;
DispatcherTimer mouseHoverTimer;
Point mouseHoverStartPoint;
MouseEventArgs mouseHoverLastEventArgs;
bool mouseHovering;
/// <summary>
/// Creates a new instance and attaches itself to the <paramref name="target" /> UIElement.
/// </summary>
public MouseHoverLogic(UIElement target)
{
if (target == null)
throw new ArgumentNullException("target");
this.target = target;
this.target.MouseLeave += MouseHoverLogicMouseLeave;
this.target.MouseMove += MouseHoverLogicMouseMove;
this.target.MouseEnter += MouseHoverLogicMouseEnter;
}
void MouseHoverLogicMouseMove(object sender, MouseEventArgs e)
{
Vector mouseMovement = mouseHoverStartPoint - e.GetPosition(this.target);
if (Math.Abs(mouseMovement.X) > SystemParameters.MouseHoverWidth
|| Math.Abs(mouseMovement.Y) > SystemParameters.MouseHoverHeight) {
StartHovering(e);
}
// do not set e.Handled - allow others to also handle MouseMove
}
void MouseHoverLogicMouseEnter(object sender, MouseEventArgs e)
{
StartHovering(e);
// do not set e.Handled - allow others to also handle MouseEnter
}
void StartHovering(MouseEventArgs e)
{
StopHovering();
mouseHoverStartPoint = e.GetPosition(this.target);
mouseHoverLastEventArgs = e;
mouseHoverTimer = new DispatcherTimer(SystemParameters.MouseHoverTime, DispatcherPriority.Background, OnMouseHoverTimerElapsed, this.target.Dispatcher);
mouseHoverTimer.Start();
}
void MouseHoverLogicMouseLeave(object sender, MouseEventArgs e)
{
StopHovering();
// do not set e.Handled - allow others to also handle MouseLeave
}
void StopHovering()
{
if (mouseHoverTimer != null) {
mouseHoverTimer.Stop();
mouseHoverTimer = null;
}
if (mouseHovering) {
mouseHovering = false;
OnMouseHoverStopped(mouseHoverLastEventArgs);
}
}
void OnMouseHoverTimerElapsed(object sender, EventArgs e)
{
mouseHoverTimer.Stop();
mouseHoverTimer = null;
mouseHovering = true;
OnMouseHover(mouseHoverLastEventArgs);
}
/// <summary>
/// Occurs when the mouse starts hovering over a certain location.
/// </summary>
public event EventHandler<MouseEventArgs> MouseHover;
/// <summary>
/// Raises the <see cref="MouseHover"/> event.
/// </summary>
protected virtual void OnMouseHover(MouseEventArgs e)
{
if (MouseHover != null) {
MouseHover(this, e);
}
}
/// <summary>
/// Occurs when the mouse stops hovering over a certain location.
/// </summary>
public event EventHandler<MouseEventArgs> MouseHoverStopped;
/// <summary>
/// Raises the <see cref="MouseHoverStopped"/> event.
/// </summary>
protected virtual void OnMouseHoverStopped(MouseEventArgs e)
{
if (MouseHoverStopped != null) {
MouseHoverStopped(this, e);
}
}
bool disposed;
/// <summary>
/// Removes the MouseHover support from the target UIElement.
/// </summary>
public void Dispose()
{
if (!disposed) {
this.target.MouseLeave -= MouseHoverLogicMouseLeave;
this.target.MouseMove -= MouseHoverLogicMouseMove;
this.target.MouseEnter -= MouseHoverLogicMouseEnter;
}
disposed = true;
}
}
}
| 30.899329 | 155 | 0.728714 | [
"Apache-2.0"
] | sak9188/WinIO2 | WinIO/WinIO/AvalonEdit/Rendering/MouseHoverLogic.cs | 4,604 | C# |
namespace LearningCenter.Web.ViewModels.Account
{
using System.Linq;
using AutoMapper;
using LearningCenter.Data.Models;
using LearningCenter.Services.Mapping;
public class CourseViewModel : IMapFrom<Course>, IHaveCustomMappings
{
public int Id { get; set; }
public string Title { get; set; }
public decimal Price { get; set; }
public int ReviewsCount { get; set; }
public double AverageRating { get; set; }
public void CreateMappings(IProfileExpression configuration)
{
configuration.CreateMap<Course, CourseViewModel>()
.ForMember(x => x.AverageRating, opt => opt.MapFrom(c => c.Ratings.Average(r => r.Value)));
}
}
}
| 26.714286 | 107 | 0.635027 | [
"MIT"
] | NikolayStefanov/Learning-Center | Web/LearningCenter.Web.ViewModels/Account/CourseViewModel.cs | 750 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PositionsForFlying :
IAdjacentFinder
{
IEvaluateHex checkHex = new IsNewFlying();
public void GetAdjacentHexesExtended(BattleHex initialHex)
{
List<BattleHex> neighboursToCkeck = NeighboursFinder.GetAdjacentHexes(initialHex, checkHex);
foreach (BattleHex hex in neighboursToCkeck)
{
hex.isNeighbourgHex = true;
hex.distanceText.SetDistanceFofFlyingUnit(initialHex);
hex.MakeAvailable();
}
}
}
| 26.227273 | 100 | 0.69844 | [
"MIT"
] | rafaelmmedeiros/Apocaliptatics | Assets/Scripts/AvailablePosition/PositionsForFlying.cs | 579 | C# |
/*
* Copyright (c) 2016 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
using Google.Cloud.Logging.V2;
using Grpc.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using Xunit;
namespace GoogleCloudSamples
{
public class BaseTest
{
private readonly string _projectId;
private readonly List<string> _logsToDelete = new List<string>();
private readonly List<string> _sinksToDelete = new List<string>();
private readonly CommandLineRunner _runner = new CommandLineRunner()
{
Command = "LoggingSample",
Main = LoggingSample.Main
};
private readonly RetryRobot _retryRobot = new RetryRobot()
{
ShouldRetry = (Exception e) =>
{
if (e is Xunit.Sdk.XunitException)
return true;
var rpcException = e as RpcException;
if (rpcException != null)
{
return new[] { StatusCode.Aborted, StatusCode.Internal,
StatusCode.Cancelled, StatusCode.NotFound }
.Contains(rpcException.Status.StatusCode);
}
return false;
},
DelayMultiplier = 3
};
public BaseTest()
{
_projectId = Environment.GetEnvironmentVariable("GOOGLE_PROJECT_ID");
}
/// <summary>Runs LoggingSample.exe with the provided arguments</summary>
/// <returns>The console output of this program</returns>
public ConsoleOutput Run(params string[] arguments) =>
_runner.Run(arguments);
public void Eventually(Action a) => _retryRobot.Eventually(a);
public class LoggingTest : BaseTest, IDisposable
{
public void Dispose()
{
var exceptions = new List<Exception>();
// Delete all logs created from running the tests.
foreach (string log in _logsToDelete)
{
try
{
Run("delete-log", log);
}
catch (RpcException ex)
when (ex.Status.StatusCode == StatusCode.NotFound)
{ }
catch (Exception e)
{
exceptions.Add(e);
}
}
// Delete all the log sinks created from running the tests.
foreach (string sink in _sinksToDelete)
{
try
{
Run("delete-sink", sink);
}
catch (RpcException ex)
when (ex.Status.StatusCode == StatusCode.NotFound)
{ }
catch (Exception e)
{
exceptions.Add(e);
}
}
if (exceptions.Count > 0)
{
throw new AggregateException(exceptions);
}
}
static string RandomName() =>
GoogleCloudSamples.TestUtil.RandomName();
[Fact]
public void TestCreateLogEntry()
{
string logId = "logForTestCreateLogEntry" + RandomName();
string message = "Example log entry.";
_logsToDelete.Add(logId);
// Try creating a log entry.
var created = Run("create-log-entry", logId, message);
created.AssertSucceeded();
Eventually(() =>
{
// Retrieve the log entry just added, using the logId as a filter.
var results = Run("list-log-entries", logId);
// Confirm returned log entry contains expected value.
Assert.Contains(message, results.Stdout);
});
}
[Fact(Skip = "https://github.com/GoogleCloudPlatform/dotnet-docs-samples/issues/1066")]
public void TestListEntries()
{
string logId = "logForTestListEntries" + RandomName();
string message1 = "Example log entry.";
string message2 = "Another example log entry.";
string message3 = "Additional example log entry.";
_logsToDelete.Add(logId);
// Try creating three log entries.
Run("create-log-entry", logId, message1).AssertSucceeded();
Run("create-log-entry", logId, message2).AssertSucceeded();
Run("create-log-entry", logId, message3).AssertSucceeded();
Eventually(() =>
{
// Retrieve the log entries just added, using the logId as a filter.
var results = Run("list-log-entries", logId);
// Confirm returned log entry contains expected value.
Assert.Contains(message3, results.Stdout);
});
}
[Fact]
public void TestWithLogId()
{
StackdriverLogWriter.ProjectId = _projectId;
StackdriverLogWriter.LogId = "TestWithLogId" + RandomName();
string message1 = "TestWithLogId test example";
_logsToDelete.Add(StackdriverLogWriter.LogId);
StackdriverLogWriter.WriteLog("TestWithLogId test example");
Eventually(() =>
{
// Retrieve the log entries just added, using the logId as a filter.
var results = Run("list-log-entries", StackdriverLogWriter.LogId);
// Confirm returned log entry contains expected value.
Assert.Contains(message1, results.Stdout);
});
}
[Fact(Skip = "delete-log most often reports NotFound, even after 5 " +
"minutes or so. The eventual consistency of the API is so " +
"long that it can't be tested in the limited time " +
"allotted to a unit test.")]
public void TestDeleteLog()
{
string logId = "logForTestDeleteLog" + RandomName();
string message = "Example log entry.";
//Try creating a log entry
var created = Run("create-log-entry", logId, message);
created.AssertSucceeded();
// Try deleting log and assert on success.
Eventually(() =>
{
Run("delete-log", logId).AssertSucceeded();
});
}
[Fact]
public void TestCreateSink()
{
string sinkId = "sinkForTestCreateSink" + RandomName();
string logId = "logForTestCreateSink" + RandomName();
LogSinkName sinkName = new LogSinkName(_projectId, sinkId);
string message = "Example log entry.";
_sinksToDelete.Add(sinkId);
_logsToDelete.Add(logId);
// Try creating log with log entry.
var created1 = Run("create-log-entry", logId, message);
created1.AssertSucceeded();
// Try creating sink.
var created2 = Run("create-sink", sinkId, logId);
created2.AssertSucceeded();
var sinkClient = ConfigServiceV2Client.Create();
var results = sinkClient.GetSink(sinkName);
// Confirm newly created sink is returned.
Assert.NotNull(results);
}
[Fact]
public void TestListSinks()
{
string sinkId = "sinkForTestListSinks" + RandomName();
string logId = "logForTestListSinks" + RandomName();
string sinkName = $"projects/{_projectId}/sinks/{sinkId}";
string message = "Example log entry.";
_logsToDelete.Add(logId);
_sinksToDelete.Add(sinkId);
// Try creating log with log entry.
var created1 = Run("create-log-entry", logId, message);
created1.AssertSucceeded();
// Try creating sink.
var created2 = Run("create-sink", sinkId, logId);
created2.AssertSucceeded();
Eventually(() =>
{
// Try listing sinks.
var results = Run("list-sinks");
Assert.Equal(0, results.ExitCode);
});
}
[Fact]
public void TestUpdateSink()
{
string sinkId = "sinkForTestUpdateSink" + RandomName();
string logId = "logForTestUpdateSink" + RandomName();
string newLogId = "newlogForTestUpdateSink" + RandomName();
LogSinkName sinkName = new LogSinkName(_projectId, sinkId);
string message = "Example log entry.";
_sinksToDelete.Add(sinkId);
_logsToDelete.Add(logId);
_logsToDelete.Add(newLogId);
// Try creating logs with log entries.
Run("create-log-entry", logId, message).AssertSucceeded();
Run("create-log-entry", newLogId, message).AssertSucceeded();
Run("create-sink", sinkId, logId).AssertSucceeded();
// Try updating sink.
Run("update-sink", sinkId, newLogId).AssertSucceeded();
// Get sink to confirm that log has been updated.
var sinkClient = ConfigServiceV2Client.Create();
var results = sinkClient.GetSink(sinkName);
var currentLog = results.Filter;
Assert.Contains(newLogId, currentLog);
}
[Fact]
public void TestDeleteSink()
{
string sinkId = "sinkForTestDeleteSink" + RandomName();
string logId = "logForTestDeleteSink" + RandomName();
LogSinkName sinkName = new LogSinkName(_projectId, sinkId);
string message = "Example log entry.";
_sinksToDelete.Add(sinkId);
_logsToDelete.Add(logId);
// Try creating log with log entry.
Run("create-log-entry", logId, message).AssertSucceeded();
// Try creating sink.
Run("create-sink", sinkId, logId).AssertSucceeded();
// Try deleting sink.
Run("delete-sink", sinkId);
// Get sink to confirm it has been deleted.
var sinkClient = ConfigServiceV2Client.Create();
Exception ex = Assert.Throws<Grpc.Core.RpcException>(() =>
sinkClient.GetSink(sinkName));
}
readonly CommandLineRunner _quickStart = new CommandLineRunner()
{
VoidMain = QuickStart.Main,
Command = "dotnet run"
};
[Fact]
public void TestRunQuickStart()
{
string expectedOutput = "Log Entry created.";
// This logId should match the logId value set in QuickStart\QuickStart.cs
string logId = "my-log";
string message = "Hello World!";
_logsToDelete.Add(logId);
var output = _quickStart.Run();
Assert.Equal(expectedOutput, output.Stdout.Trim());
Eventually(() =>
{
// Retrieve the log entry just added, using the logId as a filter.
var results = Run("list-log-entries", logId);
// Confirm returned log entry contains expected value.
Assert.Contains(message, results.Stdout);
});
}
}
}
}
| 42.016667 | 99 | 0.515272 | [
"Apache-2.0"
] | joaopaulofcastro/dotnet-docs-samples | logging/api/LoggingTest/LoggingTest.cs | 12,607 | C# |
using J2N.Numerics;
using Lucene.Net.Diagnostics;
using Lucene.Net.Support;
using System;
using System.Runtime.CompilerServices;
namespace Lucene.Net.Util
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/// <summary>
/// BitSet of fixed length (<see cref="numBits"/>), backed by accessible (<see cref="GetBits()"/>)
/// <see cref="T:long[]"/>, accessed with a <see cref="long"/> index. Use it only if you intend to store more
/// than 2.1B bits, otherwise you should use <see cref="FixedBitSet"/>.
/// <para/>
/// NOTE: This was LongBitSet in Lucene
/// <para/>
/// @lucene.internal
/// </summary>
#if FEATURE_SERIALIZABLE
[Serializable]
#endif
public sealed class Int64BitSet
{
internal readonly long[] bits; // LUCENENET: Internal for testing
private readonly long numBits;
internal readonly int numWords; // LUCENENET: Internal for testing
/// <summary>
/// If the given <see cref="Int64BitSet"/> is large enough to hold
/// <paramref name="numBits"/>, returns the given <paramref name="bits"/>, otherwise returns a new
/// <see cref="Int64BitSet"/> which can hold the requested number of bits.
///
/// <para/>
/// <b>NOTE:</b> the returned bitset reuses the underlying <see cref="T:long[]"/> of
/// the given <paramref name="bits"/> if possible. Also, reading <see cref="Length"/> on the
/// returned bits may return a value greater than <paramref name="numBits"/>.
/// </summary>
public static Int64BitSet EnsureCapacity(Int64BitSet bits, long numBits)
{
if (numBits < bits.Length)
{
return bits;
}
else
{
int numWords = Bits2words(numBits);
long[] arr = bits.GetBits();
if (numWords >= arr.Length)
{
arr = ArrayUtil.Grow(arr, numWords + 1);
}
return new Int64BitSet(arr, arr.Length << 6);
}
}
/// <summary>
/// Returns the number of 64 bit words it would take to hold <paramref name="numBits"/>. </summary>
public static int Bits2words(long numBits)
{
int numLong = (int)numBits.TripleShift(6);
if ((numBits & 63) != 0)
{
numLong++;
}
return numLong;
}
public Int64BitSet(long numBits)
{
this.numBits = numBits;
bits = new long[Bits2words(numBits)];
numWords = bits.Length;
}
public Int64BitSet(long[] storedBits, long numBits)
{
this.numWords = Bits2words(numBits);
if (numWords > storedBits.Length)
{
throw new ArgumentException("The given long array is too small to hold " + numBits + " bits");
}
this.numBits = numBits;
this.bits = storedBits;
}
/// <summary>
/// Returns the number of bits stored in this bitset. </summary>
public long Length => numBits;
/// <summary>
/// Expert. </summary>
[WritableArray]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public long[] GetBits()
{
return bits;
}
/// <summary>
/// Gets the number of set bits. NOTE: this visits every
/// long in the backing bits array, and the result is not
/// internally cached!
/// </summary>
public long Cardinality
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => BitUtil.Pop_Array(bits, 0, bits.Length);
}
public bool Get(long index)
{
if (Debugging.AssertsEnabled) Debugging.Assert(index >= 0 && index < numBits, "index={0}", index);
int i = (int)(index >> 6); // div 64
// signed shift will keep a negative index and force an
// array-index-out-of-bounds-exception, removing the need for an explicit check.
int bit = (int)(index & 0x3f); // mod 64
long bitmask = 1L << bit;
return (bits[i] & bitmask) != 0;
}
public void Set(long index)
{
if (Debugging.AssertsEnabled) Debugging.Assert(index >= 0 && index < numBits, "index={0} numBits={1}", index, numBits);
int wordNum = (int)(index >> 6); // div 64
int bit = (int)(index & 0x3f); // mod 64
long bitmask = 1L << bit;
bits[wordNum] |= bitmask;
}
public bool GetAndSet(long index)
{
if (Debugging.AssertsEnabled) Debugging.Assert(index >= 0 && index < numBits);
int wordNum = (int)(index >> 6); // div 64
int bit = (int)(index & 0x3f); // mod 64
long bitmask = 1L << bit;
bool val = (bits[wordNum] & bitmask) != 0;
bits[wordNum] |= bitmask;
return val;
}
public void Clear(long index)
{
if (Debugging.AssertsEnabled) Debugging.Assert(index >= 0 && index < numBits);
int wordNum = (int)(index >> 6);
int bit = (int)(index & 0x03f);
long bitmask = 1L << bit;
bits[wordNum] &= ~bitmask;
}
public bool GetAndClear(long index)
{
if (Debugging.AssertsEnabled) Debugging.Assert(index >= 0 && index < numBits);
int wordNum = (int)(index >> 6); // div 64
int bit = (int)(index & 0x3f); // mod 64
long bitmask = 1L << bit;
bool val = (bits[wordNum] & bitmask) != 0;
bits[wordNum] &= ~bitmask;
return val;
}
/// <summary>
/// Returns the index of the first set bit starting at the <paramref name="index"/> specified.
/// -1 is returned if there are no more set bits.
/// </summary>
public long NextSetBit(long index)
{
if (Debugging.AssertsEnabled) Debugging.Assert(index >= 0 && index < numBits);
int i = (int)(index >> 6);
int subIndex = (int)(index & 0x3f); // index within the word
long word = bits[i] >> subIndex; // skip all the bits to the right of index
if (word != 0)
{
return index + word.TrailingZeroCount();
}
while (++i < numWords)
{
word = bits[i];
if (word != 0)
{
return (i << 6) + word.TrailingZeroCount();
}
}
return -1;
}
/// <summary>
/// Returns the index of the last set bit before or on the <paramref name="index"/> specified.
/// -1 is returned if there are no more set bits.
/// </summary>
public long PrevSetBit(long index)
{
if (Debugging.AssertsEnabled) Debugging.Assert(index >= 0 && index < numBits, "index={0} numBits={1}", index, numBits);
int i = (int)(index >> 6);
int subIndex = (int)(index & 0x3f); // index within the word
long word = (bits[i] << (63 - subIndex)); // skip all the bits to the left of index
if (word != 0)
{
return (i << 6) + subIndex - word.LeadingZeroCount(); // See LUCENE-3197
}
while (--i >= 0)
{
word = bits[i];
if (word != 0)
{
return (i << 6) + 63 - word.LeadingZeroCount();
}
}
return -1;
}
/// <summary>
/// this = this OR other </summary>
public void Or(Int64BitSet other)
{
if (Debugging.AssertsEnabled) Debugging.Assert(other.numWords <= numWords, "numWords={0}, other.numWords={1}", numWords, other.numWords);
int pos = Math.Min(numWords, other.numWords);
while (--pos >= 0)
{
bits[pos] |= other.bits[pos];
}
}
/// <summary>
/// this = this XOR other </summary>
public void Xor(Int64BitSet other)
{
if (Debugging.AssertsEnabled) Debugging.Assert(other.numWords <= numWords, "numWords={0}, other.numWords={1}", numWords, other.numWords);
int pos = Math.Min(numWords, other.numWords);
while (--pos >= 0)
{
bits[pos] ^= other.bits[pos];
}
}
/// <summary>
/// Returns <c>true</c> if the sets have any elements in common </summary>
public bool Intersects(Int64BitSet other)
{
int pos = Math.Min(numWords, other.numWords);
while (--pos >= 0)
{
if ((bits[pos] & other.bits[pos]) != 0)
{
return true;
}
}
return false;
}
/// <summary>
/// this = this AND other </summary>
public void And(Int64BitSet other)
{
int pos = Math.Min(numWords, other.numWords);
while (--pos >= 0)
{
bits[pos] &= other.bits[pos];
}
if (numWords > other.numWords)
{
Arrays.Fill(bits, other.numWords, numWords, 0L);
}
}
/// <summary>
/// this = this AND NOT other </summary>
public void AndNot(Int64BitSet other)
{
int pos = Math.Min(numWords, other.bits.Length);
while (--pos >= 0)
{
bits[pos] &= ~other.bits[pos];
}
}
// NOTE: no .isEmpty() here because that's trappy (ie,
// typically isEmpty is low cost, but this one wouldn't
// be)
/// <summary>
/// Flips a range of bits
/// </summary>
/// <param name="startIndex"> Lower index </param>
/// <param name="endIndex"> One-past the last bit to flip </param>
public void Flip(long startIndex, long endIndex)
{
if (Debugging.AssertsEnabled)
{
Debugging.Assert(startIndex >= 0 && startIndex < numBits);
Debugging.Assert(endIndex >= 0 && endIndex <= numBits);
}
if (endIndex <= startIndex)
{
return;
}
int startWord = (int)(startIndex >> 6);
int endWord = (int)((endIndex - 1) >> 6);
/*
///* Grrr, java shifting wraps around so -1L>>>64 == -1
/// for that reason, make sure not to use endmask if the bits to flip will
/// be zero in the last word (redefine endWord to be the last changed...)
/// long startmask = -1L << (startIndex & 0x3f); // example: 11111...111000
/// long endmask = -1L >>> (64-(endIndex & 0x3f)); // example: 00111...111111
/// **
*/
long startmask = -1L << (int)startIndex;
long endmask = (-1L).TripleShift((int)-endIndex); // 64-(endIndex&0x3f) is the same as -endIndex due to wrap
if (startWord == endWord)
{
bits[startWord] ^= (startmask & endmask);
return;
}
bits[startWord] ^= startmask;
for (int i = startWord + 1; i < endWord; i++)
{
bits[i] = ~bits[i];
}
bits[endWord] ^= endmask;
}
/// <summary>
/// Sets a range of bits
/// </summary>
/// <param name="startIndex"> Lower index </param>
/// <param name="endIndex"> One-past the last bit to set </param>
public void Set(long startIndex, long endIndex)
{
if (Debugging.AssertsEnabled)
{
Debugging.Assert(startIndex >= 0 && startIndex < numBits);
Debugging.Assert(endIndex >= 0 && endIndex <= numBits);
}
if (endIndex <= startIndex)
{
return;
}
int startWord = (int)(startIndex >> 6);
int endWord = (int)((endIndex - 1) >> 6);
long startmask = -1L << (int)startIndex;
long endmask = (-1L).TripleShift((int)-endIndex); // 64-(endIndex&0x3f) is the same as -endIndex due to wrap
if (startWord == endWord)
{
bits[startWord] |= (startmask & endmask);
return;
}
bits[startWord] |= startmask;
Arrays.Fill(bits, startWord + 1, endWord, -1L);
bits[endWord] |= endmask;
}
/// <summary>
/// Clears a range of bits.
/// </summary>
/// <param name="startIndex"> Lower index </param>
/// <param name="endIndex"> One-past the last bit to clear </param>
public void Clear(long startIndex, long endIndex)
{
if (Debugging.AssertsEnabled)
{
Debugging.Assert(startIndex >= 0 && startIndex < numBits);
Debugging.Assert(endIndex >= 0 && endIndex <= numBits);
}
if (endIndex <= startIndex)
{
return;
}
int startWord = (int)(startIndex >> 6);
int endWord = (int)((endIndex - 1) >> 6);
// Casting long to int discards MSBs, so it is no problem because we are taking mod 64.
long startmask = (-1L) << (int)startIndex; // -1 << (startIndex mod 64)
long endmask = (-1L) << (int)endIndex; // -1 << (endIndex mod 64)
if ((endIndex & 0x3f) == 0)
{
endmask = 0;
}
startmask = ~startmask;
if (startWord == endWord)
{
bits[startWord] &= (startmask | endmask);
return;
}
bits[startWord] &= startmask;
Arrays.Fill(bits, startWord + 1, endWord, 0L);
bits[endWord] &= endmask;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Int64BitSet Clone()
{
long[] bits = new long[this.bits.Length];
Array.Copy(this.bits, 0, bits, 0, bits.Length);
return new Int64BitSet(bits, numBits);
}
/// <summary>
/// Returns <c>true</c> if both sets have the same bits set </summary>
public override bool Equals(object o)
{
if (this == o)
{
return true;
}
if (!(o is Int64BitSet))
{
return false;
}
Int64BitSet other = (Int64BitSet)o;
if (numBits != other.Length)
{
return false;
}
return Arrays.Equals(bits, other.bits);
}
public override int GetHashCode()
{
long h = 0;
for (int i = numWords; --i >= 0; )
{
h ^= bits[i];
h = (h << 1) | (h.TripleShift(63)); // rotate left
}
// fold leftmost bits into right and add a constant to prevent
// empty sets from returning 0, which is too common.
return (int)((h >> 32) ^ h) + unchecked((int)0x98761234);
}
}
} | 35.092275 | 149 | 0.498196 | [
"Apache-2.0"
] | 10088/lucenenet | src/Lucene.Net/Util/LongBitSet.cs | 16,355 | C# |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
[System.Serializable]
public class AxleInfo
{
public WheelCollider leftWheel;
public WheelCollider rightWheel;
public bool motor;
public bool steering;
}
public class SimpleCarController : MonoBehaviour
{
public List<AxleInfo> axleInfos;
public float maxMotorTorque;
public float maxSteeringAngle;
// finds the corresponding visual wheel
// correctly applies the transform
public void ApplyLocalPositionToVisuals(WheelCollider collider)
{
if (collider.transform.childCount == 0)
{
return;
}
Transform visualWheel = collider.transform.GetChild(0);
Vector3 position;
Quaternion rotation;
collider.GetWorldPose(out position, out rotation);
visualWheel.transform.position = position;
visualWheel.transform.rotation = rotation;
}
public void FixedUpdate()
{
float motor = maxMotorTorque * Input.GetAxis("Vertical");
float steering = maxSteeringAngle * Input.GetAxis("Horizontal");
foreach (AxleInfo axleInfo in axleInfos)
{
if (axleInfo.steering)
{
axleInfo.leftWheel.steerAngle = steering;
axleInfo.rightWheel.steerAngle = steering;
}
if (axleInfo.motor)
{
axleInfo.leftWheel.motorTorque = motor;
axleInfo.rightWheel.motorTorque = motor;
}
ApplyLocalPositionToVisuals(axleInfo.leftWheel);
ApplyLocalPositionToVisuals(axleInfo.rightWheel);
}
}
} | 27.42623 | 72 | 0.641363 | [
"MIT"
] | seweiss-hci/VRoad | Assets/Scripts/SimpleCarController.cs | 1,675 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
namespace FalconNet.Common
{
public class PluginManager : ISystem
{
static PluginManager() { }
private static PluginManager _instance = new PluginManager();
public static PluginManager Instance { get { return _instance; } }
private PluginManager()
{
LoadList = new List<string>();
Plugins = new List<IPlugin>();
}
public List<string> LoadList { get; private set; }
public List<IPlugin> Plugins { get; private set; }
public bool RegisterPlugin(string fileName)
{
if (LoadList != null)
{
LoadList.Add(fileName);
return true;
}
return LoadPlugin(fileName);
}
public void LoadPlugins()
{
if (LoadList == null)
return;
foreach (string fileName in LoadList)
LoadPlugin(fileName);
LoadList = null;
}
private bool LoadPlugin(string fileName)
{
fileName = Path.GetFullPath(fileName);
if (!File.Exists(fileName))
return false;
Assembly ass = Assembly.LoadFile(fileName);
foreach (IPlugin plugin in from type in ass.GetExportedTypes() where type.GetInterfaces().Any(x => x == typeof(IPlugin)) select (IPlugin)Activator.CreateInstance(type))
{
if (plugin.Initialize())
Plugins.Add(plugin);
else
return false;
break;
}
return true;
}
public string Name
{
get { return "Plugin Manager"; }
}
public bool Initialize()
{
LoadPlugins();
return true;
}
public void Shutdown()
{
throw new NotImplementedException();
}
}
}
| 24.139535 | 180 | 0.519268 | [
"MIT"
] | agustinsantos/FalconNet | Common/Plugin/PluginManager.cs | 2,078 | C# |
// ------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version: 12.0.0.0
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
// ------------------------------------------------------------------------------
namespace ServiceClientGenerator.Generators.Marshallers
{
using System.Linq;
using System.Text;
using System.Collections.Generic;
using System;
/// <summary>
/// Class to produce the template output
/// </summary>
#line 1 "C:\Codebase\v3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCResponseUnmarshaller.tt"
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TextTemplating", "12.0.0.0")]
public partial class JsonRPCResponseUnmarshaller : BaseResponseUnmarshaller
{
#line hidden
/// <summary>
/// Create the template output
/// </summary>
public override string TransformText()
{
#line 6 "C:\Codebase\v3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCResponseUnmarshaller.tt"
AddLicenseHeader();
AddCommonUsingStatements();
#line default
#line hidden
this.Write("using ThirdParty.Json.LitJson;\r\n\r\nnamespace ");
#line 13 "C:\Codebase\v3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Config.Namespace));
#line default
#line hidden
this.Write(".Model.Internal.MarshallTransformations\r\n{\r\n /// <summary>\r\n /// Response U" +
"nmarshaller for ");
#line 16 "C:\Codebase\v3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.UnmarshallerBaseName));
#line default
#line hidden
this.Write(" operation\r\n /// </summary> \r\n public class ");
#line 18 "C:\Codebase\v3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.UnmarshallerBaseName));
#line default
#line hidden
this.Write(@"ResponseUnmarshaller : JsonResponseUnmarshaller
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name=""context""></param>
/// <returns></returns>
public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context)
{
");
#line 27 "C:\Codebase\v3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.UnmarshallerBaseName));
#line default
#line hidden
this.Write("Response response = new ");
#line 27 "C:\Codebase\v3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Operation.Name));
#line default
#line hidden
this.Write("Response();\r\n\r\n");
#line 29 "C:\Codebase\v3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCResponseUnmarshaller.tt"
var payload = this.Operation.ResponsePayloadMember;
var unmarshallPayload = payload != null && payload.IsStructure;
var payloadIsStream= payload != null && !unmarshallPayload;
if( this.Operation.ResponseHasBodyMembers || payload != null )
{
if (payloadIsStream)
{
if (payload.IsStreaming)
{
#line default
#line hidden
this.Write(" response.");
#line 40 "C:\Codebase\v3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(payload.PropertyName));
#line default
#line hidden
this.Write(" = context.Stream;\r\n");
#line 41 "C:\Codebase\v3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCResponseUnmarshaller.tt"
}
else
{
#line default
#line hidden
this.Write(" var ms = new MemoryStream();\r\n Amazon.Util.AWSSDKUtils.Cop" +
"yStream(context.Stream, ms);\r\n ms.Seek(0, SeekOrigin.Begin);\r\n " +
" response.");
#line 49 "C:\Codebase\v3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(payload.PropertyName));
#line default
#line hidden
this.Write(" = ms;\r\n");
#line 50 "C:\Codebase\v3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCResponseUnmarshaller.tt"
}
}
else if (unmarshallPayload)
{
#line default
#line hidden
this.Write(" var unmarshaller = ");
#line 56 "C:\Codebase\v3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(payload.DetermineTypeUnmarshallerInstantiate()));
#line default
#line hidden
this.Write(";\r\n response.");
#line 57 "C:\Codebase\v3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(payload.PropertyName));
#line default
#line hidden
this.Write(" = unmarshaller.Unmarshall(context);\r\n");
#line 58 "C:\Codebase\v3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCResponseUnmarshaller.tt"
}
else if(this.IsWrapped)
{
#line default
#line hidden
this.Write("\t\t\tresponse.");
#line 63 "C:\Codebase\v3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.WrappedResultMember));
#line default
#line hidden
this.Write(" = ");
#line 63 "C:\Codebase\v3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.Structure.Name));
#line default
#line hidden
this.Write("Unmarshaller.Instance.Unmarshall(context);\r\n");
#line 64 "C:\Codebase\v3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCResponseUnmarshaller.tt"
}
else
{
#line default
#line hidden
this.Write(" context.Read();\r\n int targetDepth = context.CurrentDepth;\r" +
"\n while (context.ReadAtDepth(targetDepth))\r\n {\r\n");
#line 73 "C:\Codebase\v3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCResponseUnmarshaller.tt"
foreach (var member in this.Operation.ResponseBodyMembers)
{
#line default
#line hidden
this.Write(" if (context.TestExpression(\"");
#line 78 "C:\Codebase\v3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.MarshallName));
#line default
#line hidden
this.Write("\", targetDepth))\r\n {\r\n var unmarshaller = ");
#line 80 "C:\Codebase\v3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.DetermineTypeUnmarshallerInstantiate()));
#line default
#line hidden
this.Write(";\r\n response.");
#line 81 "C:\Codebase\v3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(member.PropertyName));
#line default
#line hidden
this.Write(" = unmarshaller.Unmarshall(context);\r\n continue;\r\n " +
" }\r\n");
#line 84 "C:\Codebase\v3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCResponseUnmarshaller.tt"
}
#line default
#line hidden
this.Write(" }\r\n");
#line 88 "C:\Codebase\v3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCResponseUnmarshaller.tt"
}
}
UnmarshallHeaders();
ProcessStatusCode();
#line default
#line hidden
this.Write(@"
return response;
}
/// <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(JsonUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode)
{
ErrorResponse errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context);
");
#line 108 "C:\Codebase\v3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCResponseUnmarshaller.tt"
foreach (var exception in this.Operation.Exceptions)
{
#line default
#line hidden
this.Write(" if (errorResponse.Code != null && errorResponse.Code.Equals(\"");
#line 112 "C:\Codebase\v3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(exception.Code));
#line default
#line hidden
this.Write("\"))\r\n {\r\n return new ");
#line 114 "C:\Codebase\v3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(exception.Name));
#line default
#line hidden
this.Write("(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, e" +
"rrorResponse.RequestId, statusCode);\r\n }\r\n");
#line 116 "C:\Codebase\v3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCResponseUnmarshaller.tt"
}
#line default
#line hidden
this.Write(" return new ");
#line 119 "C:\Codebase\v3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCResponseUnmarshaller.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(this.BaseException));
#line default
#line hidden
this.Write("(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, e" +
"rrorResponse.RequestId, statusCode);\r\n }\r\n\r\n");
#line 122 "C:\Codebase\v3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCResponseUnmarshaller.tt"
if (payload != null && payload.IsStreaming)
{
#line default
#line hidden
this.Write(@" /// <summary>
/// Overriden to return true indicating the response contains streaming data.
/// </summary>
public override bool HasStreamingProperty
{
get
{
return true;
}
}
");
#line 137 "C:\Codebase\v3\AWSDotNetPublic\generator\ServiceClientGeneratorLib\Generators\Marshallers\JsonRPCResponseUnmarshaller.tt"
}
this.AddResponseSingletonMethod();
#line default
#line hidden
this.Write(" }\r\n}");
return this.GenerationEnvironment.ToString();
}
}
#line default
#line hidden
}
| 41.318713 | 152 | 0.592386 | [
"Apache-2.0"
] | SaschaHaertel/AmazonAWS | generator/ServiceClientGeneratorLib/Generators/Marshallers/JsonRPCResponseUnmarshaller.cs | 14,133 | C# |
/*
Copyright 2019 Georg Eckert (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 ETV;
using GraphicalPrimitive;
using Model;
namespace MetaVisualization
{
/// <summary>
/// Dummy Implementation of AMetaVisFactory, for the client (pETV).
/// </summary>
public class NullMetaVisFactory : AMetaVisFactory
{
public override AETV CreateFlexiblePCP(DataSet data, string[] attIDs, AAxis axisA, AAxis axisB)
{
return new ETV3DFlexiblePCP();
}
public override AETV CreateMetaFlexibleLinedAxes(DataSet data, string[] attIDs, AAxis axisA, AAxis axisB)
{
throw new System.NotImplementedException();
}
public override AETV CreateMetaHeatmap3D(DataSet data, string[] attIDs, bool manualLength=false, float lengthA=1f, float lengthB=1f)
{
throw new System.NotImplementedException();
}
public override AETV CreateMetaScatterplot2D(DataSet data, string[] attIDs)
{
throw new System.NotImplementedException();
}
}
}
| 39.277778 | 141 | 0.712871 | [
"MIT"
] | limbusdev/VinkedViewsMR | HoloLens/Assets/Scripts/MetaVis/NullMetaVisFactory.cs | 2,123 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace MusicTracker.Properties
{
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
{
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default
{
get
{
return defaultInstance;
}
}
}
}
| 34.419355 | 151 | 0.582006 | [
"Apache-2.0"
] | Vultour/music-tracker | MusicTracker/MusicTracker/Properties/Settings.Designer.cs | 1,069 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace LinkedList.Classes
{
public class SLinkedList
{
/// <summary>
/// Assigns Head to the first node
/// </summary>
public Node Head { get; set; }
/// <summary>
/// Is a reference to allow transversing the Linked List
/// </summary>
public Node Current { get; set; }
/// <summary>
/// Required at the creation of a Linked List. Adds a node assigned to Head.
/// </summary>
/// <param name="node">This node will become the head</param>
public SLinkedList(Node node)
{
Head = node;
Current = node;
}
/// <summary>
/// This method prints out a list of integers that are in the Linked List
/// </summary>
public void Print()
{
Current = Head;
while (Current.Next != null)
{
Console.Write($"{Current.Data} =>");
Current = Current.Next;
}
Console.Write($"{Current.Data} => Null");
}
/// <summary>
/// This method checks to see if a praticular integer is in the Linked list
/// </summary>
/// <param name="data">Takes in an integer to see if it is in the Linked List</param>
/// <returns>Returns true if it is in the linked list; returns false if it isn't</returns>
public bool Includes(int data)
{
Current = Head;
if (Current.Data == data)
{
return true;
}
while (Current.Next != null)
{
if (Current.Data == data)
{
return true;
}
Current = Current.Next;
}
if (Current.Data == data)
{
return true;
}
return false;
}
/*
/// <summary>
/// Converts Linked List into an Array
/// </summary>
/// <returns>Array with data from Linked List</returns>
public int[] LLToArray()
{
int indexLength = LLLength();
int[] lLArray = new int[indexLength];
int i = 0;
Current = Head;
while (Current.Next != null)
{
lLArray[i] = Current.Data;
Current = Current.Next;
i++;
}
lLArray[i] = Current.Data;
return lLArray;
}
*/
/// <summary>
/// Determins the length of the Linked List in order to create the array in the LLToArray method
/// </summary>
/// <returns>length of the Linked List</returns>
public int LLLength()
{
Current = Head;
int indexLength = 0;
while (Current.Next != null)
{
Current = Current.Next;
indexLength++;
}
indexLength++;
return indexLength;
}
/// <summary>
/// Given an index number, returns the value at the Node at that index number
/// </summary>
/// <param name="k">Target index number to get a value from</param>
/// <returns>Get a value at a praticular index</returns>
public int ValueAtIndex(int k)
{
int count = LLLength();
Current = Head;
if (k > count || k < 0)
{
Console.WriteLine("Sorry, The value that you specified is outside the limits");
return -1;
}
while (Current.Next != null && k > 0)
{
Current = Current.Next;
k--;
}
var current2 = Head;
while (Current.Next != null)
{
Current = Current.Next;
current2 = current2.Next;
}
return current2.Data;
}
/*
public int[] MergeTwoLL(SLinkedList list1, SLinkedList list2)
{
int length1 = list1.LLLength();
int length2 = list2.LLLength();
if (length2 > length1)
{
list2.Head = list2.Current;
list1.Head = list1.Current;
SLinkedList list = new SLinkedList(list2.Current);
list.Insert(list1.Current);
list2.Current = list2.Current.Next;
list1.Current = list1.Current.Next;
while (list2.Current.Next != null && list1.Current.Next != null)
{
list.Insert(list2.Current);
list.Insert(list1.Current);
list2.Current = list2.Current.Next;
list1.Current = list1.Current.Next;
}
list.Insert(list2.Current);
list.Insert(list1.Current);
int[] lLArray = new int[10];
lLArray = ReturnLinkedListArray(list);
return lLArray;
}
else
{
list1.Head = list1.Current;
list2.Head = list2.Current;
SLinkedList list = new SLinkedList(list1.Current);
list.Insert(list1.Current);
list1.Current = list1.Current.Next;
list2.Current = list2.Current.Next;
while (list1.Current.Next != null && list2.Current.Next != null)
{
list.Insert(list1.Current);
list.Insert(list2.Current);
list1.Current = list1.Current.Next;
list2.Current = list2.Current.Next;
}
list.Insert(list1.Current);
list.Insert(list2.Current);
list.Insert(list2.Current);
list.Insert(list1.Current);
int[] lLArray = new int[10];
lLArray = ReturnLinkedListArray(list);
return lLArray;
}
}
public int[] ReturnLinkedListArray(SLinkedList list)
{
int indexLength = LLLength();
int[] lLArray = new int[indexLength];
int i = 0;
Current = Head;
while (Current.Next != null)
{
lLArray[i] = Current.Data;
Current = Current.Next;
i++;
}
lLArray[i] = Current.Data;
return lLArray;
}
*/
/// <summary>
/// This method inserts a node into the Linked List
/// </summary>
/// <param name="node"></param>
public void Insert(int data)
{
Node node = new Node(data);
node.Next = Head;
Head = node;
}
/// <summary>
/// Appends a new node to the end of the Linked List
/// </summary>
/// <param name="newNode">the node to be added</param>
public void Append(int data)
{
Current = Head;
while (Current.Next != null)
{
Current = Current.Next;
}
Node node = new Node(data);
Current.Next = node;
}
/// <summary>
/// Inserts a new node int thte list before a given node
/// </summary>
/// <param name="newNode">The node to be added</param>
/// <param name="targetNode">The node that will follow the newly added node</param>
public void InsertBefore(Node newNode, Node targetNode)
{
Current = Head;
if (Head.Data == targetNode.Data)
{
Insert(newNode.Data);
return;
}
while (Current.Next != null)
{
if (Current.Next.Data == targetNode.Data)
{
newNode.Next = Current.Next;
Current.Next = newNode;
return;
}
Current = Current.Next;
}
}
/// <summary>
/// Inserts a new node into the list after a given node
/// </summary>
/// <param name="newNode">The node to be added</param>
/// <param name="targetNode">The node before the newly added node</param>
public void InsertAfter(Node newNode, Node targetNode)
{
Current = Head;
while (Current.Next != null)
{
if (Current.Data == targetNode.Data)
{
newNode.Next = Current.Next;
Current.Next = newNode;
return;
}
Current = Current.Next;
}
}
}
}
| 29.45098 | 104 | 0.45273 | [
"MIT"
] | Michael-S-Kelly/data-structures-and-algorithms | DataStructures/LinkedList/LinkedList/Classes/LinkedList.cs | 9,014 | 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.CostManagement.V20180801Preview.Outputs
{
/// <summary>
/// The group by expression to be used in the report.
/// </summary>
[OutputType]
public sealed class ReportGroupingResponse
{
/// <summary>
/// The name of the column to group.
/// </summary>
public readonly string Name;
/// <summary>
/// Has type of the column to group.
/// </summary>
public readonly string Type;
[OutputConstructor]
private ReportGroupingResponse(
string name,
string type)
{
Name = name;
Type = type;
}
}
}
| 25.333333 | 81 | 0.605263 | [
"Apache-2.0"
] | polivbr/pulumi-azure-native | sdk/dotnet/CostManagement/V20180801Preview/Outputs/ReportGroupingResponse.cs | 988 | C# |
using System.Xml.Serialization;
namespace Essensoft.AspNetCore.Payment.WeChatPay.V2.Notify
{
/// <summary>
/// 申请退款 - 退款结果通知 (普通商户 / 服务商)
/// </summary>
[XmlRoot("xml")]
public class WeChatPayRefundNotify : WeChatPayNotify
{
/// <summary>
/// 返回状态码
/// </summary>
[XmlElement("return_code")]
public string ReturnCode { get; set; }
/// <summary>
/// 返回信息
/// </summary>
[XmlElement("return_msg")]
public string ReturnMsg { get; set; }
/// <summary>
/// 应用号
/// </summary>
[XmlElement("appid")]
public string AppId { get; set; }
/// <summary>
/// 商户号
/// </summary>
[XmlElement("mch_id")]
public string MchId { get; set; }
/// <summary>
/// 子商户应用号
/// </summary>
[XmlElement("sub_appid")]
public string SubAppId { get; set; }
/// <summary>
/// 子商户号
/// </summary>
[XmlElement("sub_mch_id")]
public string SubMchId { get; set; }
/// <summary>
/// 随机字符串
/// </summary>
[XmlElement("nonce_str")]
public string NonceStr { get; set; }
/// <summary>
/// 加密信息
/// </summary>
[XmlElement("req_info")]
public string ReqInfo { get; set; }
// 解密后的信息
/// <summary>
/// 微信订单号
/// </summary>
[XmlElement("transaction_id")]
public string TransactionId { get; set; }
/// <summary>
/// 商户订单号
/// </summary>
[XmlElement("out_trade_no")]
public string OutTradeNo { get; set; }
/// <summary>
/// 微信退款单号
/// </summary>
[XmlElement("refund_id")]
public string RefundId { get; set; }
/// <summary>
/// 商户退款单号
/// </summary>
[XmlElement("out_refund_no")]
public string OutRefundNo { get; set; }
/// <summary>
/// 订单金额
/// </summary>
[XmlElement("total_fee")]
public int TotalFee { get; set; }
/// <summary>
/// 应结订单金额
/// </summary>
[XmlElement("settlement_total_fee")]
public int SettlementTotalFee { get; set; }
/// <summary>
/// 申请退款金额
/// </summary>
[XmlElement("refund_fee")]
public int RefundFee { get; set; }
/// <summary>
/// 退款金额
/// </summary>
[XmlElement("settlement_refund_fee")]
public int SettlementRefundFee { get; set; }
/// <summary>
/// 退款状态
/// </summary>
[XmlElement("refund_status")]
public string RefundStatus { get; set; }
/// <summary>
/// 退款成功时间
/// </summary>
[XmlElement("success_time")]
public string SuccessTime { get; set; }
/// <summary>
/// 退款入账账户
/// </summary>
[XmlElement("refund_recv_accout")]
public string RefundRecvAccout { get; set; }
/// <summary>
/// 退款资金来源
/// </summary>
[XmlElement("refund_account")]
public string RefundAccount { get; set; }
/// <summary>
/// 退款发起来源
/// </summary>
[XmlElement("refund_request_source")]
public string RefundRequestSource { get; set; }
}
}
| 24.221429 | 58 | 0.480094 | [
"MIT"
] | LuohuaRain/payment | src/Essensoft.AspNetCore.Payment.WeChatPay/V2/Notify/WeChatPayRefundNotify.cs | 3,647 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Управление общими сведениями о сборке осуществляется посредством следующего
// набора атрибутов. Измените значения этих атрибутов, чтобы изменить сведения,
// связанные со сборкой.
[assembly: AssemblyTitle("Tests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Tests")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Задание значения false для атрибута ComVisible приведет к тому, что типы из этой сборки станут невидимыми
// для COM-компонентов. Если к одному из типов этой сборки необходимо обращаться из
// модели COM, задайте для атрибута ComVisible этого типа значение true.
[assembly: ComVisible(false)]
// Если данный проект доступен для модели COM, следующий GUID используется в качестве идентификатора библиотеки типов
[assembly: Guid("99aada93-08ef-431b-ad1e-50984384a82d")]
// Сведения о версии сборки состоят из следующих четырех значений:
//
// Основной номер версии
// Дополнительный номер версии
// Номер сборки
// Редакция
//
// Можно задать все значения или принять номера сборки и редакции по умолчанию
// используя "*", как показано ниже:
// [сборка: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 39.810811 | 117 | 0.763069 | [
"MIT"
] | ROM-II/rom_db_editor | Tests/Properties/AssemblyInfo.cs | 2,109 | C# |
/* Copyright (c) Citrix Systems Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms,
* with or without modification, are permitted provided
* that the following conditions are met:
*
* * Redistributions of source code must retain the above
* copyright notice, this list of conditions and the
* following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Text;
using XenAdmin.Commands;
using XenAdmin;
using XenAPI;
using NUnit.Framework;
using XenAdmin.Core;
using XenAdmin.Controls;
namespace XenAdminTests.CommandTests
{
[TestFixture, Category(TestCategories.UICategoryA)]
public class AddHostToPoolCommandTestGeorge : MainWindowLauncher_TestFixture
{
public AddHostToPoolCommandTestGeorge()
: base(true, CommandTestsDatabase.George, CommandTestsDatabase.SingleHost)
{ }
[Test]
[Timeout(100 * 1000)]
public void Run()
{
AddHostToPoolCommandTest tester = new AddHostToPoolCommandTest();
tester.TestAddGeorgeHostToGeorgePool();
}
}
[TestFixture, Category(TestCategories.UICategoryA)]
public class AddHostToPoolCommandTestMidnightRide : MainWindowLauncher_TestFixture
{
public AddHostToPoolCommandTestMidnightRide()
: base(true, CommandTestsDatabase.MidnightRide, CommandTestsDatabase.SingleHost)
{ }
[Test]
public void Run()
{
AddHostToPoolCommandTest tester = new AddHostToPoolCommandTest();
tester.TestAddGeorgeHostToMidnightRidePool();
}
}
public class AddHostToPoolCommandTest : CommandTest
{
internal override Command CreateCommand()
{
return new AddHostToPoolCommand(Program.MainWindow.CommandInterface, new List<Host> { GetAnyHost(h => h.name_label == "krakout") }, GetAnyPool(), false);
}
private bool Finished()
{
VirtualTreeView.VirtualTreeNodeCollection poolNodes = MainWindowWrapper.TreeView.Nodes[0].Nodes[0].Nodes;
return poolNodes.Count > 2 && poolNodes[0].Text == "inflames" && poolNodes[1].Text == "incubus" && poolNodes[2].Text == "krakout";
}
public void TestAddGeorgeHostToGeorgePool()
{
foreach (Pool pool in RunTest(GetAnyPool))
{
MW(Command.Execute);
MWWaitFor(Finished, "AddHostToPoolCommandTest.TestRbacGeorge() didn't finish.");
}
}
public void TestAddGeorgeHostToMidnightRidePool()
{
foreach (Pool pool in RunTest(GetAnyPool))
{
HandleModalDialog<CommandErrorDialogWrapper>("Error Adding Server to Pool", Command.Execute, d => d.CloseButton.PerformClick());
}
}
}
}
| 37.886792 | 166 | 0.662849 | [
"BSD-2-Clause"
] | ChrisH4rding/xenadmin | XenAdminTests/CommandTests/AddHostToPoolCommandTest.cs | 4,018 | C# |
using UnityEngine;
using UnityEngine.VR;
public class MainScene : MonoBehaviour
{
void Start()
{
if (Utils.CurrentPlayerType == Utils.PlayerType.Unknown)
{
Debug.LogError("Unknown headset type: " + VRSettings.loadedDeviceName);
}
}
}
| 21.214286 | 84 | 0.602694 | [
"MIT"
] | dag10/HoloViveObserver | HoloViveObserver/Assets/Scripts/MainScene.cs | 299 | C# |
/*
********************************************************************
*
* 曹旭升(sheng.c)
* E-mail: cao.silhouette@msn.com
* QQ: 279060597
* https://github.com/iccb1013
* http://shengxunwei.com
*
* © Copyright 2016
*
********************************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Sheng.WeixinConstruction.Client.Shell.Models
{
public class CreatePictureVoteItemArgs
{
/// <summary>
/// 需要下载的图片的服务器端ID,由uploadImage接口获得
/// </summary>
public string ImageServerId
{
get;
set;
}
public string Title
{
get;
set;
}
public string Description
{
get;
set;
}
public Guid CampaignId
{
get;
set;
}
}
} | 18.490196 | 69 | 0.42842 | [
"MIT"
] | 1002753959/Sheng.WeixinConstruction | SourceCode/Sheng.WeixinConstruction.Client.Shell/Models/Campaign/CreatePictureVoteItemArgs.cs | 992 | C# |
using System;
namespace TurboYang.Dynamic.Expression.Expressions
{
public sealed class OrExpression : BinaryExpression
{
public override String Pattern => @"^\|\|$";
public sealed override Int32 Priority => 3;
protected sealed override String Symbol => "||";
public override Object Evaluate(ExpressionContext context)
{
OperandValue1 = Operand1.Evaluate(context);
OperandValue2 = Operand2.Evaluate(context);
return OperandValue1 || OperandValue2;
}
}
}
| 27.65 | 66 | 0.640145 | [
"MIT"
] | turboyang-cn/TurboYang.Dynamic.Expression | TurboYang.Dynamic.Expression/Expressions/OrExpression.cs | 555 | C# |
// *** WARNING: this file was generated by pulumigen. ***
// *** 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.Kubernetes.Types.Outputs.Core.V1
{
[OutputType]
public sealed class Handler
{
/// <summary>
/// One and only one of the following should be specified. Exec specifies the action to take.
/// </summary>
public readonly Pulumi.Kubernetes.Types.Outputs.Core.V1.ExecAction Exec;
/// <summary>
/// HTTPGet specifies the http request to perform.
/// </summary>
public readonly Pulumi.Kubernetes.Types.Outputs.Core.V1.HTTPGetAction HttpGet;
/// <summary>
/// TCPSocket specifies an action involving a TCP port. TCP hooks not yet supported
/// </summary>
public readonly Pulumi.Kubernetes.Types.Outputs.Core.V1.TCPSocketAction TcpSocket;
[OutputConstructor]
private Handler(
Pulumi.Kubernetes.Types.Outputs.Core.V1.ExecAction exec,
Pulumi.Kubernetes.Types.Outputs.Core.V1.HTTPGetAction httpGet,
Pulumi.Kubernetes.Types.Outputs.Core.V1.TCPSocketAction tcpSocket)
{
Exec = exec;
HttpGet = httpGet;
TcpSocket = tcpSocket;
}
}
}
| 33.418605 | 101 | 0.655532 | [
"Apache-2.0"
] | Teshel/pulumi-kubernetes | sdk/dotnet/Core/V1/Outputs/Handler.cs | 1,437 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenNLP.Tools.Util;
namespace OpenNLP.Tools.Ling
{
/// <summary>
/// This class is mainly for use with RTE in terms of the methods it provides,
/// but on a more general level, it provides a {@link CoreLabel} that uses its
/// DocIDAnnotation, SentenceIndexAnnotation, and IndexAnnotation to implement
/// Comparable/compareTo, hashCode, and equals. This means no other annotations,
/// including the identity of the word, are taken into account when using these
/// methods.
///
/// The actual implementation is to wrap a <code>CoreLabel</code>.
/// This avoids breaking the <code>equals()</code> and
/// <code>hashCode()</code> contract and also avoids expensive copying
/// when used to represent the same data as the original <code>CoreLabel</code>.
///
/// @author rafferty
///
/// Code retrieved on the Stanford parser and ported to C# (see http://nlp.stanford.edu/software/lex-parser.shtml)
/// </summary>
public class IndexedWord : IAbstractCoreLabel, IComparable<IndexedWord>
{
/// <summary>
/// The identifier that points to no word.
/// </summary>
public static readonly IndexedWord NoWord = new IndexedWord(null, -1, -1);
private readonly CoreLabel label;
/// <summary>
/// Default constructor; uses {@link CoreLabel} default constructor
/// </summary>
public IndexedWord()
{
label = new CoreLabel();
}
/// <summary>
/// Copy Constructor - relies on {@link CoreLabel} copy constructor.
/// It will set the value, and if the word is not set otherwise, set
/// the word to the value.
/// </summary>
/// <param name="w">A Label to initialize this IndexedWord from</param>
public IndexedWord(ILabel w)
{
if (w is CoreLabel)
{
label = (CoreLabel) w;
}
else
{
label = new CoreLabel(w);
if (label.GetWord() == null)
{
label.SetWord(label.Value());
}
}
}
/// <summary>
/// Construct an IndexedWord from a CoreLabel just as for a CoreMap.
/// <i>Implementation note:</i> this is a the same as the constructor
/// that takes a CoreMap, but is needed to ensure unique most specific
/// type inference for selecting a constructor at compile-time.
/// </summary>
/// <param name="w">A Label to initialize this IndexedWord from</param>
public IndexedWord(CoreLabel w)
{
label = w;
}
/// <summary>
/// Constructor for setting docID, sentenceIndex, and
/// index without any other annotations.
/// </summary>
/// <param name="docId">The document ID (arbitrary string)</param>
/// <param name="sentenceIndex">The sentence number in the document (normally 0-based)</param>
/// <param name="index">The index of the word in the sentence (normally 0-based)</param>
public IndexedWord(string docId, int sentenceIndex, int index)
{
label = new CoreLabel();
label.Set(typeof (CoreAnnotations.DocIdAnnotation), docId);
label.Set(typeof (CoreAnnotations.SentenceIndexAnnotation), sentenceIndex);
label.Set(typeof (CoreAnnotations.IndexAnnotation), index);
}
public IndexedWord MakeCopy(int count)
{
var labelCopy = new CoreLabel(label);
var copy = new IndexedWord(labelCopy);
copy.SetCopyCount(count);
return copy;
}
/**
* TODO: would be nice to get rid of this. Only used in two places in RTE.
*/
//public CoreLabel backingLabel() { return label; }
public /*<VALUE> VALUE*/ object Get( /*Class<? extends TypesafeMap.Key<VALUE>>*/ Type key)
{
return label.Get(key);
}
public /*<VALUE>*/ bool Has( /*Class<? extends TypesafeMap.Key<VALUE>>*/ Type key)
{
return label.Has(key);
}
public /*<VALUE>*/ bool ContainsKey( /*Class<? extends TypesafeMap.Key<VALUE>>*/ Type key)
{
return label.ContainsKey(key);
}
public /*<VALUE> VALUE*/ object Set( /*Class<? extends TypesafeMap.Key<VALUE>>*/ Type key, /*VALUE*/object value)
{
return label.Set(key, value);
}
public /*<KEY extends TypesafeMap.Key<string>>*/ string GetString( /*Class<KEY>*/ Type key)
{
return label.GetString(key);
}
public /*<VALUE> VALUE*/ object Remove( /*Class<? extends Key<VALUE>>*/ Type key)
{
return label.Remove(key);
}
public Set< /*Class<?>*/ Type> KeySet()
{
return label.KeySet();
}
public int Size()
{
return label.Size();
}
public string Value()
{
return label.Value();
}
public void SetValue(string value)
{
label.SetValue(value);
}
public string Tag()
{
return label.Tag();
}
public void SetTag(string tag)
{
label.SetTag(tag);
}
public string GetWord()
{
return label.GetWord();
}
public void SetWord(string word)
{
label.SetWord(word);
}
public string Lemma()
{
return label.Lemma();
}
public void SetLemma(string lemma)
{
label.SetLemma(lemma);
}
public string Ner()
{
return label.Ner();
}
public void SetNer(string ner)
{
label.SetNer(ner);
}
public string DocId()
{
return label.DocId();
}
public void SetDocId(string docId)
{
label.SetDocId(docId);
}
public int Index()
{
return label.Index();
}
public void SetIndex(int index)
{
label.SetIndex(index);
}
public int SentIndex()
{
return label.SentIndex();
}
public void SetSentIndex(int sentIndex)
{
label.SetSentIndex(sentIndex);
}
public string OriginalText()
{
return label.OriginalText();
}
public void SetOriginalText(string originalText)
{
label.SetOriginalText(originalText);
}
public int BeginPosition()
{
return label.BeginPosition();
}
public int EndPosition()
{
return label.EndPosition();
}
public void SetBeginPosition(int beginPos)
{
label.SetBeginPosition(beginPos);
}
public void SetEndPosition(int endPos)
{
label.SetEndPosition(endPos);
}
public int CopyCount()
{
return label.CopyCount();
}
public void SetCopyCount(int count)
{
label.SetCopyCount(count);
}
public string ToPrimes()
{
var copy = label.CopyCount();
return StringUtils.Repeat('\'', copy);
}
/// <summary>
/// This .equals is dependent only on docID, sentenceIndex, and index.
/// It doesn't consider the actual word value, but assumes that it is
/// validly represented by token position.
/// All IndexedWords that lack these fields will be regarded as equal.
/// </summary>
public override bool Equals(Object o)
{
if (this == o) return true;
if (!(o is IndexedWord)) return false;
//now compare on appropriate keys
var otherWord = (IndexedWord) o;
var myInd = Get(typeof (CoreAnnotations.IndexAnnotation));
var otherInd = otherWord.Get(typeof (CoreAnnotations.IndexAnnotation));
if (myInd == null)
{
if (otherInd != null)
return false;
}
else if (! ((int) myInd).Equals((int) otherInd))
{
return false;
}
var mySentInd = Get(typeof (CoreAnnotations.SentenceIndexAnnotation));
var otherSentInd = otherWord.Get(typeof (CoreAnnotations.SentenceIndexAnnotation));
if (mySentInd == null)
{
if (otherSentInd != null)
return false;
}
else if (! ((int) mySentInd).Equals((int) otherSentInd))
{
return false;
}
var myDocId = GetString(typeof (CoreAnnotations.DocIdAnnotation));
var otherDocId = otherWord.GetString(typeof (CoreAnnotations.DocIdAnnotation));
if (myDocId == null)
{
if (otherDocId != null)
return false;
}
else if (! myDocId.Equals(otherDocId))
{
return false;
}
if (CopyCount() != otherWord.CopyCount())
{
return false;
}
return true;
}
/// <summary>
/// This hashCode uses only the docID, sentenceIndex, and index. See compareTo for more info.
/// </summary>
public override int GetHashCode()
{
var sensible = false;
var result = 0;
if (Get(typeof (CoreAnnotations.DocIdAnnotation)) != null)
{
result = Get(typeof (CoreAnnotations.DocIdAnnotation)).GetHashCode();
sensible = true;
}
if (Has(typeof (CoreAnnotations.SentenceIndexAnnotation)))
{
result = 29*result + Get(typeof (CoreAnnotations.SentenceIndexAnnotation)).GetHashCode();
sensible = true;
}
if (Has(typeof (CoreAnnotations.IndexAnnotation)))
{
result = 29*result + Get(typeof (CoreAnnotations.IndexAnnotation)).GetHashCode();
sensible = true;
}
return result;
}
/// <summary>
/// NOTE: This compareTo is based on and made to be compatible with the one
/// from IndexedFeatureLabel. You <em>must</em> have a DocIDAnnotation,
/// SentenceIndexAnnotation, and IndexAnnotation for this to make sense and
/// be guaranteed to work properly. Currently, it won't error out and will
/// try to return something sensible if these are not defined, but that really
/// isn't proper usage!
///
/// This compareTo method is based not by value elements like the word(),
/// but on passage position. It puts NO_WORD elements first, and then orders
/// by document, sentence, and word index. If these do not differ, it returns equal.
/// </summary>
public int CompareTo(IndexedWord w)
{
if (Equals(NoWord))
{
if (w.Equals(NoWord))
{
return 0;
}
else
{
return -1;
}
}
if (w.Equals(NoWord))
{
return 1;
}
var docId = GetString(typeof (CoreAnnotations.DocIdAnnotation));
var docComp = docId.CompareTo(w.GetString(typeof (CoreAnnotations.DocIdAnnotation)));
if (docComp != 0) return docComp;
var sentComp = SentIndex() - w.SentIndex();
if (sentComp != 0) return sentComp;
var indexComp = Index() - w.Index();
if (indexComp != 0) return indexComp;
return CopyCount() - w.CopyCount();
}
/// <summary>Returns the value-tag of this label.</summary>
public override string ToString()
{
return label.ToString(CoreLabel.OutputFormat.VALUE_TAG);
//return label.ToString();
}
public string ToString(CoreLabel.OutputFormat format)
{
return label.ToString(format);
}
public void SetFromString(string labelStr)
{
throw new InvalidOperationException("Cannot set from string");
}
public class LabFact : ILabelFactory
{
public ILabel NewLabel(string labelStr)
{
var label = new CoreLabel();
label.SetValue(labelStr);
return new IndexedWord(label);
}
public ILabel NewLabel(string labelStr, int options)
{
return NewLabel(labelStr);
}
public ILabel NewLabelFromString(string encodedLabelStr)
{
throw new InvalidOperationException("This code branch left blank" +
" because we do not understand what this method should do.");
}
public ILabel NewLabel(ILabel oldLabel)
{
return new IndexedWord(oldLabel);
}
}
/*public static LabelFactory factory() {
return new LabelFactory() {
public Label newLabel(string labelStr) {
CoreLabel label = new CoreLabel();
label.setValue(labelStr);
return new IndexedWord(label);
}
public Label newLabel(string labelStr, int options) {
return newLabel(labelStr);
}
public Label newLabel(Label oldLabel) {
return new IndexedWord(oldLabel);
}
public Label newLabelFromString(string encodedLabelStr) {
throw new UnsupportedOperationException("This code branch left blank" +
" because we do not understand what this method should do.");
}
};
}*/
public static ILabelFactory Factory()
{
return new LabFact();
}
public ILabelFactory LabelFactory()
{
return Factory();
}
}
} | 30.677966 | 121 | 0.531699 | [
"MIT"
] | mattcolefla/OpenNLP-Plus | IndexedWord.cs | 14,482 | C# |
namespace Microsoft.AspNetCore.Mvc.Versioning
{
using Microsoft.AspNet.OData;
using Microsoft.AspNet.OData.Extensions;
using Microsoft.AspNet.OData.Routing;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Abstractions;
using Microsoft.AspNetCore.Mvc.ActionConstraints;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.ModelBinding.Binders;
using Microsoft.AspNetCore.Mvc.Routing;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.OData.Edm;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using static System.Linq.Expressions.Expression;
/// <summary>
/// Represents the logic for selecting an API-versioned, action method with additional support for OData actions.
/// </summary>
[CLSCompliant( false )]
public class ODataApiVersionActionSelector : ApiVersionActionSelector
{
static readonly Func<object, IReadOnlyList<IEdmOptionalParameter>> getOptionalParameters = NewGetOptionalParametersFunc();
readonly IModelBinderFactory modelBinderFactory;
readonly IModelMetadataProvider modelMetadataProvider;
readonly IOptions<MvcOptions> mvcOptions;
/// <summary>
/// Initializes a new instance of the <see cref="ODataApiVersionActionSelector"/> class.
/// </summary>
/// <param name="actionDescriptorCollectionProvider">The <see cref="IActionDescriptorCollectionProvider "/> used to select candidate routes.</param>
/// <param name="actionConstraintProviders">The <see cref="IEnumerable{T}">sequence</see> of <see cref="IActionConstraintProvider">action constraint providers</see>.</param>
/// <param name="options">The <see cref="ApiVersioningOptions">options</see> associated with the action selector.</param>
/// <param name="loggerFactory">The <see cref="ILoggerFactory"/>.</param>
/// <param name="routePolicy">The <see cref="IApiVersionRoutePolicy">route policy</see> applied to candidate matches.</param>
/// <param name="modelBinderFactory">The <see cref="IModelBinderFactory"/> used to create model binders.</param>
/// <param name="modelMetadataProvider">The <see cref="IModelMetadataProvider"/> used to resolve model metadata.</param>
/// <param name="mvcOptions">The <see cref="MvcOptions">MVC options</see> associated with the action selector.</param>
public ODataApiVersionActionSelector(
IActionDescriptorCollectionProvider actionDescriptorCollectionProvider,
IEnumerable<IActionConstraintProvider> actionConstraintProviders,
IOptions<ApiVersioningOptions> options,
ILoggerFactory loggerFactory,
IApiVersionRoutePolicy routePolicy,
IModelBinderFactory modelBinderFactory,
IModelMetadataProvider modelMetadataProvider,
IOptions<MvcOptions> mvcOptions )
: base( actionDescriptorCollectionProvider, actionConstraintProviders, options, loggerFactory, routePolicy )
{
this.modelBinderFactory = modelBinderFactory;
this.modelMetadataProvider = modelMetadataProvider;
this.mvcOptions = mvcOptions;
}
/// <summary>
/// Gets a value indicating whether endpoint routing is enabled.
/// </summary>
/// <value>True if endpoint routing is enabled; otherwise, false.</value>
protected bool UsingEndpointRouting => mvcOptions.Value.EnableEndpointRouting;
/// <inheritdoc />
public override IReadOnlyList<ActionDescriptor> SelectCandidates( RouteContext context )
{
if ( context == null )
{
throw new ArgumentNullException( nameof( context ) );
}
var httpContext = context.HttpContext;
var feature = httpContext.ODataFeature();
var odataPath = feature.Path;
var routeValues = context.RouteData.Values;
var notODataCandidate = odataPath == null || routeValues.ContainsKey( ODataRouteConstants.Action );
if ( notODataCandidate )
{
return base.SelectCandidates( context );
}
var routingConventions = httpContext.Request.GetRoutingConventions();
if ( routingConventions == null )
{
return base.SelectCandidates( context );
}
var bestCandidates = new List<ActionDescriptor>();
var actionNames = new HashSet<string>( StringComparer.OrdinalIgnoreCase );
var container = httpContext.RequestServices.GetRequiredService<IPerRouteContainer>();
var routePrefix = container.GetRoutePrefix( feature.RouteName );
var comparer = StringComparer.OrdinalIgnoreCase;
foreach ( var convention in routingConventions )
{
var candidates = convention.SelectAction( context );
if ( candidates is null )
{
continue;
}
foreach ( var candidate in candidates )
{
if ( candidate.AttributeRouteInfo is not ODataAttributeRouteInfo info ||
!comparer.Equals( routePrefix, info.RoutePrefix ) )
{
continue;
}
actionNames.Add( candidate.ActionName );
bestCandidates.Add( candidate );
}
}
if ( bestCandidates.Count == 0 )
{
return base.SelectCandidates( context );
}
if ( !routeValues.ContainsKey( ODataRouteConstants.Action ) && actionNames.Count == 1 )
{
routeValues[ODataRouteConstants.Action] = actionNames.Single();
}
return bestCandidates;
}
/// <inheritdoc />
public override ActionDescriptor? SelectBestCandidate( RouteContext context, IReadOnlyList<ActionDescriptor> candidates )
{
if ( context == null )
{
throw new ArgumentNullException( nameof( context ) );
}
if ( candidates == null )
{
throw new ArgumentNullException( nameof( candidates ) );
}
var httpContext = context.HttpContext;
var odata = httpContext.ODataFeature();
var odataRouteCandidate = odata.Path != null;
if ( !odataRouteCandidate )
{
return base.SelectBestCandidate( context, candidates );
}
if ( IsRequestedApiVersionAmbiguous( context, out var apiVersion ) )
{
return null;
}
var matches = EvaluateActionConstraints( context, candidates );
var selectionContext = new ActionSelectionContext( httpContext, matches, apiVersion );
var bestActions = SelectBestActions( selectionContext );
var finalMatches = Array.Empty<ActionDescriptor>();
if ( bestActions.Count > 0 )
{
// REF: https://github.com/OData/WebApi/blob/master/src/Microsoft.AspNetCore.OData/Routing/ODataActionSelector.cs
var routeValues = context.RouteData.Values;
var conventionsStore = odata.RoutingConventionsStore ?? new Dictionary<string, object>( capacity: 0 );
var availableKeys = new HashSet<string>( routeValues.Keys.Where( IsAvailableKey ), StringComparer.OrdinalIgnoreCase );
var availableKeysCount = conventionsStore.TryGetValue( ODataRouteConstants.KeyCount, out var v ) ? (int) v : 0;
var possibleCandidates = bestActions.Select( candidate => new ActionIdAndParameters( candidate, ParameterHasRegisteredModelBinder ) );
var optionalParameters = routeValues.TryGetValue( ODataRouteConstants.OptionalParameters, out var wrapper ) ?
GetOptionalParameters( wrapper ) :
Array.Empty<IEdmOptionalParameter>();
var matchedCandidates = possibleCandidates
.Where( c => TryMatch( httpContext, c, availableKeys, conventionsStore, optionalParameters, availableKeysCount ) )
.OrderByDescending( c => c.FilteredParameters.Count )
.ThenByDescending( c => c.TotalParameterCount )
.ToArray();
if ( matchedCandidates.Length == 1 )
{
finalMatches = new[] { matchedCandidates[0].Action };
}
else if ( matchedCandidates.Length > 1 )
{
var results = matchedCandidates.Where( c => ActionAcceptsMethod( c.Action, httpContext.Request.Method ) ).ToArray();
finalMatches = results.Length switch
{
0 => matchedCandidates.Where( c => c.FilteredParameters.Count == availableKeysCount ).Select( c => c.Action ).ToArray(),
1 => new[] { results[0].Action },
_ => results.Where( c => c.FilteredParameters.Count == availableKeysCount ).Select( c => c.Action ).ToArray(),
};
}
}
var feature = httpContext.ApiVersioningFeature();
var selectionResult = feature.SelectionResult;
feature.RequestedApiVersion = selectionContext.RequestedVersion;
selectionResult.AddCandidates( candidates );
if ( finalMatches.Length > 0 )
{
selectionResult.AddMatches( finalMatches );
}
else
{
// OData endpoint routing calls back through IActionSelector. if endpoint routing is enabled
// then the answer is final; proceed to route policy. if classic routing, it's possible the
// IActionSelector will be entered again
if ( !UsingEndpointRouting )
{
return null;
}
}
return RoutePolicy.Evaluate( context, selectionResult );
}
static bool IsRouteParameter( string key )
{
if ( string.IsNullOrEmpty( key ) )
{
return false;
}
return key[0] == '{' && key.Length > 1 && key[^1] == '}';
}
static bool IsAvailableKey( string key ) => !IsRouteParameter( key ) && key != ODataRouteConstants.Action && key != ODataRouteConstants.ODataPath;
static bool RequestHasBody( HttpContext context )
{
var method = context.Request.Method.ToUpperInvariant();
return method switch
{
"POST" or "PUT" or "PATCH" or "MERGE" => true,
_ => false,
};
}
static bool ActionAcceptsMethod( ActionDescriptor action, string method ) =>
action.GetHttpMethods().Contains( method, StringComparer.OrdinalIgnoreCase );
static Func<object, IReadOnlyList<IEdmOptionalParameter>> NewGetOptionalParametersFunc()
{
var type = Type.GetType( "Microsoft.AspNet.OData.Routing.ODataOptionalParameter, Microsoft.AspNetCore.OData", throwOnError: true, ignoreCase: false );
var p = Parameter( typeof( object ) );
var body = Property( Convert( p, type ), "OptionalParameters" );
var lambda = Lambda<Func<object, IReadOnlyList<IEdmOptionalParameter>>>( body, p );
return lambda.Compile();
}
static IReadOnlyList<IEdmOptionalParameter> GetOptionalParameters( object value )
{
if ( value is null )
{
return Array.Empty<IEdmOptionalParameter>();
}
return getOptionalParameters( value );
}
bool TryMatch(
HttpContext context,
ActionIdAndParameters action,
ISet<string> availableKeys,
IDictionary<string, object> conventionsStore,
IReadOnlyList<IEdmOptionalParameter> optionalParameters,
int availableKeysCount )
{
var parameters = action.FilteredParameters;
var totalParameterCount = action.TotalParameterCount;
if ( availableKeys.Contains( ODataRouteConstants.NavigationProperty ) )
{
availableKeysCount -= 1;
}
if ( totalParameterCount < availableKeysCount )
{
return false;
}
var matchedBody = false;
var keys = conventionsStore.Keys.ToArray();
for ( var i = 0; i < parameters.Count; i++ )
{
var parameter = parameters[i];
var parameterName = parameter.Name;
if ( availableKeys.Contains( parameterName ) )
{
continue;
}
var matchesKey = false;
for ( var j = 0; j < keys.Length; j++ )
{
if ( keys[j].Contains( parameterName, StringComparison.Ordinal ) )
{
matchesKey = true;
break;
}
}
if ( matchesKey )
{
continue;
}
if ( context.Request.Query.ContainsKey( parameterName ) )
{
continue;
}
if ( parameter is ControllerParameterDescriptor param && optionalParameters.Count > 0 )
{
if ( param.ParameterInfo.IsOptional && optionalParameters.Any( p => string.Equals( p.Name, parameterName, StringComparison.OrdinalIgnoreCase ) ) )
{
continue;
}
}
if ( ParameterHasRegisteredModelBinder( parameter ) )
{
continue;
}
if ( !matchedBody && RequestHasBody( context ) )
{
matchedBody = true;
continue;
}
return false;
}
return true;
}
bool ParameterHasRegisteredModelBinder( ParameterDescriptor parameter )
{
var modelMetadata = modelMetadataProvider.GetMetadataForType( parameter.ParameterType );
var binderContext = new ModelBinderFactoryContext()
{
Metadata = modelMetadata,
BindingInfo = parameter.BindingInfo,
CacheToken = modelMetadata,
};
IModelBinder? binder;
try
{
binder = modelBinderFactory.CreateBinder( binderContext );
}
#pragma warning disable CA1031 // Do not catch general exception types
catch
#pragma warning restore CA1031
{
binder = default;
}
return !( binder is SimpleTypeModelBinder ) &&
!( binder is BodyModelBinder ) &&
!( binder is ComplexTypeModelBinder ) &&
!( binder is BinderTypeModelBinder ) &&
!( binder is ICollectionModelBinder );
}
[DebuggerDisplay( "{Action.DisplayName,nq}" )]
sealed class ActionIdAndParameters
{
internal ActionIdAndParameters( ActionDescriptor action, Func<ParameterDescriptor, bool> modelBound )
{
Action = action;
var filteredParameters = new List<ParameterDescriptor>();
foreach ( var parameter in action.Parameters )
{
TotalParameterCount += 1;
if ( !parameter.ParameterType.IsModelBound() && !modelBound( parameter ) )
{
filteredParameters.Add( parameter );
}
}
FilteredParameters = filteredParameters.ToArray();
}
public int TotalParameterCount { get; }
public IReadOnlyList<ParameterDescriptor> FilteredParameters { get; }
public ActionDescriptor Action { get; }
}
}
} | 40.941463 | 181 | 0.57536 | [
"MIT"
] | Microsoft/aspnet-api-versioning | src/Microsoft.AspNetCore.OData.Versioning/AspNetCore.Mvc/Versioning/ODataApiVersionActionSelector.cs | 16,788 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Reflection;
[assembly: Microsoft.AspNetCore.Mvc.ApplicationParts.RelatedAssemblyAttribute("DPaul Final.Views")]
// Generated by the MSBuild WriteCodeFragment class.
| 32.888889 | 99 | 0.533784 | [
"MIT"
] | usf-comp494-spring2021/davidp | DPaul Final/DPaul Final/obj/Debug/net5.0/DPaul Final.RazorAssemblyInfo.cs | 592 | C# |
////////////////////////////////////////////////////////////////////////////////
//NUnit tests for "EF Core Provider for LCPI OLE DB"
// IBProvider and Contributors. 07.12.2021.
using System;
using System.Data;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using NUnit.Framework;
using xdb=lcpi.data.oledb;
namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D3.Query.Funcs.Int64.SET001.STD.Equals.Complete.Single{
////////////////////////////////////////////////////////////////////////////////
using T_DATA1 =System.Int64;
using T_DATA2 =System.Single;
////////////////////////////////////////////////////////////////////////////////
//class TestSet_504__param__01__VV
public static class TestSet_504__param__01__VV
{
private const string c_NameOf__TABLE ="DUAL";
private sealed class MyContext:TestBaseDbContext
{
[Table(c_NameOf__TABLE)]
public sealed class TEST_RECORD
{
[Key]
[Column("ID")]
public System.Int32? TEST_ID { get; set; }
};//class TEST_RECORD
//----------------------------------------------------------------------
public DbSet<TEST_RECORD> testTable { get; set; }
//----------------------------------------------------------------------
public MyContext(xdb.OleDbTransaction tr)
:base(tr)
{
}//MyContext
};//class MyContext
//-----------------------------------------------------------------------
[Test]
public static void Test_001__less()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
T_DATA1 vv1=3;
T_DATA2 vv2=4;
var recs=db.testTable.Where(r => (vv1) /*OP{*/ .Equals /*}OP*/ (vv2));
foreach(var r in recs)
{
TestServices.ThrowSelectedRow();
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("d","ID").EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL()
.T("WHERE ").P_BOOL("__Exec_V_V_0"));
}//using db
tr.Commit();
}//using tr
}//using cn
}//Test_001__less
//-----------------------------------------------------------------------
[Test]
public static void Test_002__equal()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
T_DATA1 vv1=4;
T_DATA2 vv2=4;
var recs=db.testTable.Where(r => (vv1) /*OP{*/ .Equals /*}OP*/ (vv2));
int nRecs=0;
foreach(var r in recs)
{
Assert.AreEqual
(0,
nRecs);
++nRecs;
Assert.IsTrue
(r.TEST_ID.HasValue);
Assert.AreEqual
(1,
r.TEST_ID.Value);
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("d","ID").EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL()
.T("WHERE ").P_BOOL("__Exec_V_V_0"));
Assert.AreEqual
(1,
nRecs);
}//using db
tr.Commit();
}//using tr
}//using cn
}//Test_002__equal
//-----------------------------------------------------------------------
[Test]
public static void Test_003__greater()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
T_DATA1 vv1=4;
T_DATA2 vv2=3;
var recs=db.testTable.Where(r => (vv1) /*OP{*/ .Equals /*}OP*/ (vv2));
foreach(var r in recs)
{
TestServices.ThrowSelectedRow();
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("d","ID").EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL()
.T("WHERE ").P_BOOL("__Exec_V_V_0"));
}//using db
tr.Commit();
}//using tr
}//using cn
}//Test_003__greater
//-----------------------------------------------------------------------
[Test]
public static void Test_ZA01NV()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
object vv1__null_obj=null;
T_DATA2 vv2=4;
var recs=db.testTable.Where(r => ((T_DATA1)vv1__null_obj) /*OP{*/ .Equals /*}OP*/ (vv2));
foreach(var r in recs)
{
TestServices.ThrowSelectedRow();
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("d","ID").EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL()
.T("WHERE ").P_BOOL("__Exec_V_V_0"));
}//using db
tr.Commit();
}//using tr
}//using cn
}//Test_ZA01NV
//-----------------------------------------------------------------------
[Test]
public static void Test_ZA02VN()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
T_DATA1 vv1=3;
object vv2__null_obj=null;
var recs=db.testTable.Where(r => (vv1) /*OP{*/ .Equals /*}OP*/ ((T_DATA2)vv2__null_obj));
foreach(var r in recs)
{
TestServices.ThrowSelectedRow();
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("d","ID").EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL()
.T("WHERE ").P_BOOL("__Exec_V_V_0"));
}//using db
tr.Commit();
}//using tr
}//using cn
}//Test_ZA02VN
//-----------------------------------------------------------------------
[Test]
public static void Test_ZA03NN()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
object vv1__null_obj=null;
object vv2__null_obj=null;
var recs=db.testTable.Where(r => ((T_DATA1)vv1__null_obj) /*OP{*/ .Equals /*}OP*/ ((T_DATA2)vv2__null_obj));
int nRecs=0;
foreach(var r in recs)
{
Assert.AreEqual
(0,
nRecs);
++nRecs;
Assert.IsTrue
(r.TEST_ID.HasValue);
Assert.AreEqual
(1,
r.TEST_ID.Value);
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("d","ID").EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL()
.T("WHERE ").P_BOOL("__Exec_V_V_0"));
Assert.AreEqual
(1,
nRecs);
}//using db
tr.Commit();
}//using tr
}//using cn
}//Test_ZA03NN
//-----------------------------------------------------------------------
[Test]
public static void Test_ZB01NV()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
object vv1__null_obj=null;
T_DATA2 vv2=4;
var recs=db.testTable.Where(r => !(((T_DATA1)vv1__null_obj) /*OP{*/ .Equals /*}OP*/ (vv2)));
int nRecs=0;
foreach(var r in recs)
{
Assert.AreEqual
(0,
nRecs);
++nRecs;
Assert.IsTrue
(r.TEST_ID.HasValue);
Assert.AreEqual
(1,
r.TEST_ID.Value);
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("d","ID").EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL()
.T("WHERE ").P_BOOL("__Exec_V_0"));
Assert.AreEqual
(1,
nRecs);
}//using db
tr.Commit();
}//using tr
}//using cn
}//Test_ZB01NV
//-----------------------------------------------------------------------
[Test]
public static void Test_ZB02VN()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
T_DATA1 vv1=3;
object vv2__null_obj=null;
var recs=db.testTable.Where(r => !((vv1) /*OP{*/ .Equals /*}OP*/ ((T_DATA2)vv2__null_obj)));
int nRecs=0;
foreach(var r in recs)
{
Assert.AreEqual
(0,
nRecs);
++nRecs;
Assert.IsTrue
(r.TEST_ID.HasValue);
Assert.AreEqual
(1,
r.TEST_ID.Value);
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("d","ID").EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL()
.T("WHERE ").P_BOOL("__Exec_V_0"));
Assert.AreEqual
(1,
nRecs);
}//using db
tr.Commit();
}//using tr
}//using cn
}//Test_ZB02VN
//-----------------------------------------------------------------------
[Test]
public static void Test_ZB03NN()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
object vv1__null_obj=null;
object vv2__null_obj=null;
var recs=db.testTable.Where(r => !(((T_DATA1)vv1__null_obj) /*OP{*/ .Equals /*}OP*/ ((T_DATA2)vv2__null_obj)));
foreach(var r in recs)
{
TestServices.ThrowSelectedRow();
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("d","ID").EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL()
.T("WHERE ").P_BOOL("__Exec_V_0"));
}//using db
tr.Commit();
}//using tr
}//using cn
}//Test_ZB03NN
};//class TestSet_504__param__01__VV
////////////////////////////////////////////////////////////////////////////////
}//namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D3.Query.Funcs.Int64.SET001.STD.Equals.Complete.Single
| 23.524249 | 125 | 0.526016 | [
"MIT"
] | ibprovider/Lcpi.EFCore.LcpiOleDb | Tests/General/Source/Work/DBMS/Firebird/V03_0_0/D3/Query/Funcs/Int64/SET001/STD/Equals/Complete/Single/TestSet_504__param__01__VV.cs | 10,188 | C# |
using System;
namespace SFA.DAS.Hmrc.ExecutionPolicy
{
[AttributeUsage(AttributeTargets.Parameter)]
public class RequiredPolicyAttribute : Attribute
{
public RequiredPolicyAttribute(string name)
{
Name = name;
}
public string Name { get; }
}
} | 20.4 | 52 | 0.630719 | [
"MIT"
] | SkillsFundingAgency/das-shared-packages | SFA.DAS.Hmrc/SFA.DAS.Hmrc/ExecutionPolicy/RequiredPolicyAttribute.cs | 308 | C# |
using System;
using System.Configuration;
namespace QuoteService.Features.Notifications
{
public interface INotificationsConfiguration
{
string SendGridApiKey { get; set; }
}
public class NotificationsConfiguration : ConfigurationSection, INotificationsConfiguration
{
[ConfigurationProperty("sendGridApiKey", IsRequired = true)]
public string SendGridApiKey
{
get { return (string)this["sendGridApiKey"]; }
set { this["sendGridApiKey"] = value; }
}
public static readonly Lazy<INotificationsConfiguration> LazyConfig = new Lazy<INotificationsConfiguration>(() =>
{
var section = ConfigurationManager.GetSection("notificationsConfiguration") as INotificationsConfiguration;
if (section == null)
{
throw new ConfigurationErrorsException("notificationsConfiguration");
}
return section;
}, true);
}
}
| 31 | 121 | 0.650202 | [
"MIT"
] | QuinntyneBrown/QuoteService | src/QuoteService/Features/Notifications/NotificationsConfiguration.cs | 994 | C# |
//---------------------------------------------------------
// <auto-generated>
// This code was generated by a tool. Changes to this
// file may cause incorrect behavior and will be lost
// if the code is regenerated.
//
// Generated on 2020 October 09 05:52:07 UTC
// </auto-generated>
//---------------------------------------------------------
using System;
using System.CodeDom.Compiler;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using static go.builtin;
using bytes = go.bytes_package;
using bio = go.cmd.@internal.bio_package;
using objabi = go.cmd.@internal.objabi_package;
using sys = go.cmd.@internal.sys_package;
using loader = go.cmd.oldlink.@internal.loader_package;
using sym = go.cmd.oldlink.@internal.sym_package;
using binary = go.encoding.binary_package;
using fmt = go.fmt_package;
using io = go.io_package;
using sort = go.sort_package;
using go;
#nullable enable
namespace go {
namespace cmd {
namespace oldlink {
namespace @internal
{
public static partial class loadmacho_package
{
[GeneratedCode("go2cs", "0.1.0.0")]
private partial struct ldMachoObj
{
// Constructors
public ldMachoObj(NilType _)
{
this.f = default;
this.@base = default;
this.length = default;
this.is64 = default;
this.name = default;
this.e = default;
this.cputype = default;
this.subcputype = default;
this.filetype = default;
this.flags = default;
this.cmd = default;
this.ncmd = default;
}
public ldMachoObj(ref ptr<bio.Reader> f = default, long @base = default, long length = default, bool is64 = default, @string name = default, binary.ByteOrder e = default, ulong cputype = default, ulong subcputype = default, uint filetype = default, uint flags = default, slice<ldMachoCmd> cmd = default, ulong ncmd = default)
{
this.f = f;
this.@base = @base;
this.length = length;
this.is64 = is64;
this.name = name;
this.e = e;
this.cputype = cputype;
this.subcputype = subcputype;
this.filetype = filetype;
this.flags = flags;
this.cmd = cmd;
this.ncmd = ncmd;
}
// Enable comparisons between nil and ldMachoObj struct
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator ==(ldMachoObj value, NilType nil) => value.Equals(default(ldMachoObj));
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator !=(ldMachoObj value, NilType nil) => !(value == nil);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator ==(NilType nil, ldMachoObj value) => value == nil;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator !=(NilType nil, ldMachoObj value) => value != nil;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static implicit operator ldMachoObj(NilType nil) => default(ldMachoObj);
}
[GeneratedCode("go2cs", "0.1.0.0")]
private static ldMachoObj ldMachoObj_cast(dynamic value)
{
return new ldMachoObj(ref value.f, value.@base, value.length, value.is64, value.name, value.e, value.cputype, value.subcputype, value.filetype, value.flags, value.cmd, value.ncmd);
}
}
}}}} | 38.875 | 337 | 0.589764 | [
"MIT"
] | GridProtectionAlliance/go2cs | src/go-src-converted/cmd/oldlink/internal/loadmacho/ldmacho_ldMachoObjStruct.cs | 3,732 | C# |
using System;
using System.Security.Claims;
using System.Threading.Tasks;
using Application.Common.Interfaces;
using Domain.Entities;
using Microsoft.AspNetCore.Http;
namespace WebApi.Services
{
public class CurrentUserService : ICurrentUserService
{
public async Task Initialize(ClaimsPrincipal user, ConnectionInfo connection, IUserManager userManager)
{
if (user?.Identity?.IsAuthenticated == true)
{
User = await userManager.GetCurrentUser(user.Identity.Name)
?? throw new UnauthorizedAccessException("Provided credentials are invalid");
IsAuthenticated = true;
}
Ip = connection?.RemoteIpAddress?.ToString();
}
public string Ip { get; private set; }
public AppUser User { get; private set; }
public bool IsAuthenticated { get; private set; }
}
}
| 29.580645 | 111 | 0.652126 | [
"MIT"
] | destbg/TwitterRecreated | src/WebApi/Services/CurrectUserService.cs | 919 | C# |
using ECM7.Migrator.Framework;
using Framework.Migrator.Extensions;
namespace Core.Languages.Migrations
{
/// <summary>
/// Adds Forms_Forms table.
/// </summary>
[Migration(1)]
public class Migration_AddLanguages : Migration
{
/// <summary>
/// Executes migration.
/// </summary>
public override void Apply()
{
Database.AddTable("Languages_Languages", t =>
{
t.PrimaryKey();
t.String("Title").Length(255);
t.String("Code").Length(3);
t.String("Culture").Length(10);
t.Bool("IsDefault").Bool();
});
}
/// <summary>
/// Rollbacks migration.
/// </summary>
public override void Revert()
{
Database.RemoveTable("Languages_Languages");
}
}
}
| 24.805556 | 57 | 0.503919 | [
"BSD-2-Clause"
] | coreframework/Core-Framework | Source/Core.Languages.Migrations/Migration_AddLanguages.cs | 895 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace WDE.Common.Managers
{
public interface ISolutionEditorManager
{
void Register<T>(Func<object, DocumentEditor> getter) where T : ISolutionItem;
DocumentEditor GetEditor<T>(T item) where T : ISolutionItem;
}
}
| 24.642857 | 86 | 0.733333 | [
"Unlicense"
] | Refuge89/WoWDatabaseEditor | WDE.Common/Managers/ISolutionEditorManager.cs | 347 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
namespace Microsoft.Omex.System.Logging
{
/// <summary>
/// Event ids enum.
/// </summary>
public enum EventIds : ushort
{
/// <summary>
/// Event Id for logging general info message.
/// </summary>
LogInfoEventId = 1,
/// <summary>
/// Event Id for logging error message.
/// </summary>
LogErrorEventId = 2,
/// <summary>
/// Event Id for logging warning message.
/// </summary>
LogWarningEventId = 3,
/// <summary>
/// Event Id for logging verbose message.
/// </summary>
LogVerboseEventId = 4,
/// <summary>
/// Event Id for logging spam message.
/// </summary>
LogSpamEventId = 5,
/// <summary>
/// Event Id for logging timed scopes.
/// </summary>
LogTimedScopeEventId = 6,
/// <summary>
/// Event Id for test context timed scopes; ex: health checks, observers
/// </summary>
LogTimedScopeTestContextEventId = 7,
/// <summary>
/// Event Id for service type registered.
/// </summary>
ServiceTypeRegisteredEventId = 11,
/// <summary>
/// Event Id for service host initialization failed.
/// </summary>
ServiceHostInitializationFailedEventId = 12,
/// <summary>
/// Event Id for actor type registered.
/// </summary>
ActorTypeRegisteredEventId = 13,
/// <summary>
/// Event Id for actor host initialization failed.
/// </summary>
ActorHostInitializationFailedEventId = 14,
/// <summary>
/// Event Id for logging Analytics information.
/// </summary>
LogAnalyticsEvent = 15,
}
}
| 22.111111 | 74 | 0.646985 | [
"MIT"
] | QPC-database/Omex | src/System/Logging/EventIds.cs | 1,594 | C# |
using Afonsoft.Ranking.Sessions.Dto;
namespace Afonsoft.Ranking.Web.Views.Shared.Components.AccountLogo
{
public class AccountLogoViewModel
{
public GetCurrentLoginInformationsOutput LoginInformations { get; }
private string _skin = "light";
public AccountLogoViewModel(GetCurrentLoginInformationsOutput loginInformations, string skin)
{
LoginInformations = loginInformations;
_skin = skin;
}
public string GetLogoUrl(string appPath)
{
if (LoginInformations?.Tenant?.LogoId == null)
{
return appPath + "Common/Images/app-logo-on-" + _skin + ".svg";
}
return appPath + "TenantCustomization/GetLogo?tenantId=" + LoginInformations?.Tenant?.Id;
}
}
} | 30.222222 | 101 | 0.632353 | [
"MIT"
] | afonsoft/Ranking | src/Afonsoft.Ranking.Web.Mvc/Views/Shared/Components/AccountLogo/AccountLogoViewModel.cs | 818 | C# |
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
namespace CronExpressionTests {
[TestClass]
[TestCategory("Days")]
public class DayOfWeekTests {
[DataTestMethod]
[DataRow(DayOfWeek.Sunday, "1/3/2022 03:43:12"/*Mon*/, "01/09/2022 00:00")]
[DataRow(DayOfWeek.Saturday, "1/5/2022 03:43:12"/*Wed*/, "01/08/2022 00:00")]
[DataRow(DayOfWeek.Tuesday, "1/5/2022 03:43:12"/*Wed*/, "01/11/2022 00:00")]
[TestProperty("Type", "Positive")]
public void ValidDayNextTest(int value, string targetAsString, string expectedAsString) {
var target = DateTimeOffset.Parse(targetAsString);
var expected = DateTimeOffset.Parse(expectedAsString);
var expression = new System.CronExpression($"* * * * {value}");
var nextInterval = expression.Next(target);
Assert.AreEqual(expected, nextInterval);
}
[DataTestMethod]
[DataRow(2/*Tue*/, 5/*Fri*/, "1/6/2021 10:59:12"/*Wed*/, "1/6/2021 11:00")]
[DataRow(2/*Tue*/, 5/*Fri*/, "1/8/2021 23:59:12"/*Fri*/, "1/12/2021 00:00")]
[TestProperty("Type", "Positive")]
public void ValidDayRangesTest(int start, int end, string targetAsString, string expectedAsString) {
var target = DateTimeOffset.Parse(targetAsString);
var expected = DateTimeOffset.Parse(expectedAsString);
var expression = new System.CronExpression($"* * * * {start}-{end}");
var nextInterval = expression.Next(target);
Assert.AreEqual(expected, nextInterval);
}
[DataTestMethod]
[DataRow(1/*Mon*/, 2, "1/2/2022 10:59:12"/*Sun*/, "1/3/2022 00:00"/*Mon*/)]
[DataRow(1/*Mon*/, 2, "1/3/2022 10:59:12"/*Mon*/, "1/3/2022 11:00"/*Mon*/)]
[DataRow(1/*Mon*/, 2, "1/4/2022 10:59:12"/*Tue*/, "1/5/2022 00:00"/*Wed*/)]
[TestProperty("Type", "Positive")]
public void ValidDayStepTest(int start, int step, string targetAsString, string expectedAsString) {
var target = DateTimeOffset.Parse(targetAsString);
var expected = DateTimeOffset.Parse(expectedAsString);
var expression = new System.CronExpression($"* * * * {start}/{step}");
var nextInterval = expression.Next(target);
Assert.AreEqual(expected, nextInterval);
}
[DataTestMethod]
// Sun,Wed,Sat
// ^ Tue
// ^ ^ Thu-Fri
// ^ ^ ^
[DataRow("0/3,2,4-5", "1/1/2022 23:59:12"/*Sat*/, "1/2/2022 00:00"/*Sun*/)]
[DataRow("0/3,2,4-5", "1/2/2022 23:59:12"/*Sun*/, "1/4/2022 00:00"/*Tue*/)]
[DataRow("0/3,2,4-5", "1/4/2022 23:59:12"/*Tue*/, "1/5/2022 00:00"/*Wed*/)]
[DataRow("0/3,2,4-5", "1/5/2022 23:59:12"/*Wed*/, "1/6/2022 00:00"/*Thu*/)]
[DataRow("0/3,2,4-5", "1/7/2022 23:59:12"/*Fri*/, "1/8/2022 00:00"/*Sat*/)]
[TestProperty("Type", "Positive")]
public void ValidDaySplitsTest(string splits, string targetAsString, string expectedAsString) {
var target = DateTimeOffset.Parse(targetAsString);
var expected = DateTimeOffset.Parse(expectedAsString);
var expression = new System.CronExpression($"* * * * {splits}");
var nextInterval = expression.Next(target);
Assert.AreEqual(expected, nextInterval);
}
}
}
| 40.810811 | 102 | 0.65596 | [
"MIT"
] | rashadrivera/CronExpression | CronExpressionTests/DayOfWeekTests.cs | 3,020 | C# |
using System;
using JetBrains.Annotations;
using Unity.Cloud.Collaborate.Presenters;
namespace Unity.Cloud.Collaborate.Views
{
/// <summary>
/// Interface for all views in the UI.
/// </summary>
/// <typeparam name="T">Type of presenter this view takes.</typeparam>
interface IView<in T> where T : IPresenter
{
/// <summary>
/// Presenter for this view.
/// </summary>
[NotNull]
T Presenter { set; }
}
}
| 23.65 | 74 | 0.604651 | [
"MIT"
] | 11xdev-coder/Snek | Library/PackageCache/com.unity.collab-proxy@1.5.7/Editor/Collaborate/Views/IView.cs | 473 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.