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
sequence | repository_name
stringlengths 7
92
| path
stringlengths 3
249
| size
int64 5
1.04M
| lang
stringclasses 2
values |
---|---|---|---|---|---|---|---|---|
using System;
using System.Linq;
using BlainePain.Geometry;
using BlainePain.Navigation;
namespace BlainePain.Rail
{
public static class TrackBuilder
{
private static readonly char?[] ValidTrackPieces = new char?[] { '-', '|', '/', '\\', '+', 'X', 'S' };
public static bool IsTrackPiece(char? checkChar) => ValidTrackPieces.Contains(checkChar);
public static Direction checkStraight(char? checkVal, Direction defaultDir, Direction option1, Direction option2)
{
return checkVal switch
{
'/' => option1,
'\\' => option2,
_ => defaultDir,
};
}
public static (bool Found, Coord NextPos, Direction NextDir) GetNextTrackPiece(IGridNavigator nav, IGrid grid, Coord pos, Direction dir)
{
var res = nav.CheckDirection(grid, pos, dir);
var nextDir = dir;
char?[] validChars;
switch (dir)
{
case Direction.North:
nextDir = checkStraight(res.NewValue, Direction.North, Direction.Northeast, Direction.Northwest);
break;
case Direction.South:
nextDir = checkStraight(res.NewValue, Direction.South, Direction.Southwest, Direction.Southeast);
break;
case Direction.East:
nextDir = checkStraight(res.NewValue, Direction.East, Direction.Northeast, Direction.Southeast);
break;
case Direction.West:
nextDir = checkStraight(res.NewValue, Direction.West, Direction.Southwest, Direction.Northwest);
break;
case Direction.Northwest:
validChars = new char?[] { '\\', 'X', 'S' };
if (res.IsInGrid && validChars.Contains(res.NewValue))
break;
nextDir = Direction.North;
validChars = new char?[] { '|', '+', 'S' };
res = nav.CheckDirection(grid, pos, nextDir);
if (res.IsInGrid && validChars.Contains(res.NewValue))
break;
nextDir = Direction.West;
validChars = new char?[] { '-', '+', 'S' };
res = nav.CheckDirection(grid, pos, nextDir);
if (res.IsInGrid && validChars.Contains(res.NewValue))
break;
break;
case Direction.Northeast:
validChars = new char?[] { '/', 'X', 'S' };
if (res.IsInGrid && validChars.Contains(res.NewValue))
break;
nextDir = Direction.North;
validChars = new char?[] { '|', '+', 'S' };
res = nav.CheckDirection(grid, pos, nextDir);
if (res.IsInGrid && validChars.Contains(res.NewValue))
break;
nextDir = Direction.East;
validChars = new char?[] { '-', '+', 'S' };
res = nav.CheckDirection(grid, pos, nextDir);
if (res.IsInGrid && validChars.Contains(res.NewValue))
break;
break;
case Direction.Southeast:
validChars = new char?[] { '\\', 'X', 'S' };
if (res.IsInGrid && validChars.Contains(res.NewValue))
break;
nextDir = Direction.South;
validChars = new char?[] { '|', '+', 'S' };
res = nav.CheckDirection(grid, pos, nextDir);
if (res.IsInGrid && validChars.Contains(res.NewValue))
break;
nextDir = Direction.East;
validChars = new char?[] { '-', '+', 'S' };
res = nav.CheckDirection(grid, pos, nextDir);
if (res.IsInGrid && validChars.Contains(res.NewValue))
break;
break;
case Direction.Southwest:
validChars = new char?[] { '/', 'X', 'S' };
if (res.IsInGrid && validChars.Contains(res.NewValue))
break;
nextDir = Direction.South;
validChars = new char?[] { '|', '+', 'S' };
res = nav.CheckDirection(grid, pos, nextDir);
if (res.IsInGrid && validChars.Contains(res.NewValue))
break;
nextDir = Direction.West;
validChars = new char?[] { '-', '+', 'S' };
res = nav.CheckDirection(grid, pos, nextDir);
if (res.IsInGrid && validChars.Contains(res.NewValue))
break;
break;
default:
throw new Exception("Unhandled Direction");
}
return (res.IsInGrid && IsTrackPiece(res.NewValue), res.NewPosition, nextDir);
}
public static Track GetTrack(Coord start, IGrid grid)
{
bool moreTrack = true;
Coord pos = start;
var direction = Direction.East;
var track = new Track();
var nav = new GridNavigator();
do
{
char piece = grid[pos];
if (!IsTrackPiece(piece))
throw new InvalidOperationException($"Invalid Track Piece specified: {piece}. At {pos}.");
track.AddTrackPiece(piece, pos);
var res = GetNextTrackPiece(nav, grid, pos, direction);
moreTrack = res.Found;
pos = res.NextPos;
direction = res.NextDir;
} while (moreTrack && pos != start);
return track;
}
}
} | 39.833333 | 144 | 0.470126 | [
"MIT"
] | mattjhooper/BlainePain | BlainePain/Rail/TrackBuilder.cs | 5,975 | 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 devicefarm-2015-06-23.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Serialization;
using Amazon.DeviceFarm.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.DeviceFarm.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for CreateRemoteAccessSession operation
/// </summary>
public class CreateRemoteAccessSessionResponseUnmarshaller : 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)
{
CreateRemoteAccessSessionResponse response = new CreateRemoteAccessSessionResponse();
context.Read();
int targetDepth = context.CurrentDepth;
while (context.ReadAtDepth(targetDepth))
{
if (context.TestExpression("remoteAccessSession", targetDepth))
{
var unmarshaller = RemoteAccessSessionUnmarshaller.Instance;
response.RemoteAccessSession = unmarshaller.Unmarshall(context);
continue;
}
}
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);
if (errorResponse.Code != null && errorResponse.Code.Equals("ArgumentException"))
{
return new ArgumentException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("LimitExceededException"))
{
return new LimitExceededException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("NotFoundException"))
{
return new NotFoundException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("ServiceAccountException"))
{
return new ServiceAccountException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
return new AmazonDeviceFarmException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
private static CreateRemoteAccessSessionResponseUnmarshaller _instance = new CreateRemoteAccessSessionResponseUnmarshaller();
internal static CreateRemoteAccessSessionResponseUnmarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static CreateRemoteAccessSessionResponseUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 41.309735 | 167 | 0.668166 | [
"Apache-2.0"
] | Bio2hazard/aws-sdk-net | sdk/src/Services/DeviceFarm/Generated/Model/Internal/MarshallTransformations/CreateRemoteAccessSessionResponseUnmarshaller.cs | 4,668 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.HttpRepl.Commands;
using Microsoft.HttpRepl.Fakes;
using Microsoft.HttpRepl.Preferences;
using Microsoft.HttpRepl.Resources;
using Microsoft.Repl.ConsoleHandling;
using Microsoft.Repl.Parsing;
using Xunit;
namespace Microsoft.HttpRepl.Tests.Commands
{
public class DeleteCommandTests : CommandTestsBase
{
private string _baseAddress;
private string _path;
private IDictionary<string, string> _urlsWithResponse = new Dictionary<string, string>();
public DeleteCommandTests()
{
_baseAddress = "http://localhost:5050/";
_path = "a/file/path.txt";
_urlsWithResponse.Add(_baseAddress, "Root delete received successfully.");
_urlsWithResponse.Add(_baseAddress + _path, "File path delete received successfully.");
}
[Fact]
public async Task ExecuteAsync_WithNoBasePath_VerifyError()
{
ArrangeInputs(commandText: "DELETE",
baseAddress: null,
path: null,
urlsWithResponse: null,
out MockedShellState shellState,
out HttpState httpState,
out ICoreParseResult parseResult,
out MockedFileSystem fileSystem,
out IPreferences preferences);
string expectedErrorMessage = Strings.Error_NoBasePath.SetColor(httpState.ErrorColor);
DeleteCommand deleteCommand = new DeleteCommand(fileSystem, preferences, new NullTelemetry());
await deleteCommand.ExecuteAsync(shellState, httpState, parseResult, CancellationToken.None);
Assert.Equal(expectedErrorMessage, shellState.ErrorMessage);
}
[Fact]
public async Task ExecuteAsync_WithMultipartRoute_VerifyOutput()
{
ArrangeInputs(commandText: "DELETE",
baseAddress: _baseAddress,
path: _path,
urlsWithResponse: _urlsWithResponse,
out MockedShellState shellState,
out HttpState httpState,
out ICoreParseResult parseResult,
out MockedFileSystem fileSystem,
out IPreferences preferences);
DeleteCommand deleteCommand = new DeleteCommand(fileSystem, preferences, new NullTelemetry());
await deleteCommand.ExecuteAsync(shellState, httpState, parseResult, CancellationToken.None);
string expectedResponse = "File path delete received successfully.";
List<string> result = shellState.Output;
Assert.Equal(2, result.Count);
Assert.Contains("HTTP/1.1 200 OK", result);
Assert.Contains(expectedResponse, result);
}
[Fact]
public async Task ExecuteAsync_WithOnlyBaseAddress_VerifyOutput()
{
ArrangeInputs(commandText: "DELETE",
baseAddress: _baseAddress,
path: null,
urlsWithResponse: _urlsWithResponse,
out MockedShellState shellState,
out HttpState httpState,
out ICoreParseResult parseResult,
out MockedFileSystem fileSystem,
out IPreferences preferences);
DeleteCommand deleteCommand = new DeleteCommand(fileSystem, preferences, new NullTelemetry());
await deleteCommand.ExecuteAsync(shellState, httpState, parseResult, CancellationToken.None);
string expectedResponse = "Root delete received successfully.";
List<string> result = shellState.Output;
Assert.Equal(2, result.Count);
Assert.Contains("HTTP/1.1 200 OK", result);
Assert.Contains(expectedResponse, result);
}
}
}
| 39.382353 | 111 | 0.648743 | [
"Apache-2.0"
] | calebjenkins/HttpRepl | test/Microsoft.HttpRepl.Tests/Commands/DeleteCommandsTests.cs | 4,017 | C# |
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using UnityEngine;
namespace HuaweiAREngineRemote
{
/// <summary>
/// 运行在 Editor 中
/// </summary>
public class TcpClient : TcpBase
{
private PreviewStreamVisualizer _previewVisualizer;
private PointCloudVisualizer _pointCloudVisualizer;
private ARPlaneVisualizer _arPlaneVisualizer;
private ARSceneMeshVisulizer _arSceneVisualizer;
private ARHandVisualizer _arHandVisualizer;
private ARFaceVisualizer _arFaceVisualizer;
public TcpClient(string ip, int port, SceneState st, Action<string, TcpState> notify) : base(st)
{
try
{
sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
sock.NoDelay = true;
callback = notify;
InitVisualizer();
Connect(ip, port);
}
catch (Exception ex)
{
Debug.LogError(ex);
}
}
private void InitVisualizer()
{
var obj = Resources.Load<GameObject>("ClientARDevice");
GameObject.Instantiate(obj);
obj = new GameObject("PreviewStreamVisualizer");
_previewVisualizer = obj.AddComponent<PreviewStreamVisualizer>();
_previewVisualizer.Init(sceneState);
if (sceneState == SceneState.World)
{
var ob = Resources.Load<GameObject>("PointCloudVisualizer");
obj = GameObject.Instantiate(ob);
obj.name = "PointCloudVisualizer";
_pointCloudVisualizer = obj.AddComponent<PointCloudVisualizer>();
_pointCloudVisualizer.Init(sceneState);
ob = Resources.Load<GameObject>("PlaneVisualizer");
obj = GameObject.Instantiate(ob);
obj.name = "PlaneVisualizer";
_arPlaneVisualizer = obj.AddComponent<ARPlaneVisualizer>();
_arPlaneVisualizer.Init(sceneState);
}
if (sceneState == SceneState.Scene)
{
var ob = Resources.Load<GameObject>("SceneMeshVisulizer");
obj = GameObject.Instantiate(ob);
obj.name = "ARSceneMeshVisulizer";
_arSceneVisualizer = obj.AddComponent<ARSceneMeshVisulizer>();
_arSceneVisualizer.Init(sceneState);
}
if (sceneState == SceneState.Hand)
{
obj = new GameObject("HandVisualizer");
_arHandVisualizer = obj.AddComponent<ARHandVisualizer>();
_arHandVisualizer.Init(sceneState);
}
if (sceneState == SceneState.Face)
{
var ob = Resources.Load<GameObject>("FaceVisualizer");
obj = GameObject.Instantiate(ob);
obj.name = "FaceVisualizer";
_arFaceVisualizer = obj.AddComponent<ARFaceVisualizer>();
_arFaceVisualizer.Init(sceneState);
}
}
private void Connect(string ip, int port)
{
try
{
var ipaddress = IPAddress.Parse(ip);
var endpoint = new IPEndPoint(ipaddress, port);
sock.Connect(endpoint);
callback(" connect server success", TcpState.Connect);
thread = new Thread(Receive);
thread.IsBackground = true;
thread.Start();
}
catch (Exception ex)
{
Debug.LogError(ex);
callback(" connect failed", TcpState.Connect);
}
}
private void Receive()
{
Recv(sock);
}
protected override void Process(int length)
{
int offset = headLen;
var head = (TcpHead) recvBuf[4];
switch (head)
{
case TcpHead.Preview:
_previewVisualizer.ProcessData(recvBuf, ref offset);
break;
case TcpHead.PointCloud:
_pointCloudVisualizer.ProcessData(recvBuf, ref offset);
break;
case TcpHead.Plane:
_arPlaneVisualizer.ProcessData(recvBuf, ref offset);
break;
case TcpHead.SceneMesh:
_arSceneVisualizer.ProcessData(recvBuf, ref offset);
break;
case TcpHead.Hand:
_arHandVisualizer.ProcessData(recvBuf, ref offset);
break;
case TcpHead.Face:
_arFaceVisualizer.ProcessData(recvBuf, ref offset);
break;
case TcpHead.String:
var strRecMsg = Encoding.UTF8.GetString(recvBuf, headLen, length - headLen);
Debug.Log(sock.RemoteEndPoint + " " + DateTime.Now + "\n" + strRecMsg);
callback(strRecMsg, TcpState.Receive);
break;
case TcpHead.Quit:
callback("connect quit", TcpState.Quit);
Close(false);
break;
default:
Debug.Log("not process " + head);
break;
}
}
public override void Update()
{
_previewVisualizer.Update();
switch (sceneState)
{
case SceneState.World:
_pointCloudVisualizer.Update();
_arPlaneVisualizer.Update();
break;
case SceneState.Scene:
_arSceneVisualizer.Update();
break;
case SceneState.Hand:
_arHandVisualizer.Update();
break;
case SceneState.Face:
_arFaceVisualizer.Update();
break;
}
}
public override void Close(bool notify)
{
if (sock == null) return;
try
{
base.Close(notify);
}
catch (Exception ex)
{
Debug.LogError(ex);
}
sock = null;
}
}
} | 35.777778 | 104 | 0.506832 | [
"MIT"
] | dingxiaowei/AREngineRemote | Unity/Assets/AREngineRemote/Scripts/Tcp/TcpClient.cs | 6,450 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Aspire.Studio.Plugin
{
public class PluginMenuStrip : MenuStrip
{
private List<string> pluginItems = new List<string>();
public void AddPlugin(PluginInfo pluginInfo)
{
#region Main Plugin Node
var pluginItem = new ToolStripMenuItem(pluginInfo.Plugin.Title);
pluginItem.Tag = pluginInfo;
try
{
if (!string.IsNullOrEmpty(pluginInfo.Plugin.Icon))
pluginItem.Image = Image.FromFile(pluginInfo.Plugin.Icon);
}
catch (NotImplementedException) { } // No icon
if (pluginInfo.Plugin is IFormPlugin)
pluginItem.Click += new EventHandler(pluginItem_Click);
#endregion
ToolStripMenuItem subGroup = null;
try
{
if (!string.IsNullOrEmpty(pluginInfo.Plugin.SubGroup))
{
subGroup = new ToolStripMenuItem(pluginInfo.Plugin.SubGroup);
subGroup.DropDownItems.Add(pluginItem);
}
}
catch (NotImplementedException)
{
// Do nothing (check for main group next)
}
ToolStripMenuItem group = null;
try
{
if (!string.IsNullOrEmpty(pluginInfo.Plugin.Group))
{
group = new ToolStripMenuItem(pluginInfo.Plugin.Group);
if (subGroup != null)
group.DropDownItems.Add(subGroup);
else
group.DropDownItems.Add(pluginItem);
//this.Items.Add(group);
EnsureItem(group);
pluginItems.Add(pluginInfo.Plugin.Group);
}
}
catch (NotImplementedException)
{
if (subGroup != null)
{
this.Items.Add(subGroup);
pluginItems.Add(pluginInfo.Plugin.SubGroup);
}
else
{
this.Items.Add(pluginItem);
pluginItems.Add(pluginInfo.Plugin.Title);
}
return;
}
if (group == null && subGroup == null)
{
this.Items.Add(pluginItem);
pluginItems.Add(pluginInfo.Plugin.Title);
}
}
private ToolStripMenuItem EnsureItem(ToolStripMenuItem menuItem)
{
ToolStripMenuItem item = (from x in this.Items.Cast<ToolStripMenuItem>()
where x.Text == menuItem.Text
select x).SingleOrDefault();
if (item == null)
{
this.Items.Add(menuItem);
return menuItem;
}
else
{
foreach (ToolStripMenuItem subItem in menuItem.DropDownItems)
item.DropDownItems.Add(subItem);
return item;
}
}
public void RemovePlugins()
{
foreach (var item in pluginItems)
{
this.Items.RemoveByKey(item);
}
}
void pluginItem_Click(object sender, EventArgs e)
{
var menuItem = sender as ToolStripMenuItem;
var pluginInfo = menuItem.Tag as PluginInfo;
var plugin = pluginInfo.Plugin as IFormPlugin;
Form form = plugin.Content;
if (form.IsDisposed)
{
form = PluginHelper.CreateNewInstance<Form>(pluginInfo.AssemblyPath);
}
if (plugin.ShowAs == ShowAs.Dialog)
{
form.ShowDialog();
}
else
{
form.Show();
}
}
}
}
| 21.71223 | 75 | 0.672962 | [
"Apache-2.0"
] | AeroNexus/AspireStudio | AspireStudio/Plugin/PluginMenuStrip.cs | 3,020 | C# |
global using Edvella.Devices;
global using FluentAssertions;
global using Microsoft.VisualStudio.TestTools.UnitTesting;
global using NSubstitute;
global using SixKeysOfTangrin;
global using SixKeysOfTangrin.Effects; | 36 | 58 | 0.865741 | [
"MIT"
] | edvella/SixKeysOfTangrin | SixKeysOfTangrinTests/GlobalUsings.cs | 218 | 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.Tcaplusdb.V20190823.Models
{
using Newtonsoft.Json;
using System.Collections.Generic;
using TencentCloud.Common;
public class ApplyResult : AbstractModel
{
/// <summary>
/// 申请单id
/// </summary>
[JsonProperty("ApplicationId")]
public string ApplicationId{ get; set; }
/// <summary>
/// 申请类型
/// </summary>
[JsonProperty("ApplicationType")]
public long? ApplicationType{ get; set; }
/// <summary>
/// 处理状态 0-待审核 1-已经审核并提交任务 2-已驳回
/// 注意:此字段可能返回 null,表示取不到有效值。
/// </summary>
[JsonProperty("ApplicationStatus")]
public long? ApplicationStatus{ get; set; }
/// <summary>
/// 已提交的任务Id
/// 注意:此字段可能返回 null,表示取不到有效值。
/// </summary>
[JsonProperty("TaskId")]
public string TaskId{ get; set; }
/// <summary>
/// 错误信息
/// 注意:此字段可能返回 null,表示取不到有效值。
/// </summary>
[JsonProperty("Error")]
public ErrorInfo Error{ 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 + "ApplicationId", this.ApplicationId);
this.SetParamSimple(map, prefix + "ApplicationType", this.ApplicationType);
this.SetParamSimple(map, prefix + "ApplicationStatus", this.ApplicationStatus);
this.SetParamSimple(map, prefix + "TaskId", this.TaskId);
this.SetParamObj(map, prefix + "Error.", this.Error);
}
}
}
| 31.373333 | 91 | 0.60816 | [
"Apache-2.0"
] | TencentCloud/tencentcloud-sdk-dotnet | TencentCloud/Tcaplusdb/V20190823/Models/ApplyResult.cs | 2,545 | C# |
/**
* 作 者:朱晓春([email protected])
* 创建时间:2018-12-22 14.27:00
* 版 本 号:1.0.0
* 功能说明:数据库函数显示字段成生实现类
* ----------------------------------
*/
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Data.SQLite;
using System.Reflection;
using DotNet.Standard.Common.Utilities;
using DotNet.Standard.NParsing.Utilities;
using DotNet.Standard.NParsing.Interface;
namespace DotNet.Standard.NParsing.SQLite
{
public class ObProperty : ObPropertyBase
{
public ObProperty(IObProperty iObProperty)
{
Brothers = iObProperty.Brothers;
AriSymbol = iObProperty.AriSymbol;
ModelType = iObProperty.ModelType;
TableName = iObProperty.TableName;
ColumnName = iObProperty.ColumnName;
PropertyName = iObProperty.PropertyName;
DbFunc = iObProperty.DbFunc;
}
public override string ToString()
{
IList<DbParameter> dbParameters = new List<DbParameter>();
return CreateSql(this, true, '.', ref dbParameters);
}
public override string ToString(char separator)
{
IList<DbParameter> dbParameters = new List<DbParameter>();
return CreateSql(this, true, separator, ref dbParameters);
}
public override string ToString(ref IList<DbParameter> dbParameters)
{
return CreateSql(this, false, '.', ref dbParameters);
}
public override string ToString(char separator, ref IList<DbParameter> dbParameters)
{
return CreateSql(this, false, separator, ref dbParameters);
}
private string CreateSql(object value, ref IList<DbParameter> dbParameter)
{
return CreateSql(value, false, '.', ref dbParameter);
}
private string CreateSql(object value, bool renaming, char separator, ref IList<DbParameter> dbParameter)
{
IList<object> brothers;
var brotherIndex = 0;
var columnNames = string.Empty;
bool isAll;
var asString = "";
if (value is IObProperty iObProperty)
{
string obSettledValue = null;
foreach (var propertyInfo in iObProperty.ModelType.GetProperties(BindingFlags.Instance | BindingFlags.Public))
{
if (propertyInfo.ToColumnName() == iObProperty.ColumnName)
{
obSettledValue = propertyInfo.GetSettledValue();
break;
}
}
var columnValue = obSettledValue ?? string.Format("{0}{2}{1}", iObProperty.TableName, iObProperty.ColumnName, separator);
brothers = iObProperty.Brothers;
brotherIndex = iObProperty.FuncBrotherCount;
if (iObProperty.CustomParams == null)
{
columnValue = CreateSql(columnValue, brothers, 0, brotherIndex, ref dbParameter);
}
else
{
columnValue = "";
foreach (var customParam in iObProperty.CustomParams)
{
if (columnValue.Length > 0)
columnValue += ",";
columnValue += CreateSql(customParam, ref dbParameter);
}
}
switch (DbFunc)
{
case DbFunc.Null:
columnNames += $"{columnValue}";
break;
case DbFunc.Avg:
columnNames += $"AVG({columnValue})";
break;
case DbFunc.Count:
columnNames += $"COUNT({columnValue})";
break;
case DbFunc.Max:
columnNames += $"MAX({columnValue})";
break;
case DbFunc.Min:
columnNames += $"MIN({columnValue})";
break;
case DbFunc.Sum:
columnNames += $"SUM({columnValue})";
break;
case DbFunc.Replace:
columnNames += $"REPLACE({columnValue})";
break;
case DbFunc.SubString:
columnNames += $"SUBSTRING({columnValue})";
break;
case DbFunc.IndexOf:
columnNames += "-1";
break;
case DbFunc.ToInt16:
columnNames += $"CONVERT(SMALLINT, {columnValue})";
break;
case DbFunc.ToInt32:
columnNames += $"CONVERT(INT, {columnValue})";
break;
case DbFunc.ToInt64:
columnNames += $"CONVERT(BIGINT, {columnValue})";
break;
case DbFunc.ToSingle:
columnNames += $"CONVERT(FLOAT, {columnValue})";
break;
case DbFunc.ToDouble:
columnNames += $"CONVERT(DOUBLE, {columnValue})";
break;
case DbFunc.ToDecimal:
var cvs = columnValue.Split(',');
columnNames += $"CONVERT(DECIMAL({cvs[1]}, {cvs[2]}), {cvs[0]})";
break;
case DbFunc.ToDateTime:
columnNames += $"CONVERT(DATETIME, {columnValue})";
break;
case DbFunc.ToString:
columnNames += $"CONVERT(VARCHAR, {columnValue})";
break;
case DbFunc.Format:
columnNames += $"FORMAT({columnValue})";
break;
}
asString = renaming ? $" AS {iObProperty.AsProperty.TableName}_{iObProperty.AsProperty.PropertyName}" : "";
isAll = iObProperty.AriSymbol == DbAriSymbol.Null;
}
else if (value is IObValue iObValue)
{
var parameterName = "$NPaValue";
SQLiteParameter sqlParameter = null;
#region 防止重复参数名
var i = 0;
foreach (var parameter in dbParameter)
{
if (parameter.ParameterName.StartsWith(parameterName))
{
if (parameter.Value.Equals(iObValue.Value))
{
sqlParameter = (SQLiteParameter)parameter;
parameterName = parameter.ParameterName;
break;
}
i++;
}
}
#endregion
if (sqlParameter == null)
{
parameterName += i == 0 ? "" : i.ToString();
sqlParameter = new SQLiteParameter { ParameterName = parameterName };
if (iObValue.Value.IsString())
{
var vv = iObValue.Value.ToString();
sqlParameter.DbType = DbType.String;
sqlParameter.Size = vv.Length == 0 ? 1 : vv.Length;
}
sqlParameter.Value = iObValue.Value;
dbParameter.Add(sqlParameter);
}
columnNames += parameterName;
brothers = iObValue.Brothers;
isAll = iObValue.AriSymbol == DbAriSymbol.Null;
}
else if (value is Type type)
{
var parameterName = "";
if (type == typeof(short))
{
parameterName = "SMALLINT";
}
else if (type == typeof(int))
{
parameterName = "INT";
}
else if (type == typeof(long))
{
parameterName = "BIGINT";
}
else if (type == typeof(float))
{
parameterName = "FLOAT";
}
else if (type == typeof(double))
{
parameterName = "DOUBLE";
}
else if (type == typeof(decimal))
{
parameterName = "DECIMAL(38,8)";
}
else if (type == typeof(DateTime))
{
parameterName = "DATETIME";
}
else if (type == typeof(string))
{
parameterName = "VARCHAR";
}
columnNames += parameterName;
brothers = new List<object>();
isAll = false;
}
else
{
var parameterName = "$NPaValue";
SQLiteParameter sqlParameter = null;
#region 防止重复参数名
var i = 0;
foreach (var parameter in dbParameter)
{
if (parameter.ParameterName.StartsWith(parameterName))
{
if (parameter.Value.Equals(value))
{
sqlParameter = (SQLiteParameter)parameter;
parameterName = parameter.ParameterName;
break;
}
i++;
}
}
#endregion
if (sqlParameter == null)
{
parameterName += i == 0 ? "" : i.ToString();
sqlParameter = new SQLiteParameter { ParameterName = parameterName };
if (value.IsString())
{
var vv = value.ToString();
sqlParameter.DbType = DbType.String;
sqlParameter.Size = vv.Length == 0 ? 1 : vv.Length;
}
sqlParameter.Value = value;
dbParameter.Add(sqlParameter);
}
columnNames += parameterName;
brothers = new List<object>();
isAll = false;
}
var iBrotherCount = brothers.Count;
isAll = isAll && iBrotherCount > brotherIndex;
columnNames = CreateSql(columnNames, brothers, brotherIndex, iBrotherCount, ref dbParameter);
if (isAll)
return "(" + columnNames + ")" + asString;
return columnNames + asString;
}
/// <summary>
/// 算术运算
/// </summary>
/// <param name="columnValue"></param>
/// <param name="brothers"></param>
/// <param name="start"></param>
/// <param name="end"></param>
/// <param name="dbParameter"></param>
/// <returns></returns>
private string CreateSql(string columnValue, IList<object> brothers, int start, int end, ref IList<DbParameter> dbParameter)
{
for (var i = start; i < end; i++)
{
var brother = brothers[i];
DbAriSymbol ariSymbol;
int brothersCount;
if (brother is IObProperty property)
{
ariSymbol = property.AriSymbol;
brothersCount = property.Brothers.Count;
}
else
{
ariSymbol = ((IObValue)brother).AriSymbol;
brothersCount = ((IObValue)brother).Brothers.Count;
}
switch (ariSymbol)
{
case DbAriSymbol.Plus:
columnValue += "+";
break;
case DbAriSymbol.Minus:
columnValue += "-";
break;
case DbAriSymbol.Multiply:
columnValue += "*";
break;
case DbAriSymbol.Except:
columnValue += "/";
break;
case DbAriSymbol.Mod:
columnValue += "%";
break;
case DbAriSymbol.And:
columnValue += "&";
break;
case DbAriSymbol.Or:
columnValue += "|";
break;
}
var andorWhere = "{0}";
if (brothersCount > 0)
{
andorWhere = "(" + andorWhere + ")";
}
columnValue += string.Format(andorWhere, CreateSql(brother, ref dbParameter));
}
return columnValue;
}
}
} | 38.369942 | 137 | 0.433112 | [
"Apache-2.0"
] | JTOne123/NParsing | src/DotNet.Standard.NParsing.SQLite/ObProperty.cs | 13,382 | C# |
using System;
using System.Globalization;
using Common;
using Fairweather.Service;
namespace Standardization
{
public static class Formatting
{
const string comma_format = "#,#0.00";
public static string ToString(this decimal dec, bool use_default) {
if (use_default)
return dec.ToString(cst_decimal_format);
else
return dec.ToString();
}
public static string ToString(this decimal dec, bool use_default, bool use_commas) {
if (use_default) {
if (use_commas)
return dec.ToString(comma_format);
else
return dec.ToString(cst_decimal_format);
}
else {
return dec.ToString();
}
}
public static string ToString(this decimal dec, int decimal_places) {
return dec.ToString("F" + decimal_places.ToString());
}
public static string ToString(this DateTime dt, bool use_default) {
return dt.ToString(use_default, false);
}
public static string ToString(this DateTime dt, bool use_default, bool sortable) {
if (use_default)
return dt.ToString(Data.Date_Format(sortable));
else
return dt.ToString();
}
public static decimal FromString(this string dec_str) {
var ret = dec_str.DecimalOrZero(cst_decimal_precision);
return ret;
}
public static DateTime FromString(this string date_str, bool sortable) {
string format = Data.Date_Format(sortable);
var ret = DateTime.ParseExact(date_str, format, null, DateTimeStyles.AllowWhiteSpaces);
return ret;
}
static readonly string cst_decimal_format = "F" + cst_decimal_precision.ToString();
const int cst_decimal_precision = Data.DEF_DISPLAY_PRECISION;
}
} | 28.929577 | 100 | 0.572541 | [
"MIT"
] | staafl/dotnet-bclext | to-integrate/libcs_staaflutil/Business/Standardization/Formatting.cs | 2,054 | C# |
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.Gcp.Compute.Outputs
{
[OutputType]
public sealed class RegionNetworkEndpointGroupAppEngine
{
/// <summary>
/// Optional serving service.
/// The service name must be 1-63 characters long, and comply with RFC1035.
/// Example value: "default", "my-service".
/// </summary>
public readonly string? Service;
/// <summary>
/// A template to parse function field from a request URL. URL mask allows
/// for routing to multiple Cloud Functions without having to create
/// multiple Network Endpoint Groups and backend services.
/// For example, request URLs "mydomain.com/function1" and "mydomain.com/function2"
/// can be backed by the same Serverless NEG with URL mask "/". The URL mask
/// will parse them to { function = "function1" } and { function = "function2" } respectively.
/// </summary>
public readonly string? UrlMask;
/// <summary>
/// Optional serving version.
/// The version must be 1-63 characters long, and comply with RFC1035.
/// Example value: "v1", "v2".
/// </summary>
public readonly string? Version;
[OutputConstructor]
private RegionNetworkEndpointGroupAppEngine(
string? service,
string? urlMask,
string? version)
{
Service = service;
UrlMask = urlMask;
Version = version;
}
}
}
| 35.096154 | 102 | 0.620822 | [
"ECL-2.0",
"Apache-2.0"
] | dimpu47/pulumi-gcp | sdk/dotnet/Compute/Outputs/RegionNetworkEndpointGroupAppEngine.cs | 1,825 | C# |
using FluentMigrator.Runner.Generators.Oracle;
using FluentMigrator.Runner.Processors.Oracle;
namespace FluentMigrator.Runner.Processors.DotConnectOracle
{
public class DotConnectOracleProcessorFactory : MigrationProcessorFactory
{
public override IMigrationProcessor Create(string connectionString, IAnnouncer announcer, IMigrationProcessorOptions options)
{
var factory = new DotConnectOracleDbFactory();
var connection = factory.CreateConnection(connectionString);
return new DotConnectOracleProcessor(connection, new OracleGenerator(), announcer, options, factory);
}
}
} | 43.266667 | 133 | 0.75963 | [
"Apache-2.0"
] | Athari/FluentMigrator | src/FluentMigrator.Runner/Processors/DotConnectOracle/DotConnectOracleProcessorFactory.cs | 651 | 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.Diagnostics;
using ILCompiler.DependencyAnalysisFramework;
using Internal.Text;
using Internal.TypeSystem;
namespace ILCompiler.DependencyAnalysis
{
internal class CppMethodCodeNode : DependencyNodeCore<NodeFactory>, IMethodBodyNode
{
private MethodDesc _method;
private string _methodCode;
private IEnumerable<Object> _dependencies;
public CppMethodCodeNode(MethodDesc method)
{
Debug.Assert(!method.IsAbstract);
_method = method;
}
public void SetCode(string methodCode, IEnumerable<Object> dependencies)
{
Debug.Assert(_methodCode == null);
_methodCode = methodCode;
_dependencies = dependencies;
}
public string CppCode
{
get
{
return _methodCode;
}
}
public MethodDesc Method
{
get
{
return _method;
}
}
protected override string GetName(NodeFactory factory) => this.GetMangledName(factory.NameMangler);
public override bool StaticDependenciesAreComputed => _methodCode != null;
public void AppendMangledName(NameMangler nameMangler, Utf8StringBuilder sb)
{
sb.Append(nameMangler.GetMangledMethodName(_method));
}
public int Offset => 0;
public bool RepresentsIndirectionCell => false;
public override bool InterestingForDynamicDependencyAnalysis => false;
public override bool HasDynamicDependencies => false;
public override bool HasConditionalStaticDependencies => false;
public override IEnumerable<DependencyListEntry> GetStaticDependencies(NodeFactory factory)
{
var dependencies = new DependencyList();
foreach (Object node in _dependencies)
dependencies.Add(node, "CPP code ");
return dependencies;
}
public override IEnumerable<CombinedDependencyListEntry> GetConditionalStaticDependencies(NodeFactory factory) => null;
public override IEnumerable<CombinedDependencyListEntry> SearchDynamicDependencies(List<DependencyNodeCore<NodeFactory>> markedNodes, int firstNode, NodeFactory factory) => null;
int ISortableNode.ClassCode => 1643555522;
int ISortableNode.CompareToImpl(ISortableNode other, CompilerComparer comparer)
{
return comparer.Compare(_method, ((CppMethodCodeNode)other)._method);
}
}
}
| 32.413793 | 186 | 0.666312 | [
"MIT"
] | cmoski/corert | src/ILCompiler.CppCodeGen/src/Compiler/DependencyAnalysis/CppMethodCodeNode.cs | 2,820 | C# |
// ------------------------------------------------------------------------------
// <auto-generated>
// Generated by Xsd2Code. Version 3.4.0.18239 Microsoft Reciprocal License (Ms-RL)
// <NameSpace>Mim.V6301</NameSpace><Collection>Array</Collection><codeType>CSharp</codeType><EnableDataBinding>False</EnableDataBinding><EnableLazyLoading>False</EnableLazyLoading><TrackingChangesEnable>False</TrackingChangesEnable><GenTrackingClasses>False</GenTrackingClasses><HidePrivateFieldInIDE>False</HidePrivateFieldInIDE><EnableSummaryComment>True</EnableSummaryComment><VirtualProp>False</VirtualProp><IncludeSerializeMethod>True</IncludeSerializeMethod><UseBaseClass>False</UseBaseClass><GenBaseClass>False</GenBaseClass><GenerateCloneMethod>True</GenerateCloneMethod><GenerateDataContracts>False</GenerateDataContracts><CodeBaseTag>Net35</CodeBaseTag><SerializeMethodName>Serialize</SerializeMethodName><DeserializeMethodName>Deserialize</DeserializeMethodName><SaveToFileMethodName>SaveToFile</SaveToFileMethodName><LoadFromFileMethodName>LoadFromFile</LoadFromFileMethodName><GenerateXMLAttributes>True</GenerateXMLAttributes><OrderXMLAttrib>False</OrderXMLAttrib><EnableEncoding>False</EnableEncoding><AutomaticProperties>False</AutomaticProperties><GenerateShouldSerialize>False</GenerateShouldSerialize><DisableDebug>False</DisableDebug><PropNameSpecified>Default</PropNameSpecified><Encoder>UTF8</Encoder><CustomUsings></CustomUsings><ExcludeIncludedTypes>True</ExcludeIncludedTypes><EnableInitializeFields>False</EnableInitializeFields>
// </auto-generated>
// ------------------------------------------------------------------------------
namespace Mim.V6301 {
using System;
using System.Diagnostics;
using System.Xml.Serialization;
using System.Collections;
using System.Xml.Schema;
using System.ComponentModel;
using System.IO;
using System.Text;
[System.CodeDom.Compiler.GeneratedCodeAttribute("Xsd2Code", "3.4.0.18239")]
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true, Namespace="urn:hl7-org:v3")]
public partial class POCD_IN180002UK05MCCI_MT010101UK12MessageVersionCode : CS {
private static System.Xml.Serialization.XmlSerializer serializer;
private static System.Xml.Serialization.XmlSerializer Serializer {
get {
if ((serializer == null)) {
serializer = new System.Xml.Serialization.XmlSerializer(typeof(POCD_IN180002UK05MCCI_MT010101UK12MessageVersionCode));
}
return serializer;
}
}
#region Serialize/Deserialize
/// <summary>
/// Serializes current POCD_IN180002UK05MCCI_MT010101UK12MessageVersionCode object into an XML document
/// </summary>
/// <returns>string XML value</returns>
public virtual string Serialize() {
System.IO.StreamReader streamReader = null;
System.IO.MemoryStream memoryStream = null;
try {
memoryStream = new System.IO.MemoryStream();
Serializer.Serialize(memoryStream, this);
memoryStream.Seek(0, System.IO.SeekOrigin.Begin);
streamReader = new System.IO.StreamReader(memoryStream);
return streamReader.ReadToEnd();
}
finally {
if ((streamReader != null)) {
streamReader.Dispose();
}
if ((memoryStream != null)) {
memoryStream.Dispose();
}
}
}
/// <summary>
/// Deserializes workflow markup into an POCD_IN180002UK05MCCI_MT010101UK12MessageVersionCode object
/// </summary>
/// <param name="xml">string workflow markup to deserialize</param>
/// <param name="obj">Output POCD_IN180002UK05MCCI_MT010101UK12MessageVersionCode object</param>
/// <param name="exception">output Exception value if deserialize failed</param>
/// <returns>true if this XmlSerializer can deserialize the object; otherwise, false</returns>
public static bool Deserialize(string xml, out POCD_IN180002UK05MCCI_MT010101UK12MessageVersionCode obj, out System.Exception exception) {
exception = null;
obj = default(POCD_IN180002UK05MCCI_MT010101UK12MessageVersionCode);
try {
obj = Deserialize(xml);
return true;
}
catch (System.Exception ex) {
exception = ex;
return false;
}
}
public static bool Deserialize(string xml, out POCD_IN180002UK05MCCI_MT010101UK12MessageVersionCode obj) {
System.Exception exception = null;
return Deserialize(xml, out obj, out exception);
}
public static POCD_IN180002UK05MCCI_MT010101UK12MessageVersionCode Deserialize(string xml) {
System.IO.StringReader stringReader = null;
try {
stringReader = new System.IO.StringReader(xml);
return ((POCD_IN180002UK05MCCI_MT010101UK12MessageVersionCode)(Serializer.Deserialize(System.Xml.XmlReader.Create(stringReader))));
}
finally {
if ((stringReader != null)) {
stringReader.Dispose();
}
}
}
/// <summary>
/// Serializes current POCD_IN180002UK05MCCI_MT010101UK12MessageVersionCode object into file
/// </summary>
/// <param name="fileName">full path of outupt xml file</param>
/// <param name="exception">output Exception value if failed</param>
/// <returns>true if can serialize and save into file; otherwise, false</returns>
public virtual bool SaveToFile(string fileName, out System.Exception exception) {
exception = null;
try {
SaveToFile(fileName);
return true;
}
catch (System.Exception e) {
exception = e;
return false;
}
}
public virtual void SaveToFile(string fileName) {
System.IO.StreamWriter streamWriter = null;
try {
string xmlString = Serialize();
System.IO.FileInfo xmlFile = new System.IO.FileInfo(fileName);
streamWriter = xmlFile.CreateText();
streamWriter.WriteLine(xmlString);
streamWriter.Close();
}
finally {
if ((streamWriter != null)) {
streamWriter.Dispose();
}
}
}
/// <summary>
/// Deserializes xml markup from file into an POCD_IN180002UK05MCCI_MT010101UK12MessageVersionCode object
/// </summary>
/// <param name="fileName">string xml file to load and deserialize</param>
/// <param name="obj">Output POCD_IN180002UK05MCCI_MT010101UK12MessageVersionCode object</param>
/// <param name="exception">output Exception value if deserialize failed</param>
/// <returns>true if this XmlSerializer can deserialize the object; otherwise, false</returns>
public static bool LoadFromFile(string fileName, out POCD_IN180002UK05MCCI_MT010101UK12MessageVersionCode obj, out System.Exception exception) {
exception = null;
obj = default(POCD_IN180002UK05MCCI_MT010101UK12MessageVersionCode);
try {
obj = LoadFromFile(fileName);
return true;
}
catch (System.Exception ex) {
exception = ex;
return false;
}
}
public static bool LoadFromFile(string fileName, out POCD_IN180002UK05MCCI_MT010101UK12MessageVersionCode obj) {
System.Exception exception = null;
return LoadFromFile(fileName, out obj, out exception);
}
public static POCD_IN180002UK05MCCI_MT010101UK12MessageVersionCode LoadFromFile(string fileName) {
System.IO.FileStream file = null;
System.IO.StreamReader sr = null;
try {
file = new System.IO.FileStream(fileName, FileMode.Open, FileAccess.Read);
sr = new System.IO.StreamReader(file);
string xmlString = sr.ReadToEnd();
sr.Close();
file.Close();
return Deserialize(xmlString);
}
finally {
if ((file != null)) {
file.Dispose();
}
if ((sr != null)) {
sr.Dispose();
}
}
}
#endregion
#region Clone method
/// <summary>
/// Create a clone of this POCD_IN180002UK05MCCI_MT010101UK12MessageVersionCode object
/// </summary>
public virtual POCD_IN180002UK05MCCI_MT010101UK12MessageVersionCode Clone() {
return ((POCD_IN180002UK05MCCI_MT010101UK12MessageVersionCode)(this.MemberwiseClone()));
}
#endregion
}
}
| 49.497354 | 1,358 | 0.617745 | [
"MIT"
] | Kusnaditjung/MimDms | src/Mim.V6301/Generated/POCD_IN180002UK05MCCI_MT010101UK12MessageVersionCode.cs | 9,355 | C# |
using Sdl.Web.Common.Models;
using System;
namespace Sdl.Web.Modules.Impress.Models
{
[Serializable]
public class Message : EntityModel
{
public RichText Content { get; set; }
}
}
| 17.166667 | 45 | 0.665049 | [
"Apache-2.0"
] | RWS/dxa-modules | webapp-net/Impress/Models/Message.cs | 208 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using AdaptiveExpressions.Converters;
using AdaptiveExpressions.Memory;
using Newtonsoft.Json;
namespace AdaptiveExpressions
{
/// <summary>
/// Type expected from evaluating an expression.
/// </summary>
public enum ReturnType
{
/// <summary>
/// True or false boolean value.
/// </summary>
Boolean,
/// <summary>
/// Numerical value like int, float, double, ...
/// </summary>
Number,
/// <summary>
/// Any value is possible.
/// </summary>
Object,
/// <summary>
/// String value.
/// </summary>
String,
}
/// <summary>
/// An expression which can be analyzed or evaluated to produce a value.
/// </summary>
/// <remarks>
/// This provides an open-ended wrapper that supports a number of built-in functions and can also be extended at runtime.
/// It also supports validation of the correctness of an expression and evaluation that should be exception free.
/// </remarks>
[JsonConverter(typeof(ExpressionConverter))]
public class Expression
{
/// <summary>
/// Dictionary of function => ExpressionEvaluator.
/// </summary>
/// <remarks>
/// This is all available functions, you can add custom functions to it, but you cannot
/// replace builtin functions. If you clear the dictionary, it will be reset to the built in functions.
/// </remarks>
public static readonly FunctionTable Functions = new FunctionTable();
/// <summary>
/// Initializes a new instance of the <see cref="Expression"/> class.
/// Built-in expression constructor.
/// </summary>
/// <param name="type">Type of built-in expression from <see cref="ExpressionType"/>.</param>
/// <param name="children">Child expressions.</param>
public Expression(string type, params Expression[] children)
{
Evaluator = Functions[type] ?? throw new SyntaxErrorException($"{type} does not have an evaluator, it's not a built-in function or a custom function.");
Children = children;
}
/// <summary>
/// Initializes a new instance of the <see cref="Expression"/> class.
/// Expression constructor.
/// </summary>
/// <param name="evaluator">Information about how to validate and evaluate expression.</param>
/// <param name="children">Child expressions.</param>
public Expression(ExpressionEvaluator evaluator, params Expression[] children)
{
Evaluator = evaluator ?? throw new ArgumentNullException(nameof(evaluator));
Children = children;
}
/// <summary>
/// Gets type of expression.
/// </summary>
/// <value>
/// Type of expression.
/// </value>
public string Type => Evaluator.Type;
/// <summary>
/// Gets expression evaluator.
/// </summary>
/// <value>
/// expression evaluator.
/// </value>
public ExpressionEvaluator Evaluator { get; }
/// <summary>
/// Gets or sets children expressions.
/// </summary>
/// <value>
/// Children expressions.
/// </value>
public Expression[] Children { get; set; }
/// <summary>
/// Gets expected result of evaluating expression.
/// </summary>
/// <value>
/// Expected result of evaluating expression.
/// </value>
public ReturnType ReturnType => Evaluator.ReturnType;
/// <summary>
/// allow a string to be implicitly assigned to an expression property.
/// </summary>
/// <param name="expression">string expression.</param>
public static implicit operator Expression(string expression) => Expression.Parse(expression);
/// <summary>
/// Parse an expression string into an expression object.
/// </summary>
/// <param name="expression">expression string.</param>
/// <param name="lookup">Optional function lookup when parsing the expression. Default is Expression.Lookup which uses Expression.Functions table.</param>
/// <returns>expression object.</returns>
public static Expression Parse(string expression, EvaluatorLookup lookup = null) => new ExpressionParser(lookup ?? Expression.Lookup).Parse(expression);
/// <summary>
/// Lookup a ExpressionEvaluator (function) by name.
/// </summary>
/// <param name="functionName">function name.</param>
/// <returns>ExpressionEvaluator.</returns>
public static ExpressionEvaluator Lookup(string functionName) => Functions.TryGetValue(functionName, out var function) ? function : null;
/// <summary>
/// Make an expression and validate it.
/// </summary>
/// <param name="type">Type of expression from <see cref="ExpressionType"/>.</param>
/// <param name="children">Child expressions.</param>
/// <returns>New expression.</returns>
public static Expression MakeExpression(string type, params Expression[] children)
{
var expr = new Expression(type, children);
expr.Validate();
return expr;
}
/// <summary>
/// Make an expression and validate it.
/// </summary>
/// <param name="evaluator">Information about how to validate and evaluate expression.</param>
/// <param name="children">Child expressions.</param>
/// <returns>New expression.</returns>
public static Expression MakeExpression(ExpressionEvaluator evaluator, params Expression[] children)
{
var expr = new Expression(evaluator, children);
expr.Validate();
return expr;
}
/// <summary>
/// Construct an expression from a <see cref="EvaluateExpressionDelegate"/>.
/// </summary>
/// <param name="function">Function to create an expression from.</param>
/// <returns>New expression.</returns>
public static Expression LambaExpression(EvaluateExpressionDelegate function)
=> new Expression(new ExpressionEvaluator(ExpressionType.Lambda, function));
/// <summary>
/// Construct an expression from a lambda expression over the state.
/// </summary>
/// <remarks>Exceptions will be caught and surfaced as an error string.</remarks>
/// <param name="function">Lambda expression to evaluate.</param>
/// <returns>New expression.</returns>
public static Expression Lambda(Func<object, object> function)
=> new Expression(new ExpressionEvaluator(ExpressionType.Lambda, (expression, state, _) =>
{
object value = null;
string error = null;
try
{
value = function(state);
}
catch (Exception e)
{
error = e.Message;
}
return (value, error);
}));
/// <summary>
/// Construct and validate an Set a property expression to a value expression.
/// </summary>
/// <param name="property">property expression.</param>
/// <param name="value">value expression.</param>
/// <returns>New expression.</returns>
public static Expression SetPathToValue(Expression property, Expression value)
=> Expression.MakeExpression(ExpressionType.SetPathToValue, property, value);
/// <summary>
/// Construct and validate an Set a property expression to a value expression.
/// </summary>
/// <param name="property">property expression.</param>
/// <param name="value">value object.</param>
/// <returns>New expression.</returns>
public static Expression SetPathToValue(Expression property, object value)
{
if (value is Expression)
{
return Expression.MakeExpression(ExpressionType.SetPathToValue, property, (Expression)value);
}
else
{
return Expression.MakeExpression(ExpressionType.SetPathToValue, property, ConstantExpression(value));
}
}
/// <summary>
/// Construct and validate an Equals expression.
/// </summary>
/// <param name="children">Child clauses.</param>
/// <returns>New expression.</returns>
public static Expression EqualsExpression(params Expression[] children)
=> Expression.MakeExpression(ExpressionType.Equal, children);
/// <summary>
/// Construct and validate an And expression.
/// </summary>
/// <param name="children">Child clauses.</param>
/// <returns>New expression.</returns>
public static Expression AndExpression(params Expression[] children)
{
if (children.Count() > 1)
{
return Expression.MakeExpression(ExpressionType.And, children);
}
return children.Single();
}
/// <summary>
/// Construct and validate an Or expression.
/// </summary>
/// <param name="children">Child clauses.</param>
/// <returns>New expression.</returns>
public static Expression OrExpression(params Expression[] children)
{
if (children.Count() > 1)
{
return Expression.MakeExpression(ExpressionType.Or, children);
}
return children.Single();
}
/// <summary>
/// Construct and validate a Not expression.
/// </summary>
/// <param name="child">Child clauses.</param>
/// <returns>New expression.</returns>
public static Expression NotExpression(Expression child)
=> Expression.MakeExpression(ExpressionType.Not, child);
/// <summary>
/// Construct a constant expression.
/// </summary>
/// <param name="value">Constant value.</param>
/// <returns>New expression.</returns>
public static Expression ConstantExpression(object value)
=> new Constant(value);
/// <summary>
/// Construct and validate a property accessor.
/// </summary>
/// <param name="property">Property to lookup.</param>
/// <param name="instance">Expression to get instance that contains property or null for global state.</param>
/// <returns>New expression.</returns>
public static Expression Accessor(string property, Expression instance = null)
=> instance == null
? MakeExpression(ExpressionType.Accessor, ConstantExpression(property))
: MakeExpression(ExpressionType.Accessor, ConstantExpression(property), instance);
/// <summary>
/// Do a deep equality between expressions.
/// </summary>
/// <param name="other">Other expression.</param>
/// <returns>True if expressions are the same.</returns>
public virtual bool DeepEquals(Expression other)
{
var eq = false;
if (other != null)
{
eq = this.Type == other.Type;
if (eq)
{
eq = this.Children.Count() == other.Children.Count();
if (this.Type == ExpressionType.And || this.Type == ExpressionType.Or)
{
// And/Or do not depend on order
for (var i = 0; eq && i < this.Children.Count(); ++i)
{
var primary = this.Children[i];
var found = false;
for (var j = 0; j < this.Children.Count(); ++j)
{
if (primary.DeepEquals(other.Children[j]))
{
found = true;
break;
}
}
eq = found;
}
}
else
{
for (var i = 0; eq && i < this.Children.Count(); ++i)
{
eq = this.Children[i].DeepEquals(other.Children[i]);
}
}
}
}
return eq;
}
/// <summary>
/// Return the static reference paths to memory.
/// </summary>
/// <remarks>
/// Return all static paths to memory. If there is a computed element index, then the path is terminated there,
/// but you might get other paths from the computed part as well.
/// </remarks>
/// <param name="expression">Expression to get references from.</param>
/// <returns>List of the static reference paths.</returns>
public IReadOnlyList<string> References()
{
var (path, refs) = ReferenceWalk(this);
if (path != null)
{
refs.Add(path);
}
return refs.ToList();
}
/// <summary>
/// Walking function for identifying static memory references in an expression.
/// </summary>
/// <param name="expression">Expression to analyze.</param>
/// <param name="extension">If present, called to override lookup for things like template expansion.</param>
/// <returns>Accessor path of expression which is a potential partial path and the full path found so far.</returns>
public (string path, HashSet<string> references) ReferenceWalk(Expression expression, Func<Expression, bool> extension = null)
{
string path = null;
var refs = new HashSet<string>();
if (extension == null || !extension(expression))
{
var children = expression.Children;
if (expression.Type == ExpressionType.Accessor)
{
var prop = (string)((Constant)children[0]).Value;
if (children.Length == 1)
{
path = prop;
}
if (children.Length == 2)
{
(path, refs) = ReferenceWalk(children[1], extension);
if (path != null)
{
path = path + "." + prop;
}
// if path is null we still keep it null, won't append prop
// because for example, first(items).x should not return x as refs
}
}
else if (expression.Type == ExpressionType.Element)
{
(path, refs) = ReferenceWalk(children[0], extension);
if (path != null)
{
if (children[1] is Constant cnst)
{
if (cnst.ReturnType == ReturnType.String)
{
path += $".{cnst.Value}";
}
else
{
path += $"[{cnst.Value}]";
}
}
else
{
refs.Add(path);
}
}
var (idxPath, refs1) = ReferenceWalk(children[1], extension);
refs.UnionWith(refs1);
if (idxPath != null)
{
refs.Add(idxPath);
}
}
else if (expression.Type == ExpressionType.Foreach ||
expression.Type == ExpressionType.Where ||
expression.Type == ExpressionType.Select)
{
var (child0Path, refs0) = ReferenceWalk(children[0], extension);
if (child0Path != null)
{
refs0.Add(child0Path);
}
var (child2Path, refs2) = ReferenceWalk(children[2], extension);
if (child2Path != null)
{
refs2.Add(child2Path);
}
var iteratorName = (string)(children[1].Children[0] as Constant).Value;
// filter references found in children 2 with iterator name
var nonLocalRefs2 = refs2.Where(x => !(x.Equals(iteratorName) || x.StartsWith(iteratorName + '.') || x.StartsWith(iteratorName + '[')))
.ToList();
refs.UnionWith(refs0);
refs.UnionWith(nonLocalRefs2);
}
else
{
foreach (var child in expression.Children)
{
var (childPath, refs0) = ReferenceWalk(child, extension);
refs.UnionWith(refs0);
if (childPath != null)
{
refs.Add(childPath);
}
}
}
}
return (path, refs);
}
/// <summary>
/// Validate immediate expression.
/// </summary>
public void Validate() => Evaluator.ValidateExpression(this);
/// <summary>
/// Recursively validate the expression tree.
/// </summary>
public void ValidateTree()
{
Validate();
foreach (var child in Children)
{
child.ValidateTree();
}
}
/// <summary>
/// Evaluate the expression.
/// </summary>
/// <param name="state">
/// Global state to evaluate accessor expressions against. Can be <see cref="System.Collections.Generic.IDictionary{String, Object}"/>,
/// <see cref="System.Collections.IDictionary"/> otherwise reflection is used to access property and then indexer.
/// </param>
/// <param name="options">Options used in the evaluation. </param>
/// <returns>Computed value and an error string. If the string is non-null, then there was an evaluation error.</returns>
public (object value, string error) TryEvaluate(object state, Options options = null)
=> this.TryEvaluate<object>(MemoryFactory.Create(state), options);
/// <summary>
/// Evaluate the expression.
/// </summary>
/// <param name="state">
/// Global state to evaluate accessor expressions against. Can be <see cref="System.Collections.Generic.IDictionary{String, Object}"/>,
/// <see cref="System.Collections.IDictionary"/> otherwise reflection is used to access property and then indexer.
/// </param>
/// <param name="options">Options used in the evaluation. </param>
/// <returns>Computed value and an error string. If the string is non-null, then there was an evaluation error.</returns>
public (object value, string error) TryEvaluate(IMemory state, Options options = null)
=> this.TryEvaluate<object>(state, options);
/// <summary>
/// Evaluate the expression.
/// </summary>
/// <typeparam name="T">type of result of the expression.</typeparam>
/// <param name="state">
/// Global state to evaluate accessor expressions against. Can be <see cref="System.Collections.Generic.IDictionary{String, Object}"/>,
/// <see cref="System.Collections.IDictionary"/> otherwise reflection is used to access property and then indexer.
/// </param>
/// <param name="options">Options used in the evaluation. </param>
/// <returns>Computed value and an error string. If the string is non-null, then there was an evaluation error.</returns>
public (T value, string error) TryEvaluate<T>(object state, Options options = null)
=> this.TryEvaluate<T>(MemoryFactory.Create(state), options);
/// <summary>
/// Evaluate the expression.
/// </summary>
/// <typeparam name="T">type of result of the expression.</typeparam>
/// <param name="state">
/// Global state to evaluate accessor expressions against. Can be <see cref="System.Collections.Generic.IDictionary{String, Object}"/>,
/// <see cref="System.Collections.IDictionary"/> otherwise reflection is used to access property and then indexer.
/// </param>
/// <param name="options">Options used in the evaluation. </param>
/// <returns>Computed value and an error string. If the string is non-null, then there was an evaluation error.</returns>
public (T value, string error) TryEvaluate<T>(IMemory state, Options options = null)
{
var opts = options ?? new Options();
var (result, error) = Evaluator.TryEvaluate(this, state, opts);
if (error != null)
{
return (default(T), error);
}
if (result is T)
{
return ((T)result, error);
}
try
{
if (typeof(T) == typeof(object))
{
if (result == null)
{
return (default(T), error);
}
return ((T)result, error);
}
if (typeof(T) == typeof(string))
{
if (result == null)
{
return (default(T), null);
}
return ((T)(object)result.ToString(), error);
}
if (typeof(T) == typeof(bool))
{
return ((T)(object)Convert.ToBoolean(result), error);
}
if (typeof(T) == typeof(byte))
{
return ((T)(object)Convert.ToByte(result), (Convert.ToByte(result) == Convert.ToDouble(result)) ? null : Error<T>(result));
}
if (typeof(T) == typeof(short))
{
return ((T)(object)Convert.ToInt16(result), (Convert.ToInt16(result) == Convert.ToDouble(result)) ? null : Error<T>(result));
}
if (typeof(T) == typeof(int))
{
return ((T)(object)Convert.ToInt32(result), (Convert.ToInt32(result) == Convert.ToDouble(result)) ? null : Error<T>(result));
}
if (typeof(T) == typeof(long))
{
return ((T)(object)Convert.ToInt64(result), (Convert.ToInt64(result) == Convert.ToDouble(result)) ? null : Error<T>(result));
}
if (typeof(T) == typeof(ushort))
{
return ((T)(object)Convert.ToUInt16(result), (Convert.ToUInt16(result) == Convert.ToDouble(result)) ? null : Error<T>(result));
}
if (typeof(T) == typeof(uint))
{
return ((T)(object)Convert.ToUInt32(result), (Convert.ToUInt32(result) == Convert.ToDouble(result)) ? null : Error<T>(result));
}
if (typeof(T) == typeof(ulong))
{
return ((T)(object)Convert.ToUInt64(result), (Convert.ToUInt64(result) == Convert.ToDouble(result)) ? null : Error<T>(result));
}
if (typeof(T) == typeof(float))
{
return ((T)(object)Convert.ToSingle(Convert.ToDecimal(result)), null);
}
if (typeof(T) == typeof(double))
{
return ((T)(object)Convert.ToDouble(Convert.ToDecimal(result)), null);
}
if (result == null)
{
return (default(T), error);
}
return (JsonConvert.DeserializeObject<T>(JsonConvert.SerializeObject(result)), null);
}
catch
{
return (default(T), Error<T>(result));
}
}
public override string ToString()
{
var builder = new StringBuilder();
var valid = false;
// Special support for memory paths
if (Type == ExpressionType.Accessor && Children.Length >= 1)
{
if (Children[0] is Constant cnst
&& cnst.Value is string prop)
{
if (Children.Length == 1)
{
valid = true;
builder.Append(prop);
}
else if (Children.Length == 2)
{
valid = true;
builder.Append(Children[1].ToString());
builder.Append('.');
builder.Append(prop);
}
}
}
// Element support
else if (Type == ExpressionType.Element && Children.Length == 2)
{
valid = true;
builder.Append(Children[0].ToString());
builder.Append('[');
builder.Append(Children[1].ToString());
builder.Append(']');
}
// Generic version
if (!valid)
{
var infix = Type.Length > 0 && !char.IsLetter(Type[0]) && Children.Count() >= 2;
if (!infix)
{
builder.Append(Type);
}
builder.Append('(');
var first = true;
foreach (var child in Children)
{
if (first)
{
first = false;
}
else
{
if (infix)
{
builder.Append(' ');
builder.Append(Type);
builder.Append(' ');
}
else
{
builder.Append(", ");
}
}
builder.Append(child.ToString());
}
builder.Append(')');
}
return builder.ToString();
}
private string Error<T>(object result)
{
return $"'{result}' is not of type {typeof(T).Name}";
}
/// <summary>
/// FunctionTable is a dictionary which merges BuiltinFunctions.Functions with a CustomDictionary.
/// </summary>
public class FunctionTable : IDictionary<string, ExpressionEvaluator>
{
private readonly ConcurrentDictionary<string, ExpressionEvaluator> customFunctions = new ConcurrentDictionary<string, ExpressionEvaluator>(StringComparer.InvariantCultureIgnoreCase);
public ICollection<string> Keys => ExpressionFunctions.StandardFunctions.Keys.Concat(this.customFunctions.Keys).ToList();
public ICollection<ExpressionEvaluator> Values => ExpressionFunctions.StandardFunctions.Values.Concat(this.customFunctions.Values).ToList();
public int Count => ExpressionFunctions.StandardFunctions.Count + this.customFunctions.Count;
public bool IsReadOnly => false;
public ExpressionEvaluator this[string key]
{
get
{
if (ExpressionFunctions.StandardFunctions.TryGetValue(key, out var function))
{
return function;
}
if (customFunctions.TryGetValue(key, out function))
{
return function;
}
return null;
}
set
{
if (ExpressionFunctions.StandardFunctions.ContainsKey(key))
{
throw new NotSupportedException("You can't overwrite a built in function.");
}
customFunctions[key] = value;
}
}
public void Add(string key, ExpressionEvaluator value) => this[key] = value;
public void Add(string key, Func<IReadOnlyList<dynamic>, object> func)
{
Add(key, new ExpressionEvaluator(key, ExpressionFunctions.Apply(func)));
}
public void Add(KeyValuePair<string, ExpressionEvaluator> item) => this[item.Key] = item.Value;
public void Clear() => this.customFunctions.Clear();
public bool Contains(KeyValuePair<string, ExpressionEvaluator> item) => ExpressionFunctions.StandardFunctions.Contains(item) || this.customFunctions.Contains(item);
public bool ContainsKey(string key) => ExpressionFunctions.StandardFunctions.ContainsKey(key) || this.customFunctions.ContainsKey(key);
public void CopyTo(KeyValuePair<string, ExpressionEvaluator>[] array, int arrayIndex) => throw new NotImplementedException();
public IEnumerator<KeyValuePair<string, ExpressionEvaluator>> GetEnumerator() => ExpressionFunctions.StandardFunctions.Concat(this.customFunctions).GetEnumerator();
public bool Remove(string key) => this.customFunctions.TryRemove(key, out var oldVal);
public bool Remove(KeyValuePair<string, ExpressionEvaluator> item) => Remove(item.Key);
public bool TryGetValue(string key, out ExpressionEvaluator value)
{
if (ExpressionFunctions.StandardFunctions.TryGetValue(key, out value))
{
return true;
}
if (this.customFunctions.TryGetValue(key, out value))
{
return true;
}
return false;
}
IEnumerator IEnumerable.GetEnumerator() => ExpressionFunctions.StandardFunctions.Concat(this.customFunctions).GetEnumerator();
}
}
}
| 39.603295 | 194 | 0.514001 | [
"MIT"
] | NickEricson/botbuilder-dotnet | libraries/AdaptiveExpressions/Expression.cs | 31,249 | C# |
using System.Collections.Generic;
using System.Linq;
using WhetStone.SystemExtensions;
namespace WhetStone.Looping
{
/// <summary>
/// A static container for identity method
/// </summary>
public static class allEqual
{
/// <summary>
/// Checks whether all members of an <see cref="IEnumerable{T}"/> are equal.
/// </summary>
/// <typeparam name="T">The type of the <see cref="IEnumerable{T}"/>.</typeparam>
/// <param name="this">The <see cref="IEnumerable{T}"/> to check.</param>
/// <param name="comp">The <see cref="IEqualityComparer{T}"/> to use, to check all the elements all are the same.</param>
/// <returns>Whether all the elements in <paramref name="this"/> are equal.</returns>
/// <remarks><para>This compares every element to <paramref name="this"/>'s first element.</para><para>If <paramref name="this"/> is empty, <see langword="true"/> is returned.</para></remarks>
public static bool AllEqual<T>(this IEnumerable<T> @this, IEqualityComparer<T> comp = null)
{
@this.ThrowIfNull(nameof(@this));
comp = comp ?? EqualityComparer<T>.Default;
using (IEnumerator<T> tor = @this.GetEnumerator())
{
if (!tor.MoveNext())
return true;
T mem = tor.Current;
while (tor.MoveNext())
{
if (!comp.Equals(mem, tor.Current))
return false;
}
}
return true;
}
/// <summary>
/// Checks whether all members of an <see cref="IEnumerable{T}"/> are equal to a value.
/// </summary>
/// <typeparam name="T">The type of the <see cref="IEnumerable{T}"/>.</typeparam>
/// <param name="this">The <see cref="IEnumerable{T}"/> to check.</param>
/// <param name="value">The value to compare all elements to.</param>
/// <param name="comp">The <see cref="IEqualityComparer{T}"/> to use, to check all the elements all are the same.</param>
/// <returns>Whether all the elements in <paramref name="this"/> are equal to <paramref name="value"/>.</returns>
/// <remarks><para>If <paramref name="this"/> is empty, <see langword="true"/> is returned.</para></remarks>
public static bool AllEqual<T>(this IEnumerable<T> @this, T value, IEqualityComparer<T> comp = null)
{
@this.ThrowIfNull(nameof(@this));
comp = comp ?? EqualityComparer<T>.Default;
return @this.All(a => comp.Equals(value, a));
}
}
}
| 48.888889 | 200 | 0.572727 | [
"MIT"
] | bentheiii/WhetStone | WhetStone/AllEqual.cs | 2,642 | C# |
namespace ExpressionsTest
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using Bond;
using Bond.Expressions;
using Bond.Protocols;
using Bond.IO.Unsafe;
using Bond.Internal.Reflection;
internal static class DebugViewHelper
{
static readonly PropertyInfo debugView;
static DebugViewHelper()
{
debugView = typeof(Expression).GetDeclaredProperty("DebugView", typeof(string));
}
public static string ToString(Expression expression)
{
return (string)debugView.GetValue(expression);
}
public static string ToString(IEnumerable<Expression> expressions)
{
return string.Concat(expressions.Select(ToString));
}
}
interface IDebugView
{
string DebugView { get; }
}
internal class Transcoder<R, W> : IDebugView
{
readonly string debugView;
readonly Action<R, W>[] transcode = null;
public Transcoder(Type type)
: this(type, ParserFactory<R>.Create(type))
{}
public Transcoder(RuntimeSchema schema)
: this(schema, ParserFactory<R>.Create(schema))
{ }
public Transcoder()
: this(new RuntimeSchema())
{}
Transcoder(Type type, IParser parser)
{
var serializerTransform = SerializerGeneratorFactory<R, W>.Create(
(r, w, i) => transcode[i](r, w), type);
var expressions = serializerTransform.Generate(parser);
debugView = DebugViewHelper.ToString(expressions);
}
Transcoder(RuntimeSchema schema, IParser parser)
{
var serializerTransform = SerializerGeneratorFactory<R, W>.Create(
(r, w, i) => transcode[i](r, w), schema);
var expressions = serializerTransform.Generate(parser);
debugView = DebugViewHelper.ToString(expressions);
}
string IDebugView.DebugView { get { return debugView; } }
}
internal class DeserializerDebugView<R> : IDebugView
{
readonly string debugView;
readonly Func<R, object>[] deserialize = null;
public DeserializerDebugView(Type type)
{
var parser = ParserFactory<R>.Create(type);
var expressions = new DeserializerTransform<R>(
(r, i) => deserialize[i](r))
.Generate(parser, type);
debugView = DebugViewHelper.ToString(expressions);
}
string IDebugView.DebugView { get { return debugView; } }
}
internal class SerializerDebugView<W> : IDebugView
{
readonly string debugView;
readonly Action<object, W>[] serialize = null;
public SerializerDebugView(Type type)
{
var parser = new ObjectParser(type);
var serializerTransform = SerializerGeneratorFactory<object, W>.Create(
(o, w, i) => serialize[i](o, w), type);
var expressions = serializerTransform.Generate(parser);
debugView = DebugViewHelper.ToString(expressions);
}
string IDebugView.DebugView { get { return debugView; } }
}
static class Program
{
static void Write(string name, IDebugView codegen)
{
using (var file = File.Create(name))
{
using (var sw = new StreamWriter(file))
{
sw.Write(codegen.DebugView);
}
}
}
static void Main(string[] args)
{
Write("TranscodeCBCB.expressions",
new Transcoder<CompactBinaryReader<InputStream>, CompactBinaryWriter<OutputStream>>());
Write("TranscodeSPCB.expressions",
new Transcoder<SimpleBinaryReader<InputStream>, CompactBinaryWriter<OutputStream>>(typeof(Example)));
Write("TranscodeCBSP.expressions",
new Transcoder<CompactBinaryReader<InputStream>, SimpleBinaryWriter<OutputStream>>(typeof(Example)));
Write("DeserializeCB.expressions",
new DeserializerDebugView<CompactBinaryReader<InputStream>>(typeof(Example)));
Write("DeserializeSP.expressions",
new DeserializerDebugView<SimpleBinaryReader<InputStream>>(typeof(Example)));
Write("DeserializeXml.expressions",
new DeserializerDebugView<SimpleXmlReader>(typeof(Example)));
Write("DeserializeJson.expressions",
new DeserializerDebugView<SimpleJsonReader>(typeof(Example)));
Write("SerializeSP.expressions",
new SerializerDebugView<SimpleBinaryWriter<OutputStream>>(typeof(Example)));
Write("SerializeCB.expressions",
new SerializerDebugView<CompactBinaryWriter<OutputStream>>(typeof(Example)));
Write("SerializeXml.expressions",
new SerializerDebugView<SimpleXmlWriter>(typeof(Example)));
}
}
}
| 32.563291 | 117 | 0.606997 | [
"MIT"
] | Arshia001/OrleansBondBasedSerializer | Bond/cs/test/expressions/Program.cs | 5,147 | C# |
using MediatR;
using X.PagedList;
namespace SupportManager.Web.Features.PhoneNumber
{
public class PhoneNumberListQuery : IRequest<IPagedList<PhoneNumberListItem>>
{
public int? PageNumber { get; set; }
}
} | 22.8 | 81 | 0.723684 | [
"MIT"
] | mycroes/SupportManager | SupportManager.Web/Features/PhoneNumber/PhoneNumberListQuery.cs | 230 | C# |
using MasterDevs.ChromeDevTools;
using Newtonsoft.Json;
using System.Collections.Generic;
namespace MasterDevs.ChromeDevTools.Protocol.DOM
{
/// <summary>
/// Returns attributes for the specified node.
/// </summary>
[Command(ProtocolName.DOM.GetAttributes)]
public class GetAttributesCommand
{
/// <summary>
/// Gets or sets Id of the node to retrieve attibutes for.
/// </summary>
public long NodeId { get; set; }
}
}
| 22.947368 | 60 | 0.724771 | [
"MIT"
] | brewdente/AutoWebPerf | MasterDevs.ChromeDevTools/Protocol/DOM/GetAttributesCommand.cs | 436 | C# |
using FluentValidation;
using PS.Domain.Models;
namespace PS.Domain.Validations
{
public class PetValidator : AbstractValidator<Pet>
{
public PetValidator()
{
RuleFor(x => x.Name).NotEmpty().WithMessage("Name required");
}
}
} | 21.230769 | 73 | 0.626812 | [
"MIT"
] | RafaCarva/PetShop | src/PS.Domain/Validations/PetValidator.cs | 278 | C# |
//-----------------------------------------------------------------------
// <copyright file="ActorSelectionSpec.cs" company="Akka.NET Project">
// Copyright (C) 2009-2021 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2021 .NET Foundation <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using Akka.Actor;
using Akka.Actor.Internal;
using Akka.Actor.Dsl;
using Akka.Event;
using Akka.TestKit;
using Akka.Util.Internal;
using FluentAssertions;
using Xunit;
namespace Akka.Tests.Actor
{
using Akka.Util;
public class ActorSelectionSpec : AkkaSpec
{
private const string Config = @"
akka.test.default-timeout = 5 s
akka.loglevel=DEBUG
";
private readonly IActorRef _c1;
private readonly IActorRef _c2;
private readonly IActorRef _c21;
private readonly IActorRef[] _all;
public ActorSelectionSpec() : base(Config)
{
_c1 = Sys.ActorOf(Props, "c1");
_c2 = Sys.ActorOf(Props, "c2");
_c21 = _c2.Ask<IActorRef>(new Create("c21")).Result;
_all = new[] { _c1, _c2, _c21 };
}
private ActorSystemImpl SystemImpl => Sys as ActorSystemImpl;
private IInternalActorRef User => SystemImpl.Guardian;
private IInternalActorRef System => SystemImpl.SystemGuardian;
private IInternalActorRef Root => SystemImpl.LookupRoot;
private IActorRef Identify(ActorSelection selection)
{
var idProbe = CreateTestProbe();
selection.Tell(new Identify(selection), idProbe.Ref);
var result = idProbe.ExpectMsg<ActorIdentity>().Subject;
var asked = selection.Ask<ActorIdentity>(new Identify(selection)).Result;
asked.Subject.ShouldBe(result);
asked.MessageId.ShouldBe(selection);
IActorRef resolved;
try
{
resolved = selection.ResolveOne(TimeSpan.FromSeconds(3)).Result;
}
catch
{
resolved = null;
}
resolved.ShouldBe(result);
return result;
}
private IActorRef Identify(string path) => Identify(Sys.ActorSelection(path));
private IActorRef Identify(ActorPath path) => Identify(Sys.ActorSelection(path));
private IActorRef AskNode(IActorRef node, IQuery query)
{
var result = node.Ask(query).Result;
if (result is IActorRef actorRef)
return actorRef;
return result is ActorSelection selection ? Identify(selection) : null;
}
[Fact]
public void An_ActorSystem_must_select_actors_by_their_path()
{
Identify(_c1.Path).ShouldBe(_c1);
Identify(_c2.Path).ShouldBe(_c2);
Identify(_c21.Path).ShouldBe(_c21);
Identify("user/c1").ShouldBe(_c1);
Identify("user/c2").ShouldBe(_c2);
Identify("user/c2/c21").ShouldBe(_c21);
}
[Fact]
public void An_ActorSystem_must_select_actors_by_their_string_path_representation()
{
Identify(_c1.Path.ToString()).ShouldBe(_c1);
Identify(_c2.Path.ToString()).ShouldBe(_c2);
Identify(_c21.Path.ToString()).ShouldBe(_c21);
Identify(_c1.Path.ToStringWithoutAddress()).ShouldBe(_c1);
Identify(_c2.Path.ToStringWithoutAddress()).ShouldBe(_c2);
Identify(_c21.Path.ToStringWithoutAddress()).ShouldBe(_c21);
}
[Fact]
public void An_ActorSystem_must_take_actor_incarnation_into_account_when_comparing_actor_references()
{
const string name = "abcdefg";
var a1 = Sys.ActorOf(Props, name);
Watch(a1);
a1.Tell(PoisonPill.Instance);
ExpectMsg<Terminated>().ActorRef.ShouldBe(a1);
//not equal because it's terminated
Identify(a1.Path).ShouldBe(null);
var a2 = Sys.ActorOf(Props, name);
a2.Path.ShouldBe(a1.Path);
a2.Path.ToString().ShouldBe(a1.Path.ToString());
a2.ShouldNotBe(a1);
a2.ToString().ShouldNotBe(a1.ToString());
Watch(a2);
a2.Tell(PoisonPill.Instance);
ExpectMsg<Terminated>().ActorRef.ShouldBe(a2);
}
[Fact]
public void An_ActorSystem_must_select_actors_by_their_root_anchored_relative_path()
{
Identify(_c1.Path.ToStringWithoutAddress()).ShouldBe(_c1);
Identify(_c2.Path.ToStringWithoutAddress()).ShouldBe(_c2);
Identify(_c21.Path.ToStringWithoutAddress()).ShouldBe(_c21);
}
[Fact]
public void An_ActorSystem_must_select_actors_by_their_relative_path()
{
Identify(_c1.Path.Elements.Join("/")).ShouldBe(_c1);
Identify(_c2.Path.Elements.Join("/")).ShouldBe(_c2);
Identify(_c21.Path.Elements.Join("/")).ShouldBe(_c21);
}
[Fact]
public void An_ActorSystem_must_select_system_generated_actors()
{
Identify("/user").ShouldBe(User);
Identify("/system").ShouldBe(System);
Identify(System.Path).ShouldBe(System);
Identify(System.Path.ToStringWithoutAddress()).ShouldBe(System);
Identify("/").ShouldBe(Root);
//We return Nobody for an empty path
//Identify("").ShouldBe(Root);
Identify("").ShouldBe(Nobody.Instance);
Identify(new RootActorPath(Root.Path.Address)).ShouldBe(Root);
Identify("..").ShouldBe(Root);
Identify(Root.Path).ShouldBe(Root);
Identify(Root.Path.ToStringWithoutAddress()).ShouldBe(Root);
Identify("user").ShouldBe(User);
Identify("system").ShouldBe(System);
Identify("user/").ShouldBe(User);
Identify("system/").ShouldBe(System);
}
[Fact]
public void An_ActorSystem_must_return_ActorIdentity_None_respectively_for_non_existing_paths_and_DeadLetters()
{
Identify("a/b/c").ShouldBe(null);
Identify("a/b/c").ShouldBe(null);
Identify("akka://all-systems/Nobody").ShouldBe(null);
Identify("akka://all-systems/user").ShouldBe(null);
Identify("user/hallo").ShouldBe(null);
Identify("foo://user").ShouldBe(Nobody.Instance);
Identify("/deadLetters").ShouldBe(Nobody.Instance);
Identify("deadLetters").ShouldBe(Nobody.Instance);
Identify("deadLetters/").ShouldBe(Nobody.Instance);
}
[Fact]
public void An_ActorContext_must_select_actors_by_their_path()
{
Action<IActorRef, IActorRef> check =
(looker, result) => AskNode(looker, new SelectPath(result.Path)).ShouldBe(result);
foreach (var l in _all)
foreach (var r in _all)
check(l, r);
}
[Fact]
public void An_ActorContext_must_select_actor_by_their_string_path_representation()
{
Action<IActorRef, IActorRef> check = (looker, result) =>
{
AskNode(looker, new SelectString(result.Path.ToStringWithoutAddress())).ShouldBe(result);
// with trailing /
AskNode(looker, new SelectString(result.Path.ToStringWithoutAddress() + "/")).ShouldBe(result);
};
foreach (var l in _all)
foreach (var r in _all)
check(l, r);
}
[Fact]
public void An_ActorContext_must_select_actors_by_their_root_anchored_relative_path()
{
Action<IActorRef, IActorRef> check = (looker, result) =>
{
AskNode(looker, new SelectString(result.Path.ToStringWithoutAddress())).ShouldBe(result);
AskNode(looker, new SelectString("/" + result.Path.Elements.Join("/") + "/")).ShouldBe(result);
};
foreach (var l in _all)
foreach (var r in _all)
check(l, r);
}
[Fact]
public void An_ActorContext_must_select_actors_by_their_relative_path()
{
Action<IActorRef, IActorRef, string[]> check = (looker, result, elements) =>
{
AskNode(looker, new SelectString(elements.Join("/"))).ShouldBe(result);
AskNode(looker, new SelectString(elements.Join("/") + "/")).ShouldBe(result);
};
check(_c1, User, new[] { ".." });
foreach (var l in new[] { _c1, _c2 })
foreach (var r in _all)
{
var elements = new List<string> { ".." };
elements.AddRange(r.Path.Elements.Drop(1));
check(l, r, elements.ToArray());
}
check(_c21, User, new[] { "..", ".." });
check(_c21, Root, new[] { "..", "..", ".." });
check(_c21, Root, new[] { "..", "..", "..", ".." });
}
[Fact]
public void An_ActorContext_must_find_system_generated_actors()
{
Action<IActorRef> check = target =>
{
foreach (var looker in _all)
{
AskNode(looker, new SelectPath(target.Path)).ShouldBe(target);
AskNode(looker, new SelectString(target.Path.ToString())).ShouldBe(target);
AskNode(looker, new SelectString(target.Path.ToString() + "/")).ShouldBe(target);
}
if (!Equals(target, Root))
AskNode(_c1, new SelectString("../../" + target.Path.Elements.Join("/") + "/")).ShouldBe(target);
};
new[] { Root, System, User }.ForEach(check);
}
[Fact]
public void An_ActorContext_must_return_deadLetters_or_ActorIdentity_None_respectively_for_non_existing_paths()
{
Action<IActorRef, IQuery> checkOne = (looker, query) =>
{
var lookup = AskNode(looker, query);
lookup.ShouldBe(null);
};
Action<IActorRef> check = looker =>
{
new IQuery[]
{
new SelectString("a/b/c"),
new SelectString("akka://all-systems/Nobody"),
new SelectPath(User.Path / "hallo"),
new SelectPath(looker.Path / "hallo"),
new SelectPath(looker.Path / new []{"a","b"}),
}.ForEach(t => checkOne(looker, t));
};
_all.ForEach(check);
}
[Fact]
public void An_ActorSelection_must_send_messages_directly()
{
new ActorSelection(_c1, "").Tell(new GetSender(TestActor));
ExpectMsg(TestActor);
LastSender.ShouldBe(_c1);
}
[Fact]
public void An_ActorSelection_must_send_messages_to_string_path()
{
Sys.ActorSelection("/user/c2/c21").Tell(new GetSender(TestActor));
ExpectMsg(TestActor);
LastSender.ShouldBe(_c21);
}
[Fact]
public void An_ActorSelection_must_send_messages_to_actor_path()
{
Sys.ActorSelection(_c2.Path / "c21").Tell(new GetSender(TestActor));
ExpectMsg(TestActor);
LastSender.ShouldBe(_c21);
}
[Fact]
public void An_ActorSelection_must_send_messages_with_correct_sender()
{
new ActorSelection(_c21, "../../*").Tell(new GetSender(TestActor), _c1);
//Three messages because the selection includes the TestActor, GetSender -> TestActor + response from c1 and c2 to TestActor
var actors = ReceiveWhile(_ => LastSender, msgs: 3).Distinct();
actors.Should().BeEquivalentTo(new[] { _c1, _c2 });
ExpectNoMsg(TimeSpan.FromSeconds(1));
}
[Fact]
public void An_ActorSelection_must_drop_messages_which_cannot_be_delivered()
{
new ActorSelection(_c21, "../../*/c21").Tell(new GetSender(TestActor), _c2);
var actors = ReceiveWhile(_ => LastSender, msgs: 2).Distinct();
actors.Should().HaveCount(1).And.Subject.First().ShouldBe(_c21);
ExpectNoMsg(TimeSpan.FromSeconds(1));
}
[Fact]
public void An_ActorSelection_must_resolve_one_actor_with_timeout()
{
var s = Sys.ActorSelection("user/c2");
s.ResolveOne(Dilated(TimeSpan.FromSeconds(1))).Result.ShouldBe(_c2);
}
[Fact]
public void An_ActorSelection_must_resolve_non_existing_with_failure()
{
var task = Sys.ActorSelection("user/none").ResolveOne(Dilated(TimeSpan.FromSeconds(1)));
task.Invoking(t => t.Wait()).Should().Throw<ActorNotFoundException>();
}
[Fact]
public void An_ActorSelection_must_compare_equally()
{
new ActorSelection(_c21, "../*/hello").ShouldBe(new ActorSelection(_c21, "../*/hello"));
new ActorSelection(_c21, "../*/hello").GetHashCode().ShouldBe(new ActorSelection(_c21, "../*/hello").GetHashCode());
new ActorSelection(_c2, "../*/hello").ShouldNotBe(new ActorSelection(_c21, "../*/hello"));
new ActorSelection(_c2, "../*/hello").GetHashCode().ShouldNotBe(new ActorSelection(_c21, "../*/hello").GetHashCode());
new ActorSelection(_c21, "../*/hell").ShouldNotBe(new ActorSelection(_c21, "../*/hello"));
new ActorSelection(_c21, "../*/hell").GetHashCode().ShouldNotBe(new ActorSelection(_c21, "../*/hello").GetHashCode());
}
[Fact]
public void An_ActorSelection_must_print_nicely()
{
var expected = $"ActorSelection[Anchor(akka://{Sys.Name}/user/c2/c21#{_c21.Path.Uid}), Path(/../*/hello)]";
new ActorSelection(_c21, "../*/hello").ToString().ShouldBe(expected);
}
[Fact(Skip = "ActorSelection doesn't support serializable format by itself")]
public void An_ActorSelection_must_have_a_stringly_serializable_path()
{
}
[Fact]
public void An_ActorSelection_must_send_ActorSelection_targeted_to_missing_actor_to_deadLetters()
{
var p = CreateTestProbe();
Sys.EventStream.Subscribe(p.Ref, typeof(DeadLetter));
Sys.ActorSelection("/user/missing").Tell("boom", TestActor);
var d = p.ExpectMsg<DeadLetter>();
d.Message.ShouldBe("boom");
d.Sender.ShouldBe(TestActor);
d.Recipient.Path.ToStringWithoutAddress().ShouldBe("/user/missing");
}
[Theory]
[InlineData("/user/foo/*/bar")]
[InlineData("/user/foo/bar/*")]
public void Bugfix3420_A_wilcard_ActorSelection_that_selects_no_actors_must_go_to_DeadLetters(string actorPathStr)
{
var actorA = Sys.ActorOf(act =>
{
act.ReceiveAny((o, context) =>
{
context.ActorSelection(actorPathStr).Tell(o);
});
}, "a");
Sys.EventStream.Subscribe(TestActor, typeof(DeadLetter));
// deliver two ActorSelections - one from outside any actors, one from inside
// they have different anchors to start with, so the results may differ
Sys.ActorSelection(actorPathStr).Tell("foo");
ExpectMsg<DeadLetter>().Message.Should().Be("foo");
actorA.Tell("foo");
ExpectMsg<DeadLetter>().Message.Should().Be("foo");
}
[Fact]
public void An_ActorSelection_must_identify_actors_with_wildcard_selection_correctly()
{
var creator = CreateTestProbe();
var top = Sys.ActorOf(Props, "a");
var b1 = top.Ask<IActorRef>(new Create("b1"), TimeSpan.FromSeconds(3)).Result;
var b2 = top.Ask<IActorRef>(new Create("b2"), TimeSpan.FromSeconds(3)).Result;
var c = b2.Ask<IActorRef>(new Create("c"), TimeSpan.FromSeconds(3)).Result;
var d = c.Ask<IActorRef>(new Create("d"), TimeSpan.FromSeconds(3)).Result;
var probe = CreateTestProbe();
Sys.ActorSelection("/user/a/*").Tell(new Identify(1), probe.Ref);
probe.ReceiveN(2)
.Cast<ActorIdentity>()
.Select(i => i.Subject)
.Should().BeEquivalentTo(new[] { b1, b2 });
probe.ExpectNoMsg(TimeSpan.FromMilliseconds(200));
Sys.ActorSelection("/user/a/b1/*").Tell(new Identify(2), probe.Ref);
probe.ExpectMsg<ActorIdentity>().Should().BeEquivalentTo(new ActorIdentity(2, null));
Sys.ActorSelection("/user/a/*/c").Tell(new Identify(3), probe.Ref);
probe.ExpectMsg<ActorIdentity>().Should().BeEquivalentTo(new ActorIdentity(3, c));
probe.ExpectNoMsg(TimeSpan.FromMilliseconds(200));
Sys.ActorSelection("/user/a/b2/*/d").Tell(new Identify(4), probe.Ref);
probe.ExpectMsg<ActorIdentity>().Should().BeEquivalentTo(new ActorIdentity(4, d));
probe.ExpectNoMsg(TimeSpan.FromMilliseconds(200));
Sys.ActorSelection("/user/a/*/*/d").Tell(new Identify(5), probe.Ref);
probe.ExpectMsg<ActorIdentity>().Should().BeEquivalentTo(new ActorIdentity(5, d));
probe.ExpectNoMsg(TimeSpan.FromMilliseconds(200));
Sys.ActorSelection("/user/a/*/c/*").Tell(new Identify(6), probe.Ref);
probe.ExpectMsg<ActorIdentity>().Should().BeEquivalentTo(new ActorIdentity(6, d));
probe.ExpectNoMsg(TimeSpan.FromMilliseconds(200));
Sys.ActorSelection("/user/a/b2/*/d/e").Tell(new Identify(7), probe.Ref);
probe.ExpectMsg<ActorIdentity>().Should().BeEquivalentTo(new ActorIdentity(7, null));
probe.ExpectNoMsg(TimeSpan.FromMilliseconds(200));
Sys.ActorSelection("/user/a/*/c/d/e").Tell(new Identify(8), probe.Ref);
probe.ExpectNoMsg(TimeSpan.FromMilliseconds(500));
}
[Fact]
public void An_ActorSelection_must_identify_actors_with_double_wildcard_selection_correctly()
{
var creator = CreateTestProbe();
var top = Sys.ActorOf(Props, "a");
var b1 = top.Ask<IActorRef>(new Create("b1"), TimeSpan.FromSeconds(3)).Result;
var b2 = top.Ask<IActorRef>(new Create("b2"), TimeSpan.FromSeconds(3)).Result;
var b3 = top.Ask<IActorRef>(new Create("b3"), TimeSpan.FromSeconds(3)).Result;
var c1 = b2.Ask<IActorRef>(new Create("c1"), TimeSpan.FromSeconds(3)).Result;
var c2 = b2.Ask<IActorRef>(new Create("c2"), TimeSpan.FromSeconds(3)).Result;
var d = c1.Ask<IActorRef>(new Create("d"), TimeSpan.FromSeconds(3)).Result;
var probe = CreateTestProbe();
// grab everything below /user/a
Sys.ActorSelection("/user/a/**").Tell(new Identify(1), probe.Ref);
probe.ReceiveN(6)
.Cast<ActorIdentity>()
.Select(i => i.Subject)
.Should().BeEquivalentTo(new[] { b1, b2, b3, c1, c2, d });
probe.ExpectNoMsg(TimeSpan.FromMilliseconds(500));
// grab everything below /user/a/b2
Sys.ActorSelection("/user/a/b2/**").Tell(new Identify(2), probe.Ref);
probe.ReceiveN(3)
.Cast<ActorIdentity>()
.Select(i => i.Subject)
.Should().BeEquivalentTo(new[] { c1, c2, d });
probe.ExpectNoMsg(TimeSpan.FromMilliseconds(500));
// nothing under /user/a/b2/c1/d
Sys.ActorSelection("/user/a/b2/c1/d/**").Tell(new Identify(3), probe.Ref);
probe.ExpectNoMsg(TimeSpan.FromMilliseconds(500));
Action illegalDoubleWildCard = () => Sys.ActorSelection("/user/a/**/d").Tell(new Identify(4), probe.Ref);
illegalDoubleWildCard.Should().Throw<IllegalActorNameException>();
}
[Fact]
public void An_ActorSelection_must_forward_to_selection()
{
_c2.Tell(new Forward("c21", "hello"), TestActor);
ExpectMsg("hello");
LastSender.ShouldBe(_c21);
}
[Theory]
[InlineData("worker", "w.rker", false)]
[InlineData("w..ker", "w..ker", true)]
[InlineData("w^rker", "w^rker", true)]
[InlineData("w$rker", "w$rker", true)]
[InlineData("w$rk", "w$rker", false)]
[InlineData("work.r", "*.r", true)]
[InlineData("work.r", "*k.", false)]
[InlineData("work.r", "*k.r", true)]
[InlineData("worker", "*ke", false)]
[InlineData("worker", "*ker", true)]
[InlineData("worker", "*ker*", true)]
[InlineData("worker", "^worker", false)]
[InlineData("worker", "^worker$", false)]
[InlineData("worker", "ker*", false)]
[InlineData("worker", "worker", true)]
[InlineData("worker", "worker$", false)]
[InlineData("worker", "worker*", true)]
public void Selections_are_implicitly_anchored(string data, string pattern, bool isMatch)
{
var predicate = isMatch ? "matches" : "does not match";
WildcardMatch.Like(data, pattern).ShouldBe(isMatch, $"'{pattern}' {predicate} '{data}'");
}
#region Test classes
private sealed class Create
{
public Create(string child)
{
Child = child;
}
public string Child { get; }
}
private interface IQuery { }
private sealed class SelectString : IQuery
{
public SelectString(string path)
{
Path = path;
}
public string Path { get; }
}
private sealed class SelectPath : IQuery
{
public SelectPath(ActorPath path)
{
Path = path;
}
public ActorPath Path { get; }
}
private sealed class GetSender : IQuery
{
public GetSender(IActorRef to)
{
To = to;
}
public IActorRef To { get; }
}
private sealed class Forward : IQuery
{
public Forward(string path, object message)
{
Path = path;
Message = message;
}
public string Path { get; }
public object Message { get; }
}
private static readonly Props Props = Props.Create<Node>();
private sealed class Node : ReceiveActor
{
public Node()
{
Receive<Create>(c => Sender.Tell(Context.ActorOf(Props, c.Child)));
Receive<SelectString>(s => Sender.Tell(Context.ActorSelection(s.Path)));
Receive<SelectPath>(s => Sender.Tell(Context.ActorSelection(s.Path)));
Receive<GetSender>(g => g.To.Tell(Sender));
Receive<Forward>(f => Context.ActorSelection(f.Path).Tell(f.Message, Sender));
ReceiveAny(msg => Sender.Tell(msg));
}
}
#endregion
}
}
| 39.23 | 136 | 0.56772 | [
"Apache-2.0"
] | Aaronontheweb/akka.net | src/core/Akka.Tests/Actor/ActorSelectionSpec.cs | 23,540 | C# |
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Bot.Builder;
using Microsoft.Bot.Builder.Azure;
using Microsoft.Bot.Builder.Dialogs;
using Microsoft.Bot.Configuration;
using Microsoft.Bot.Schema;
using Microsoft.Bot.Solutions.Authentication;
using Microsoft.Bot.Solutions.Extensions;
using Microsoft.Bot.Solutions.Middleware;
using Microsoft.Bot.Solutions.Middleware.Telemetry;
using Microsoft.Bot.Solutions.Resources;
namespace Microsoft.Bot.Solutions.Skills
{
public class SkillDialog : ComponentDialog
{
// Fields
private SkillDefinition _skillDefinition;
private SkillConfigurationBase _skillConfiguration;
private EndpointService _endpointService;
private IBotTelemetryClient _telemetryClient;
private InProcAdapter _inProcAdapter;
private IBot _activatedSkill;
private bool _skillInitialized;
private bool _useCachedTokens;
public SkillDialog(SkillDefinition skillDefinition, SkillConfigurationBase skillConfiguration, EndpointService endpointService, IBotTelemetryClient telemetryClient, bool useCachedTokens = true)
: base(skillDefinition.Id)
{
_skillDefinition = skillDefinition;
_skillConfiguration = skillConfiguration;
_endpointService = endpointService;
_telemetryClient = telemetryClient;
_useCachedTokens = useCachedTokens;
AddDialog(new MultiProviderAuthDialog(skillConfiguration));
}
protected override async Task<DialogTurnResult> OnBeginDialogAsync(DialogContext innerDc, object options, CancellationToken cancellationToken = default(CancellationToken))
{
var skillOptions = (SkillDialogOptions)options;
// Send parameters to skill in skillBegin event
var userData = new Dictionary<string, object>();
if (_skillDefinition.Parameters != null)
{
foreach (var parameter in _skillDefinition.Parameters)
{
if (skillOptions.Parameters.TryGetValue(parameter, out var paramValue))
{
userData.TryAdd(parameter, paramValue);
}
}
}
var activity = innerDc.Context.Activity;
var skillBeginEvent = new Activity(
type: ActivityTypes.Event,
channelId: activity.ChannelId,
from: new ChannelAccount(id: activity.From.Id, name: activity.From.Name),
recipient: new ChannelAccount(id: activity.Recipient.Id, name: activity.Recipient.Name),
conversation: new ConversationAccount(id: activity.Conversation.Id),
name: Events.SkillBeginEventName,
value: userData);
// Send event to Skill/Bot
return await ForwardToSkill(innerDc, skillBeginEvent);
}
protected override async Task<DialogTurnResult> OnContinueDialogAsync(DialogContext innerDc, CancellationToken cancellationToken = default(CancellationToken))
{
var activity = innerDc.Context.Activity;
if (innerDc.ActiveDialog?.Id == nameof(MultiProviderAuthDialog))
{
// Handle magic code auth
var result = await innerDc.ContinueDialogAsync(cancellationToken);
// forward the token response to the skill
if (result.Status == DialogTurnStatus.Complete && result.Result is ProviderTokenResponse)
{
activity.Type = ActivityTypes.Event;
activity.Name = Events.TokenResponseEventName;
activity.Value = result.Result as ProviderTokenResponse;
}
else
{
return result;
}
}
return await ForwardToSkill(innerDc, activity);
}
protected override Task<DialogTurnResult> EndComponentAsync(DialogContext outerDc, object result, CancellationToken cancellationToken)
{
return outerDc.EndDialogAsync(result, cancellationToken);
}
private async Task InitializeSkill(DialogContext dc)
{
try
{
IStorage storage;
if (_skillConfiguration.CosmosDbOptions != null)
{
var cosmosDbOptions = _skillConfiguration.CosmosDbOptions;
cosmosDbOptions.CollectionId = _skillDefinition.Name;
storage = new CosmosDbStorage(cosmosDbOptions);
}
else
{
storage = new MemoryStorage();
}
// Initialize skill state
var userState = new UserState(storage);
var conversationState = new ConversationState(storage);
// Create skill instance
try
{
var skillType = Type.GetType(_skillDefinition.Assembly);
_activatedSkill = (IBot)Activator.CreateInstance(skillType, _skillConfiguration, conversationState, userState, _telemetryClient, null, true);
}
catch (Exception e)
{
var message = $"Skill ({_skillDefinition.Name}) could not be created.";
throw new InvalidOperationException(message, e);
}
_inProcAdapter = new InProcAdapter
{
// set up skill turn error handling
OnTurnError = async (context, exception) =>
{
await context.SendActivityAsync(context.Activity.CreateReply(CommonResponses.ErrorMessage_SkillError));
await dc.Context.SendActivityAsync(new Activity(type: ActivityTypes.Trace, text: $"Skill Error: {exception.Message} | {exception.StackTrace}"));
// Log exception in AppInsights
_telemetryClient.TrackExceptionEx(exception, context.Activity);
},
};
_inProcAdapter.Use(new EventDebuggerMiddleware());
_inProcAdapter.Use(new SetLocaleMiddleware(dc.Context.Activity.Locale ?? "en-us"));
_inProcAdapter.Use(new AutoSaveStateMiddleware(userState, conversationState));
_skillInitialized = true;
}
catch
{
// something went wrong initializing the skill, so end dialog cleanly and throw so the error is logged
_skillInitialized = false;
await dc.EndDialogAsync();
throw;
}
}
private async Task<DialogTurnResult> ForwardToSkill(DialogContext innerDc, Activity activity)
{
try
{
if (!_skillInitialized)
{
await InitializeSkill(innerDc);
}
_inProcAdapter.ProcessActivity(activity, async (skillContext, ct) =>
{
await _activatedSkill.OnTurnAsync(skillContext);
}).Wait();
var queue = new List<Activity>();
var endOfConversation = false;
var skillResponse = _inProcAdapter.GetNextReply();
while (skillResponse != null)
{
if (skillResponse.Type == ActivityTypes.EndOfConversation)
{
endOfConversation = true;
}
else if (skillResponse?.Name == Events.TokenRequestEventName)
{
// Send trace to emulator
await innerDc.Context.SendActivityAsync(new Activity(type: ActivityTypes.Trace, text: $"<--Received a Token Request from a skill"));
if (!_useCachedTokens)
{
var adapter = innerDc.Context.Adapter as BotFrameworkAdapter;
var tokens = await adapter.GetTokenStatusAsync(innerDc.Context, innerDc.Context.Activity.From.Id);
foreach (var token in tokens)
{
await adapter.SignOutUserAsync(innerDc.Context, token.ConnectionName, innerDc.Context.Activity.From.Id, default(CancellationToken));
}
}
var authResult = await innerDc.BeginDialogAsync(nameof(MultiProviderAuthDialog));
if (authResult.Result?.GetType() == typeof(ProviderTokenResponse))
{
var tokenEvent = skillResponse.CreateReply();
tokenEvent.Type = ActivityTypes.Event;
tokenEvent.Name = Events.TokenResponseEventName;
tokenEvent.Value = authResult.Result as ProviderTokenResponse;
return await ForwardToSkill(innerDc, tokenEvent);
}
else
{
return authResult;
}
}
else
{
if (skillResponse.Type == ActivityTypes.Trace)
{
// Write out any trace messages from the skill to the emulator
await innerDc.Context.SendActivityAsync(skillResponse);
}
else
{
queue.Add(skillResponse);
}
}
skillResponse = _inProcAdapter.GetNextReply();
}
// send skill queue to User
if (queue.Count > 0)
{
var firstActivity = queue[0];
if (firstActivity.Conversation.Id == innerDc.Context.Activity.Conversation.Id)
{
// if the conversation id from the activity is the same as the context activity, it's reactive message
await innerDc.Context.SendActivitiesAsync(queue.ToArray());
}
else
{
// if the conversation id from the activity is differnt from the context activity, it's proactive message
await innerDc.Context.Adapter.ContinueConversationAsync(_endpointService.AppId, firstActivity.GetConversationReference(), CreateCallback(queue.ToArray()), default(CancellationToken));
}
}
// handle ending the skill conversation
if (endOfConversation)
{
await innerDc.Context.SendActivityAsync(new Activity(type: ActivityTypes.Trace, text: $"<--Ending the skill conversation"));
return await innerDc.EndDialogAsync();
}
else
{
return EndOfTurn;
}
}
catch
{
// something went wrong forwarding to the skill, so end dialog cleanly and throw so the error is logged.
// NOTE: errors within the skill itself are handled by the OnTurnError handler on the adapter.
await innerDc.EndDialogAsync();
throw;
}
}
private BotCallbackHandler CreateCallback(Activity[] activities)
{
return async (turnContext, token) =>
{
// Send back the activities in the proactive context
await turnContext.SendActivitiesAsync(activities, token);
};
}
private class Events
{
public const string SkillBeginEventName = "skillBegin";
public const string TokenRequestEventName = "tokens/request";
public const string TokenResponseEventName = "tokens/response";
}
}
} | 42.412371 | 207 | 0.552423 | [
"MIT"
] | geva/AI | solutions/Virtual-Assistant/src/csharp/microsoft.bot.solutions/Skills/SkillDialog.cs | 12,344 | C# |
using System.Collections.Generic;
namespace DotvvmAcademy.Validation
{
public class GlobalValidationDiagnostic : IValidationDiagnostic
{
public GlobalValidationDiagnostic(string message, IEnumerable<object> arguments, ValidationSeverity severity)
{
Message = message;
Arguments = arguments;
Severity = severity;
}
public IEnumerable<object> Arguments { get; }
public int End { get; } = -1;
public string Message { get; }
public ValidationSeverity Severity { get; }
public ISourceCode Source { get; } = null;
public int Start { get; } = -1;
public object UnderlyingObject { get; } = null;
}
} | 26 | 117 | 0.625 | [
"Apache-2.0"
] | ammogcoder/dotvvm-samples-academy | src/DotvvmAcademy.Validation/GlobalValidationDiagnostic.cs | 730 | C# |
using Newtonsoft.Json.Linq;
using Skybrud.Essentials.Json.Extensions;
namespace Skybrud.Social.Dropbox.Models.Files {
/// <summary>
/// Class representing the sharing information of a Dropbox folder.
/// </summary>
/// <see>
/// <cref>https://www.dropbox.com/developers/documentation/http/documentation#FolderSharingInfo</cref>
/// </see>
public class DropboxFolderSharingInfo : DropboxObject {
#region Properties
/// <summary>
/// <c>true</c> if the file or folder is inside a read-only shared folder.
/// </summary>
public bool ReadOnly { get; }
/// <summary>
/// Set if the folder is contained by a shared folder.
/// </summary>
public string ParentSharedFolderId { get; }
/// <summary>
/// If this folder is a shared folder mount point, the ID of the shared folder mounted at this location. This
/// field is optional.
/// </summary>
public string SharedFolderId { get; }
/// <summary>
/// Specifies that the folder can only be traversed and the user can only see a limited subset of the contents
/// of this folder because they don't have read access to this folder. They do, however, have access to some
/// sub folder.
/// </summary>
public bool TraverseOnly { get; }
/// <summary>
/// Specifies that the folder cannot be accessed by the user.
/// </summary>
public bool NoAccess { get; }
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance based on the specified <paramref name="obj"/>.
/// </summary>
/// <param name="obj">The instance of <see cref="JObject"/> to parse.</param>
protected DropboxFolderSharingInfo(JObject obj) : base(obj) {
ReadOnly = obj.GetBoolean("read_only");
ParentSharedFolderId = obj.GetString("parent_shared_folder_id");
SharedFolderId = obj.GetString("shared_folder_id");
TraverseOnly = obj.GetBoolean("traverse_only");
NoAccess = obj.GetBoolean("no_access");
}
#endregion
#region Static methods
/// <summary>
/// Gets an instance of <see cref="DropboxFolderSharingInfo"/> from the specified <paramref name="obj"/>.
/// </summary>
/// <param name="obj">The instance of <see cref="JObject"/> to parse.</param>
/// <returns>An instance of <see cref="DropboxFolderSharingInfo"/>.</returns>
public static DropboxFolderSharingInfo Parse(JObject obj) {
return obj == null ? null : new DropboxFolderSharingInfo(obj);
}
#endregion
}
} | 35.688312 | 118 | 0.606259 | [
"MIT"
] | abjerner/Skybrud.Social.Dropbox | src/Skybrud.Social.Dropbox/Models/Files/DropboxFolderSharingInfo.cs | 2,750 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using System.Threading;
using System.Diagnostics;
using System.Windows.Threading;
using Microsoft.Win32;
using System.Linq;
using System.Text;
using Sensorit.Base;
using DS4WinWPF.DS4Control;
using DS4Windows.DS4Control;
using Nefarius.ViGEm.Client;
using static DS4Windows.Global;
namespace DS4Windows
{
public class ControlService
{
public ViGEmClient vigemTestClient = null;
// Might be useful for ScpVBus build
public const int EXPANDED_CONTROLLER_COUNT = 8;
public const int MAX_DS4_CONTROLLER_COUNT = Global.MAX_DS4_CONTROLLER_COUNT;
#if FORCE_4_INPUT
public static int CURRENT_DS4_CONTROLLER_LIMIT = Global.OLD_XINPUT_CONTROLLER_COUNT;
#else
public static int CURRENT_DS4_CONTROLLER_LIMIT = Global.IsWin8OrGreater() ? MAX_DS4_CONTROLLER_COUNT : Global.OLD_XINPUT_CONTROLLER_COUNT;
#endif
public static bool USING_MAX_CONTROLLERS = CURRENT_DS4_CONTROLLER_LIMIT == EXPANDED_CONTROLLER_COUNT;
public DS4Device[] DS4Controllers = new DS4Device[MAX_DS4_CONTROLLER_COUNT];
public int activeControllers = 0;
public Mouse[] touchPad = new Mouse[MAX_DS4_CONTROLLER_COUNT];
public bool running = false;
public bool loopControllers = true;
public bool inServiceTask = false;
private DS4State[] MappedState = new DS4State[MAX_DS4_CONTROLLER_COUNT];
private DS4State[] CurrentState = new DS4State[MAX_DS4_CONTROLLER_COUNT];
private DS4State[] PreviousState = new DS4State[MAX_DS4_CONTROLLER_COUNT];
private DS4State[] TempState = new DS4State[MAX_DS4_CONTROLLER_COUNT];
public DS4StateExposed[] ExposedState = new DS4StateExposed[MAX_DS4_CONTROLLER_COUNT];
public ControllerSlotManager slotManager = new ControllerSlotManager();
public bool recordingMacro = false;
public event EventHandler<DebugEventArgs> Debug = null;
bool[] buttonsdown = new bool[MAX_DS4_CONTROLLER_COUNT] { false, false, false, false, false, false, false, false };
bool[] held = new bool[MAX_DS4_CONTROLLER_COUNT];
int[] oldmouse = new int[MAX_DS4_CONTROLLER_COUNT] { -1, -1, -1, -1, -1, -1, -1, -1 };
public OutputDevice[] outputDevices = new OutputDevice[MAX_DS4_CONTROLLER_COUNT] { null, null, null, null, null, null, null, null };
private OneEuroFilter3D[] udpEuroPairAccel = new OneEuroFilter3D[UdpServer.NUMBER_SLOTS]
{
new OneEuroFilter3D(), new OneEuroFilter3D(),
new OneEuroFilter3D(), new OneEuroFilter3D(),
};
private OneEuroFilter3D[] udpEuroPairGyro = new OneEuroFilter3D[UdpServer.NUMBER_SLOTS]
{
new OneEuroFilter3D(), new OneEuroFilter3D(),
new OneEuroFilter3D(), new OneEuroFilter3D(),
};
Thread tempThread;
Thread tempBusThread;
Thread eventDispatchThread;
Dispatcher eventDispatcher;
public bool suspending;
//SoundPlayer sp = new SoundPlayer();
private UdpServer _udpServer;
private OutputSlotManager outputslotMan;
private HashSet<string> hidDeviceHidingAffectedDevs = new HashSet<string>();
private HashSet<string> hidDeviceHidingExemptedDevs = new HashSet<string>();
private bool hidDeviceHidingForced = false;
private bool hidDeviceHidingEnabled = false;
private ControlServiceDeviceOptions deviceOptions;
public ControlServiceDeviceOptions DeviceOptions { get => deviceOptions; }
private DS4WinWPF.ArgumentParser cmdParser;
public event EventHandler ServiceStarted;
public event EventHandler PreServiceStop;
public event EventHandler ServiceStopped;
public event EventHandler RunningChanged;
//public event EventHandler HotplugFinished;
public delegate void HotplugControllerHandler(ControlService sender, DS4Device device, int index);
public event HotplugControllerHandler HotplugController;
private byte[][] udpOutBuffers = new byte[UdpServer.NUMBER_SLOTS][]
{
new byte[100], new byte[100],
new byte[100], new byte[100],
};
void GetPadDetailForIdx(int padIdx, ref DualShockPadMeta meta)
{
//meta = new DualShockPadMeta();
meta.PadId = (byte) padIdx;
meta.Model = DsModel.DS4;
var d = DS4Controllers[padIdx];
if (d == null || !d.PrimaryDevice)
{
meta.PadMacAddress = null;
meta.PadState = DsState.Disconnected;
meta.ConnectionType = DsConnection.None;
meta.Model = DsModel.None;
meta.BatteryStatus = 0;
meta.IsActive = false;
return;
//return meta;
}
bool isValidSerial = false;
string stringMac = d.getMacAddress();
if (!string.IsNullOrEmpty(stringMac))
{
stringMac = string.Join("", stringMac.Split(':'));
//stringMac = stringMac.Replace(":", "").Trim();
meta.PadMacAddress = System.Net.NetworkInformation.PhysicalAddress.Parse(stringMac);
isValidSerial = d.isValidSerial();
}
if (!isValidSerial)
{
//meta.PadMacAddress = null;
meta.PadState = DsState.Disconnected;
}
else
{
if (d.isSynced() || d.IsAlive())
meta.PadState = DsState.Connected;
else
meta.PadState = DsState.Reserved;
}
meta.ConnectionType = (d.getConnectionType() == ConnectionType.USB) ? DsConnection.Usb : DsConnection.Bluetooth;
meta.IsActive = !d.isDS4Idle();
int batteryLevel = d.getBattery();
if (d.isCharging() && batteryLevel >= 100)
meta.BatteryStatus = DsBattery.Charged;
else
{
if (batteryLevel >= 95)
meta.BatteryStatus = DsBattery.Full;
else if (batteryLevel >= 70)
meta.BatteryStatus = DsBattery.High;
else if (batteryLevel >= 50)
meta.BatteryStatus = DsBattery.Medium;
else if (batteryLevel >= 20)
meta.BatteryStatus = DsBattery.Low;
else if (batteryLevel >= 5)
meta.BatteryStatus = DsBattery.Dying;
else
meta.BatteryStatus = DsBattery.None;
}
//return meta;
}
private object busThrLck = new object();
private bool busThrRunning = false;
private Queue<Action> busEvtQueue = new Queue<Action>();
private object busEvtQueueLock = new object();
public ControlService(DS4WinWPF.ArgumentParser cmdParser)
{
this.cmdParser = cmdParser;
Crc32Algorithm.InitializeTable(DS4Device.DefaultPolynomial);
InitOutputKBMHandler();
//sp.Stream = DS4WinWPF.Properties.Resources.EE;
// Cause thread affinity to not be tied to main GUI thread
tempBusThread = new Thread(() =>
{
//_udpServer = new UdpServer(GetPadDetailForIdx);
busThrRunning = true;
while (busThrRunning)
{
lock (busEvtQueueLock)
{
Action tempAct = null;
for (int actInd = 0, actLen = busEvtQueue.Count; actInd < actLen; actInd++)
{
tempAct = busEvtQueue.Dequeue();
tempAct.Invoke();
}
}
lock (busThrLck)
Monitor.Wait(busThrLck);
}
});
tempBusThread.Priority = ThreadPriority.Normal;
tempBusThread.IsBackground = true;
tempBusThread.Start();
//while (_udpServer == null)
//{
// Thread.SpinWait(500);
//}
eventDispatchThread = new Thread(() =>
{
Dispatcher currentDis = Dispatcher.CurrentDispatcher;
eventDispatcher = currentDis;
Dispatcher.Run();
});
eventDispatchThread.IsBackground = true;
eventDispatchThread.Priority = ThreadPriority.Normal;
eventDispatchThread.Name = "ControlService Events";
eventDispatchThread.Start();
for (int i = 0, arlength = DS4Controllers.Length; i < arlength; i++)
{
MappedState[i] = new DS4State();
CurrentState[i] = new DS4State();
TempState[i] = new DS4State();
PreviousState[i] = new DS4State();
ExposedState[i] = new DS4StateExposed(CurrentState[i]);
int tempDev = i;
Global.L2OutputSettings[i].TwoStageModeChanged += (sender, e) =>
{
Mapping.l2TwoStageMappingData[tempDev].Reset();
};
Global.R2OutputSettings[i].TwoStageModeChanged += (sender, e) =>
{
Mapping.r2TwoStageMappingData[tempDev].Reset();
};
}
outputslotMan = new OutputSlotManager();
deviceOptions = Global.DeviceOptions;
DS4Devices.RequestElevation += DS4Devices_RequestElevation;
DS4Devices.checkVirtualFunc = CheckForVirtualDevice;
DS4Devices.PrepareDS4Init = PrepareDS4DeviceInit;
DS4Devices.PostDS4Init = PostDS4DeviceInit;
DS4Devices.PreparePendingDevice = CheckForSupportedDevice;
outputslotMan.ViGEmFailure += OutputslotMan_ViGEmFailure;
Global.UDPServerSmoothingMincutoffChanged += ChangeUdpSmoothingAttrs;
Global.UDPServerSmoothingBetaChanged += ChangeUdpSmoothingAttrs;
}
public void RefreshOutputKBMHandler()
{
if (Global.outputKBMHandler != null)
{
Global.outputKBMHandler.Disconnect();
Global.outputKBMHandler = null;
}
if (Global.outputKBMMapping != null)
{
Global.outputKBMMapping = null;
}
InitOutputKBMHandler();
}
private void InitOutputKBMHandler()
{
string attemptVirtualkbmHandler = cmdParser.VirtualkbmHandler;
Global.InitOutputKBMHandler(attemptVirtualkbmHandler);
if (!Global.outputKBMHandler.Connect() &&
attemptVirtualkbmHandler != VirtualKBMFactory.GetFallbackHandlerIdentifier())
{
Global.outputKBMHandler = VirtualKBMFactory.GetFallbackHandler();
}
else
{
// Connection was made. Check if version number should get populated
if (outputKBMHandler.GetIdentifier() == FakerInputHandler.IDENTIFIER)
{
Global.outputKBMHandler.Version = Global.fakerInputVersion;
}
}
Global.InitOutputKBMMapping(Global.outputKBMHandler.GetIdentifier());
Global.outputKBMMapping.PopulateConstants();
Global.outputKBMMapping.PopulateMappings();
}
private void OutputslotMan_ViGEmFailure(object sender, EventArgs e)
{
eventDispatcher.BeginInvoke((Action)(() =>
{
loopControllers = false;
while (inServiceTask)
Thread.SpinWait(1000);
LogDebug(DS4WinWPF.Translations.Strings.ViGEmPluginFailure, true);
Stop();
}));
}
public void PostDS4DeviceInit(DS4Device device)
{
if (device.DeviceType == InputDevices.InputDeviceType.JoyConL ||
device.DeviceType == InputDevices.InputDeviceType.JoyConR)
{
if (deviceOptions.JoyConDeviceOpts.LinkedMode == JoyConDeviceOptions.LinkMode.Joined)
{
InputDevices.JoyConDevice tempJoyDev = device as InputDevices.JoyConDevice;
tempJoyDev.PerformStateMerge = true;
if (device.DeviceType == InputDevices.InputDeviceType.JoyConL)
{
tempJoyDev.PrimaryDevice = true;
if (deviceOptions.JoyConDeviceOpts.JoinGyroProv == JoyConDeviceOptions.JoinedGyroProvider.JoyConL)
{
tempJoyDev.OutputMapGyro = true;
}
else
{
tempJoyDev.OutputMapGyro = false;
}
}
else
{
tempJoyDev.PrimaryDevice = false;
if (deviceOptions.JoyConDeviceOpts.JoinGyroProv == JoyConDeviceOptions.JoinedGyroProvider.JoyConR)
{
tempJoyDev.OutputMapGyro = true;
}
else
{
tempJoyDev.OutputMapGyro = false;
}
}
}
}
}
private void PrepareDS4DeviceSettingHooks(DS4Device device)
{
if (device.DeviceType == InputDevices.InputDeviceType.DualSense)
{
InputDevices.DualSenseDevice tempDSDev = device as InputDevices.DualSenseDevice;
DualSenseControllerOptions dSOpts = tempDSDev.NativeOptionsStore;
dSOpts.LedModeChanged += (sender, e) => { tempDSDev.CheckControllerNumDeviceSettings(activeControllers); };
}
else if (device.DeviceType == InputDevices.InputDeviceType.JoyConL ||
device.DeviceType == InputDevices.InputDeviceType.JoyConR)
{
}
}
public bool CheckForSupportedDevice(HidDevice device, VidPidInfo metaInfo)
{
bool result = false;
switch (metaInfo.inputDevType)
{
case InputDevices.InputDeviceType.DS4:
result = deviceOptions.DS4DeviceOpts.Enabled;
break;
case InputDevices.InputDeviceType.DualSense:
result = deviceOptions.DualSenseOpts.Enabled;
break;
case InputDevices.InputDeviceType.SwitchPro:
result = deviceOptions.SwitchProDeviceOpts.Enabled;
break;
case InputDevices.InputDeviceType.JoyConL:
case InputDevices.InputDeviceType.JoyConR:
result = deviceOptions.JoyConDeviceOpts.Enabled;
break;
default:
break;
}
return result;
}
public void PrepareDS4DeviceInit(DS4Device device)
{
if (!Global.IsWin8OrGreater())
{
device.BTOutputMethod = DS4Device.BTOutputReportMethod.HidD_SetOutputReport;
}
}
public CheckVirtualInfo CheckForVirtualDevice(string deviceInstanceId)
{
string temp = Global.GetDeviceProperty(deviceInstanceId,
NativeMethods.DEVPKEY_Device_UINumber);
CheckVirtualInfo info = new CheckVirtualInfo()
{
PropertyValue = temp,
DeviceInstanceId = deviceInstanceId,
};
return info;
}
public void ShutDown()
{
DS4Devices.checkVirtualFunc = null;
outputslotMan.ShutDown();
OutputSlotPersist.WriteConfig(outputslotMan);
outputKBMHandler.Disconnect();
eventDispatcher.InvokeShutdown();
eventDispatcher = null;
eventDispatchThread.Join();
eventDispatchThread = null;
}
private void DS4Devices_RequestElevation(RequestElevationArgs args)
{
// Launches an elevated child process to re-enable device
ProcessStartInfo startInfo =
new ProcessStartInfo(Global.exelocation);
startInfo.Verb = "runas";
startInfo.Arguments = "re-enabledevice " + args.InstanceId;
startInfo.UseShellExecute = true;
try
{
Process child = Process.Start(startInfo);
if (!child.WaitForExit(30000))
{
child.Kill();
}
else
{
args.StatusCode = child.ExitCode;
}
child.Dispose();
}
catch { }
}
public void CheckHidHidePresence()
{
if (Global.hidHideInstalled)
{
LogDebug("HidHide control device found");
using (HidHideAPIDevice hidHideDevice = new HidHideAPIDevice())
{
if (!hidHideDevice.IsOpen())
{
return;
}
List<string> dosPaths = hidHideDevice.GetWhitelist();
int maxPathCheckLength = 512;
StringBuilder sb = new StringBuilder(maxPathCheckLength);
string driveLetter = Path.GetPathRoot(Global.exelocation).Replace("\\", "");
uint _ = NativeMethods.QueryDosDevice(driveLetter, sb, maxPathCheckLength);
//int error = Marshal.GetLastWin32Error();
string dosDrivePath = sb.ToString();
// Strip a possible \??\ prefix.
if (dosDrivePath.StartsWith(@"\??\"))
{
dosDrivePath = dosDrivePath.Remove(0, 4);
}
string partial = Global.exelocation.Replace(driveLetter, "");
// Need to trim starting '\\' from path2 or Path.Combine will
// treat it as an absolute path and only return path2
string realPath = Path.Combine(dosDrivePath, partial.TrimStart('\\'));
bool exists = dosPaths.Contains(realPath);
if (!exists)
{
LogDebug("DS4Windows not found in HidHide whitelist. Adding DS4Windows to list");
dosPaths.Add(realPath);
hidHideDevice.SetWhitelist(dosPaths);
}
}
}
}
public void LoadPermanentSlotsConfig()
{
OutputSlotPersist.ReadConfig(outputslotMan);
}
public void UpdateHidHideAttributes()
{
if (Global.hidHideInstalled)
{
hidDeviceHidingAffectedDevs.Clear();
hidDeviceHidingExemptedDevs.Clear(); // No known equivalent in HidHide
hidDeviceHidingForced = false; // No known equivalent in HidHide
hidDeviceHidingEnabled = false;
using (HidHideAPIDevice hidHideDevice = new HidHideAPIDevice())
{
if (!hidHideDevice.IsOpen())
{
return;
}
bool active = hidHideDevice.GetActiveState();
List<string> instances = hidHideDevice.GetBlacklist();
hidDeviceHidingEnabled = active;
foreach (string instance in instances)
{
hidDeviceHidingAffectedDevs.Add(instance.ToUpper());
}
}
}
}
public void UpdateHidHiddenAttributes()
{
if (Global.hidHideInstalled)
{
UpdateHidHideAttributes();
}
}
private bool CheckAffected(DS4Device dev)
{
bool result = false;
if (dev != null && hidDeviceHidingEnabled)
{
string deviceInstanceId = DS4Devices.devicePathToInstanceId(dev.HidDevice.DevicePath);
if (Global.hidHideInstalled)
{
result = Global.CheckHidHideAffectedStatus(deviceInstanceId,
hidDeviceHidingAffectedDevs, hidDeviceHidingExemptedDevs, hidDeviceHidingForced);
}
}
return result;
}
private List<DS4Controls> GetKnownExtraButtons(DS4Device dev)
{
List<DS4Controls> result = new List<DS4Controls>();
switch (dev.DeviceType)
{
case InputDevices.InputDeviceType.JoyConL:
case InputDevices.InputDeviceType.JoyConR:
result.AddRange(new DS4Controls[] { DS4Controls.Capture, DS4Controls.SideL, DS4Controls.SideR });
break;
case InputDevices.InputDeviceType.SwitchPro:
result.AddRange(new DS4Controls[] { DS4Controls.Capture });
break;
default:
break;
}
return result;
}
private void ChangeExclusiveStatus(DS4Device dev)
{
if (Global.hidHideInstalled)
{
dev.CurrentExclusiveStatus = DS4Device.ExclusiveStatus.HidHideAffected;
}
}
private void TestQueueBus(Action temp)
{
lock (busEvtQueueLock)
{
busEvtQueue.Enqueue(temp);
}
lock (busThrLck)
Monitor.Pulse(busThrLck);
}
public void ChangeUDPStatus(bool state, bool openPort=true)
{
if (state && _udpServer == null)
{
udpChangeStatus = true;
TestQueueBus(() =>
{
_udpServer = new UdpServer(GetPadDetailForIdx);
if (openPort)
{
// Change thread affinity of object to have normal priority
Task.Run(() =>
{
var UDP_SERVER_PORT = Global.getUDPServerPortNum();
var UDP_SERVER_LISTEN_ADDRESS = Global.getUDPServerListenAddress();
try
{
_udpServer.Start(UDP_SERVER_PORT, UDP_SERVER_LISTEN_ADDRESS);
LogDebug($"UDP server listening on address {UDP_SERVER_LISTEN_ADDRESS} port {UDP_SERVER_PORT}");
}
catch (System.Net.Sockets.SocketException ex)
{
var errMsg = String.Format("Couldn't start UDP server on address {0}:{1}, outside applications won't be able to access pad data ({2})", UDP_SERVER_LISTEN_ADDRESS, UDP_SERVER_PORT, ex.SocketErrorCode);
LogDebug(errMsg, true);
AppLogger.LogToTray(errMsg, true, true);
}
}).Wait();
}
udpChangeStatus = false;
});
}
else if (!state && _udpServer != null)
{
TestQueueBus(() =>
{
udpChangeStatus = true;
_udpServer.Stop();
_udpServer = null;
AppLogger.LogToGui("Closed UDP server", false);
udpChangeStatus = false;
for (int i = 0; i < UdpServer.NUMBER_SLOTS; i++)
{
ResetUdpSmoothingFilters(i);
}
});
}
}
public void ChangeMotionEventStatus(bool state)
{
IEnumerable<DS4Device> devices = DS4Devices.getDS4Controllers();
if (state)
{
int i = 0;
foreach (DS4Device dev in devices)
{
int tempIdx = i;
dev.queueEvent(() =>
{
if (i < UdpServer.NUMBER_SLOTS && dev.PrimaryDevice)
{
PrepareDevUDPMotion(dev, tempIdx);
}
});
i++;
}
}
else
{
foreach (DS4Device dev in devices)
{
dev.queueEvent(() =>
{
if (dev.MotionEvent != null)
{
dev.Report -= dev.MotionEvent;
dev.MotionEvent = null;
}
});
}
}
}
private bool udpChangeStatus = false;
public bool changingUDPPort = false;
public async void UseUDPPort()
{
changingUDPPort = true;
IEnumerable<DS4Device> devices = DS4Devices.getDS4Controllers();
foreach (DS4Device dev in devices)
{
dev.queueEvent(() =>
{
if (dev.MotionEvent != null)
{
dev.Report -= dev.MotionEvent;
}
});
}
await Task.Delay(100);
var UDP_SERVER_PORT = Global.getUDPServerPortNum();
var UDP_SERVER_LISTEN_ADDRESS = Global.getUDPServerListenAddress();
try
{
_udpServer.Start(UDP_SERVER_PORT, UDP_SERVER_LISTEN_ADDRESS);
foreach (DS4Device dev in devices)
{
dev.queueEvent(() =>
{
if (dev.MotionEvent != null)
{
dev.Report += dev.MotionEvent;
}
});
}
LogDebug($"UDP server listening on address {UDP_SERVER_LISTEN_ADDRESS} port {UDP_SERVER_PORT}");
}
catch (System.Net.Sockets.SocketException ex)
{
var errMsg = String.Format("Couldn't start UDP server on address {0}:{1}, outside applications won't be able to access pad data ({2})", UDP_SERVER_LISTEN_ADDRESS, UDP_SERVER_PORT, ex.SocketErrorCode);
LogDebug(errMsg, true);
AppLogger.LogToTray(errMsg, true, true);
}
changingUDPPort = false;
}
private void WarnExclusiveModeFailure(DS4Device device)
{
if (DS4Devices.isExclusiveMode && !device.isExclusive())
{
string message = DS4WinWPF.Properties.Resources.CouldNotOpenDS4.Replace("*Mac address*", device.getMacAddress()) + " " +
DS4WinWPF.Properties.Resources.QuitOtherPrograms;
LogDebug(message, true);
AppLogger.LogToTray(message, true);
}
}
private void StartViGEm()
{
// Refresh internal ViGEmBus info
Global.RefreshViGEmBusInfo();
if (Global.IsRunningSupportedViGEmBus())
{
tempThread = new Thread(() =>
{
try
{
vigemTestClient = new ViGEmClient();
}
catch {}
});
tempThread.Priority = ThreadPriority.AboveNormal;
tempThread.IsBackground = true;
tempThread.Start();
while (tempThread.IsAlive)
{
Thread.SpinWait(500);
}
}
tempThread = null;
}
private void StopViGEm()
{
if (vigemTestClient != null)
{
vigemTestClient.Dispose();
vigemTestClient = null;
}
}
public void AssignInitialDevices()
{
foreach(OutSlotDevice slotDevice in outputslotMan.OutputSlots)
{
if (slotDevice.CurrentReserveStatus ==
OutSlotDevice.ReserveStatus.Permanent)
{
OutputDevice outDevice = EstablishOutDevice(0, slotDevice.PermanentType);
outputslotMan.DeferredPlugin(outDevice, -1, outputDevices, slotDevice.PermanentType);
}
}
/*OutSlotDevice slotDevice =
outputslotMan.FindExistUnboundSlotType(OutContType.X360);
if (slotDevice == null)
{
slotDevice = outputslotMan.FindOpenSlot();
slotDevice.CurrentReserveStatus = OutSlotDevice.ReserveStatus.Permanent;
slotDevice.PermanentType = OutContType.X360;
OutputDevice outDevice = EstablishOutDevice(0, OutContType.X360);
Xbox360OutDevice tempXbox = outDevice as Xbox360OutDevice;
outputslotMan.DeferredPlugin(tempXbox, -1, outputDevices, OutContType.X360);
}
*/
/*slotDevice = outputslotMan.FindExistUnboundSlotType(OutContType.X360);
if (slotDevice == null)
{
slotDevice = outputslotMan.FindOpenSlot();
slotDevice.CurrentReserveStatus = OutSlotDevice.ReserveStatus.Permanent;
slotDevice.DesiredType = OutContType.X360;
OutputDevice outDevice = EstablishOutDevice(1, OutContType.X360);
Xbox360OutDevice tempXbox = outDevice as Xbox360OutDevice;
outputslotMan.DeferredPlugin(tempXbox, 1, outputDevices);
}*/
}
private OutputDevice EstablishOutDevice(int index, OutContType contType)
{
OutputDevice temp = null;
temp = outputslotMan.AllocateController(contType, vigemTestClient);
return temp;
}
public void EstablishOutFeedback(int index, OutContType contType,
OutputDevice outDevice, DS4Device device)
{
int devIndex = index;
if (contType == OutContType.X360)
{
Xbox360OutDevice tempXbox = outDevice as Xbox360OutDevice;
Nefarius.ViGEm.Client.Targets.Xbox360FeedbackReceivedEventHandler p = (sender, args) =>
{
//Console.WriteLine("Rumble ({0}, {1}) {2}",
// args.LargeMotor, args.SmallMotor, DateTime.Now.ToString("hh:mm:ss.FFFF"));
SetDevRumble(device, args.LargeMotor, args.SmallMotor, devIndex);
};
tempXbox.cont.FeedbackReceived += p;
tempXbox.forceFeedbacksDict.Add(index, p);
}
//else if (contType == OutContType.DS4)
//{
// DS4OutDevice tempDS4 = outDevice as DS4OutDevice;
// LightbarSettingInfo deviceLightbarSettingsInfo = Global.LightbarSettingsInfo[devIndex];
// Nefarius.ViGEm.Client.Targets.DualShock4FeedbackReceivedEventHandler p = (sender, args) =>
// {
// bool useRumble = false; bool useLight = false;
// byte largeMotor = args.LargeMotor;
// byte smallMotor = args.SmallMotor;
// //SetDevRumble(device, largeMotor, smallMotor, devIndex);
// DS4Color color = new DS4Color(args.LightbarColor.Red,
// args.LightbarColor.Green,
// args.LightbarColor.Blue);
// //Console.WriteLine("IN EVENT");
// //Console.WriteLine("Rumble ({0}, {1}) | Light ({2}, {3}, {4}) {5}",
// // largeMotor, smallMotor, color.red, color.green, color.blue, DateTime.Now.ToString("hh:mm:ss.FFFF"));
// if (largeMotor != 0 || smallMotor != 0)
// {
// useRumble = true;
// }
// // Let games to control lightbar only when the mode is Passthru (otherwise DS4Windows controls the light)
// if (deviceLightbarSettingsInfo.Mode == LightbarMode.Passthru && (color.red != 0 || color.green != 0 || color.blue != 0))
// {
// useLight = true;
// }
// if (!useRumble && !useLight)
// {
// //Console.WriteLine("Fallback");
// if (device.LeftHeavySlowRumble != 0 || device.RightLightFastRumble != 0)
// {
// useRumble = true;
// }
// else if (deviceLightbarSettingsInfo.Mode == LightbarMode.Passthru &&
// (device.LightBarColor.red != 0 ||
// device.LightBarColor.green != 0 ||
// device.LightBarColor.blue != 0))
// {
// useLight = true;
// }
// }
// if (useRumble)
// {
// //Console.WriteLine("Perform rumble");
// SetDevRumble(device, largeMotor, smallMotor, devIndex);
// }
// if (useLight)
// {
// //Console.WriteLine("Change lightbar color");
// /*DS4HapticState haptics = new DS4HapticState
// {
// LightBarColor = color,
// };
// device.SetHapticState(ref haptics);
// */
// DS4LightbarState lightState = new DS4LightbarState
// {
// LightBarColor = color,
// };
// device.SetLightbarState(ref lightState);
// }
// //Console.WriteLine();
// };
// tempDS4.cont.FeedbackReceived += p;
// tempDS4.forceFeedbacksDict.Add(index, p);
//}
}
public void RemoveOutFeedback(OutContType contType, OutputDevice outDevice, int inIdx)
{
if (contType == OutContType.X360)
{
Xbox360OutDevice tempXbox = outDevice as Xbox360OutDevice;
tempXbox.RemoveFeedback(inIdx);
//tempXbox.cont.FeedbackReceived -= tempXbox.forceFeedbackCall;
//tempXbox.forceFeedbackCall = null;
}
//else if (contType == OutContType.DS4)
//{
// DS4OutDevice tempDS4 = outDevice as DS4OutDevice;
// tempDS4.RemoveFeedback(inIdx);
// //tempDS4.cont.FeedbackReceived -= tempDS4.forceFeedbackCall;
// //tempDS4.forceFeedbackCall = null;
//}
}
public void AttachNewUnboundOutDev(OutContType contType)
{
OutSlotDevice slotDevice = outputslotMan.FindOpenSlot();
if (slotDevice != null &&
slotDevice.CurrentAttachedStatus == OutSlotDevice.AttachedStatus.UnAttached)
{
OutputDevice outDevice = EstablishOutDevice(-1, contType);
outputslotMan.DeferredPlugin(outDevice, -1, outputDevices, contType);
LogDebug($"Plugging virtual {contType} Controller");
}
}
public void AttachUnboundOutDev(OutSlotDevice slotDevice, OutContType contType)
{
if (slotDevice.CurrentAttachedStatus == OutSlotDevice.AttachedStatus.UnAttached &&
slotDevice.CurrentInputBound == OutSlotDevice.InputBound.Unbound)
{
OutputDevice outDevice = EstablishOutDevice(-1, contType);
outputslotMan.DeferredPlugin(outDevice, -1, outputDevices, contType);
LogDebug($"Plugging virtual {contType} Controller");
}
}
public void DetachUnboundOutDev(OutSlotDevice slotDevice)
{
if (slotDevice.CurrentInputBound == OutSlotDevice.InputBound.Unbound)
{
OutputDevice dev = slotDevice.OutputDevice;
string tempType = dev.GetDeviceType();
slotDevice.CurrentInputBound = OutSlotDevice.InputBound.Unbound;
outputslotMan.DeferredRemoval(dev, -1, outputDevices, false);
LogDebug($"Unplugging virtual {tempType} Controller");
}
}
public void PluginOutDev(int index, DS4Device device)
{
OutContType contType = Global.OutContType[index];
OutSlotDevice slotDevice = null;
if (!getDInputOnly(index))
{
slotDevice = outputslotMan.FindExistUnboundSlotType(contType);
}
if (useDInputOnly[index])
{
bool success = false;
if (contType == OutContType.X360)
{
activeOutDevType[index] = OutContType.X360;
if (slotDevice == null)
{
slotDevice = outputslotMan.FindOpenSlot();
if (slotDevice != null)
{
Xbox360OutDevice tempXbox = EstablishOutDevice(index, OutContType.X360)
as Xbox360OutDevice;
//outputDevices[index] = tempXbox;
// Enable ViGem feedback callback handler only if lightbar/rumble data output is enabled (if those are disabled then no point enabling ViGem callback handler call)
if (Global.EnableOutputDataToDS4[index])
{
EstablishOutFeedback(index, OutContType.X360, tempXbox, device);
if (device.JointDeviceSlotNumber != -1)
{
DS4Device tempDS4Device = DS4Controllers[device.JointDeviceSlotNumber];
if (tempDS4Device != null)
{
EstablishOutFeedback(device.JointDeviceSlotNumber, OutContType.X360, tempXbox, tempDS4Device);
}
}
}
outputslotMan.DeferredPlugin(tempXbox, index, outputDevices, contType);
//slotDevice.CurrentInputBound = OutSlotDevice.InputBound.Bound;
LogDebug("Plugging in virtual X360 Controller");
success = true;
}
else
{
LogDebug("Failed. No open output slot found");
}
}
else
{
slotDevice.CurrentInputBound = OutSlotDevice.InputBound.Bound;
Xbox360OutDevice tempXbox = slotDevice.OutputDevice as Xbox360OutDevice;
// Enable ViGem feedback callback handler only if lightbar/rumble data output is enabled (if those are disabled then no point enabling ViGem callback handler call)
if (Global.EnableOutputDataToDS4[index])
{
EstablishOutFeedback(index, OutContType.X360, tempXbox, device);
if (device.JointDeviceSlotNumber != -1)
{
DS4Device tempDS4Device = DS4Controllers[device.JointDeviceSlotNumber];
if (tempDS4Device != null)
{
EstablishOutFeedback(device.JointDeviceSlotNumber, OutContType.X360, tempXbox, tempDS4Device);
}
}
}
outputDevices[index] = tempXbox;
slotDevice.CurrentType = contType;
success = true;
}
if (success)
{
LogDebug($"Associate X360 Controller in{(slotDevice.PermanentType != OutContType.None ? " permanent" : "")} slot #{slotDevice.Index + 1} for input {device.DisplayName} controller #{index + 1}");
}
//tempXbox.Connect();
//LogDebug("X360 Controller #" + (index + 1) + " connected");
}
else if (contType == OutContType.DS4)
{
activeOutDevType[index] = OutContType.DS4;
if (slotDevice == null)
{
slotDevice = outputslotMan.FindOpenSlot();
if (slotDevice != null)
{
DS4OutDevice tempDS4 = EstablishOutDevice(index, OutContType.DS4)
as DS4OutDevice;
// Enable ViGem feedback callback handler only if DS4 lightbar/rumble data output is enabled (if those are disabled then no point enabling ViGem callback handler call)
if (Global.EnableOutputDataToDS4[index])
{
EstablishOutFeedback(index, OutContType.DS4, tempDS4, device);
if (device.JointDeviceSlotNumber != -1)
{
DS4Device tempDS4Device = DS4Controllers[device.JointDeviceSlotNumber];
if (tempDS4Device != null)
{
EstablishOutFeedback(device.JointDeviceSlotNumber, OutContType.DS4, tempDS4, tempDS4Device);
}
}
}
outputslotMan.DeferredPlugin(tempDS4, index, outputDevices, contType);
//slotDevice.CurrentInputBound = OutSlotDevice.InputBound.Bound;
LogDebug("Plugging in virtual DS4 Controller");
success = true;
}
else
{
LogDebug("Failed. No open output slot found");
}
}
else
{
slotDevice.CurrentInputBound = OutSlotDevice.InputBound.Bound;
DS4OutDevice tempDS4 = slotDevice.OutputDevice as DS4OutDevice;
// Enable ViGem feedback callback handler only if lightbar/rumble data output is enabled (if those are disabled then no point enabling ViGem callback handler call)
if (Global.EnableOutputDataToDS4[index])
{
EstablishOutFeedback(index, OutContType.DS4, tempDS4, device);
if (device.JointDeviceSlotNumber != -1)
{
DS4Device tempDS4Device = DS4Controllers[device.JointDeviceSlotNumber];
if (tempDS4Device != null)
{
EstablishOutFeedback(device.JointDeviceSlotNumber, OutContType.DS4, tempDS4, tempDS4Device);
}
}
}
outputDevices[index] = tempDS4;
slotDevice.CurrentType = contType;
success = true;
}
if (success)
{
LogDebug($"Associate DS4 Controller in{(slotDevice.PermanentType != OutContType.None ? " permanent" : "")} slot #{slotDevice.Index + 1} for input {device.DisplayName} controller #{index + 1}");
}
//DS4OutDevice tempDS4 = new DS4OutDevice(vigemTestClient);
//DS4OutDevice tempDS4 = outputslotMan.AllocateController(OutContType.DS4, vigemTestClient)
// as DS4OutDevice;
//outputDevices[index] = tempDS4;
//tempDS4.Connect();
//LogDebug("DS4 Controller #" + (index + 1) + " connected");
}
if (success)
{
useDInputOnly[index] = false;
}
}
}
public void UnplugOutDev(int index, DS4Device device, bool immediate = false, bool force = false)
{
if (!useDInputOnly[index])
{
//OutContType contType = Global.OutContType[index];
OutputDevice dev = outputDevices[index];
OutSlotDevice slotDevice = outputslotMan.GetOutSlotDevice(dev);
if (dev != null && slotDevice != null)
{
string tempType = dev.GetDeviceType();
LogDebug($"Disassociate {tempType} Controller from{(slotDevice.CurrentReserveStatus == OutSlotDevice.ReserveStatus.Permanent ? " permanent" : "")} slot #{slotDevice.Index+1} for input {device.DisplayName} controller #{index + 1}", false);
OutContType currentType = activeOutDevType[index];
outputDevices[index] = null;
activeOutDevType[index] = OutContType.None;
if ((slotDevice.CurrentAttachedStatus == OutSlotDevice.AttachedStatus.Attached &&
slotDevice.CurrentReserveStatus == OutSlotDevice.ReserveStatus.Dynamic) || force)
{
//slotDevice.CurrentInputBound = OutSlotDevice.InputBound.Unbound;
outputslotMan.DeferredRemoval(dev, index, outputDevices, immediate);
LogDebug($"Unplugging virtual {tempType} Controller");
}
else if (slotDevice.CurrentAttachedStatus == OutSlotDevice.AttachedStatus.Attached)
{
slotDevice.CurrentInputBound = OutSlotDevice.InputBound.Unbound;
dev.ResetState();
dev.RemoveFeedbacks();
//RemoveOutFeedback(currentType, dev);
}
//dev.Disconnect();
//LogDebug(tempType + " Controller # " + (index + 1) + " unplugged");
}
useDInputOnly[index] = true;
}
}
public bool Start(bool showlog = true)
{
inServiceTask = true;
StartViGEm();
if (vigemTestClient != null)
//if (x360Bus.Open() && x360Bus.Start())
{
if (showlog)
LogDebug(DS4WinWPF.Properties.Resources.Starting);
LogDebug($"Using output KB+M handler: {DS4Windows.Global.outputKBMHandler.GetFullDisplayName()}");
LogDebug($"Connection to ViGEmBus {Global.vigembusVersion} established");
DS4Devices.isExclusiveMode = getUseExclusiveMode(); //Re-enable Exclusive Mode
UpdateHidHiddenAttributes();
//uiContext = tempui as SynchronizationContext;
if (showlog)
{
LogDebug(DS4WinWPF.Properties.Resources.SearchingController);
LogDebug(DS4Devices.isExclusiveMode ? DS4WinWPF.Properties.Resources.UsingExclusive : DS4WinWPF.Properties.Resources.UsingShared);
}
if (isUsingUDPServer() && _udpServer == null)
{
ChangeUDPStatus(true, false);
while (udpChangeStatus == true)
{
Thread.SpinWait(500);
}
}
try
{
loopControllers = true;
AssignInitialDevices();
eventDispatcher.Invoke(() =>
{
DS4Devices.findControllers();
});
IEnumerable<DS4Device> devices = DS4Devices.getDS4Controllers();
int numControllers = new List<DS4Device>(devices).Count;
activeControllers = numControllers;
//int ind = 0;
DS4LightBar.defaultLight = false;
//foreach (DS4Device device in devices)
//for (int i = 0, devCount = devices.Count(); i < devCount; i++)
int i = 0;
InputDevices.JoyConDevice tempPrimaryJoyDev = null;
for (var devEnum = devices.GetEnumerator(); devEnum.MoveNext() && loopControllers; i++)
{
DS4Device device = devEnum.Current;
if (showlog)
LogDebug(DS4WinWPF.Properties.Resources.FoundController + " " + device.getMacAddress() + " (" + device.getConnectionType() + ") (" +
device.DisplayName + ")");
if (hidDeviceHidingEnabled && CheckAffected(device))
{
//device.CurrentExclusiveStatus = DS4Device.ExclusiveStatus.HidGuardAffected;
ChangeExclusiveStatus(device);
}
Task task = new Task(() => { Thread.Sleep(5); WarnExclusiveModeFailure(device); });
task.Start();
PrepareDS4DeviceSettingHooks(device);
if (deviceOptions.JoyConDeviceOpts.LinkedMode == JoyConDeviceOptions.LinkMode.Joined)
{
if ((device.DeviceType == InputDevices.InputDeviceType.JoyConL ||
device.DeviceType == InputDevices.InputDeviceType.JoyConR) && device.PerformStateMerge)
{
if (tempPrimaryJoyDev == null)
{
tempPrimaryJoyDev = device as InputDevices.JoyConDevice;
}
else
{
InputDevices.JoyConDevice currentJoyDev = device as InputDevices.JoyConDevice;
tempPrimaryJoyDev.JointDevice = currentJoyDev;
currentJoyDev.JointDevice = tempPrimaryJoyDev;
tempPrimaryJoyDev.JointState = currentJoyDev.JointState;
InputDevices.JoyConDevice parentJoy = tempPrimaryJoyDev;
tempPrimaryJoyDev.Removal += (sender, args) => { currentJoyDev.JointDevice = null; };
currentJoyDev.Removal += (sender, args) => { parentJoy.JointDevice = null; };
tempPrimaryJoyDev = null;
}
}
}
DS4Controllers[i] = device;
device.DeviceSlotNumber = i;
Global.RefreshExtrasButtons(i, GetKnownExtraButtons(device));
Global.LoadControllerConfigs(device);
device.LoadStoreSettings();
device.CheckControllerNumDeviceSettings(numControllers);
slotManager.AddController(device, i);
device.Removal += this.On_DS4Removal;
device.Removal += DS4Devices.On_Removal;
device.SyncChange += this.On_SyncChange;
device.SyncChange += DS4Devices.UpdateSerial;
device.SerialChange += this.On_SerialChange;
device.ChargingChanged += CheckQuickCharge;
touchPad[i] = new Mouse(i, device);
bool profileLoaded = false;
bool useAutoProfile = useTempProfile[i];
if (!useAutoProfile)
{
if (device.isValidSerial() && containsLinkedProfile(device.getMacAddress()))
{
ProfilePath[i] = getLinkedProfile(device.getMacAddress());
Global.linkedProfileCheck[i] = true;
}
else
{
ProfilePath[i] = OlderProfilePath[i];
Global.linkedProfileCheck[i] = false;
}
profileLoaded = LoadProfile(i, false, this, false, false);
}
if (profileLoaded || useAutoProfile)
{
device.LightBarColor = getMainColor(i);
if (!getDInputOnly(i) && device.isSynced())
{
if (device.PrimaryDevice)
{
PluginOutDev(i, device);
}
else if (device.JointDeviceSlotNumber != DS4Device.DEFAULT_JOINT_SLOT_NUMBER)
{
int otherIdx = device.JointDeviceSlotNumber;
OutputDevice tempOutDev = outputDevices[otherIdx];
if (tempOutDev != null)
{
OutContType tempConType = activeOutDevType[otherIdx];
EstablishOutFeedback(i, tempConType, tempOutDev, device);
outputDevices[i] = tempOutDev;
Global.activeOutDevType[i] = tempConType;
}
}
}
else
{
useDInputOnly[i] = true;
Global.activeOutDevType[i] = OutContType.None;
}
if (device.PrimaryDevice && device.OutputMapGyro)
{
TouchPadOn(i, device);
}
else if (device.JointDeviceSlotNumber != DS4Device.DEFAULT_JOINT_SLOT_NUMBER)
{
int otherIdx = device.JointDeviceSlotNumber;
DS4Device tempDev = DS4Controllers[otherIdx];
if (tempDev != null)
{
int mappedIdx = tempDev.PrimaryDevice ? otherIdx : i;
DS4Device gyroDev = device.OutputMapGyro ? device : (tempDev.OutputMapGyro ? tempDev : null);
if (gyroDev != null)
{
TouchPadOn(mappedIdx, gyroDev);
}
}
}
CheckProfileOptions(i, device, true);
SetupInitialHookEvents(i, device);
}
int tempIdx = i;
device.Report += (sender, e) =>
{
this.On_Report(sender, e, tempIdx);
};
if (_udpServer != null && i < UdpServer.NUMBER_SLOTS && device.PrimaryDevice)
{
PrepareDevUDPMotion(device, tempIdx);
}
device.StartUpdate();
//string filename = ProfilePath[ind];
//ind++;
if (i >= CURRENT_DS4_CONTROLLER_LIMIT) // out of Xinput devices!
break;
}
}
catch (Exception e)
{
LogDebug(e.Message, true);
AppLogger.LogToTray(e.Message, true);
}
running = true;
if (_udpServer != null)
{
//var UDP_SERVER_PORT = 26760;
var UDP_SERVER_PORT = Global.getUDPServerPortNum();
var UDP_SERVER_LISTEN_ADDRESS = Global.getUDPServerListenAddress();
try
{
_udpServer.Start(UDP_SERVER_PORT, UDP_SERVER_LISTEN_ADDRESS);
LogDebug($"UDP server listening on address {UDP_SERVER_LISTEN_ADDRESS} port {UDP_SERVER_PORT}");
}
catch (System.Net.Sockets.SocketException ex)
{
var errMsg = String.Format("Couldn't start UDP server on address {0}:{1}, outside applications won't be able to access pad data ({2})", UDP_SERVER_LISTEN_ADDRESS, UDP_SERVER_PORT, ex.SocketErrorCode);
LogDebug(errMsg, true);
AppLogger.LogToTray(errMsg, true, true);
}
}
}
else
{
string logMessage = string.Empty;
if (!vigemInstalled)
{
logMessage = "ViGEmBus is not installed";
}
else if (!Global.IsRunningSupportedViGEmBus())
{
logMessage = string.Format("Unsupported ViGEmBus found ({0}). Please install at least ViGEmBus 1.17.333.0", Global.vigembusVersion);
}
else
{
logMessage = "Could not connect to ViGEmBus. Please check the status of the System device in Device Manager and if Visual C++ 2017 Redistributable is installed.";
}
LogDebug(logMessage);
AppLogger.LogToTray(logMessage);
}
inServiceTask = false;
runHotPlug = true;
ServiceStarted?.Invoke(this, EventArgs.Empty);
RunningChanged?.Invoke(this, EventArgs.Empty);
return true;
}
private void PrepareDevUDPMotion(DS4Device device, int index)
{
int tempIdx = index;
DS4Device.ReportHandler<EventArgs> tempEvnt = (sender, args) =>
{
DualShockPadMeta padDetail = new DualShockPadMeta();
GetPadDetailForIdx(tempIdx, ref padDetail);
DS4State stateForUdp = TempState[tempIdx];
CurrentState[tempIdx].CopyTo(stateForUdp);
if (Global.IsUsingUDPServerSmoothing())
{
if (stateForUdp.elapsedTime == 0)
{
// No timestamp was found. Exit out of routine
return;
}
double rate = 1.0 / stateForUdp.elapsedTime;
OneEuroFilter3D accelFilter = udpEuroPairAccel[tempIdx];
stateForUdp.Motion.accelXG = accelFilter.axis1Filter.Filter(stateForUdp.Motion.accelXG, rate);
stateForUdp.Motion.accelYG = accelFilter.axis2Filter.Filter(stateForUdp.Motion.accelYG, rate);
stateForUdp.Motion.accelZG = accelFilter.axis3Filter.Filter(stateForUdp.Motion.accelZG, rate);
OneEuroFilter3D gyroFilter = udpEuroPairGyro[tempIdx];
stateForUdp.Motion.angVelYaw = gyroFilter.axis1Filter.Filter(stateForUdp.Motion.angVelYaw, rate);
stateForUdp.Motion.angVelPitch = gyroFilter.axis2Filter.Filter(stateForUdp.Motion.angVelPitch, rate);
stateForUdp.Motion.angVelRoll = gyroFilter.axis3Filter.Filter(stateForUdp.Motion.angVelRoll, rate);
}
_udpServer.NewReportIncoming(ref padDetail, stateForUdp, udpOutBuffers[tempIdx]);
};
device.MotionEvent = tempEvnt;
device.Report += tempEvnt;
}
private void CheckQuickCharge(object sender, EventArgs e)
{
DS4Device device = sender as DS4Device;
if (device.ConnectionType == ConnectionType.BT && getQuickCharge() &&
device.Charging)
{
// Set disconnect flag here. Later Hotplug event will check
// for presence of flag and remove the device then
device.ReadyQuickChargeDisconnect = true;
}
}
public void PrepareAbort()
{
for (int i = 0, arlength = DS4Controllers.Length; i < arlength; i++)
{
DS4Device tempDevice = DS4Controllers[i];
if (tempDevice != null)
{
tempDevice.PrepareAbort();
}
}
}
public bool Stop(bool showlog = true, bool immediateUnplug = false)
{
if (running)
{
running = false;
runHotPlug = false;
inServiceTask = true;
PreServiceStop?.Invoke(this, EventArgs.Empty);
if (showlog)
LogDebug(DS4WinWPF.Properties.Resources.StoppingX360);
LogDebug("Closing connection to ViGEmBus");
bool anyUnplugged = false;
for (int i = 0, arlength = DS4Controllers.Length; i < arlength; i++)
{
DS4Device tempDevice = DS4Controllers[i];
if (tempDevice != null)
{
if ((DCBTatStop && !tempDevice.isCharging()) || suspending)
{
if (tempDevice.getConnectionType() == ConnectionType.BT)
{
tempDevice.StopUpdate();
tempDevice.DisconnectBT(true);
}
else if (tempDevice.getConnectionType() == ConnectionType.SONYWA)
{
tempDevice.StopUpdate();
tempDevice.DisconnectDongle(true);
}
else
{
tempDevice.StopUpdate();
}
}
else
{
DS4LightBar.forcelight[i] = false;
DS4LightBar.forcedFlash[i] = 0;
DS4LightBar.defaultLight = true;
DS4LightBar.updateLightBar(DS4Controllers[i], i);
tempDevice.IsRemoved = true;
tempDevice.StopUpdate();
DS4Devices.RemoveDevice(tempDevice);
Thread.Sleep(50);
}
CurrentState[i].Battery = PreviousState[i].Battery = 0; // Reset for the next connection's initial status change.
OutputDevice tempout = outputDevices[i];
if (tempout != null)
{
UnplugOutDev(i, tempDevice, immediate: immediateUnplug, force: true);
anyUnplugged = true;
}
//outputDevices[i] = null;
//useDInputOnly[i] = true;
//Global.activeOutDevType[i] = OutContType.None;
useDInputOnly[i] = true;
DS4Controllers[i] = null;
touchPad[i] = null;
lag[i] = false;
inWarnMonitor[i] = false;
}
}
if (showlog)
LogDebug(DS4WinWPF.Properties.Resources.StoppingDS4);
DS4Devices.stopControllers();
slotManager.ClearControllerList();
if (_udpServer != null)
{
ChangeUDPStatus(false);
}
if (showlog)
LogDebug(DS4WinWPF.Properties.Resources.StoppedDS4Windows);
while (outputslotMan.RunningQueue)
{
Thread.SpinWait(500);
}
outputslotMan.Stop(true);
if (anyUnplugged)
{
Thread.Sleep(OutputSlotManager.DELAY_TIME);
}
StopViGEm();
inServiceTask = false;
activeControllers = 0;
}
runHotPlug = false;
ServiceStopped?.Invoke(this, EventArgs.Empty);
RunningChanged?.Invoke(this, EventArgs.Empty);
return true;
}
public bool HotPlug()
{
if (running)
{
inServiceTask = true;
loopControllers = true;
eventDispatcher.Invoke(() =>
{
DS4Devices.findControllers();
});
IEnumerable<DS4Device> devices = DS4Devices.getDS4Controllers();
int numControllers = new List<DS4Device>(devices).Count;
activeControllers = numControllers;
//foreach (DS4Device device in devices)
//for (int i = 0, devlen = devices.Count(); i < devlen; i++)
InputDevices.JoyConDevice tempPrimaryJoyDev = null;
InputDevices.JoyConDevice tempSecondaryJoyDev = null;
if (deviceOptions.JoyConDeviceOpts.LinkedMode == JoyConDeviceOptions.LinkMode.Joined)
{
tempPrimaryJoyDev = devices.Where(d =>
(d.DeviceType == InputDevices.InputDeviceType.JoyConL || d.DeviceType == InputDevices.InputDeviceType.JoyConR)
&& d.PrimaryDevice && d.JointDeviceSlotNumber == -1).FirstOrDefault() as InputDevices.JoyConDevice;
tempSecondaryJoyDev = devices.Where(d =>
(d.DeviceType == InputDevices.InputDeviceType.JoyConL || d.DeviceType == InputDevices.InputDeviceType.JoyConR)
&& !d.PrimaryDevice && d.JointDeviceSlotNumber == -1).FirstOrDefault() as InputDevices.JoyConDevice;
}
for (var devEnum = devices.GetEnumerator(); devEnum.MoveNext() && loopControllers;)
{
DS4Device device = devEnum.Current;
if (device.isDisconnectingStatus())
continue;
if (((Func<bool>)delegate
{
for (Int32 Index = 0, arlength = DS4Controllers.Length; Index < arlength; Index++)
{
if (DS4Controllers[Index] != null &&
DS4Controllers[Index].getMacAddress() == device.getMacAddress())
{
device.CheckControllerNumDeviceSettings(numControllers);
return true;
}
}
return false;
})())
{
continue;
}
for (Int32 Index = 0, arlength = DS4Controllers.Length; Index < arlength && Index < CURRENT_DS4_CONTROLLER_LIMIT; Index++)
{
if (DS4Controllers[Index] == null)
{
//LogDebug(DS4WinWPF.Properties.Resources.FoundController + device.getMacAddress() + " (" + device.getConnectionType() + ")");
LogDebug(DS4WinWPF.Properties.Resources.FoundController + " " + device.getMacAddress() + " (" + device.getConnectionType() + ") (" +
device.DisplayName + ")");
if (hidDeviceHidingEnabled && CheckAffected(device))
{
//device.CurrentExclusiveStatus = DS4Device.ExclusiveStatus.HidGuardAffected;
ChangeExclusiveStatus(device);
}
Task task = new Task(() => { Thread.Sleep(5); WarnExclusiveModeFailure(device); });
task.Start();
PrepareDS4DeviceSettingHooks(device);
if (deviceOptions.JoyConDeviceOpts.LinkedMode == JoyConDeviceOptions.LinkMode.Joined)
{
if ((device.DeviceType == InputDevices.InputDeviceType.JoyConL ||
device.DeviceType == InputDevices.InputDeviceType.JoyConR) && device.PerformStateMerge)
{
if (device.PrimaryDevice &&
tempSecondaryJoyDev != null)
{
InputDevices.JoyConDevice currentJoyDev = device as InputDevices.JoyConDevice;
tempSecondaryJoyDev.JointDevice = currentJoyDev;
currentJoyDev.JointDevice = tempSecondaryJoyDev;
tempSecondaryJoyDev.JointState = currentJoyDev.JointState;
InputDevices.JoyConDevice secondaryJoy = tempSecondaryJoyDev;
secondaryJoy.Removal += (sender, args) => { currentJoyDev.JointDevice = null; };
currentJoyDev.Removal += (sender, args) => { secondaryJoy.JointDevice = null; };
tempSecondaryJoyDev = null;
tempPrimaryJoyDev = null;
}
else if (!device.PrimaryDevice &&
tempPrimaryJoyDev != null)
{
InputDevices.JoyConDevice currentJoyDev = device as InputDevices.JoyConDevice;
tempPrimaryJoyDev.JointDevice = currentJoyDev;
currentJoyDev.JointDevice = tempPrimaryJoyDev;
tempPrimaryJoyDev.JointState = currentJoyDev.JointState;
InputDevices.JoyConDevice parentJoy = tempPrimaryJoyDev;
tempPrimaryJoyDev.Removal += (sender, args) => { currentJoyDev.JointDevice = null; };
currentJoyDev.Removal += (sender, args) => { parentJoy.JointDevice = null; };
tempPrimaryJoyDev = null;
}
}
}
DS4Controllers[Index] = device;
device.DeviceSlotNumber = Index;
Global.RefreshExtrasButtons(Index, GetKnownExtraButtons(device));
Global.LoadControllerConfigs(device);
device.LoadStoreSettings();
device.CheckControllerNumDeviceSettings(numControllers);
slotManager.AddController(device, Index);
device.Removal += this.On_DS4Removal;
device.Removal += DS4Devices.On_Removal;
device.SyncChange += this.On_SyncChange;
device.SyncChange += DS4Devices.UpdateSerial;
device.SerialChange += this.On_SerialChange;
device.ChargingChanged += CheckQuickCharge;
touchPad[Index] = new Mouse(Index, device);
bool profileLoaded = false;
bool useAutoProfile = useTempProfile[Index];
if (!useAutoProfile)
{
if (device.isValidSerial() && containsLinkedProfile(device.getMacAddress()))
{
ProfilePath[Index] = getLinkedProfile(device.getMacAddress());
Global.linkedProfileCheck[Index] = true;
}
else
{
ProfilePath[Index] = OlderProfilePath[Index];
Global.linkedProfileCheck[Index] = false;
}
profileLoaded = LoadProfile(Index, false, this, false, false);
}
if (profileLoaded || useAutoProfile)
{
device.LightBarColor = getMainColor(Index);
if (!getDInputOnly(Index) && device.isSynced())
{
if (device.PrimaryDevice)
{
PluginOutDev(Index, device);
}
else if (device.JointDeviceSlotNumber != DS4Device.DEFAULT_JOINT_SLOT_NUMBER)
{
int otherIdx = device.JointDeviceSlotNumber;
OutputDevice tempOutDev = outputDevices[otherIdx];
if (tempOutDev != null)
{
OutContType tempConType = activeOutDevType[otherIdx];
EstablishOutFeedback(Index, tempConType, tempOutDev, device);
outputDevices[Index] = tempOutDev;
Global.activeOutDevType[Index] = tempConType;
}
}
}
else
{
useDInputOnly[Index] = true;
Global.activeOutDevType[Index] = OutContType.None;
}
if (device.PrimaryDevice && device.OutputMapGyro)
{
TouchPadOn(Index, device);
}
else if (device.JointDeviceSlotNumber != DS4Device.DEFAULT_JOINT_SLOT_NUMBER)
{
int otherIdx = device.JointDeviceSlotNumber;
DS4Device tempDev = DS4Controllers[otherIdx];
if (tempDev != null)
{
int mappedIdx = tempDev.PrimaryDevice ? otherIdx : Index;
DS4Device gyroDev = device.OutputMapGyro ? device : (tempDev.OutputMapGyro ? tempDev : null);
if (gyroDev != null)
{
TouchPadOn(mappedIdx, gyroDev);
}
}
}
CheckProfileOptions(Index, device);
SetupInitialHookEvents(Index, device);
}
int tempIdx = Index;
device.Report += (sender, e) =>
{
this.On_Report(sender, e, tempIdx);
};
if (_udpServer != null && Index < UdpServer.NUMBER_SLOTS && device.PrimaryDevice)
{
PrepareDevUDPMotion(device, tempIdx);
}
device.StartUpdate();
HotplugController?.Invoke(this, device, Index);
break;
}
}
}
inServiceTask = false;
}
return true;
}
public void ResetUdpSmoothingFilters(int idx)
{
if (idx < UdpServer.NUMBER_SLOTS)
{
OneEuroFilter3D temp = udpEuroPairAccel[idx] = new OneEuroFilter3D();
temp.SetFilterAttrs(Global.UDPServerSmoothingMincutoff, Global.UDPServerSmoothingBeta);
temp = udpEuroPairGyro[idx] = new OneEuroFilter3D();
temp.SetFilterAttrs(Global.UDPServerSmoothingMincutoff, Global.UDPServerSmoothingBeta);
}
}
private void ChangeUdpSmoothingAttrs(object sender, EventArgs e)
{
for (int i = 0; i < udpEuroPairAccel.Length; i++)
{
OneEuroFilter3D temp = udpEuroPairAccel[i];
temp.SetFilterAttrs(Global.UDPServerSmoothingMincutoff, Global.UDPServerSmoothingBeta);
}
for (int i = 0; i < udpEuroPairGyro.Length; i++)
{
OneEuroFilter3D temp = udpEuroPairGyro[i];
temp.SetFilterAttrs(Global.UDPServerSmoothingMincutoff, Global.UDPServerSmoothingBeta);
}
}
public void CheckProfileOptions(int ind, DS4Device device, bool startUp=false)
{
device.ModifyFeatureSetFlag(VidPidFeatureSet.NoOutputData, !getEnableOutputDataToDS4(ind));
if (!getEnableOutputDataToDS4(ind))
LogDebug("Output data to DS4 disabled. Lightbar and rumble events are not written to DS4 gamepad. If the gamepad is connected over BT then IdleDisconnect option is recommended to let DS4Windows to close the connection after long period of idling.");
device.setIdleTimeout(getIdleDisconnectTimeout(ind));
device.setBTPollRate(getBTPollRate(ind));
touchPad[ind].ResetTrackAccel(getTrackballFriction(ind));
touchPad[ind].ResetToggleGyroModes();
// Reset current flick stick progress from previous profile
Mapping.flickMappingData[ind].Reset();
Global.L2OutputSettings[ind].TrigEffectSettings.maxValue = (byte)(Math.Max(Global.L2ModInfo[ind].maxOutput, Global.L2ModInfo[ind].maxZone) / 100.0 * 255);
Global.R2OutputSettings[ind].TrigEffectSettings.maxValue = (byte)(Math.Max(Global.R2ModInfo[ind].maxOutput, Global.R2ModInfo[ind].maxZone) / 100.0 * 255);
device.PrepareTriggerEffect(InputDevices.TriggerId.LeftTrigger, Global.L2OutputSettings[ind].TriggerEffect,
Global.L2OutputSettings[ind].TrigEffectSettings);
device.PrepareTriggerEffect(InputDevices.TriggerId.RightTrigger, Global.R2OutputSettings[ind].TriggerEffect,
Global.R2OutputSettings[ind].TrigEffectSettings);
device.RumbleAutostopTime = getRumbleAutostopTime(ind);
device.setRumble(0, 0);
device.LightBarColor = Global.getMainColor(ind);
if (!startUp)
{
CheckLauchProfileOption(ind, device);
}
}
private void CheckLauchProfileOption(int ind, DS4Device device)
{
string programPath = LaunchProgram[ind];
if (programPath != string.Empty)
{
System.Diagnostics.Process[] localAll = System.Diagnostics.Process.GetProcesses();
bool procFound = false;
for (int procInd = 0, procsLen = localAll.Length; !procFound && procInd < procsLen; procInd++)
{
try
{
string temp = localAll[procInd].MainModule.FileName;
if (temp == programPath)
{
procFound = true;
}
}
// Ignore any process for which this information
// is not exposed
catch { }
}
if (!procFound)
{
Task processTask = new Task(() =>
{
Thread.Sleep(5000);
System.Diagnostics.Process tempProcess = new System.Diagnostics.Process();
tempProcess.StartInfo.FileName = programPath;
tempProcess.StartInfo.WorkingDirectory = new FileInfo(programPath).Directory.ToString();
//tempProcess.StartInfo.UseShellExecute = false;
try { tempProcess.Start(); }
catch { }
});
processTask.Start();
}
}
}
private void SetupInitialHookEvents(int ind, DS4Device device)
{
ResetUdpSmoothingFilters(ind);
// Set up filter for new input device
OneEuroFilter tempFilter = new OneEuroFilter(OneEuroFilterPair.DEFAULT_WHEEL_CUTOFF,
OneEuroFilterPair.DEFAULT_WHEEL_BETA);
Mapping.wheelFilters[ind] = tempFilter;
// Carry over initial profile wheel smoothing values to filter instances.
// Set up event hooks to keep values in sync
SteeringWheelSmoothingInfo wheelSmoothInfo = WheelSmoothInfo[ind];
wheelSmoothInfo.SetFilterAttrs(tempFilter);
wheelSmoothInfo.SetRefreshEvents(tempFilter);
FlickStickSettings flickStickSettings = Global.LSOutputSettings[ind].outputSettings.flickSettings;
flickStickSettings.RemoveRefreshEvents();
flickStickSettings.SetRefreshEvents(Mapping.flickMappingData[ind].flickFilter);
flickStickSettings = Global.RSOutputSettings[ind].outputSettings.flickSettings;
flickStickSettings.RemoveRefreshEvents();
flickStickSettings.SetRefreshEvents(Mapping.flickMappingData[ind].flickFilter);
int tempIdx = ind;
Global.L2OutputSettings[ind].ResetEvents();
Global.L2ModInfo[ind].ResetEvents();
Global.L2OutputSettings[ind].TriggerEffectChanged += (sender, e) =>
{
device.PrepareTriggerEffect(InputDevices.TriggerId.LeftTrigger, Global.L2OutputSettings[tempIdx].TriggerEffect,
Global.L2OutputSettings[tempIdx].TrigEffectSettings);
};
Global.L2ModInfo[ind].MaxOutputChanged += (sender, e) =>
{
TriggerDeadZoneZInfo tempInfo = sender as TriggerDeadZoneZInfo;
L2OutputSettings[tempIdx].TrigEffectSettings.maxValue = (byte)(Math.Max(tempInfo.maxOutput, tempInfo.maxZone) / 100.0 * 255.0);
// Refresh trigger effect
device.PrepareTriggerEffect(InputDevices.TriggerId.LeftTrigger, Global.L2OutputSettings[tempIdx].TriggerEffect,
Global.L2OutputSettings[tempIdx].TrigEffectSettings);
};
Global.L2ModInfo[ind].MaxZoneChanged += (sender, e) =>
{
TriggerDeadZoneZInfo tempInfo = sender as TriggerDeadZoneZInfo;
L2OutputSettings[tempIdx].TrigEffectSettings.maxValue = (byte)(Math.Max(tempInfo.maxOutput, tempInfo.maxZone) / 100.0 * 255.0);
// Refresh trigger effect
device.PrepareTriggerEffect(InputDevices.TriggerId.LeftTrigger, Global.L2OutputSettings[tempIdx].TriggerEffect,
Global.L2OutputSettings[tempIdx].TrigEffectSettings);
};
Global.R2OutputSettings[ind].ResetEvents();
Global.R2OutputSettings[ind].TriggerEffectChanged += (sender, e) =>
{
device.PrepareTriggerEffect(InputDevices.TriggerId.RightTrigger, Global.R2OutputSettings[tempIdx].TriggerEffect,
Global.R2OutputSettings[tempIdx].TrigEffectSettings);
};
Global.R2ModInfo[ind].MaxOutputChanged += (sender, e) =>
{
TriggerDeadZoneZInfo tempInfo = sender as TriggerDeadZoneZInfo;
R2OutputSettings[tempIdx].TrigEffectSettings.maxValue = (byte)(tempInfo.maxOutput / 100.0 * 255.0);
// Refresh trigger effect
device.PrepareTriggerEffect(InputDevices.TriggerId.RightTrigger, Global.R2OutputSettings[tempIdx].TriggerEffect,
Global.R2OutputSettings[tempIdx].TrigEffectSettings);
};
Global.R2ModInfo[ind].MaxZoneChanged += (sender, e) =>
{
TriggerDeadZoneZInfo tempInfo = sender as TriggerDeadZoneZInfo;
R2OutputSettings[tempIdx].TrigEffectSettings.maxValue = (byte)(tempInfo.maxOutput / 100.0 * 255.0);
// Refresh trigger effect
device.PrepareTriggerEffect(InputDevices.TriggerId.RightTrigger, Global.R2OutputSettings[tempIdx].TriggerEffect,
Global.R2OutputSettings[tempIdx].TrigEffectSettings);
};
}
public void TouchPadOn(int ind, DS4Device device)
{
Mouse tPad = touchPad[ind];
//ITouchpadBehaviour tPad = touchPad[ind];
device.Touchpad.TouchButtonDown += tPad.touchButtonDown;
device.Touchpad.TouchButtonUp += tPad.touchButtonUp;
device.Touchpad.TouchesBegan += tPad.touchesBegan;
device.Touchpad.TouchesMoved += tPad.touchesMoved;
device.Touchpad.TouchesEnded += tPad.touchesEnded;
device.Touchpad.TouchUnchanged += tPad.touchUnchanged;
//device.Touchpad.PreTouchProcess += delegate { touchPad[ind].populatePriorButtonStates(); };
device.Touchpad.PreTouchProcess += (sender, args) => { touchPad[ind].populatePriorButtonStates(); };
device.SixAxis.SixAccelMoved += tPad.sixaxisMoved;
//LogDebug("Touchpad mode for " + device.MacAddress + " is now " + tmode.ToString());
//Log.LogToTray("Touchpad mode for " + device.MacAddress + " is now " + tmode.ToString());
}
public string GetDS4Battery(int index)
{
DS4Device d = DS4Controllers[index];
if (d != null)
{
string battery;
if (!d.IsAlive())
battery = "...";
if (d.isCharging())
{
if (d.getBattery() >= 100)
battery = DS4WinWPF.Properties.Resources.Full;
else
battery = d.getBattery() + "%+";
}
else
{
battery = d.getBattery() + "%";
}
return battery;
}
else
return DS4WinWPF.Properties.Resources.NA;
}
public string getDS4Status(int index)
{
DS4Device d = DS4Controllers[index];
if (d != null)
{
return d.getConnectionType() + "";
}
else
return DS4WinWPF.Properties.Resources.NoneText;
}
protected void On_SerialChange(object sender, EventArgs e)
{
DS4Device device = (DS4Device)sender;
int ind = -1;
for (int i = 0, arlength = MAX_DS4_CONTROLLER_COUNT; ind == -1 && i < arlength; i++)
{
DS4Device tempDev = DS4Controllers[i];
if (tempDev != null && device == tempDev)
ind = i;
}
if (ind >= 0)
{
OnDeviceSerialChange(this, ind, device.getMacAddress());
}
}
protected void On_SyncChange(object sender, EventArgs e)
{
DS4Device device = (DS4Device)sender;
int ind = -1;
for (int i = 0, arlength = CURRENT_DS4_CONTROLLER_LIMIT; ind == -1 && i < arlength; i++)
{
DS4Device tempDev = DS4Controllers[i];
if (tempDev != null && device == tempDev)
ind = i;
}
if (ind >= 0)
{
bool synced = device.isSynced();
if (!synced)
{
if (!useDInputOnly[ind])
{
Global.activeOutDevType[ind] = OutContType.None;
UnplugOutDev(ind, device);
}
}
else
{
if (!getDInputOnly(ind))
{
touchPad[ind].ReplaceOneEuroFilterPair();
touchPad[ind].ReplaceOneEuroFilterPair();
touchPad[ind].Cursor.ReplaceOneEuroFilterPair();
touchPad[ind].Cursor.SetupLateOneEuroFilters();
PluginOutDev(ind, device);
}
}
}
}
//Called when DS4 is disconnected or timed out
protected virtual void On_DS4Removal(object sender, EventArgs e)
{
DS4Device device = (DS4Device)sender;
int ind = -1;
for (int i = 0, arlength = DS4Controllers.Length; ind == -1 && i < arlength; i++)
{
if (DS4Controllers[i] != null && device.getMacAddress() == DS4Controllers[i].getMacAddress())
ind = i;
}
if (ind != -1)
{
bool removingStatus = false;
lock (device.removeLocker)
{
if (!device.IsRemoving)
{
removingStatus = true;
device.IsRemoving = true;
}
}
if (removingStatus)
{
CurrentState[ind].Battery = PreviousState[ind].Battery = 0; // Reset for the next connection's initial status change.
if (!useDInputOnly[ind])
{
UnplugOutDev(ind, device);
}
else if (!device.PrimaryDevice)
{
OutputDevice outDev = outputDevices[ind];
if (outDev != null)
{
outDev.RemoveFeedback(ind);
outputDevices[ind] = null;
}
}
// Use Task to reset device synth state and commit it
Task.Run(() =>
{
Mapping.Commit(ind);
}).Wait();
string removed = DS4WinWPF.Properties.Resources.ControllerWasRemoved.Replace("*Mac address*", (ind + 1).ToString());
if (device.getBattery() <= 20 &&
device.getConnectionType() == ConnectionType.BT && !device.isCharging())
{
removed += ". " + DS4WinWPF.Properties.Resources.ChargeController;
}
LogDebug(removed);
AppLogger.LogToTray(removed);
/*Stopwatch sw = new Stopwatch();
sw.Start();
while (sw.ElapsedMilliseconds < XINPUT_UNPLUG_SETTLE_TIME)
{
// Use SpinWait to keep control of current thread. Using Sleep could potentially
// cause other events to get run out of order
System.Threading.Thread.SpinWait(500);
}
sw.Stop();
*/
device.IsRemoved = true;
device.Synced = false;
DS4Controllers[ind] = null;
//eventDispatcher.Invoke(() =>
//{
slotManager.RemoveController(device, ind);
//});
touchPad[ind] = null;
lag[ind] = false;
inWarnMonitor[ind] = false;
useDInputOnly[ind] = true;
Global.activeOutDevType[ind] = OutContType.None;
/* Leave up to Auto Profile system to change the following flags? */
//Global.useTempProfile[ind] = false;
//Global.tempprofilename[ind] = string.Empty;
//Global.tempprofileDistance[ind] = false;
//Thread.Sleep(XINPUT_UNPLUG_SETTLE_TIME);
}
}
}
public bool[] lag = new bool[MAX_DS4_CONTROLLER_COUNT] { false, false, false, false, false, false, false, false };
public bool[] inWarnMonitor = new bool[MAX_DS4_CONTROLLER_COUNT] { false, false, false, false, false, false, false, false };
private byte[] currentBattery = new byte[MAX_DS4_CONTROLLER_COUNT] { 0, 0, 0, 0, 0, 0, 0, 0 };
private bool[] charging = new bool[MAX_DS4_CONTROLLER_COUNT] { false, false, false, false, false, false, false, false };
private string[] tempStrings = new string[MAX_DS4_CONTROLLER_COUNT] { string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty };
// Called every time a new input report has arrived
protected virtual void On_Report(DS4Device device, EventArgs e, int ind)
{
if (ind != -1)
{
string devError = tempStrings[ind] = device.error;
if (!string.IsNullOrEmpty(devError))
{
LogDebug(devError);
}
if (inWarnMonitor[ind])
{
int flashWhenLateAt = getFlashWhenLateAt();
if (!lag[ind] && device.Latency >= flashWhenLateAt)
{
lag[ind] = true;
LagFlashWarning(device, ind, true);
}
else if (lag[ind] && device.Latency < flashWhenLateAt)
{
lag[ind] = false;
LagFlashWarning(device, ind, false);
}
}
else
{
if (DateTime.UtcNow - device.firstActive > TimeSpan.FromSeconds(5))
{
inWarnMonitor[ind] = true;
}
}
DS4State cState;
if (!device.PerformStateMerge)
{
cState = CurrentState[ind];
device.getRawCurrentState(cState);
}
else
{
cState = device.JointState;
device.MergeStateData(cState);
// Need to copy state object info for use in UDP server
cState.CopyTo(CurrentState[ind]);
}
DS4State pState = device.getPreviousStateRef();
//device.getPreviousState(PreviousState[ind]);
//DS4State pState = PreviousState[ind];
if (device.firstReport && device.isSynced())
{
// Only send Log message when device is considered a primary device
if (device.PrimaryDevice)
{
if (File.Exists(appdatapath + "\\Profiles\\" + ProfilePath[ind] + ".xml"))
{
string prolog = string.Format(DS4WinWPF.Properties.Resources.UsingProfile, (ind + 1).ToString(), ProfilePath[ind], $"{device.Battery}");
LogDebug(prolog);
AppLogger.LogToTray(prolog);
}
else
{
string prolog = string.Format(DS4WinWPF.Properties.Resources.NotUsingProfile, (ind + 1).ToString(), $"{device.Battery}");
LogDebug(prolog);
AppLogger.LogToTray(prolog);
}
}
device.firstReport = false;
}
if (!device.PrimaryDevice)
{
// Skip mapping routine if part of a joined device
return;
}
if (getEnableTouchToggle(ind))
{
CheckForTouchToggle(ind, cState, pState);
}
cState = Mapping.SetCurveAndDeadzone(ind, cState, TempState[ind]);
if (!recordingMacro && (useTempProfile[ind] ||
containsCustomAction(ind) || containsCustomExtras(ind) ||
getProfileActionCount(ind) > 0))
{
DS4State tempMapState = MappedState[ind];
Mapping.MapCustom(ind, cState, tempMapState, ExposedState[ind], touchPad[ind], this);
// Copy current Touchpad and Gyro data
// Might change to use new DS4State.CopyExtrasTo method
tempMapState.Motion = cState.Motion;
tempMapState.ds4Timestamp = cState.ds4Timestamp;
tempMapState.FrameCounter = cState.FrameCounter;
tempMapState.TouchPacketCounter = cState.TouchPacketCounter;
tempMapState.TrackPadTouch0 = cState.TrackPadTouch0;
tempMapState.TrackPadTouch1 = cState.TrackPadTouch1;
cState = tempMapState;
}
if (!useDInputOnly[ind])
{
outputDevices[ind]?.ConvertandSendReport(cState, ind);
//testNewReport(ref x360reports[ind], cState, ind);
//x360controls[ind]?.SendReport(x360reports[ind]);
//x360Bus.Parse(cState, processingData[ind].Report, ind);
// We push the translated Xinput state, and simultaneously we
// pull back any possible rumble data coming from Xinput consumers.
/*if (x360Bus.Report(processingData[ind].Report, processingData[ind].Rumble))
{
byte Big = processingData[ind].Rumble[3];
byte Small = processingData[ind].Rumble[4];
if (processingData[ind].Rumble[1] == 0x08)
{
SetDevRumble(device, Big, Small, ind);
}
}
*/
}
else
{
// UseDInputOnly profile may re-map sixaxis gyro sensor values as a VJoy joystick axis (steering wheel emulation mode using VJoy output device). Handle this option because VJoy output works even in USeDInputOnly mode.
// If steering wheel emulation uses LS/RS/R2/L2 output axies then the profile should NOT use UseDInputOnly option at all because those require a virtual output device.
SASteeringWheelEmulationAxisType steeringWheelMappedAxis = Global.GetSASteeringWheelEmulationAxis(ind);
switch (steeringWheelMappedAxis)
{
case SASteeringWheelEmulationAxisType.None: break;
case SASteeringWheelEmulationAxisType.VJoy1X:
case SASteeringWheelEmulationAxisType.VJoy2X:
DS4Windows.VJoyFeeder.vJoyFeeder.FeedAxisValue(cState.SASteeringWheelEmulationUnit, ((((uint)steeringWheelMappedAxis) - ((uint)SASteeringWheelEmulationAxisType.VJoy1X)) / 3) + 1, DS4Windows.VJoyFeeder.HID_USAGES.HID_USAGE_X);
break;
case SASteeringWheelEmulationAxisType.VJoy1Y:
case SASteeringWheelEmulationAxisType.VJoy2Y:
DS4Windows.VJoyFeeder.vJoyFeeder.FeedAxisValue(cState.SASteeringWheelEmulationUnit, ((((uint)steeringWheelMappedAxis) - ((uint)SASteeringWheelEmulationAxisType.VJoy1X)) / 3) + 1, DS4Windows.VJoyFeeder.HID_USAGES.HID_USAGE_Y);
break;
case SASteeringWheelEmulationAxisType.VJoy1Z:
case SASteeringWheelEmulationAxisType.VJoy2Z:
DS4Windows.VJoyFeeder.vJoyFeeder.FeedAxisValue(cState.SASteeringWheelEmulationUnit, ((((uint)steeringWheelMappedAxis) - ((uint)SASteeringWheelEmulationAxisType.VJoy1X)) / 3) + 1, DS4Windows.VJoyFeeder.HID_USAGES.HID_USAGE_Z);
break;
}
}
// Output any synthetic events.
Mapping.Commit(ind);
// Update the Lightbar color
DS4LightBar.updateLightBar(device, ind);
if (device.PerformStateMerge)
{
device.PreserveMergedStateData();
}
}
}
public void LagFlashWarning(DS4Device device, int ind, bool on)
{
if (on)
{
lag[ind] = true;
LogDebug(string.Format(DS4WinWPF.Properties.Resources.LatencyOverTen, (ind + 1), device.Latency), true);
if (getFlashWhenLate())
{
DS4Color color = new DS4Color { red = 50, green = 0, blue = 0 };
DS4LightBar.forcedColor[ind] = color;
DS4LightBar.forcedFlash[ind] = 2;
DS4LightBar.forcelight[ind] = true;
}
}
else
{
lag[ind] = false;
LogDebug(DS4WinWPF.Properties.Resources.LatencyNotOverTen.Replace("*number*", (ind + 1).ToString()));
DS4LightBar.forcelight[ind] = false;
DS4LightBar.forcedFlash[ind] = 0;
device.LightBarColor = getMainColor(ind);
}
}
public DS4Controls GetActiveInputControl(int ind)
{
DS4State cState = CurrentState[ind];
DS4StateExposed eState = ExposedState[ind];
Mouse tp = touchPad[ind];
DS4Controls result = DS4Controls.None;
if (DS4Controllers[ind] != null)
{
if (Mapping.getBoolButtonMapping(cState.Cross))
result = DS4Controls.Cross;
else if (Mapping.getBoolButtonMapping(cState.Circle))
result = DS4Controls.Circle;
else if (Mapping.getBoolButtonMapping(cState.Triangle))
result = DS4Controls.Triangle;
else if (Mapping.getBoolButtonMapping(cState.Square))
result = DS4Controls.Square;
else if (Mapping.getBoolButtonMapping(cState.L1))
result = DS4Controls.L1;
else if (Mapping.getBoolTriggerMapping(cState.L2))
result = DS4Controls.L2;
else if (Mapping.getBoolButtonMapping(cState.L3))
result = DS4Controls.L3;
else if (Mapping.getBoolButtonMapping(cState.R1))
result = DS4Controls.R1;
else if (Mapping.getBoolTriggerMapping(cState.R2))
result = DS4Controls.R2;
else if (Mapping.getBoolButtonMapping(cState.R3))
result = DS4Controls.R3;
else if (Mapping.getBoolButtonMapping(cState.DpadUp))
result = DS4Controls.DpadUp;
else if (Mapping.getBoolButtonMapping(cState.DpadDown))
result = DS4Controls.DpadDown;
else if (Mapping.getBoolButtonMapping(cState.DpadLeft))
result = DS4Controls.DpadLeft;
else if (Mapping.getBoolButtonMapping(cState.DpadRight))
result = DS4Controls.DpadRight;
else if (Mapping.getBoolButtonMapping(cState.Share))
result = DS4Controls.Share;
else if (Mapping.getBoolButtonMapping(cState.Options))
result = DS4Controls.Options;
else if (Mapping.getBoolButtonMapping(cState.PS))
result = DS4Controls.PS;
else if (Mapping.getBoolAxisDirMapping(cState.LX, true))
result = DS4Controls.LXPos;
else if (Mapping.getBoolAxisDirMapping(cState.LX, false))
result = DS4Controls.LXNeg;
else if (Mapping.getBoolAxisDirMapping(cState.LY, true))
result = DS4Controls.LYPos;
else if (Mapping.getBoolAxisDirMapping(cState.LY, false))
result = DS4Controls.LYNeg;
else if (Mapping.getBoolAxisDirMapping(cState.RX, true))
result = DS4Controls.RXPos;
else if (Mapping.getBoolAxisDirMapping(cState.RX, false))
result = DS4Controls.RXNeg;
else if (Mapping.getBoolAxisDirMapping(cState.RY, true))
result = DS4Controls.RYPos;
else if (Mapping.getBoolAxisDirMapping(cState.RY, false))
result = DS4Controls.RYNeg;
else if (Mapping.getBoolTouchMapping(tp.leftDown))
result = DS4Controls.TouchLeft;
else if (Mapping.getBoolTouchMapping(tp.rightDown))
result = DS4Controls.TouchRight;
else if (Mapping.getBoolTouchMapping(tp.multiDown))
result = DS4Controls.TouchMulti;
else if (Mapping.getBoolTouchMapping(tp.upperDown))
result = DS4Controls.TouchUpper;
}
return result;
}
public bool[] touchreleased = new bool[MAX_DS4_CONTROLLER_COUNT] { true, true, true, true, true, true, true, true },
touchslid = new bool[MAX_DS4_CONTROLLER_COUNT] { false, false, false, false, false, false, false, false };
public Dispatcher EventDispatcher { get => eventDispatcher; }
public OutputSlotManager OutputslotMan { get => outputslotMan; }
protected virtual void CheckForTouchToggle(int deviceID, DS4State cState, DS4State pState)
{
if (!IsUsingTouchpadForControls(deviceID) && cState.Touch1 && pState.PS)
{
if (GetTouchActive(deviceID) && touchreleased[deviceID])
{
TouchActive[deviceID] = false;
LogDebug(DS4WinWPF.Properties.Resources.TouchpadMovementOff);
AppLogger.LogToTray(DS4WinWPF.Properties.Resources.TouchpadMovementOff);
touchreleased[deviceID] = false;
}
else if (touchreleased[deviceID])
{
TouchActive[deviceID] = true;
LogDebug(DS4WinWPF.Properties.Resources.TouchpadMovementOn);
AppLogger.LogToTray(DS4WinWPF.Properties.Resources.TouchpadMovementOn);
touchreleased[deviceID] = false;
}
}
else
touchreleased[deviceID] = true;
}
public virtual void StartTPOff(int deviceID)
{
if (deviceID < CURRENT_DS4_CONTROLLER_LIMIT)
{
TouchActive[deviceID] = false;
}
}
public virtual string TouchpadSlide(int ind)
{
DS4State cState = CurrentState[ind];
string slidedir = "none";
if (DS4Controllers[ind] != null && cState.Touch2 &&
!(touchPad[ind].dragging || touchPad[ind].dragging2))
{
if (touchPad[ind].slideright && !touchslid[ind])
{
slidedir = "right";
touchslid[ind] = true;
}
else if (touchPad[ind].slideleft && !touchslid[ind])
{
slidedir = "left";
touchslid[ind] = true;
}
else if (!touchPad[ind].slideleft && !touchPad[ind].slideright)
{
slidedir = "";
touchslid[ind] = false;
}
}
return slidedir;
}
public virtual void LogDebug(String Data, bool warning = false)
{
//Console.WriteLine(System.DateTime.Now.ToString("G") + "> " + Data);
if (Debug != null)
{
DebugEventArgs args = new DebugEventArgs(Data, warning);
OnDebug(this, args);
}
}
public virtual void OnDebug(object sender, DebugEventArgs args)
{
if (Debug != null)
Debug(this, args);
}
// sets the rumble adjusted with rumble boost. General use method
public virtual void setRumble(byte heavyMotor, byte lightMotor, int deviceNum)
{
if (deviceNum < CURRENT_DS4_CONTROLLER_LIMIT)
{
DS4Device device = DS4Controllers[deviceNum];
if (device != null)
SetDevRumble(device, heavyMotor, lightMotor, deviceNum);
//device.setRumble((byte)lightBoosted, (byte)heavyBoosted);
}
}
// sets the rumble adjusted with rumble boost. Method more used for
// report handling. Avoid constant checking for a device.
public void SetDevRumble(DS4Device device,
byte heavyMotor, byte lightMotor, int deviceNum)
{
byte boost = getRumbleBoost(deviceNum);
uint lightBoosted = ((uint)lightMotor * (uint)boost) / 100;
if (lightBoosted > 255)
lightBoosted = 255;
uint heavyBoosted = ((uint)heavyMotor * (uint)boost) / 100;
if (heavyBoosted > 255)
heavyBoosted = 255;
device.setRumble((byte)lightBoosted, (byte)heavyBoosted);
}
public DS4State getDS4State(int ind)
{
return CurrentState[ind];
}
public DS4State getDS4StateMapped(int ind)
{
return MappedState[ind];
}
public DS4State getDS4StateTemp(int ind)
{
return TempState[ind];
}
}
}
| 44.163154 | 265 | 0.494953 | [
"MIT"
] | Adminixtrator/DS4Windows | DS4Windows/DS4Control/ControlService.cs | 113,148 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using BikeDataProject.Integrations.Fitbit.API;
using BikeDataProject.Integrations.Fitbit.Db;
using Fitbit.Api.Portable;
using Fitbit.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
namespace BikeDataProject.Integrations.FitBit.API.Controllers
{
[ApiController]
public class SubscriptionController : ControllerBase
{
private readonly ILogger<SubscriptionController> _logger;
private readonly SubscriptionControllerSettings _configuration;
private readonly FitbitDbContext _db;
private readonly HashSet<int> _activityTypes = new();
public SubscriptionController(ILogger<SubscriptionController> logger,
SubscriptionControllerSettings configuration,
FitbitDbContext db)
{
_logger = logger;
_configuration = configuration;
_db = db;
}
private DateTime _lastActivityTypeSync = DateTime.Now;
[HttpGet]
[Route("subscriptions")]
public IActionResult Verify([FromQuery] string? verify)
{
try
{
_logger.LogInformation($"Request to verify: {verify}");
// implements verification mechanism as described:
// https://dev.fitbit.com/build/reference/web-api/subscriptions/#verify-a-subscriber
if (string.IsNullOrWhiteSpace(verify)) return new NotFoundResult();
// this is a verification request, response if the code matches.
if (_configuration.SubscriptionVerificationCode == verify)
{
return new NoContentResult();
}
return new NotFoundResult();
}
catch (Exception e)
{
_logger.LogError(e, $"{nameof(SubscriptionController)}.{nameof(Verify)}");
throw;
}
}
[HttpPost]
[Route("subscriptions")]
public async Task<IActionResult> SubscriptionData()
{
try
{
List<UpdatedResource> updatedResources; //all the updated users and which resources
using (var sr = new StreamReader(Request.Body))
{
var responseText = await sr.ReadToEndAsync();
//note, you can store the raw response from fitbit here if you like
_logger.LogWarning($"Fitbit subscription post: {responseText}");
updatedResources = SubscriptionManager.ProcessUpdateReponseBody(responseText);
}
foreach (var updatedResource in updatedResources)
{
_logger.LogInformation($"Received: {updatedResource.CollectionType}");
if (updatedResource.CollectionType != APICollectionType.activities) continue;
// get the user associated with the subscription id.
var user = _db.GetUserForSubscription(updatedResource.SubscriptionId);
if (user == null)
{
_logger.LogError(
$"No user was found for subscription id: {updatedResource.SubscriptionId}");
continue;
}
// save update resource.
var ur = _db.DaysToSync
.FirstOrDefault(x => x.UserId == user.Id && x.Day == updatedResource.Date);
if (ur != null)
{
ur.Synced = false;
_db.DaysToSync.Update(ur);
}
if (ur == null)
{
ur = new DayToSync()
{
UserId = user.Id,
User = user,
Day = updatedResource.Date,
Synced = false
};
await _db.DaysToSync.AddAsync(ur);
}
await _db.SaveChangesAsync();
}
return new NoContentResult();
}
catch (Exception e)
{
_logger.LogError(e, $"{nameof(SubscriptionController)}.{nameof(SubscriptionData)}");
throw;
}
}
private async Task<bool> SyncActivityTypes(FitbitClient fitbitClient)
{
if ((DateTime.Now - _lastActivityTypeSync).TotalHours > 2)
{
_activityTypes.Clear();
}
if (_activityTypes.Count == 0)
{
_activityTypes.UnionWith(await fitbitClient.GetBicycleActivityTypes());
_lastActivityTypeSync = DateTime.Now;
}
if (_activityTypes.Count == 0)
{
_logger.LogCritical("Bicycling activity types not found, cannot synchronize activities without them.");
return false;
}
return true;
}
}
} | 26.711409 | 107 | 0.69799 | [
"MIT"
] | bikedataproject/fitbit-integration | src/BikeDataProject.Integrations.Fitbit.API/Controllers/SubscriptionController.cs | 3,980 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace DebuggerTesting.Utilities
{
internal static class HashUtilities
{
#region Methods
public static int CombineHashCodes(int h1, int h2)
{
return (h1 << 5) + h1 ^ h2;
}
internal static int CombineHashCodes(int h1, int h2, int h3)
{
return HashUtilities.CombineHashCodes(HashUtilities.CombineHashCodes(h1, h2), h3);
}
internal static int CombineHashCodes(int h1, int h2, int h3, int h4)
{
return HashUtilities.CombineHashCodes(HashUtilities.CombineHashCodes(h1, h2), HashUtilities.CombineHashCodes(h3, h4));
}
internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5)
{
return HashUtilities.CombineHashCodes(HashUtilities.CombineHashCodes(h1, h2, h3, h4), h5);
}
#endregion
}
} | 32.21875 | 130 | 0.642095 | [
"MIT"
] | Hedges/MIEngine | test/DebuggerTesting/Utilities/HashUtilities.cs | 1,033 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace RRHH.Models
{
public class Department
{
[Key]
public Int32 DepartmentId { get; set; }
[Required]
public Int32 CompanyId { get; set; }
[StringLength(100)]
public string Name { get; set; }
public bool IsActive { get; set; }
public virtual Company Company { get; set; }
public virtual ICollection<Employee> Employees { get; set; }
}
} | 26.05 | 68 | 0.627639 | [
"CC0-1.0"
] | serpel/TimeSheetRRHH | RRHH/RRHH/Models/Department.cs | 523 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using Android.Runtime;
using Java.Interop;
namespace Android.Runtime {
[Register ("java/util/HashMap", DoNotGenerateAcw=true)]
public class JavaDictionary : Java.Lang.Object, System.Collections.IDictionary {
class DictionaryEnumerator : IDictionaryEnumerator {
IEnumerator simple_enumerator;
public DictionaryEnumerator (JavaDictionary owner)
{
simple_enumerator = (owner as IEnumerable).GetEnumerator ();
}
public object Current {
get { return simple_enumerator.Current; }
}
public DictionaryEntry Entry {
get { return (DictionaryEntry) Current; }
}
public object Key {
get { return Entry.Key; }
}
public object Value {
get { return Entry.Value; }
}
public bool MoveNext ()
{
return simple_enumerator.MoveNext ();
}
public void Reset ()
{
simple_enumerator.Reset ();
}
}
internal static IntPtr map_class = JNIEnv.FindClass ("java/util/Map");
static IntPtr id_clear;
internal static IntPtr id_containsKey;
internal static IntPtr id_get;
static IntPtr id_keySet;
internal static IntPtr id_put;
internal static IntPtr id_remove;
static IntPtr id_size;
static IntPtr id_values;
//
// Exception audit:
//
// Verdict
// Exception wrapping is required.
//
// Rationale
// `java.util.Collection.get(Object, Object)` throws a number of exceptions, see:
//
// https://developer.android.com/reference/java/util/Map#get(java.lang.Object)
//
internal object Get (object key)
{
if (id_get == IntPtr.Zero)
id_get = JNIEnv.GetMethodID (map_class, "get", "(Ljava/lang/Object;)Ljava/lang/Object;");
return JavaConvert.FromJniHandle (
JavaConvert.WithLocalJniHandle (key, lref => {
try {
return JNIEnv.CallObjectMethod (Handle, id_get, new JValue (lref));
} catch (Java.Lang.ClassCastException ex) when (JNIEnv.ShouldWrapJavaException (ex)) {
throw new InvalidCastException (ex.Message, ex);
} catch (Java.Lang.NullPointerException ex) when (JNIEnv.ShouldWrapJavaException (ex)) {
throw new NullReferenceException (ex.Message, ex);
}
}), JniHandleOwnership.TransferLocalRef);
}
//
// Exception audit:
//
// Verdict
// No need to wrap thrown exceptions in a BCL class
//
// Rationale
// `java.util.Map.keySet()` is not documented to throw any exceptions.
//
internal IntPtr GetKeys ()
{
if (id_keySet == IntPtr.Zero)
id_keySet = JNIEnv.GetMethodID (map_class, "keySet", "()Ljava/util/Set;");
return JNIEnv.CallObjectMethod (Handle, id_keySet);
}
//
// Exception audit:
//
// Verdict
// No need to wrap thrown exceptions in a BCL class
//
// Rationale
// `java.util.Map.values()` is not documented to throw any exceptions.
//
internal IntPtr GetValues ()
{
if (id_values == IntPtr.Zero)
id_values = JNIEnv.GetMethodID (map_class, "values", "()Ljava/util/Collection;");
return JNIEnv.CallObjectMethod (Handle, id_values);
}
//
// Exception audit:
//
// Verdict
// Exception wrapping is required.
//
// Rationale
// `java.util.Map.put(K, V)` throws a number of exceptions, see:
//
// https://developer.android.com/reference/java/util/Map#put(K,%20V)
//
internal void Put (object key, object value)
{
if (id_put == IntPtr.Zero)
id_put = JNIEnv.GetMethodID (map_class, "put", "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;");
IntPtr r = JavaConvert.WithLocalJniHandle (key,
lrefKey => JavaConvert.WithLocalJniHandle (value,
lrefValue => {
try {
return JNIEnv.CallObjectMethod (Handle, id_put, new JValue (lrefKey), new JValue (lrefValue));
} catch (Java.Lang.UnsupportedOperationException ex) when (JNIEnv.ShouldWrapJavaException (ex)) {
throw new NotSupportedException (ex.Message, ex);
} catch (Java.Lang.ClassCastException ex) when (JNIEnv.ShouldWrapJavaException (ex)) {
throw new InvalidCastException (ex.Message, ex);
} catch (Java.Lang.NullPointerException ex) when (JNIEnv.ShouldWrapJavaException (ex)) {
throw new NullReferenceException (ex.Message, ex);
} catch (Java.Lang.IllegalArgumentException ex) when (JNIEnv.ShouldWrapJavaException (ex)) {
throw new ArgumentException (ex.Message, ex);
}
}
)
);
JNIEnv.DeleteLocalRef (r);
}
//
// Exception audit:
//
// Verdict
// No need to wrap thrown exceptions in a BCL class
//
// Rationale
// `java.util.HasMap.ctor()` is not documented to throw any exceptions. The `else` clause below
// instantiates a type we don't know at this time, so we have no information about the exceptions
// it may throw.
//
[Register (".ctor", "()V", "")]
public JavaDictionary ()
: base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer)
{
if (Handle != IntPtr.Zero)
return;
if (GetType () == typeof (JavaDictionary)) {
SetHandle (
JNIEnv.StartCreateInstance ("java/util/HashMap", "()V"),
JniHandleOwnership.TransferLocalRef);
JNIEnv.FinishCreateInstance (Handle, "()V");
} else {
SetHandle (
JNIEnv.StartCreateInstance (GetType (), "()V"),
JniHandleOwnership.TransferLocalRef);
JNIEnv.FinishCreateInstance (Handle, "()V");
}
}
public JavaDictionary (IntPtr handle, JniHandleOwnership transfer)
: base (handle, transfer)
{
}
public JavaDictionary (IDictionary items) : this ()
{
if (items == null) {
Dispose ();
throw new ArgumentNullException ("items");
}
foreach (DictionaryEntry item in items)
Add (item.Key, item.Value);
}
//
// Exception audit:
//
// Verdict
// No need to wrap thrown exceptions in a BCL class
//
// Rationale
// `java.util.Map.size()` is not documented to throw any exceptions.
//
public int Count {
get {
if (id_size == IntPtr.Zero)
id_size = JNIEnv.GetMethodID (map_class, "size", "()I");
return JNIEnv.CallIntMethod (Handle, id_size);
}
}
public bool IsFixedSize {
get { return false; }
}
public bool IsReadOnly {
get { return false; }
}
public bool IsSynchronized {
get { return false; }
}
public ICollection Keys {
get { return new JavaSet (GetKeys (), JniHandleOwnership.TransferLocalRef); }
}
public object SyncRoot {
get { return null; }
}
public ICollection Values {
get { return new JavaCollection (GetValues (), JniHandleOwnership.TransferLocalRef); }
}
public object this [object key] {
get { return Get (key); }
set { Put (key, value); }
}
public void Add (object key, object value)
{
if (Contains (key))
throw new ArgumentException ("The key '" + key + "' already exists.", "key");
Put (key, value);
}
//
// Exception audit:
//
// Verdict
// Exception wrapping is required.
//
// Rationale
// `java.util.Map.clear()` throws an exceptions, see:
//
// https://developer.android.com/reference/java/util/Map.html?hl=en#clear()
//
public void Clear ()
{
if (id_clear == IntPtr.Zero)
id_clear = JNIEnv.GetMethodID (map_class, "clear", "()V");
try {
JNIEnv.CallVoidMethod (Handle, id_clear);
} catch (Java.Lang.UnsupportedOperationException ex) when (JNIEnv.ShouldWrapJavaException (ex)) {
throw new NotSupportedException (ex.Message, ex);
}
}
//
// Exception audit:
//
// Verdict
// Exception wrapping is required.
//
// Rationale
// `java.util.Map.containsKey(Object)` throws a number of exceptions, see:
//
// https://developer.android.com/reference/java/util/Map.html?hl=en#containsKey(java.lang.Object)
//
public bool Contains (object key)
{
if (id_containsKey == IntPtr.Zero)
id_containsKey = JNIEnv.GetMethodID (map_class, "containsKey", "(Ljava/lang/Object;)Z");
return JavaConvert.WithLocalJniHandle (key, lref => {
try {
return JNIEnv.CallBooleanMethod (Handle, id_containsKey, new JValue (lref));
} catch (Java.Lang.ClassCastException ex) when (JNIEnv.ShouldWrapJavaException (ex)) {
throw new InvalidCastException (ex.Message, ex);
} catch (Java.Lang.NullPointerException ex) when (JNIEnv.ShouldWrapJavaException (ex)) {
throw new NullReferenceException (ex.Message, ex);
}
});
}
public void CopyTo (Array array, int array_index)
{
if (array == null)
throw new ArgumentNullException ("array");
else if (array_index < 0)
throw new ArgumentOutOfRangeException ("array_index");
else if (array.Length < array_index + Count)
throw new ArgumentException ("array");
int i = 0;
foreach (object o in this)
array.SetValue (o, array_index + i++);
}
IEnumerator IEnumerable.GetEnumerator ()
{
foreach (object key in Keys)
yield return new DictionaryEntry (key, this [key]);
}
public IDictionaryEnumerator GetEnumerator ()
{
return new DictionaryEnumerator (this);
}
//
// Exception audit:
//
// Verdict
// Exception wrapping is required.
//
// Rationale
// `java.util.Map.remove(Object, Object)` throws a number of exceptions, see:
//
// https://developer.android.com/reference/java/util/Map.html?hl=en#remove(java.lang.Object,%20java.lang.Object)
//
public void Remove (object key)
{
if (id_remove == IntPtr.Zero)
id_remove = JNIEnv.GetMethodID (map_class, "remove", "(Ljava/lang/Object;)Ljava/lang/Object;");
IntPtr r = JavaConvert.WithLocalJniHandle (key, lref => {
try {
return JNIEnv.CallObjectMethod (Handle, id_remove, new JValue (lref));
} catch (Java.Lang.UnsupportedOperationException ex) when (JNIEnv.ShouldWrapJavaException (ex)) {
throw new NotSupportedException (ex.Message, ex);
} catch (Java.Lang.ClassCastException ex) when (JNIEnv.ShouldWrapJavaException (ex)) {
throw new InvalidCastException (ex.Message, ex);
} catch (Java.Lang.NullPointerException ex) when (JNIEnv.ShouldWrapJavaException (ex)) {
throw new NullReferenceException (ex.Message, ex);
}
});
JNIEnv.DeleteLocalRef (r);
}
[Preserve (Conditional=true)]
public static IDictionary FromJniHandle (IntPtr handle, JniHandleOwnership transfer)
{
if (handle == IntPtr.Zero)
return null;
IJavaObject inst = Java.Lang.Object.PeekObject (handle);
if (inst == null)
inst = new JavaDictionary (handle, transfer);
else
JNIEnv.DeleteRef (handle, transfer);
return (IDictionary) inst;
}
[Preserve (Conditional=true)]
public static IntPtr ToLocalJniHandle (IDictionary dictionary)
{
if (dictionary == null)
return IntPtr.Zero;
var d = dictionary as JavaDictionary;
if (d != null)
return JNIEnv.ToLocalJniHandle (d);
using (d = new JavaDictionary (dictionary))
return JNIEnv.ToLocalJniHandle (d);
}
}
//
// Exception audit:
//
// Verdict
// No need to wrap thrown exceptions in a BCL class
//
// Rationale
// `java.util.HasMap.ctor()` is not documented to throw any exceptions. The `else` clause below
// instantiates a type we don't know at this time, so we have no information about the exceptions
// it may throw.
//
[Register ("java/util/HashMap", DoNotGenerateAcw=true)]
public class JavaDictionary<K, V> : JavaDictionary, IDictionary<K, V> {
[Register (".ctor", "()V", "")]
public JavaDictionary ()
: base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer)
{
if (Handle != IntPtr.Zero)
return;
if (GetType () == typeof (JavaDictionary<K, V>)) {
SetHandle (
JNIEnv.StartCreateInstance ("java/util/HashMap", "()V"),
JniHandleOwnership.TransferLocalRef);
} else {
SetHandle (
JNIEnv.StartCreateInstance (GetType (), "()V"),
JniHandleOwnership.TransferLocalRef);
}
JNIEnv.FinishCreateInstance (Handle, "()V");
}
public JavaDictionary (IntPtr handle, JniHandleOwnership transfer)
: base (handle, transfer)
{
}
public JavaDictionary (IDictionary<K, V> items) : this ()
{
if (items == null) {
Dispose ();
throw new ArgumentNullException ("items");
}
foreach (K key in items.Keys)
Add (key, items [key]);
}
//
// Exception audit:
//
// Verdict
// Exception wrapping is required.
//
// Rationale
// `java.util.Collection.get(Object, Object)` throws a number of exceptions, see:
//
// https://developer.android.com/reference/java/util/Map#get(java.lang.Object)
//
internal V Get (K key)
{
if (id_get == IntPtr.Zero)
id_get = JNIEnv.GetMethodID (map_class, "get", "(Ljava/lang/Object;)Ljava/lang/Object;");
var v = JavaConvert.WithLocalJniHandle (key, lref => {
try {
return JNIEnv.CallObjectMethod (Handle, id_get, new JValue (lref));
} catch (Java.Lang.ClassCastException ex) when (JNIEnv.ShouldWrapJavaException (ex)) {
throw new InvalidCastException (ex.Message, ex);
} catch (Java.Lang.NullPointerException ex) when (JNIEnv.ShouldWrapJavaException (ex)) {
throw new NullReferenceException (ex.Message, ex);
}
});
return JavaConvert.FromJniHandle<V>(v, JniHandleOwnership.TransferLocalRef);
}
//
// Exception audit:
//
// Verdict
// Exception wrapping is required.
//
// Rationale
// `java.util.Map.put(K, V)` throws a number of exceptions, see:
//
// https://developer.android.com/reference/java/util/Map#put(K,%20V)
//
internal void Put (K key, V value)
{
if (id_put == IntPtr.Zero)
id_put = JNIEnv.GetMethodID (map_class, "put", "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;");
IntPtr r = JavaConvert.WithLocalJniHandle (key,
lrefKey => JavaConvert.WithLocalJniHandle (value,
lrefValue => {
try {
return JNIEnv.CallObjectMethod (Handle, id_put, new JValue (lrefKey), new JValue (lrefValue));
} catch (Java.Lang.UnsupportedOperationException ex) when (JNIEnv.ShouldWrapJavaException (ex)) {
throw new NotSupportedException (ex.Message, ex);
} catch (Java.Lang.ClassCastException ex) when (JNIEnv.ShouldWrapJavaException (ex)) {
throw new InvalidCastException (ex.Message, ex);
} catch (Java.Lang.NullPointerException ex) when (JNIEnv.ShouldWrapJavaException (ex)) {
throw new NullReferenceException (ex.Message, ex);
} catch (Java.Lang.IllegalArgumentException ex) when (JNIEnv.ShouldWrapJavaException (ex)) {
throw new ArgumentException (ex.Message, ex);
}
}
)
);
JNIEnv.DeleteLocalRef (r);
}
public V this [K key] {
get {
if (!Contains (key))
throw new KeyNotFoundException ();
return Get (key);
}
set {
Put (key, value);
}
}
public ICollection<K> Keys {
get { return new JavaSet<K> (GetKeys (), JniHandleOwnership.TransferLocalRef); }
}
public ICollection<V> Values {
get { return new JavaCollection<V> (GetValues (), JniHandleOwnership.TransferLocalRef); }
}
public void Add (KeyValuePair<K, V> item)
{
Add (item.Key, item.Value);
}
public void Add (K key, V value)
{
if (ContainsKey (key))
throw new ArgumentException ("The key '" + key + "' already exists.", "key");
Put (key, value);
}
public bool Contains (KeyValuePair<K, V> item)
{
return ContainsKey (item.Key);
}
//
// Exception audit:
//
// Verdict
// Exception wrapping is required.
//
// Rationale
// `java.util.Map.containsKey(Object)` throws a number of exceptions, see:
//
// https://developer.android.com/reference/java/util/Map.html?hl=en#containsKey(java.lang.Object)
//
public bool ContainsKey (K key)
{
if (id_containsKey == IntPtr.Zero)
id_containsKey = JNIEnv.GetMethodID (map_class, "containsKey", "(Ljava/lang/Object;)Z");
return JavaConvert.WithLocalJniHandle (key, lref => {
try {
return JNIEnv.CallBooleanMethod (Handle, id_containsKey, new JValue (lref));
} catch (Java.Lang.ClassCastException ex) when (JNIEnv.ShouldWrapJavaException (ex)) {
throw new InvalidCastException (ex.Message, ex);
} catch (Java.Lang.NullPointerException ex) when (JNIEnv.ShouldWrapJavaException (ex)) {
throw new NullReferenceException (ex.Message, ex);
}
});
}
public void CopyTo (KeyValuePair<K, V>[] array, int array_index)
{
if (array == null)
throw new ArgumentNullException ("array");
else if (array_index < 0)
throw new ArgumentOutOfRangeException ("array_index");
else if (array.Length < array_index + Count)
throw new ArgumentException ("array");
int i = 0;
foreach (KeyValuePair<K, V> pair in this)
array [array_index + i++] = pair;
}
IEnumerator IEnumerable.GetEnumerator ()
{
return GetEnumerator ();
}
public IEnumerator<KeyValuePair<K, V>> GetEnumerator ()
{
foreach (K key in Keys)
yield return new KeyValuePair<K, V> (key, this [key]);
}
public bool Remove (KeyValuePair<K, V> pair)
{
return Remove (pair.Key);
}
//
// Exception audit:
//
// Verdict
// Exception wrapping is required.
//
// Rationale
// `java.util.Map.remove(Object, Object)` throws a number of exceptions, see:
//
// https://developer.android.com/reference/java/util/Map.html?hl=en#remove(java.lang.Object,%20java.lang.Object)
//
public bool Remove (K key)
{
bool contains = ContainsKey (key);
if (id_remove == IntPtr.Zero)
id_remove = JNIEnv.GetMethodID (map_class, "remove", "(Ljava/lang/Object;)Ljava/lang/Object;");
IntPtr r = JavaConvert.WithLocalJniHandle (key, lref => {
try {
return JNIEnv.CallObjectMethod (Handle, id_remove, new JValue (lref));
} catch (Java.Lang.UnsupportedOperationException ex) when (JNIEnv.ShouldWrapJavaException (ex)) {
throw new NotSupportedException (ex.Message, ex);
} catch (Java.Lang.ClassCastException ex) when (JNIEnv.ShouldWrapJavaException (ex)) {
throw new InvalidCastException (ex.Message, ex);
} catch (Java.Lang.NullPointerException ex) when (JNIEnv.ShouldWrapJavaException (ex)) {
throw new NullReferenceException (ex.Message, ex);
}
});
JNIEnv.DeleteLocalRef (r);
return contains;
}
public bool TryGetValue (K key, out V value)
{
value = Get (key);
return ContainsKey (key);
}
[Preserve (Conditional=true)]
public static IDictionary<K, V> FromJniHandle (IntPtr handle, JniHandleOwnership transfer)
{
if (handle == IntPtr.Zero)
return null;
IJavaObject inst = Java.Lang.Object.PeekObject (handle);
if (inst == null)
inst = new JavaDictionary<K, V> (handle, transfer);
else
JNIEnv.DeleteRef (handle, transfer);
return (IDictionary<K, V>) inst;
}
[Preserve (Conditional=true)]
public static IntPtr ToLocalJniHandle (IDictionary<K, V> dictionary)
{
if (dictionary == null)
return IntPtr.Zero;
var d = dictionary as JavaDictionary<K, V>;
if (d != null)
return JNIEnv.ToLocalJniHandle (d);
using (d = new JavaDictionary<K, V>(dictionary))
return JNIEnv.ToLocalJniHandle (d);
}
}
}
| 29.083714 | 118 | 0.663544 | [
"MIT"
] | BrzVlad/xamarin-android | src/Mono.Android/Android.Runtime/JavaDictionary.cs | 19,108 | C# |
using System;
namespace TronRacers
{
public class Program
{
static int firstPlayerRowPosition;
static int firstPlayerColPosition;
static int secondPlayerRowPosition;
static int secondPlayerColPosition;
static bool isAlive = true;
static void Main()
{
int size = int.Parse(Console.ReadLine());
char[,] matrix = new char[size, size];
for (int row = 0; row < size; row++)
{
var currentCol = Console.ReadLine().ToCharArray();
for (int col = 0; col < currentCol.Length; col++)
{
matrix[row, col] = currentCol[col];
if (currentCol[col] == 'f')
{
firstPlayerRowPosition = row;
firstPlayerColPosition = col;
}
else if (currentCol[col] == 's')
{
secondPlayerRowPosition = row;
secondPlayerColPosition = col;
}
}
}
while (isAlive != false)
{
var input = Console.ReadLine().Split();
var firstPlayerCommand = input[0];
var secondPlayerCommand = input[1];
FirstPlayerMovement(matrix, firstPlayerCommand);
if (isAlive != false)
{
SecondPlayerMovement(matrix, secondPlayerCommand);
}
}
for (int row = 0; row < matrix.GetLength(0); row++)
{
for (int col = 0; col < matrix.GetLength(1); col++)
{
Console.Write(matrix[row, col]);
}
Console.WriteLine();
}
}
private static void SecondPlayerMovement(char[,] matrix, string command)
{
switch (command)
{
case "up":
if (secondPlayerRowPosition - 1 < 0)
{
secondPlayerRowPosition = matrix.GetLength(0) - 1;
}
else
{
secondPlayerRowPosition--;
}
if (matrix[secondPlayerRowPosition, secondPlayerColPosition] == 'f')
{
matrix[secondPlayerRowPosition, secondPlayerColPosition] = 'x';
isAlive = false;
}
else
{
matrix[secondPlayerRowPosition, secondPlayerColPosition] = 's';
}
break;
case "down":
if (secondPlayerRowPosition + 1 > matrix.GetLength(0) - 1)
{
secondPlayerRowPosition = 0;
}
else
{
secondPlayerRowPosition++;
}
if (matrix[secondPlayerRowPosition, secondPlayerColPosition] == 'f')
{
matrix[secondPlayerRowPosition, secondPlayerColPosition] = 'x';
isAlive = false;
}
else
{
matrix[secondPlayerRowPosition, secondPlayerColPosition] = 's';
}
break;
case "left":
if (secondPlayerColPosition - 1 < 0)
{
secondPlayerColPosition = matrix.GetLength(1) - 1;
}
else
{
secondPlayerColPosition--;
}
if (matrix[secondPlayerRowPosition, secondPlayerColPosition] == 'f')
{
matrix[secondPlayerRowPosition, secondPlayerColPosition] = 'x';
isAlive = false;
}
else
{
matrix[secondPlayerRowPosition, secondPlayerColPosition] = 's';
}
break;
case "right":
if (secondPlayerColPosition + 1 > matrix.GetLength(1) - 1)
{
secondPlayerColPosition = 0;
}
else
{
secondPlayerColPosition++;
}
if (matrix[secondPlayerRowPosition, secondPlayerColPosition] == 'f')
{
matrix[secondPlayerRowPosition, secondPlayerColPosition] = 'x';
isAlive = false;
}
else
{
matrix[secondPlayerRowPosition, secondPlayerColPosition] = 's';
}
break;
}
}
private static void FirstPlayerMovement(char[,] matrix, string command)
{
switch (command)
{
case "up":
if (firstPlayerRowPosition - 1 < 0)
{
firstPlayerRowPosition = matrix.GetLength(0) - 1;
}
else
{
firstPlayerRowPosition--;
}
if (matrix[firstPlayerRowPosition, firstPlayerColPosition] == 's')
{
matrix[firstPlayerRowPosition, firstPlayerColPosition] = 'x';
isAlive = false;
}
else
{
matrix[firstPlayerRowPosition, firstPlayerColPosition] = 'f';
}
break;
case "down":
if (firstPlayerRowPosition + 1 > matrix.GetLength(0) - 1)
{
firstPlayerRowPosition = 0;
}
else
{
firstPlayerRowPosition++;
}
if (matrix[firstPlayerRowPosition, firstPlayerColPosition] == 's')
{
matrix[firstPlayerRowPosition, firstPlayerColPosition] = 'x';
isAlive = false;
}
else
{
matrix[firstPlayerRowPosition, firstPlayerColPosition] = 'f';
}
break;
case "left":
if (firstPlayerColPosition - 1 < 0)
{
firstPlayerColPosition = matrix.GetLength(1) - 1;
}
else
{
firstPlayerColPosition--;
}
if (matrix[firstPlayerRowPosition, firstPlayerColPosition] == 's')
{
matrix[firstPlayerRowPosition, firstPlayerColPosition] = 'x';
isAlive = false;
}
else
{
matrix[firstPlayerRowPosition, firstPlayerColPosition] = 'f';
}
break;
case "right":
if (firstPlayerColPosition + 1 > matrix.GetLength(1) - 1)
{
firstPlayerColPosition = 0;
}
else
{
firstPlayerColPosition++;
}
if (matrix[firstPlayerRowPosition, firstPlayerColPosition] == 's')
{
matrix[firstPlayerRowPosition, firstPlayerColPosition] = 'x';
isAlive = false;
}
else
{
matrix[firstPlayerRowPosition, firstPlayerColPosition] = 'f';
}
break;
}
}
}
}
| 32.992095 | 88 | 0.383731 | [
"MIT"
] | ITonev/SoftUni | C#-Advanced/Practice-Exams/24-February-2019/ExamProblems/TronRacers/Program.cs | 8,349 | C# |
// -----------------------------------------------------------------------
// <copyright file="UnitOfWorkAttribute.cs" company="OSharp开源团队">
// Copyright (c) 2014-2019 OSharp. All rights reserved.
// </copyright>
// <site>http://www.osharp.org</site>
// <last-editor>郭明锋</last-editor>
// <last-date>2019-05-14 17:37</last-date>
// -----------------------------------------------------------------------
using System;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.DependencyInjection;
using OSharp.Dependency;
using OSharp.Entity;
namespace OSharp.AspNetCore.Mvc.Filters
{
/// <summary>
/// 自动事务提交过滤器,在<see cref="ActionFilterAttribute.OnResultExecuted"/>方法中执行<see cref="IUnitOfWork.Commit()"/>进行事务提交
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
[Dependency(ServiceLifetime.Scoped, AddSelf = true)]
public class UnitOfWorkAttribute : ServiceFilterAttribute
{
/// <summary>
/// 初始化一个<see cref="UnitOfWorkAttribute"/>类型的新实例
/// </summary>
public UnitOfWorkAttribute()
: base(typeof(UnitOfWorkFilterImpl))
{ }
}
} | 33.277778 | 116 | 0.604341 | [
"Apache-2.0"
] | 2012desuming/osharp | src/OSharp.AspNetCore/Mvc/Filters/UnitOfWorkAttribute.cs | 1,280 | C# |
using System;
using PlainElastic.Net.Utils;
namespace PlainElastic.Net.Mappings
{
/// <summary>
/// Represents custom field mapping.
/// This type of mapping useful when you need to provide runtime property mapping.
/// </summary>
public class CustomPropertyMap<T> : PropertyBase<T, CustomPropertyMap<T>>
{
private string mappingType;
public CustomPropertyMap() {}
public CustomPropertyMap(string name, Type fieldType)
{
Field(name, fieldType);
}
public CustomPropertyMap(string name, string mappingType)
{
this.mappingType = mappingType;
Field(name);
}
/// <summary>
/// Allows explicitly specify ES type of the mapping.
/// </summary>
public CustomPropertyMap<T> Type(string mappingType)
{
this.mappingType = mappingType;
FieldType = mappingType;
return this;
}
/// <summary>
/// Allows to build a condition dependent mapping.
/// Mapping will be applied only when condition true.
/// </summary>
public CustomPropertyMap<T> When(bool condition, Func<CustomPropertyMap<T>, CustomPropertyMap<T>> mapping)
{
if (condition)
mapping(this);
return this;
}
/// <summary>
/// Allows to specify the date format.
/// All dates are UTC.
/// see http://www.elasticsearch.org/guide/reference/mapping/date-format.html
/// </summary>
public CustomPropertyMap<T> Format(string dateFormat)
{
RegisterCustomJsonMap("'format': {0}", dateFormat.Quotate());
return this;
}
/// <summary>
/// The precision step (number of terms generated for each number value). Defaults to 4.
/// </summary>
public CustomPropertyMap<T> PrecisionStep(int precisionStep = 4)
{
RegisterCustomJsonMap("'precision_step': {0}", precisionStep.AsString());
return this;
}
public CustomPropertyMap<T> TermVector(TermVector termVector)
{
RegisterCustomJsonMap("'term_vector': {0}", termVector.AsString().Quotate());
return this;
}
/// <summary>
/// Defines if norms should be omitted or not.
/// </summary>
public CustomPropertyMap<T> OmitNorms(bool omitNorms = false)
{
RegisterCustomJsonMap("'omit_norms': {0}", omitNorms.AsString());
return this;
}
/// <summary>
/// Defines if term freq and positions should be omitted.
/// </summary>
public CustomPropertyMap<T> OmitTermFreqAndPositions(bool omitTermFreqAndPositions = false)
{
RegisterCustomJsonMap("'omit_term_freq_and_positions': {0}", omitTermFreqAndPositions.AsString());
return this;
}
/// <summary>
/// The analyzer used to analyze the text contents when analyzed during indexing and when searching using a query string. Defaults to the globally configured analyzer.
/// see: http://www.elasticsearch.org/guide/reference/index-modules/analysis/
/// </summary>
public CustomPropertyMap<T> Analyzer(string analyzer)
{
RegisterCustomJsonMap("'analyzer': {0}", analyzer.Quotate());
return this;
}
/// <summary>
/// The analyzer used to analyze the text contents when analyzed during indexing and when searching using a query string. Defaults to the globally configured analyzer.
/// see: http://www.elasticsearch.org/guide/reference/index-modules/analysis/
/// </summary>
public CustomPropertyMap<T> Analyzer(DefaultAnalyzers analyzer)
{
return Analyzer(analyzer.AsString());
}
/// <summary>
/// The analyzer used to analyze the text contents when analyzed during indexing.
/// see: http://www.elasticsearch.org/guide/reference/index-modules/analysis/
/// </summary>
public CustomPropertyMap<T> IndexAnalyzer(string analyzer)
{
RegisterCustomJsonMap("'index_analyzer': {0}", analyzer.Quotate());
return this;
}
/// <summary>
/// The analyzer used to analyze the text contents when analyzed during indexing.
/// see: http://www.elasticsearch.org/guide/reference/index-modules/analysis/
/// </summary>
public CustomPropertyMap<T> IndexAnalyzer(DefaultAnalyzers analyzer)
{
return IndexAnalyzer(analyzer.AsString());
}
/// <summary>
/// The analyzer used to analyze the field when part of a query string.
/// see: http://www.elasticsearch.org/guide/reference/index-modules/analysis/
/// </summary>
public CustomPropertyMap<T> SearchAnalyzer(string analyzer)
{
RegisterCustomJsonMap("'search_analyzer': {0}", analyzer.Quotate());
return this;
}
/// <summary>
/// The analyzer used to analyze the field when part of a query string.
/// see: http://www.elasticsearch.org/guide/reference/index-modules/analysis/
/// </summary>
public CustomPropertyMap<T> SearchAnalyzer(DefaultAnalyzers analyzer)
{
return SearchAnalyzer(analyzer.AsString());
}
protected override string GetElasticFieldType(Type fieldType)
{
if (mappingType != null)
return mappingType;
return ElasticCoreTypeMapper.GetElasticType(fieldType);
}
}
} | 34.596386 | 175 | 0.597945 | [
"MIT"
] | AAATechGuy/PlainElastic.Net | src/PlainElastic.Net/Builders/Mappings/Core/CustomPropertyMap.cs | 5,743 | C# |
using System;
using NetRuntimeSystem = System;
using System.ComponentModel;
using NetOffice.Attributes;
namespace NetOffice.AccessApi
{
/// <summary>
/// DispatchInterface _Hyperlink
/// SupportByVersion Access, 9,10,11,12,14,15,16
/// </summary>
[SupportByVersion("Access", 9,10,11,12,14,15,16)]
[EntityType(EntityType.IsDispatchInterface), BaseType]
public class _Hyperlink : COMObject
{
#pragma warning disable
#region Type Information
/// <summary>
/// Instance Type
/// </summary>
[EditorBrowsable(EditorBrowsableState.Advanced), Browsable(false), Category("NetOffice"), CoreOverridden]
public override Type InstanceType
{
get
{
return LateBindingApiWrapperType;
}
}
private static Type _type;
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public static Type LateBindingApiWrapperType
{
get
{
if (null == _type)
_type = typeof(_Hyperlink);
return _type;
}
}
#endregion
#region Ctor
/// <param name="factory">current used factory core</param>
/// <param name="parentObject">object there has created the proxy</param>
/// <param name="proxyShare">proxy share instead if com proxy</param>
public _Hyperlink(Core factory, ICOMObject parentObject, COMProxyShare proxyShare) : base(factory, parentObject, proxyShare)
{
}
///<param name="factory">current used factory core</param>
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
public _Hyperlink(Core factory, ICOMObject parentObject, object comProxy) : base(factory, parentObject, comProxy)
{
}
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public _Hyperlink(ICOMObject parentObject, object comProxy) : base(parentObject, comProxy)
{
}
///<param name="factory">current used factory core</param>
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
///<param name="comProxyType">Type of inner wrapped COM proxy"</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public _Hyperlink(Core factory, ICOMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(factory, parentObject, comProxy, comProxyType)
{
}
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
///<param name="comProxyType">Type of inner wrapped COM proxy"</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public _Hyperlink(ICOMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(parentObject, comProxy, comProxyType)
{
}
///<param name="replacedObject">object to replaced. replacedObject are not usable after this action</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public _Hyperlink(ICOMObject replacedObject) : base(replacedObject)
{
}
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public _Hyperlink() : base()
{
}
/// <param name="progId">registered progID</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public _Hyperlink(string progId) : base(progId)
{
}
#endregion
#region Properties
/// <summary>
/// SupportByVersion Access 9, 10, 11, 12, 14, 15, 16
/// Get/Set
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff822025.aspx </remarks>
[SupportByVersion("Access", 9,10,11,12,14,15,16)]
public string SubAddress
{
get
{
return Factory.ExecuteStringPropertyGet(this, "SubAddress");
}
set
{
Factory.ExecuteValuePropertySet(this, "SubAddress", value);
}
}
/// <summary>
/// SupportByVersion Access 9, 10, 11, 12, 14, 15, 16
/// Get/Set
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff195258.aspx </remarks>
[SupportByVersion("Access", 9,10,11,12,14,15,16)]
public string Address
{
get
{
return Factory.ExecuteStringPropertyGet(this, "Address");
}
set
{
Factory.ExecuteValuePropertySet(this, "Address", value);
}
}
/// <summary>
/// SupportByVersion Access 9, 10, 11, 12, 14, 15, 16
/// Get/Set
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff835717.aspx </remarks>
[SupportByVersion("Access", 9,10,11,12,14,15,16)]
public string EmailSubject
{
get
{
return Factory.ExecuteStringPropertyGet(this, "EmailSubject");
}
set
{
Factory.ExecuteValuePropertySet(this, "EmailSubject", value);
}
}
/// <summary>
/// SupportByVersion Access 9, 10, 11, 12, 14, 15, 16
/// Get/Set
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff822461.aspx </remarks>
[SupportByVersion("Access", 9,10,11,12,14,15,16)]
public string ScreenTip
{
get
{
return Factory.ExecuteStringPropertyGet(this, "ScreenTip");
}
set
{
Factory.ExecuteValuePropertySet(this, "ScreenTip", value);
}
}
/// <summary>
/// SupportByVersion Access 9, 10, 11, 12, 14, 15, 16
/// Get/Set
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff194871.aspx </remarks>
[SupportByVersion("Access", 9,10,11,12,14,15,16)]
public string TextToDisplay
{
get
{
return Factory.ExecuteStringPropertyGet(this, "TextToDisplay");
}
set
{
Factory.ExecuteValuePropertySet(this, "TextToDisplay", value);
}
}
#endregion
#region Methods
/// <summary>
/// SupportByVersion Access 9, 10, 11, 12, 14, 15, 16
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff192921.aspx </remarks>
[SupportByVersion("Access", 9,10,11,12,14,15,16)]
public void AddToFavorites()
{
Factory.ExecuteMethod(this, "AddToFavorites");
}
/// <summary>
/// SupportByVersion Access 9, 10, 11, 12, 14, 15, 16
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff196761.aspx </remarks>
/// <param name="newWindow">optional bool NewWindow = false</param>
/// <param name="addHistory">optional bool AddHistory = true</param>
/// <param name="extraInfo">optional object extraInfo</param>
/// <param name="method">optional NetOffice.OfficeApi.Enums.MsoExtraInfoMethod Method = 0</param>
/// <param name="headerInfo">optional string HeaderInfo = </param>
[SupportByVersion("Access", 9,10,11,12,14,15,16)]
public void Follow(object newWindow, object addHistory, object extraInfo, object method, object headerInfo)
{
Factory.ExecuteMethod(this, "Follow", new object[]{ newWindow, addHistory, extraInfo, method, headerInfo });
}
/// <summary>
/// SupportByVersion Access 9, 10, 11, 12, 14, 15, 16
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff196761.aspx </remarks>
[CustomMethod]
[SupportByVersion("Access", 9,10,11,12,14,15,16)]
public void Follow()
{
Factory.ExecuteMethod(this, "Follow");
}
/// <summary>
/// SupportByVersion Access 9, 10, 11, 12, 14, 15, 16
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff196761.aspx </remarks>
/// <param name="newWindow">optional bool NewWindow = false</param>
[CustomMethod]
[SupportByVersion("Access", 9,10,11,12,14,15,16)]
public void Follow(object newWindow)
{
Factory.ExecuteMethod(this, "Follow", newWindow);
}
/// <summary>
/// SupportByVersion Access 9, 10, 11, 12, 14, 15, 16
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff196761.aspx </remarks>
/// <param name="newWindow">optional bool NewWindow = false</param>
/// <param name="addHistory">optional bool AddHistory = true</param>
[CustomMethod]
[SupportByVersion("Access", 9,10,11,12,14,15,16)]
public void Follow(object newWindow, object addHistory)
{
Factory.ExecuteMethod(this, "Follow", newWindow, addHistory);
}
/// <summary>
/// SupportByVersion Access 9, 10, 11, 12, 14, 15, 16
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff196761.aspx </remarks>
/// <param name="newWindow">optional bool NewWindow = false</param>
/// <param name="addHistory">optional bool AddHistory = true</param>
/// <param name="extraInfo">optional object extraInfo</param>
[CustomMethod]
[SupportByVersion("Access", 9,10,11,12,14,15,16)]
public void Follow(object newWindow, object addHistory, object extraInfo)
{
Factory.ExecuteMethod(this, "Follow", newWindow, addHistory, extraInfo);
}
/// <summary>
/// SupportByVersion Access 9, 10, 11, 12, 14, 15, 16
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff196761.aspx </remarks>
/// <param name="newWindow">optional bool NewWindow = false</param>
/// <param name="addHistory">optional bool AddHistory = true</param>
/// <param name="extraInfo">optional object extraInfo</param>
/// <param name="method">optional NetOffice.OfficeApi.Enums.MsoExtraInfoMethod Method = 0</param>
[CustomMethod]
[SupportByVersion("Access", 9,10,11,12,14,15,16)]
public void Follow(object newWindow, object addHistory, object extraInfo, object method)
{
Factory.ExecuteMethod(this, "Follow", newWindow, addHistory, extraInfo, method);
}
/// <summary>
/// SupportByVersion Access 9, 10, 11, 12, 14, 15, 16
/// </summary>
/// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff822725.aspx </remarks>
/// <param name="fileName">string fileName</param>
/// <param name="editNow">bool editNow</param>
/// <param name="overwrite">bool overwrite</param>
[SupportByVersion("Access", 9,10,11,12,14,15,16)]
public void CreateNewDocument(string fileName, bool editNow, bool overwrite)
{
Factory.ExecuteMethod(this, "CreateNewDocument", fileName, editNow, overwrite);
}
/// <summary>
/// SupportByVersion Access 11, 12, 14, 15, 16
/// </summary>
/// <param name="dispid">Int32 dispid</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
[SupportByVersion("Access", 11,12,14,15,16)]
public bool IsMemberSafe(Int32 dispid)
{
return Factory.ExecuteBoolMethodGet(this, "IsMemberSafe", dispid);
}
#endregion
#pragma warning restore
}
}
| 33.668731 | 165 | 0.680368 | [
"MIT"
] | DominikPalo/NetOffice | Source/Access/DispatchInterfaces/_Hyperlink.cs | 10,877 | C# |
using News.App.Models;
using News.Data;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using News.Data.Models;
namespace News.App.Controllers
{
public class HomeController : Controller
{
private readonly ICategoryService _categoryService;
private readonly IPostService _postService;
[BindProperty]
public Post Post { get; set; }
public HomeController(ICategoryService categoryService, IPostService postService)
{
_categoryService = categoryService;
_postService = postService;
}
public IActionResult Index()
{
var posts = _postService.GetAll().OrderByDescending(post=>post.Id);
return View(posts);
}
public IActionResult Manage()
{
return View();
}
public IActionResult Posts(int id)
{
var posts = _postService.GetByCategory(id);
ViewData["Category"] = _categoryService.GetCategoryTitle(id);
ViewData["TotalPosts"] = _postService.GetNumberOfNews(id);
ViewData["Image"] = _categoryService.GetCategoryImage(id);
return View(posts);
}
public IActionResult Detail(int id)
{
var categoryId = _postService.GetCategoryId(id);
ViewData["News"] = _postService.GetById(id);
ViewData["RelatedNews"] = _postService.GetRelatedNews(categoryId, id);
//var post = _postService.GetById(id);
return View();
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
public IActionResult Form(int? id)
{
Post = new Post();
var categories = _categoryService.GetAll().ToList();
categories.Insert(0, new Category { Id = 0, Name = "Select", Thumbnail = ""});
ViewBag.ListOfCategory = categories;
if (id == null)
{
//Create New
return View(Post);
}
//Update
Post = _postService.GetById(id);
if (Post == null)
{
return NotFound();
}
return View(Post);
}
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Form()
{
if (ModelState.IsValid)
{
if (Post.Id == 0)
{
//CREATE
_postService.Add(Post, "new"); ;
}
else
{
// _postService.Add(Post, "update");
}
return Json(new { isValid = true, html = Helper.RenderRazorViewToString(this, "_ViewAll", _postService.GetAll()) });
}
return Json(new { isValid = false, html = Helper.RenderRazorViewToString(this, "Form", Post) });
}
#region API CALLS
[HttpGet]
public IActionResult GetAll()
{
return Json(new { data = _postService.GetAll() });
}
public IActionResult Delete(int Id)
{
/*
var isDeleted = _postService.Delete(Id);
if (isDeleted == false)
{
return Json(new { success = false, message = "Error while deleting" });
}
*/
return Json(new { success = true, message = "Delete successful - deletion intentionally disabled on the demo site" });
}
#endregion
}
}
| 28.445255 | 132 | 0.538876 | [
"MIT"
] | sanoylab/Full-Stack-Dev-Challenge | news-app/News.App/Controllers/HomeController.cs | 3,899 | C# |
using TMPro;
using UnityEngine;
namespace Main.UI
{
public class LevelInfoUI : MonoBehaviour
{
public TextMeshProUGUI levelText;
public GameObject previousObject;
public GameObject currentObject;
}
}
| 17 | 44 | 0.693277 | [
"MIT"
] | khayreddinebiada/Code-HC-Prototype-Example | UI/Panel Menu/LevelInfoUI.cs | 238 | C# |
using System;
using Baseline;
using JetBrains.Annotations;
using Marten;
using McMaster.Extensions.CommandLineUtils;
using Microsoft.Extensions.Logging;
namespace Rocket.Surgery.Extensions.Marten.Commands
{
/// <summary>
/// DumpCommand.
/// </summary>
[UsedImplicitly]
[Command("dump", Description = "Dumps the entire DDL for the configured Marten database")]
public class DumpCommand
{
private readonly IDocumentStore _store;
private readonly ILogger<DumpCommand> _logger;
/// <summary>
/// Initializes a new instance of the <see cref="DumpCommand" /> class.
/// </summary>
/// <param name="store">The store.</param>
/// <param name="logger">logger.</param>
public DumpCommand(IDocumentStore store, ILogger<DumpCommand> logger)
{
_store = store;
_logger = logger;
}
/// <summary>
/// Gets or sets the name of the file.
/// </summary>
[Argument(0, Description = "File (or folder) location to write the DDL file")]
public string? FileName { get; set; }
/// <summary>
/// Write out DDL by type
/// </summary>
[Option(Description = "Opt into writing the DDL split out by file")]
public bool ByType { get; set; }
/// <summary>
/// Use transactions
/// </summary>
[Option(Description = "Option to create scripts as transactional script")]
public bool TransactionalScript { get; set; }
/// <summary>
/// Called when [execute].
/// </summary>
/// <returns>System.Int32.</returns>
public int OnExecute()
{
if (ByType)
{
_logger.LogInformation("Writing DDL files to {FileName}", FileName);
_store.Schema.WriteDDLByType(FileName, TransactionalScript);
}
else
{
_logger.LogInformation("Writing DDL file to ", FileName);
try
{
new FileSystem().CleanDirectory(FileName);
}
catch (Exception)
{
_logger.LogInformation(
"Unable to clean the directory at {FileName} before writing new files",
FileName
);
}
_store.Schema.WriteDDL(FileName, TransactionalScript);
}
return 0;
}
}
} | 30.926829 | 95 | 0.537066 | [
"MIT"
] | RocketSurgeonsGuild/Marten | src/Marten/Commands/DumpCommand.cs | 2,536 | C# |
namespace CoreLayer.Citrix.Adc.NitroClient.Api.Configuration.Basic.Servicegroup.ServicegroupUpdateRequestDatas
{
public class ServicegroupUpdateSslRequestData : ServicegroupUpdateRequestData
{
public ServicegroupUpdateSslRequestData(string servicegroupName) : base(servicegroupName)
{
}
public string Cacheable { get; set; }
public string Sc { get; set; }
public string Sp { get; set; }
public string Cmp { get; set; }
public string TcpProfileName { get; set; }
public string HttpProfileName { get; set; }
}
} | 37.6875 | 110 | 0.6733 | [
"Apache-2.0"
] | CoreLayer/CoreLayer.Citrix.Adc.Nitro | src/CoreLayer.Citrix.Adc.NitroClient/Api/Configuration/Basic/Servicegroup/ServicegroupUpdateRequestDatas/ServicegroupUpdateSslRequestData.cs | 603 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Text.RegularExpressions;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using IBM.Cloud.SDK.Utilities;
using IBM.Cloud.SDK.Authentication;
using IBM.Cloud.SDK;
using IBM.Watson.Assistant.V2;
using IBM.Cloud.SDK.DataTypes;
using IBM.Cloud.SDK.Connection;
using IBM.Cloud.SDK.Logging;
using System;
using IBM.Watson.Assistant.V2.Model;
using IBM.Watson.ToneAnalyzer.V3.Model;
public class ToneService : MonoBehaviour
{
public float emotion_threshold;
private ToneService Tone;
public string versionDate = "2019-07-03";
//public string apiKey = "";
//public string serviceUrl = "https://gateway-lon.watsonplatform.net/tone-analyzer/api";
private string _stringToTestTone1 = "START AND TEST - OK!";
private string _stringToTestTone2 = "SECOND TEST - Failed Test Sucks";
private bool _analyzeToneTested = false;
public Text ResultsAnalysis;
//public MeshRenderer MacKenzieRenderer; // main digital human
// Over the shoulder emotional spheres
public MeshRenderer sphere_emo_joyRenderer;
public MeshRenderer sphere_emo_angerRenderer;
public MeshRenderer sphere_emo_fearRenderer;
public MeshRenderer sphere_emo_disgustRenderer;
public MeshRenderer sphere_emo_sadnessRenderer;
public Material original_material;
public Material red_material;
public Material blue_material;
public Material yellow_material;
public Material green_material;
public Material purple_material;
public Material white_material;
string _testString = "<speak version=\"1.0\"><express-as type=\"HI\">How are you today?</express-as></speak>";
// Start is called before the first frame update
void Start()
{
sphere_emo_joyRenderer.material = yellow_material;
sphere_emo_angerRenderer.material = red_material;
sphere_emo_fearRenderer.material = purple_material;
sphere_emo_disgustRenderer.material = green_material;
sphere_emo_sadnessRenderer.material = blue_material;
sphere_emo_joyRenderer.transform.localScale = new Vector3(.075F, .075F, .075F);
sphere_emo_angerRenderer.transform.localScale = new Vector3(.075F, .075F, .075F);
sphere_emo_fearRenderer.transform.localScale = new Vector3(.075F, .075F, .075F);
sphere_emo_disgustRenderer.transform.localScale = new Vector3(.075F, .075F, .075F);
sphere_emo_sadnessRenderer.transform.localScale = new Vector3(.075F, .075F, .075F);
emotion_threshold = 0.75f; // for loose demo - above 75% seems to work well - may vary by signal
}
private void OnGetToneAnalyze(ToneService resp, Dictionary<string, object> customData)
{
Log.Debug("ExampleToneAnalyzer.OnGetToneAnalyze()", "{0}", customData["json"].ToString());
ResultsAnalysis.text = (customData["json"].ToString()); // works but long and cannot read
/// Logging
//Log.Debug("$$$$$ TONE LOG 0 ANGER", "{0}", resp._.tone_categories[0].tones[0].score); // ANGER resp.document_tone.tone_categories [0].tones [0].score);
//Log.Debug("$$$$$ TONE LOG 1 DISGUST", "{0}", resp.document_tone.tone_categories[0].tones[1].score); // DISGUST
//Log.Debug("$$$$$ TONE LOG 2 FEAR", "{0}", resp.document_tone.tone_categories[0].tones[2].score); // FEAR
//Log.Debug("$$$$$ TONE LOG 3 JOY", "{0}", resp.document_tone.tone_categories[0].tones[3].score); // JOY
//Log.Debug("$$$$$ TONE LOG 4 SAD", "{0}", resp.document_tone.tone_categories[0].tones[4].score); // SADNESS
//Log.Debug("$$$$$ TONE ANALYTICAL", "{0}", resp.document_tone.tone_categories[1].tones[0].score); // ANALYTICAL
//Log.Debug("$$$$$ TONE CONFIDENT", "{0}", resp.document_tone.tone_categories[1].tones[1].score); // CONFIDENT
//Log.Debug("$$$$$ TONE TENTATIVE", "{0}", resp.document_tone.tone_categories[1].tones[2].score); // TENTATIVE
//// EMOTION
//if (resp.document_tone.tone_categories[0].tones[0].score > emotion_threshold)
//{
// sphere_emo_angerRenderer.transform.localScale += new Vector3(0.025F, 0.025F, 0.025F);
//}
//else if (resp.document_tone.tone_categories[0].tones[1].score > emotion_threshold)
//{
// sphere_emo_disgustRenderer.transform.localScale += new Vector3(0.025F, 0.025F, 0.025F);
//}
//else if (resp.document_tone.tone_categories[0].tones[2].score > emotion_threshold)
//{
// sphere_emo_fearRenderer.transform.localScale += new Vector3(0.025F, 0.025F, 0.025F);
//}
//else if (resp.document_tone.tone_categories[0].tones[3].score > emotion_threshold)
//{
// sphere_emo_joyRenderer.transform.localScale += new Vector3(0.025F, 0.025F, 0.025F);
//}
//else if (resp.document_tone.tone_categories[0].tones[4].score > emotion_threshold)
//{
// sphere_emo_sadnessRenderer.transform.localScale += new Vector3(0.025F, 0.025F, 0.025F);
//}
// OTHER TEXT - Formatting for On Screen dump - LATER - pretty this up to use standard DESERIALIZE methods and table
string RAW = (customData["json"].ToString()); // works but long and cannot read
//RAW = string.Concat("Tone Response \n", RAW);
RAW = Regex.Replace(RAW, "tone_categories", " \\\n");
RAW = Regex.Replace(RAW, "}", "} \\\n");
RAW = Regex.Replace(RAW, "tone_id", " ");
RAW = Regex.Replace(RAW, "tone_name", " ");
RAW = Regex.Replace(RAW, "score", " ");
RAW = Regex.Replace(RAW, @"[{\\},:]", "");
RAW = Regex.Replace(RAW, "\"", "");
ResultsAnalysis.text = RAW;
_analyzeToneTested = true;
}
// Update is called once per frame
void Update()
{
}
}
| 42.553957 | 161 | 0.662553 | [
"Apache-2.0"
] | Yu713/daimon | Assets/_scripts/ToneService.cs | 5,915 | C# |
// <auto-generated> - Template:RepositoryBase, Version:1.1, Id:70230bd4-f88f-41d8-a9c6-6e40aded5c07
using System;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
using MSC.ConferenceMate.Repository.Entities.CM;
using MSC.ConferenceMate.Repository.Interface;
using CodeGenHero.Repository;
using cghEnums = CodeGenHero.Repository.Enums;
namespace MSC.ConferenceMate.Repository
{
public abstract partial class CMRepositoryBase : ICMRepositoryCrud
{
private ICMDataContext _ctx;
public CMRepositoryBase(ICMDataContext ctx)
{
_ctx = ctx;
// Disable lazy loading - if not, related properties are auto-loaded when
// they are accessed for the first time, which means they'll be included when
// we serialize (b/c the serialization process accesses those properties).
// We don't want that, so we turn it off. We want to eagerly load them (using Include) manually.
ctx.Configuration.LazyLoadingEnabled = false;
if (System.Diagnostics.Debugger.IsAttached)
{ // Write EF queries to the output console.
ctx.Database.Log = x => System.Diagnostics.Debug.WriteLine(x);
}
}
#region Generic Operations
private async Task<IRepositoryActionResult<TEntity>> DeleteAsync<TEntity>(TEntity item) where TEntity : class
{
try
{
if (item == null)
{
return new RepositoryActionResult<TEntity>(null, cghEnums.RepositoryActionStatus.NotFound);
}
DbSet<TEntity> itemSet = _ctx.Set<TEntity>();
itemSet.Remove(item);
await _ctx.SaveChangesAsync();
return new RepositoryActionResult<TEntity>(null, cghEnums.RepositoryActionStatus.Deleted);
}
catch(Exception ex)
{
return new RepositoryActionResult<TEntity>(null, cghEnums.RepositoryActionStatus.Error, ex);
}
}
public IQueryable<TEntity> GetQueryable<TEntity>() where TEntity : class
{
return _ctx.Set<TEntity>();
}
public async Task<IRepositoryActionResult<TEntity>> InsertAsync<TEntity>(TEntity item) where TEntity : class
{
try
{
DbSet<TEntity> itemSet = _ctx.Set<TEntity>();
itemSet.Add(item);
var result = await _ctx.SaveChangesAsync();
RunCustomLogicAfterEveryInsert<TEntity>(item, result);
if (result > 0)
{
return new RepositoryActionResult<TEntity>(item, cghEnums.RepositoryActionStatus.Created);
}
else
{
return new RepositoryActionResult<TEntity>(item, cghEnums.RepositoryActionStatus.NothingModified, null);
}
}
catch(Exception ex)
{
return new RepositoryActionResult<TEntity>(null, cghEnums.RepositoryActionStatus.Error, ex);
}
}
private async Task<IRepositoryActionResult<TEntity>> UpdateAsync<TEntity>(TEntity item, TEntity existingItem) where TEntity : class
{
try
{ // only update when a record already exists for this id
if (existingItem == null)
{
return new RepositoryActionResult<TEntity>(item, cghEnums.RepositoryActionStatus.NotFound);
}
// change the original entity status to detached; otherwise, we get an error on attach as the entity is already in the dbSet
// set original entity state to detached
_ctx.Entry(existingItem).State = EntityState.Detached;
DbSet<TEntity> itemSet = _ctx.Set<TEntity>();
itemSet.Attach(item); // attach & save
_ctx.Entry(item).State = EntityState.Modified; // set the updated entity state to modified, so it gets updated.
var result = await _ctx.SaveChangesAsync();
RunCustomLogicAfterEveryUpdate<TEntity>(newItem: item, oldItem: existingItem, numObjectsWritten: result);
if (result > 0)
{
return new RepositoryActionResult<TEntity>(item, cghEnums.RepositoryActionStatus.Updated);
}
else
{
return new RepositoryActionResult<TEntity>(item, cghEnums.RepositoryActionStatus.NothingModified, null);
}
}
catch (Exception ex)
{
return new RepositoryActionResult<TEntity>(null, cghEnums.RepositoryActionStatus.Error, ex);
}
}
partial void RunCustomLogicAfterEveryInsert<T>(T item, int numObjectsWritten) where T : class;
partial void RunCustomLogicAfterEveryUpdate<T>(T newItem, T oldItem, int numObjectsWritten) where T : class;
#endregion Generic Operations
#region Announcement
public async Task<IRepositoryActionResult<Announcement>> InsertAsync(Announcement item)
{
var result = await InsertAsync<Announcement>(item);
RunCustomLogicAfterInsert_Announcement(item, result);
return result;
}
public IQueryable<Announcement> GetQueryable_Announcement()
{
return _ctx.Set<Announcement>();
}
public async Task<Announcement> Get_AnnouncementAsync(int announcementId, int numChildLevels)
{
var qryItem = GetQueryable_Announcement().AsNoTracking();
RunCustomLogicOnGetQueryableByPK_Announcement(ref qryItem, announcementId, numChildLevels);
var dbItem = await qryItem.Where(x => x.AnnouncementId == announcementId).FirstOrDefaultAsync();
if (!(dbItem is null))
{
RunCustomLogicOnGetEntityByPK_Announcement(ref dbItem, announcementId, numChildLevels);
}
return dbItem;
}
public async Task<Announcement> GetFirstOrDefaultAsync(Announcement item)
{
return await _ctx.Announcements.Where(x => x.AnnouncementId == item.AnnouncementId).FirstOrDefaultAsync();
}
public async Task<IRepositoryActionResult<Announcement>> UpdateAsync(Announcement item)
{
var oldItem = await _ctx.Announcements.FirstOrDefaultAsync(x => x.AnnouncementId == item.AnnouncementId);
var result = await UpdateAsync<Announcement>(item, oldItem);
RunCustomLogicAfterUpdate_Announcement(newItem: item, oldItem: oldItem, result: result);
return result;
}
public async Task<IRepositoryActionResult<Announcement>> Delete_AnnouncementAsync(int announcementId)
{
return await DeleteAsync<Announcement>(_ctx.Announcements.Where(x => x.AnnouncementId == announcementId).FirstOrDefault());
}
public async Task<IRepositoryActionResult<Announcement>> DeleteAsync(Announcement item)
{
return await DeleteAsync<Announcement>(_ctx.Announcements.Where(x => x.AnnouncementId == item.AnnouncementId).FirstOrDefault());
}
partial void RunCustomLogicAfterInsert_Announcement(Announcement item, IRepositoryActionResult<Announcement> result);
partial void RunCustomLogicAfterUpdate_Announcement(Announcement newItem, Announcement oldItem, IRepositoryActionResult<Announcement> result);
partial void RunCustomLogicOnGetQueryableByPK_Announcement(ref IQueryable<Announcement> qryItem, int announcementId, int numChildLevels);
partial void RunCustomLogicOnGetEntityByPK_Announcement(ref Announcement dbItem, int announcementId, int numChildLevels);
#endregion Announcement
#region BlobFile
public async Task<IRepositoryActionResult<BlobFile>> InsertAsync(BlobFile item)
{
var result = await InsertAsync<BlobFile>(item);
RunCustomLogicAfterInsert_BlobFile(item, result);
return result;
}
public IQueryable<BlobFile> GetQueryable_BlobFile()
{
return _ctx.Set<BlobFile>();
}
public async Task<BlobFile> Get_BlobFileAsync(System.Guid blobFileId, int numChildLevels)
{
var qryItem = GetQueryable_BlobFile().AsNoTracking();
RunCustomLogicOnGetQueryableByPK_BlobFile(ref qryItem, blobFileId, numChildLevels);
var dbItem = await qryItem.Where(x => x.BlobFileId == blobFileId).FirstOrDefaultAsync();
if (!(dbItem is null))
{
RunCustomLogicOnGetEntityByPK_BlobFile(ref dbItem, blobFileId, numChildLevels);
}
return dbItem;
}
public async Task<BlobFile> GetFirstOrDefaultAsync(BlobFile item)
{
return await _ctx.BlobFiles.Where(x => x.BlobFileId == item.BlobFileId).FirstOrDefaultAsync();
}
public async Task<IRepositoryActionResult<BlobFile>> UpdateAsync(BlobFile item)
{
var oldItem = await _ctx.BlobFiles.FirstOrDefaultAsync(x => x.BlobFileId == item.BlobFileId);
var result = await UpdateAsync<BlobFile>(item, oldItem);
RunCustomLogicAfterUpdate_BlobFile(newItem: item, oldItem: oldItem, result: result);
return result;
}
public async Task<IRepositoryActionResult<BlobFile>> Delete_BlobFileAsync(System.Guid blobFileId)
{
return await DeleteAsync<BlobFile>(_ctx.BlobFiles.Where(x => x.BlobFileId == blobFileId).FirstOrDefault());
}
public async Task<IRepositoryActionResult<BlobFile>> DeleteAsync(BlobFile item)
{
return await DeleteAsync<BlobFile>(_ctx.BlobFiles.Where(x => x.BlobFileId == item.BlobFileId).FirstOrDefault());
}
partial void RunCustomLogicAfterInsert_BlobFile(BlobFile item, IRepositoryActionResult<BlobFile> result);
partial void RunCustomLogicAfterUpdate_BlobFile(BlobFile newItem, BlobFile oldItem, IRepositoryActionResult<BlobFile> result);
partial void RunCustomLogicOnGetQueryableByPK_BlobFile(ref IQueryable<BlobFile> qryItem, System.Guid blobFileId, int numChildLevels);
partial void RunCustomLogicOnGetEntityByPK_BlobFile(ref BlobFile dbItem, System.Guid blobFileId, int numChildLevels);
#endregion BlobFile
#region BlobFileType
public async Task<IRepositoryActionResult<BlobFileType>> InsertAsync(BlobFileType item)
{
var result = await InsertAsync<BlobFileType>(item);
RunCustomLogicAfterInsert_BlobFileType(item, result);
return result;
}
public IQueryable<BlobFileType> GetQueryable_BlobFileType()
{
return _ctx.Set<BlobFileType>();
}
public async Task<BlobFileType> Get_BlobFileTypeAsync(int blobFileTypeId, int numChildLevels)
{
var qryItem = GetQueryable_BlobFileType().AsNoTracking();
RunCustomLogicOnGetQueryableByPK_BlobFileType(ref qryItem, blobFileTypeId, numChildLevels);
var dbItem = await qryItem.Where(x => x.BlobFileTypeId == blobFileTypeId).FirstOrDefaultAsync();
if (!(dbItem is null))
{
RunCustomLogicOnGetEntityByPK_BlobFileType(ref dbItem, blobFileTypeId, numChildLevels);
}
return dbItem;
}
public async Task<BlobFileType> GetFirstOrDefaultAsync(BlobFileType item)
{
return await _ctx.BlobFileTypes.Where(x => x.BlobFileTypeId == item.BlobFileTypeId).FirstOrDefaultAsync();
}
public async Task<IRepositoryActionResult<BlobFileType>> UpdateAsync(BlobFileType item)
{
var oldItem = await _ctx.BlobFileTypes.FirstOrDefaultAsync(x => x.BlobFileTypeId == item.BlobFileTypeId);
var result = await UpdateAsync<BlobFileType>(item, oldItem);
RunCustomLogicAfterUpdate_BlobFileType(newItem: item, oldItem: oldItem, result: result);
return result;
}
public async Task<IRepositoryActionResult<BlobFileType>> Delete_BlobFileTypeAsync(int blobFileTypeId)
{
return await DeleteAsync<BlobFileType>(_ctx.BlobFileTypes.Where(x => x.BlobFileTypeId == blobFileTypeId).FirstOrDefault());
}
public async Task<IRepositoryActionResult<BlobFileType>> DeleteAsync(BlobFileType item)
{
return await DeleteAsync<BlobFileType>(_ctx.BlobFileTypes.Where(x => x.BlobFileTypeId == item.BlobFileTypeId).FirstOrDefault());
}
partial void RunCustomLogicAfterInsert_BlobFileType(BlobFileType item, IRepositoryActionResult<BlobFileType> result);
partial void RunCustomLogicAfterUpdate_BlobFileType(BlobFileType newItem, BlobFileType oldItem, IRepositoryActionResult<BlobFileType> result);
partial void RunCustomLogicOnGetQueryableByPK_BlobFileType(ref IQueryable<BlobFileType> qryItem, int blobFileTypeId, int numChildLevels);
partial void RunCustomLogicOnGetEntityByPK_BlobFileType(ref BlobFileType dbItem, int blobFileTypeId, int numChildLevels);
#endregion BlobFileType
#region FeaturedEvent
public async Task<IRepositoryActionResult<FeaturedEvent>> InsertAsync(FeaturedEvent item)
{
var result = await InsertAsync<FeaturedEvent>(item);
RunCustomLogicAfterInsert_FeaturedEvent(item, result);
return result;
}
public IQueryable<FeaturedEvent> GetQueryable_FeaturedEvent()
{
return _ctx.Set<FeaturedEvent>();
}
public async Task<FeaturedEvent> Get_FeaturedEventAsync(int featuredEventId, int numChildLevels)
{
var qryItem = GetQueryable_FeaturedEvent().AsNoTracking();
RunCustomLogicOnGetQueryableByPK_FeaturedEvent(ref qryItem, featuredEventId, numChildLevels);
var dbItem = await qryItem.Where(x => x.FeaturedEventId == featuredEventId).FirstOrDefaultAsync();
if (!(dbItem is null))
{
RunCustomLogicOnGetEntityByPK_FeaturedEvent(ref dbItem, featuredEventId, numChildLevels);
}
return dbItem;
}
public async Task<FeaturedEvent> GetFirstOrDefaultAsync(FeaturedEvent item)
{
return await _ctx.FeaturedEvents.Where(x => x.FeaturedEventId == item.FeaturedEventId).FirstOrDefaultAsync();
}
public async Task<IRepositoryActionResult<FeaturedEvent>> UpdateAsync(FeaturedEvent item)
{
var oldItem = await _ctx.FeaturedEvents.FirstOrDefaultAsync(x => x.FeaturedEventId == item.FeaturedEventId);
var result = await UpdateAsync<FeaturedEvent>(item, oldItem);
RunCustomLogicAfterUpdate_FeaturedEvent(newItem: item, oldItem: oldItem, result: result);
return result;
}
public async Task<IRepositoryActionResult<FeaturedEvent>> Delete_FeaturedEventAsync(int featuredEventId)
{
return await DeleteAsync<FeaturedEvent>(_ctx.FeaturedEvents.Where(x => x.FeaturedEventId == featuredEventId).FirstOrDefault());
}
public async Task<IRepositoryActionResult<FeaturedEvent>> DeleteAsync(FeaturedEvent item)
{
return await DeleteAsync<FeaturedEvent>(_ctx.FeaturedEvents.Where(x => x.FeaturedEventId == item.FeaturedEventId).FirstOrDefault());
}
partial void RunCustomLogicAfterInsert_FeaturedEvent(FeaturedEvent item, IRepositoryActionResult<FeaturedEvent> result);
partial void RunCustomLogicAfterUpdate_FeaturedEvent(FeaturedEvent newItem, FeaturedEvent oldItem, IRepositoryActionResult<FeaturedEvent> result);
partial void RunCustomLogicOnGetQueryableByPK_FeaturedEvent(ref IQueryable<FeaturedEvent> qryItem, int featuredEventId, int numChildLevels);
partial void RunCustomLogicOnGetEntityByPK_FeaturedEvent(ref FeaturedEvent dbItem, int featuredEventId, int numChildLevels);
#endregion FeaturedEvent
#region Feedback
public async Task<IRepositoryActionResult<Feedback>> InsertAsync(Feedback item)
{
var result = await InsertAsync<Feedback>(item);
RunCustomLogicAfterInsert_Feedback(item, result);
return result;
}
public IQueryable<Feedback> GetQueryable_Feedback()
{
return _ctx.Set<Feedback>();
}
public async Task<Feedback> Get_FeedbackAsync(System.Guid feedbackId, int numChildLevels)
{
var qryItem = GetQueryable_Feedback().AsNoTracking();
RunCustomLogicOnGetQueryableByPK_Feedback(ref qryItem, feedbackId, numChildLevels);
var dbItem = await qryItem.Where(x => x.FeedbackId == feedbackId).FirstOrDefaultAsync();
if (!(dbItem is null))
{
RunCustomLogicOnGetEntityByPK_Feedback(ref dbItem, feedbackId, numChildLevels);
}
return dbItem;
}
public async Task<Feedback> GetFirstOrDefaultAsync(Feedback item)
{
return await _ctx.Feedbacks.Where(x => x.FeedbackId == item.FeedbackId).FirstOrDefaultAsync();
}
public async Task<IRepositoryActionResult<Feedback>> UpdateAsync(Feedback item)
{
var oldItem = await _ctx.Feedbacks.FirstOrDefaultAsync(x => x.FeedbackId == item.FeedbackId);
var result = await UpdateAsync<Feedback>(item, oldItem);
RunCustomLogicAfterUpdate_Feedback(newItem: item, oldItem: oldItem, result: result);
return result;
}
public async Task<IRepositoryActionResult<Feedback>> Delete_FeedbackAsync(System.Guid feedbackId)
{
return await DeleteAsync<Feedback>(_ctx.Feedbacks.Where(x => x.FeedbackId == feedbackId).FirstOrDefault());
}
public async Task<IRepositoryActionResult<Feedback>> DeleteAsync(Feedback item)
{
return await DeleteAsync<Feedback>(_ctx.Feedbacks.Where(x => x.FeedbackId == item.FeedbackId).FirstOrDefault());
}
partial void RunCustomLogicAfterInsert_Feedback(Feedback item, IRepositoryActionResult<Feedback> result);
partial void RunCustomLogicAfterUpdate_Feedback(Feedback newItem, Feedback oldItem, IRepositoryActionResult<Feedback> result);
partial void RunCustomLogicOnGetQueryableByPK_Feedback(ref IQueryable<Feedback> qryItem, System.Guid feedbackId, int numChildLevels);
partial void RunCustomLogicOnGetEntityByPK_Feedback(ref Feedback dbItem, System.Guid feedbackId, int numChildLevels);
#endregion Feedback
#region FeedbackInitiatorType
public async Task<IRepositoryActionResult<FeedbackInitiatorType>> InsertAsync(FeedbackInitiatorType item)
{
var result = await InsertAsync<FeedbackInitiatorType>(item);
RunCustomLogicAfterInsert_FeedbackInitiatorType(item, result);
return result;
}
public IQueryable<FeedbackInitiatorType> GetQueryable_FeedbackInitiatorType()
{
return _ctx.Set<FeedbackInitiatorType>();
}
public async Task<FeedbackInitiatorType> Get_FeedbackInitiatorTypeAsync(int feedbackInitiatorTypeId, int numChildLevels)
{
var qryItem = GetQueryable_FeedbackInitiatorType().AsNoTracking();
RunCustomLogicOnGetQueryableByPK_FeedbackInitiatorType(ref qryItem, feedbackInitiatorTypeId, numChildLevels);
var dbItem = await qryItem.Where(x => x.FeedbackInitiatorTypeId == feedbackInitiatorTypeId).FirstOrDefaultAsync();
if (!(dbItem is null))
{
RunCustomLogicOnGetEntityByPK_FeedbackInitiatorType(ref dbItem, feedbackInitiatorTypeId, numChildLevels);
}
return dbItem;
}
public async Task<FeedbackInitiatorType> GetFirstOrDefaultAsync(FeedbackInitiatorType item)
{
return await _ctx.FeedbackInitiatorTypes.Where(x => x.FeedbackInitiatorTypeId == item.FeedbackInitiatorTypeId).FirstOrDefaultAsync();
}
public async Task<IRepositoryActionResult<FeedbackInitiatorType>> UpdateAsync(FeedbackInitiatorType item)
{
var oldItem = await _ctx.FeedbackInitiatorTypes.FirstOrDefaultAsync(x => x.FeedbackInitiatorTypeId == item.FeedbackInitiatorTypeId);
var result = await UpdateAsync<FeedbackInitiatorType>(item, oldItem);
RunCustomLogicAfterUpdate_FeedbackInitiatorType(newItem: item, oldItem: oldItem, result: result);
return result;
}
public async Task<IRepositoryActionResult<FeedbackInitiatorType>> Delete_FeedbackInitiatorTypeAsync(int feedbackInitiatorTypeId)
{
return await DeleteAsync<FeedbackInitiatorType>(_ctx.FeedbackInitiatorTypes.Where(x => x.FeedbackInitiatorTypeId == feedbackInitiatorTypeId).FirstOrDefault());
}
public async Task<IRepositoryActionResult<FeedbackInitiatorType>> DeleteAsync(FeedbackInitiatorType item)
{
return await DeleteAsync<FeedbackInitiatorType>(_ctx.FeedbackInitiatorTypes.Where(x => x.FeedbackInitiatorTypeId == item.FeedbackInitiatorTypeId).FirstOrDefault());
}
partial void RunCustomLogicAfterInsert_FeedbackInitiatorType(FeedbackInitiatorType item, IRepositoryActionResult<FeedbackInitiatorType> result);
partial void RunCustomLogicAfterUpdate_FeedbackInitiatorType(FeedbackInitiatorType newItem, FeedbackInitiatorType oldItem, IRepositoryActionResult<FeedbackInitiatorType> result);
partial void RunCustomLogicOnGetQueryableByPK_FeedbackInitiatorType(ref IQueryable<FeedbackInitiatorType> qryItem, int feedbackInitiatorTypeId, int numChildLevels);
partial void RunCustomLogicOnGetEntityByPK_FeedbackInitiatorType(ref FeedbackInitiatorType dbItem, int feedbackInitiatorTypeId, int numChildLevels);
#endregion FeedbackInitiatorType
#region FeedbackType
public async Task<IRepositoryActionResult<FeedbackType>> InsertAsync(FeedbackType item)
{
var result = await InsertAsync<FeedbackType>(item);
RunCustomLogicAfterInsert_FeedbackType(item, result);
return result;
}
public IQueryable<FeedbackType> GetQueryable_FeedbackType()
{
return _ctx.Set<FeedbackType>();
}
public async Task<FeedbackType> Get_FeedbackTypeAsync(int feedbackTypeId, int numChildLevels)
{
var qryItem = GetQueryable_FeedbackType().AsNoTracking();
RunCustomLogicOnGetQueryableByPK_FeedbackType(ref qryItem, feedbackTypeId, numChildLevels);
var dbItem = await qryItem.Where(x => x.FeedbackTypeId == feedbackTypeId).FirstOrDefaultAsync();
if (!(dbItem is null))
{
RunCustomLogicOnGetEntityByPK_FeedbackType(ref dbItem, feedbackTypeId, numChildLevels);
}
return dbItem;
}
public async Task<FeedbackType> GetFirstOrDefaultAsync(FeedbackType item)
{
return await _ctx.FeedbackTypes.Where(x => x.FeedbackTypeId == item.FeedbackTypeId).FirstOrDefaultAsync();
}
public async Task<IRepositoryActionResult<FeedbackType>> UpdateAsync(FeedbackType item)
{
var oldItem = await _ctx.FeedbackTypes.FirstOrDefaultAsync(x => x.FeedbackTypeId == item.FeedbackTypeId);
var result = await UpdateAsync<FeedbackType>(item, oldItem);
RunCustomLogicAfterUpdate_FeedbackType(newItem: item, oldItem: oldItem, result: result);
return result;
}
public async Task<IRepositoryActionResult<FeedbackType>> Delete_FeedbackTypeAsync(int feedbackTypeId)
{
return await DeleteAsync<FeedbackType>(_ctx.FeedbackTypes.Where(x => x.FeedbackTypeId == feedbackTypeId).FirstOrDefault());
}
public async Task<IRepositoryActionResult<FeedbackType>> DeleteAsync(FeedbackType item)
{
return await DeleteAsync<FeedbackType>(_ctx.FeedbackTypes.Where(x => x.FeedbackTypeId == item.FeedbackTypeId).FirstOrDefault());
}
partial void RunCustomLogicAfterInsert_FeedbackType(FeedbackType item, IRepositoryActionResult<FeedbackType> result);
partial void RunCustomLogicAfterUpdate_FeedbackType(FeedbackType newItem, FeedbackType oldItem, IRepositoryActionResult<FeedbackType> result);
partial void RunCustomLogicOnGetQueryableByPK_FeedbackType(ref IQueryable<FeedbackType> qryItem, int feedbackTypeId, int numChildLevels);
partial void RunCustomLogicOnGetEntityByPK_FeedbackType(ref FeedbackType dbItem, int feedbackTypeId, int numChildLevels);
#endregion FeedbackType
#region GenderType
public async Task<IRepositoryActionResult<GenderType>> InsertAsync(GenderType item)
{
var result = await InsertAsync<GenderType>(item);
RunCustomLogicAfterInsert_GenderType(item, result);
return result;
}
public IQueryable<GenderType> GetQueryable_GenderType()
{
return _ctx.Set<GenderType>();
}
public async Task<GenderType> Get_GenderTypeAsync(int genderTypeId, int numChildLevels)
{
var qryItem = GetQueryable_GenderType().AsNoTracking();
RunCustomLogicOnGetQueryableByPK_GenderType(ref qryItem, genderTypeId, numChildLevels);
var dbItem = await qryItem.Where(x => x.GenderTypeId == genderTypeId).FirstOrDefaultAsync();
if (!(dbItem is null))
{
RunCustomLogicOnGetEntityByPK_GenderType(ref dbItem, genderTypeId, numChildLevels);
}
return dbItem;
}
public async Task<GenderType> GetFirstOrDefaultAsync(GenderType item)
{
return await _ctx.GenderTypes.Where(x => x.GenderTypeId == item.GenderTypeId).FirstOrDefaultAsync();
}
public async Task<IRepositoryActionResult<GenderType>> UpdateAsync(GenderType item)
{
var oldItem = await _ctx.GenderTypes.FirstOrDefaultAsync(x => x.GenderTypeId == item.GenderTypeId);
var result = await UpdateAsync<GenderType>(item, oldItem);
RunCustomLogicAfterUpdate_GenderType(newItem: item, oldItem: oldItem, result: result);
return result;
}
public async Task<IRepositoryActionResult<GenderType>> Delete_GenderTypeAsync(int genderTypeId)
{
return await DeleteAsync<GenderType>(_ctx.GenderTypes.Where(x => x.GenderTypeId == genderTypeId).FirstOrDefault());
}
public async Task<IRepositoryActionResult<GenderType>> DeleteAsync(GenderType item)
{
return await DeleteAsync<GenderType>(_ctx.GenderTypes.Where(x => x.GenderTypeId == item.GenderTypeId).FirstOrDefault());
}
partial void RunCustomLogicAfterInsert_GenderType(GenderType item, IRepositoryActionResult<GenderType> result);
partial void RunCustomLogicAfterUpdate_GenderType(GenderType newItem, GenderType oldItem, IRepositoryActionResult<GenderType> result);
partial void RunCustomLogicOnGetQueryableByPK_GenderType(ref IQueryable<GenderType> qryItem, int genderTypeId, int numChildLevels);
partial void RunCustomLogicOnGetEntityByPK_GenderType(ref GenderType dbItem, int genderTypeId, int numChildLevels);
#endregion GenderType
#region LanguageType
public async Task<IRepositoryActionResult<LanguageType>> InsertAsync(LanguageType item)
{
var result = await InsertAsync<LanguageType>(item);
RunCustomLogicAfterInsert_LanguageType(item, result);
return result;
}
public IQueryable<LanguageType> GetQueryable_LanguageType()
{
return _ctx.Set<LanguageType>();
}
public async Task<LanguageType> Get_LanguageTypeAsync(int languageTypeId, int numChildLevels)
{
var qryItem = GetQueryable_LanguageType().AsNoTracking();
RunCustomLogicOnGetQueryableByPK_LanguageType(ref qryItem, languageTypeId, numChildLevels);
var dbItem = await qryItem.Where(x => x.LanguageTypeId == languageTypeId).FirstOrDefaultAsync();
if (!(dbItem is null))
{
RunCustomLogicOnGetEntityByPK_LanguageType(ref dbItem, languageTypeId, numChildLevels);
}
return dbItem;
}
public async Task<LanguageType> GetFirstOrDefaultAsync(LanguageType item)
{
return await _ctx.LanguageTypes.Where(x => x.LanguageTypeId == item.LanguageTypeId).FirstOrDefaultAsync();
}
public async Task<IRepositoryActionResult<LanguageType>> UpdateAsync(LanguageType item)
{
var oldItem = await _ctx.LanguageTypes.FirstOrDefaultAsync(x => x.LanguageTypeId == item.LanguageTypeId);
var result = await UpdateAsync<LanguageType>(item, oldItem);
RunCustomLogicAfterUpdate_LanguageType(newItem: item, oldItem: oldItem, result: result);
return result;
}
public async Task<IRepositoryActionResult<LanguageType>> Delete_LanguageTypeAsync(int languageTypeId)
{
return await DeleteAsync<LanguageType>(_ctx.LanguageTypes.Where(x => x.LanguageTypeId == languageTypeId).FirstOrDefault());
}
public async Task<IRepositoryActionResult<LanguageType>> DeleteAsync(LanguageType item)
{
return await DeleteAsync<LanguageType>(_ctx.LanguageTypes.Where(x => x.LanguageTypeId == item.LanguageTypeId).FirstOrDefault());
}
partial void RunCustomLogicAfterInsert_LanguageType(LanguageType item, IRepositoryActionResult<LanguageType> result);
partial void RunCustomLogicAfterUpdate_LanguageType(LanguageType newItem, LanguageType oldItem, IRepositoryActionResult<LanguageType> result);
partial void RunCustomLogicOnGetQueryableByPK_LanguageType(ref IQueryable<LanguageType> qryItem, int languageTypeId, int numChildLevels);
partial void RunCustomLogicOnGetEntityByPK_LanguageType(ref LanguageType dbItem, int languageTypeId, int numChildLevels);
#endregion LanguageType
#region Log
public async Task<IRepositoryActionResult<Log>> InsertAsync(Log item)
{
var result = await InsertAsync<Log>(item);
RunCustomLogicAfterInsert_Log(item, result);
return result;
}
public IQueryable<Log> GetQueryable_Log()
{
return _ctx.Set<Log>();
}
public async Task<Log> Get_LogAsync(int id, int numChildLevels)
{
var qryItem = GetQueryable_Log().AsNoTracking();
RunCustomLogicOnGetQueryableByPK_Log(ref qryItem, id, numChildLevels);
var dbItem = await qryItem.Where(x => x.Id == id).FirstOrDefaultAsync();
if (!(dbItem is null))
{
RunCustomLogicOnGetEntityByPK_Log(ref dbItem, id, numChildLevels);
}
return dbItem;
}
public async Task<Log> GetFirstOrDefaultAsync(Log item)
{
return await _ctx.Logs.Where(x => x.Id == item.Id).FirstOrDefaultAsync();
}
public async Task<IRepositoryActionResult<Log>> UpdateAsync(Log item)
{
var oldItem = await _ctx.Logs.FirstOrDefaultAsync(x => x.Id == item.Id);
var result = await UpdateAsync<Log>(item, oldItem);
RunCustomLogicAfterUpdate_Log(newItem: item, oldItem: oldItem, result: result);
return result;
}
public async Task<IRepositoryActionResult<Log>> Delete_LogAsync(int id)
{
return await DeleteAsync<Log>(_ctx.Logs.Where(x => x.Id == id).FirstOrDefault());
}
public async Task<IRepositoryActionResult<Log>> DeleteAsync(Log item)
{
return await DeleteAsync<Log>(_ctx.Logs.Where(x => x.Id == item.Id).FirstOrDefault());
}
partial void RunCustomLogicAfterInsert_Log(Log item, IRepositoryActionResult<Log> result);
partial void RunCustomLogicAfterUpdate_Log(Log newItem, Log oldItem, IRepositoryActionResult<Log> result);
partial void RunCustomLogicOnGetQueryableByPK_Log(ref IQueryable<Log> qryItem, int id, int numChildLevels);
partial void RunCustomLogicOnGetEntityByPK_Log(ref Log dbItem, int id, int numChildLevels);
#endregion Log
#region LogType
public async Task<IRepositoryActionResult<LogType>> InsertAsync(LogType item)
{
var result = await InsertAsync<LogType>(item);
RunCustomLogicAfterInsert_LogType(item, result);
return result;
}
public IQueryable<LogType> GetQueryable_LogType()
{
return _ctx.Set<LogType>();
}
public async Task<LogType> Get_LogTypeAsync(int id, int numChildLevels)
{
var qryItem = GetQueryable_LogType().AsNoTracking();
RunCustomLogicOnGetQueryableByPK_LogType(ref qryItem, id, numChildLevels);
var dbItem = await qryItem.Where(x => x.Id == id).FirstOrDefaultAsync();
if (!(dbItem is null))
{
RunCustomLogicOnGetEntityByPK_LogType(ref dbItem, id, numChildLevels);
}
return dbItem;
}
public async Task<LogType> GetFirstOrDefaultAsync(LogType item)
{
return await _ctx.LogTypes.Where(x => x.Id == item.Id).FirstOrDefaultAsync();
}
public async Task<IRepositoryActionResult<LogType>> UpdateAsync(LogType item)
{
var oldItem = await _ctx.LogTypes.FirstOrDefaultAsync(x => x.Id == item.Id);
var result = await UpdateAsync<LogType>(item, oldItem);
RunCustomLogicAfterUpdate_LogType(newItem: item, oldItem: oldItem, result: result);
return result;
}
public async Task<IRepositoryActionResult<LogType>> Delete_LogTypeAsync(int id)
{
return await DeleteAsync<LogType>(_ctx.LogTypes.Where(x => x.Id == id).FirstOrDefault());
}
public async Task<IRepositoryActionResult<LogType>> DeleteAsync(LogType item)
{
return await DeleteAsync<LogType>(_ctx.LogTypes.Where(x => x.Id == item.Id).FirstOrDefault());
}
partial void RunCustomLogicAfterInsert_LogType(LogType item, IRepositoryActionResult<LogType> result);
partial void RunCustomLogicAfterUpdate_LogType(LogType newItem, LogType oldItem, IRepositoryActionResult<LogType> result);
partial void RunCustomLogicOnGetQueryableByPK_LogType(ref IQueryable<LogType> qryItem, int id, int numChildLevels);
partial void RunCustomLogicOnGetEntityByPK_LogType(ref LogType dbItem, int id, int numChildLevels);
#endregion LogType
#region LookupList
public async Task<IRepositoryActionResult<LookupList>> InsertAsync(LookupList item)
{
var result = await InsertAsync<LookupList>(item);
RunCustomLogicAfterInsert_LookupList(item, result);
return result;
}
public IQueryable<LookupList> GetQueryable_LookupList()
{
return _ctx.Set<LookupList>();
}
public async Task<LookupList> Get_LookupListAsync(int lookupListId, int numChildLevels)
{
var qryItem = GetQueryable_LookupList().AsNoTracking();
RunCustomLogicOnGetQueryableByPK_LookupList(ref qryItem, lookupListId, numChildLevels);
var dbItem = await qryItem.Where(x => x.LookupListId == lookupListId).FirstOrDefaultAsync();
if (!(dbItem is null))
{
RunCustomLogicOnGetEntityByPK_LookupList(ref dbItem, lookupListId, numChildLevels);
}
return dbItem;
}
public async Task<LookupList> GetFirstOrDefaultAsync(LookupList item)
{
return await _ctx.LookupLists.Where(x => x.LookupListId == item.LookupListId).FirstOrDefaultAsync();
}
public async Task<IRepositoryActionResult<LookupList>> UpdateAsync(LookupList item)
{
var oldItem = await _ctx.LookupLists.FirstOrDefaultAsync(x => x.LookupListId == item.LookupListId);
var result = await UpdateAsync<LookupList>(item, oldItem);
RunCustomLogicAfterUpdate_LookupList(newItem: item, oldItem: oldItem, result: result);
return result;
}
public async Task<IRepositoryActionResult<LookupList>> Delete_LookupListAsync(int lookupListId)
{
return await DeleteAsync<LookupList>(_ctx.LookupLists.Where(x => x.LookupListId == lookupListId).FirstOrDefault());
}
public async Task<IRepositoryActionResult<LookupList>> DeleteAsync(LookupList item)
{
return await DeleteAsync<LookupList>(_ctx.LookupLists.Where(x => x.LookupListId == item.LookupListId).FirstOrDefault());
}
partial void RunCustomLogicAfterInsert_LookupList(LookupList item, IRepositoryActionResult<LookupList> result);
partial void RunCustomLogicAfterUpdate_LookupList(LookupList newItem, LookupList oldItem, IRepositoryActionResult<LookupList> result);
partial void RunCustomLogicOnGetQueryableByPK_LookupList(ref IQueryable<LookupList> qryItem, int lookupListId, int numChildLevels);
partial void RunCustomLogicOnGetEntityByPK_LookupList(ref LookupList dbItem, int lookupListId, int numChildLevels);
#endregion LookupList
#region Room
public async Task<IRepositoryActionResult<Room>> InsertAsync(Room item)
{
var result = await InsertAsync<Room>(item);
RunCustomLogicAfterInsert_Room(item, result);
return result;
}
public IQueryable<Room> GetQueryable_Room()
{
return _ctx.Set<Room>();
}
public async Task<Room> Get_RoomAsync(int roomId, int numChildLevels)
{
var qryItem = GetQueryable_Room().AsNoTracking();
RunCustomLogicOnGetQueryableByPK_Room(ref qryItem, roomId, numChildLevels);
var dbItem = await qryItem.Where(x => x.RoomId == roomId).FirstOrDefaultAsync();
if (!(dbItem is null))
{
RunCustomLogicOnGetEntityByPK_Room(ref dbItem, roomId, numChildLevels);
}
return dbItem;
}
public async Task<Room> GetFirstOrDefaultAsync(Room item)
{
return await _ctx.Rooms.Where(x => x.RoomId == item.RoomId).FirstOrDefaultAsync();
}
public async Task<IRepositoryActionResult<Room>> UpdateAsync(Room item)
{
var oldItem = await _ctx.Rooms.FirstOrDefaultAsync(x => x.RoomId == item.RoomId);
var result = await UpdateAsync<Room>(item, oldItem);
RunCustomLogicAfterUpdate_Room(newItem: item, oldItem: oldItem, result: result);
return result;
}
public async Task<IRepositoryActionResult<Room>> Delete_RoomAsync(int roomId)
{
return await DeleteAsync<Room>(_ctx.Rooms.Where(x => x.RoomId == roomId).FirstOrDefault());
}
public async Task<IRepositoryActionResult<Room>> DeleteAsync(Room item)
{
return await DeleteAsync<Room>(_ctx.Rooms.Where(x => x.RoomId == item.RoomId).FirstOrDefault());
}
partial void RunCustomLogicAfterInsert_Room(Room item, IRepositoryActionResult<Room> result);
partial void RunCustomLogicAfterUpdate_Room(Room newItem, Room oldItem, IRepositoryActionResult<Room> result);
partial void RunCustomLogicOnGetQueryableByPK_Room(ref IQueryable<Room> qryItem, int roomId, int numChildLevels);
partial void RunCustomLogicOnGetEntityByPK_Room(ref Room dbItem, int roomId, int numChildLevels);
#endregion Room
#region Session
public async Task<IRepositoryActionResult<Session>> InsertAsync(Session item)
{
var result = await InsertAsync<Session>(item);
RunCustomLogicAfterInsert_Session(item, result);
return result;
}
public IQueryable<Session> GetQueryable_Session()
{
return _ctx.Set<Session>();
}
public async Task<Session> Get_SessionAsync(int sessionId, int numChildLevels)
{
var qryItem = GetQueryable_Session().AsNoTracking();
RunCustomLogicOnGetQueryableByPK_Session(ref qryItem, sessionId, numChildLevels);
var dbItem = await qryItem.Where(x => x.SessionId == sessionId).FirstOrDefaultAsync();
if (!(dbItem is null))
{
RunCustomLogicOnGetEntityByPK_Session(ref dbItem, sessionId, numChildLevels);
}
return dbItem;
}
public async Task<Session> GetFirstOrDefaultAsync(Session item)
{
return await _ctx.Sessions.Where(x => x.SessionId == item.SessionId).FirstOrDefaultAsync();
}
public async Task<IRepositoryActionResult<Session>> UpdateAsync(Session item)
{
var oldItem = await _ctx.Sessions.FirstOrDefaultAsync(x => x.SessionId == item.SessionId);
var result = await UpdateAsync<Session>(item, oldItem);
RunCustomLogicAfterUpdate_Session(newItem: item, oldItem: oldItem, result: result);
return result;
}
public async Task<IRepositoryActionResult<Session>> Delete_SessionAsync(int sessionId)
{
return await DeleteAsync<Session>(_ctx.Sessions.Where(x => x.SessionId == sessionId).FirstOrDefault());
}
public async Task<IRepositoryActionResult<Session>> DeleteAsync(Session item)
{
return await DeleteAsync<Session>(_ctx.Sessions.Where(x => x.SessionId == item.SessionId).FirstOrDefault());
}
partial void RunCustomLogicAfterInsert_Session(Session item, IRepositoryActionResult<Session> result);
partial void RunCustomLogicAfterUpdate_Session(Session newItem, Session oldItem, IRepositoryActionResult<Session> result);
partial void RunCustomLogicOnGetQueryableByPK_Session(ref IQueryable<Session> qryItem, int sessionId, int numChildLevels);
partial void RunCustomLogicOnGetEntityByPK_Session(ref Session dbItem, int sessionId, int numChildLevels);
#endregion Session
#region SessionCategoryType
public async Task<IRepositoryActionResult<SessionCategoryType>> InsertAsync(SessionCategoryType item)
{
var result = await InsertAsync<SessionCategoryType>(item);
RunCustomLogicAfterInsert_SessionCategoryType(item, result);
return result;
}
public IQueryable<SessionCategoryType> GetQueryable_SessionCategoryType()
{
return _ctx.Set<SessionCategoryType>();
}
public async Task<SessionCategoryType> Get_SessionCategoryTypeAsync(int sessionCategoryTypeId, int numChildLevels)
{
var qryItem = GetQueryable_SessionCategoryType().AsNoTracking();
RunCustomLogicOnGetQueryableByPK_SessionCategoryType(ref qryItem, sessionCategoryTypeId, numChildLevels);
var dbItem = await qryItem.Where(x => x.SessionCategoryTypeId == sessionCategoryTypeId).FirstOrDefaultAsync();
if (!(dbItem is null))
{
RunCustomLogicOnGetEntityByPK_SessionCategoryType(ref dbItem, sessionCategoryTypeId, numChildLevels);
}
return dbItem;
}
public async Task<SessionCategoryType> GetFirstOrDefaultAsync(SessionCategoryType item)
{
return await _ctx.SessionCategoryTypes.Where(x => x.SessionCategoryTypeId == item.SessionCategoryTypeId).FirstOrDefaultAsync();
}
public async Task<IRepositoryActionResult<SessionCategoryType>> UpdateAsync(SessionCategoryType item)
{
var oldItem = await _ctx.SessionCategoryTypes.FirstOrDefaultAsync(x => x.SessionCategoryTypeId == item.SessionCategoryTypeId);
var result = await UpdateAsync<SessionCategoryType>(item, oldItem);
RunCustomLogicAfterUpdate_SessionCategoryType(newItem: item, oldItem: oldItem, result: result);
return result;
}
public async Task<IRepositoryActionResult<SessionCategoryType>> Delete_SessionCategoryTypeAsync(int sessionCategoryTypeId)
{
return await DeleteAsync<SessionCategoryType>(_ctx.SessionCategoryTypes.Where(x => x.SessionCategoryTypeId == sessionCategoryTypeId).FirstOrDefault());
}
public async Task<IRepositoryActionResult<SessionCategoryType>> DeleteAsync(SessionCategoryType item)
{
return await DeleteAsync<SessionCategoryType>(_ctx.SessionCategoryTypes.Where(x => x.SessionCategoryTypeId == item.SessionCategoryTypeId).FirstOrDefault());
}
partial void RunCustomLogicAfterInsert_SessionCategoryType(SessionCategoryType item, IRepositoryActionResult<SessionCategoryType> result);
partial void RunCustomLogicAfterUpdate_SessionCategoryType(SessionCategoryType newItem, SessionCategoryType oldItem, IRepositoryActionResult<SessionCategoryType> result);
partial void RunCustomLogicOnGetQueryableByPK_SessionCategoryType(ref IQueryable<SessionCategoryType> qryItem, int sessionCategoryTypeId, int numChildLevels);
partial void RunCustomLogicOnGetEntityByPK_SessionCategoryType(ref SessionCategoryType dbItem, int sessionCategoryTypeId, int numChildLevels);
#endregion SessionCategoryType
#region SessionLike
public async Task<IRepositoryActionResult<SessionLike>> InsertAsync(SessionLike item)
{
var result = await InsertAsync<SessionLike>(item);
RunCustomLogicAfterInsert_SessionLike(item, result);
return result;
}
public IQueryable<SessionLike> GetQueryable_SessionLike()
{
return _ctx.Set<SessionLike>();
}
public async Task<SessionLike> Get_SessionLikeAsync(int sessionId, int userProfileId, int numChildLevels)
{
var qryItem = GetQueryable_SessionLike().AsNoTracking();
RunCustomLogicOnGetQueryableByPK_SessionLike(ref qryItem, sessionId, userProfileId, numChildLevels);
var dbItem = await qryItem.Where(
x => x.SessionId == sessionId
&& x.UserProfileId == userProfileId).FirstOrDefaultAsync();
if (!(dbItem is null))
{
RunCustomLogicOnGetEntityByPK_SessionLike(ref dbItem, sessionId, userProfileId, numChildLevels);
}
return dbItem;
}
public async Task<SessionLike> GetFirstOrDefaultAsync(SessionLike item)
{
return await _ctx.SessionLikes.Where(
x => x.SessionId == item.SessionId
&& x.UserProfileId == item.UserProfileId).FirstOrDefaultAsync();
}
public async Task<IRepositoryActionResult<SessionLike>> UpdateAsync(SessionLike item)
{
var oldItem = await _ctx.SessionLikes.FirstOrDefaultAsync(
x => x.SessionId == item.SessionId
&& x.UserProfileId == item.UserProfileId);
var result = await UpdateAsync<SessionLike>(item, oldItem);
RunCustomLogicAfterUpdate_SessionLike(newItem: item, oldItem: oldItem, result: result);
return result;
}
public async Task<IRepositoryActionResult<SessionLike>> Delete_SessionLikeAsync(int sessionId, int userProfileId)
{
return await DeleteAsync<SessionLike>(_ctx.SessionLikes.Where(
x => x.SessionId == sessionId
&& x.UserProfileId == userProfileId).FirstOrDefault());
}
public async Task<IRepositoryActionResult<SessionLike>> DeleteAsync(SessionLike item)
{
return await DeleteAsync<SessionLike>(_ctx.SessionLikes.Where(
x => x.SessionId == item.SessionId
&& x.UserProfileId == item.UserProfileId).FirstOrDefault());
}
partial void RunCustomLogicAfterInsert_SessionLike(SessionLike item, IRepositoryActionResult<SessionLike> result);
partial void RunCustomLogicAfterUpdate_SessionLike(SessionLike newItem, SessionLike oldItem, IRepositoryActionResult<SessionLike> result);
partial void RunCustomLogicOnGetQueryableByPK_SessionLike(ref IQueryable<SessionLike> qryItem, int sessionId, int userProfileId, int numChildLevels);
partial void RunCustomLogicOnGetEntityByPK_SessionLike(ref SessionLike dbItem, int sessionId, int userProfileId, int numChildLevels);
#endregion SessionLike
#region SessionSessionCategoryType
public async Task<IRepositoryActionResult<SessionSessionCategoryType>> InsertAsync(SessionSessionCategoryType item)
{
var result = await InsertAsync<SessionSessionCategoryType>(item);
RunCustomLogicAfterInsert_SessionSessionCategoryType(item, result);
return result;
}
public IQueryable<SessionSessionCategoryType> GetQueryable_SessionSessionCategoryType()
{
return _ctx.Set<SessionSessionCategoryType>();
}
public async Task<SessionSessionCategoryType> Get_SessionSessionCategoryTypeAsync(int sessionId, int sessionCategoryTypeId, int numChildLevels)
{
var qryItem = GetQueryable_SessionSessionCategoryType().AsNoTracking();
RunCustomLogicOnGetQueryableByPK_SessionSessionCategoryType(ref qryItem, sessionId, sessionCategoryTypeId, numChildLevels);
var dbItem = await qryItem.Where(
x => x.SessionId == sessionId
&& x.SessionCategoryTypeId == sessionCategoryTypeId).FirstOrDefaultAsync();
if (!(dbItem is null))
{
RunCustomLogicOnGetEntityByPK_SessionSessionCategoryType(ref dbItem, sessionId, sessionCategoryTypeId, numChildLevels);
}
return dbItem;
}
public async Task<SessionSessionCategoryType> GetFirstOrDefaultAsync(SessionSessionCategoryType item)
{
return await _ctx.SessionSessionCategoryTypes.Where(
x => x.SessionId == item.SessionId
&& x.SessionCategoryTypeId == item.SessionCategoryTypeId).FirstOrDefaultAsync();
}
public async Task<IRepositoryActionResult<SessionSessionCategoryType>> UpdateAsync(SessionSessionCategoryType item)
{
var oldItem = await _ctx.SessionSessionCategoryTypes.FirstOrDefaultAsync(
x => x.SessionId == item.SessionId
&& x.SessionCategoryTypeId == item.SessionCategoryTypeId);
var result = await UpdateAsync<SessionSessionCategoryType>(item, oldItem);
RunCustomLogicAfterUpdate_SessionSessionCategoryType(newItem: item, oldItem: oldItem, result: result);
return result;
}
public async Task<IRepositoryActionResult<SessionSessionCategoryType>> Delete_SessionSessionCategoryTypeAsync(int sessionId, int sessionCategoryTypeId)
{
return await DeleteAsync<SessionSessionCategoryType>(_ctx.SessionSessionCategoryTypes.Where(
x => x.SessionId == sessionId
&& x.SessionCategoryTypeId == sessionCategoryTypeId).FirstOrDefault());
}
public async Task<IRepositoryActionResult<SessionSessionCategoryType>> DeleteAsync(SessionSessionCategoryType item)
{
return await DeleteAsync<SessionSessionCategoryType>(_ctx.SessionSessionCategoryTypes.Where(
x => x.SessionId == item.SessionId
&& x.SessionCategoryTypeId == item.SessionCategoryTypeId).FirstOrDefault());
}
partial void RunCustomLogicAfterInsert_SessionSessionCategoryType(SessionSessionCategoryType item, IRepositoryActionResult<SessionSessionCategoryType> result);
partial void RunCustomLogicAfterUpdate_SessionSessionCategoryType(SessionSessionCategoryType newItem, SessionSessionCategoryType oldItem, IRepositoryActionResult<SessionSessionCategoryType> result);
partial void RunCustomLogicOnGetQueryableByPK_SessionSessionCategoryType(ref IQueryable<SessionSessionCategoryType> qryItem, int sessionId, int sessionCategoryTypeId, int numChildLevels);
partial void RunCustomLogicOnGetEntityByPK_SessionSessionCategoryType(ref SessionSessionCategoryType dbItem, int sessionId, int sessionCategoryTypeId, int numChildLevels);
#endregion SessionSessionCategoryType
#region SessionSpeaker
public async Task<IRepositoryActionResult<SessionSpeaker>> InsertAsync(SessionSpeaker item)
{
var result = await InsertAsync<SessionSpeaker>(item);
RunCustomLogicAfterInsert_SessionSpeaker(item, result);
return result;
}
public IQueryable<SessionSpeaker> GetQueryable_SessionSpeaker()
{
return _ctx.Set<SessionSpeaker>();
}
public async Task<SessionSpeaker> Get_SessionSpeakerAsync(int sessionId, int userProfileId, int numChildLevels)
{
var qryItem = GetQueryable_SessionSpeaker().AsNoTracking();
RunCustomLogicOnGetQueryableByPK_SessionSpeaker(ref qryItem, sessionId, userProfileId, numChildLevels);
var dbItem = await qryItem.Where(
x => x.SessionId == sessionId
&& x.UserProfileId == userProfileId).FirstOrDefaultAsync();
if (!(dbItem is null))
{
RunCustomLogicOnGetEntityByPK_SessionSpeaker(ref dbItem, sessionId, userProfileId, numChildLevels);
}
return dbItem;
}
public async Task<SessionSpeaker> GetFirstOrDefaultAsync(SessionSpeaker item)
{
return await _ctx.SessionSpeakers.Where(
x => x.SessionId == item.SessionId
&& x.UserProfileId == item.UserProfileId).FirstOrDefaultAsync();
}
public async Task<IRepositoryActionResult<SessionSpeaker>> UpdateAsync(SessionSpeaker item)
{
var oldItem = await _ctx.SessionSpeakers.FirstOrDefaultAsync(
x => x.SessionId == item.SessionId
&& x.UserProfileId == item.UserProfileId);
var result = await UpdateAsync<SessionSpeaker>(item, oldItem);
RunCustomLogicAfterUpdate_SessionSpeaker(newItem: item, oldItem: oldItem, result: result);
return result;
}
public async Task<IRepositoryActionResult<SessionSpeaker>> Delete_SessionSpeakerAsync(int sessionId, int userProfileId)
{
return await DeleteAsync<SessionSpeaker>(_ctx.SessionSpeakers.Where(
x => x.SessionId == sessionId
&& x.UserProfileId == userProfileId).FirstOrDefault());
}
public async Task<IRepositoryActionResult<SessionSpeaker>> DeleteAsync(SessionSpeaker item)
{
return await DeleteAsync<SessionSpeaker>(_ctx.SessionSpeakers.Where(
x => x.SessionId == item.SessionId
&& x.UserProfileId == item.UserProfileId).FirstOrDefault());
}
partial void RunCustomLogicAfterInsert_SessionSpeaker(SessionSpeaker item, IRepositoryActionResult<SessionSpeaker> result);
partial void RunCustomLogicAfterUpdate_SessionSpeaker(SessionSpeaker newItem, SessionSpeaker oldItem, IRepositoryActionResult<SessionSpeaker> result);
partial void RunCustomLogicOnGetQueryableByPK_SessionSpeaker(ref IQueryable<SessionSpeaker> qryItem, int sessionId, int userProfileId, int numChildLevels);
partial void RunCustomLogicOnGetEntityByPK_SessionSpeaker(ref SessionSpeaker dbItem, int sessionId, int userProfileId, int numChildLevels);
#endregion SessionSpeaker
#region Sponsor
public async Task<IRepositoryActionResult<Sponsor>> InsertAsync(Sponsor item)
{
var result = await InsertAsync<Sponsor>(item);
RunCustomLogicAfterInsert_Sponsor(item, result);
return result;
}
public IQueryable<Sponsor> GetQueryable_Sponsor()
{
return _ctx.Set<Sponsor>();
}
public async Task<Sponsor> Get_SponsorAsync(int sponsorId, int numChildLevels)
{
var qryItem = GetQueryable_Sponsor().AsNoTracking();
RunCustomLogicOnGetQueryableByPK_Sponsor(ref qryItem, sponsorId, numChildLevels);
var dbItem = await qryItem.Where(x => x.SponsorId == sponsorId).FirstOrDefaultAsync();
if (!(dbItem is null))
{
RunCustomLogicOnGetEntityByPK_Sponsor(ref dbItem, sponsorId, numChildLevels);
}
return dbItem;
}
public async Task<Sponsor> GetFirstOrDefaultAsync(Sponsor item)
{
return await _ctx.Sponsors.Where(x => x.SponsorId == item.SponsorId).FirstOrDefaultAsync();
}
public async Task<IRepositoryActionResult<Sponsor>> UpdateAsync(Sponsor item)
{
var oldItem = await _ctx.Sponsors.FirstOrDefaultAsync(x => x.SponsorId == item.SponsorId);
var result = await UpdateAsync<Sponsor>(item, oldItem);
RunCustomLogicAfterUpdate_Sponsor(newItem: item, oldItem: oldItem, result: result);
return result;
}
public async Task<IRepositoryActionResult<Sponsor>> Delete_SponsorAsync(int sponsorId)
{
return await DeleteAsync<Sponsor>(_ctx.Sponsors.Where(x => x.SponsorId == sponsorId).FirstOrDefault());
}
public async Task<IRepositoryActionResult<Sponsor>> DeleteAsync(Sponsor item)
{
return await DeleteAsync<Sponsor>(_ctx.Sponsors.Where(x => x.SponsorId == item.SponsorId).FirstOrDefault());
}
partial void RunCustomLogicAfterInsert_Sponsor(Sponsor item, IRepositoryActionResult<Sponsor> result);
partial void RunCustomLogicAfterUpdate_Sponsor(Sponsor newItem, Sponsor oldItem, IRepositoryActionResult<Sponsor> result);
partial void RunCustomLogicOnGetQueryableByPK_Sponsor(ref IQueryable<Sponsor> qryItem, int sponsorId, int numChildLevels);
partial void RunCustomLogicOnGetEntityByPK_Sponsor(ref Sponsor dbItem, int sponsorId, int numChildLevels);
#endregion Sponsor
#region SponsorFeaturedEvent
public async Task<IRepositoryActionResult<SponsorFeaturedEvent>> InsertAsync(SponsorFeaturedEvent item)
{
var result = await InsertAsync<SponsorFeaturedEvent>(item);
RunCustomLogicAfterInsert_SponsorFeaturedEvent(item, result);
return result;
}
public IQueryable<SponsorFeaturedEvent> GetQueryable_SponsorFeaturedEvent()
{
return _ctx.Set<SponsorFeaturedEvent>();
}
public async Task<SponsorFeaturedEvent> Get_SponsorFeaturedEventAsync(int sponsorId, int featuredEventId, int numChildLevels)
{
var qryItem = GetQueryable_SponsorFeaturedEvent().AsNoTracking();
RunCustomLogicOnGetQueryableByPK_SponsorFeaturedEvent(ref qryItem, sponsorId, featuredEventId, numChildLevels);
var dbItem = await qryItem.Where(
x => x.SponsorId == sponsorId
&& x.FeaturedEventId == featuredEventId).FirstOrDefaultAsync();
if (!(dbItem is null))
{
RunCustomLogicOnGetEntityByPK_SponsorFeaturedEvent(ref dbItem, sponsorId, featuredEventId, numChildLevels);
}
return dbItem;
}
public async Task<SponsorFeaturedEvent> GetFirstOrDefaultAsync(SponsorFeaturedEvent item)
{
return await _ctx.SponsorFeaturedEvents.Where(
x => x.SponsorId == item.SponsorId
&& x.FeaturedEventId == item.FeaturedEventId).FirstOrDefaultAsync();
}
public async Task<IRepositoryActionResult<SponsorFeaturedEvent>> UpdateAsync(SponsorFeaturedEvent item)
{
var oldItem = await _ctx.SponsorFeaturedEvents.FirstOrDefaultAsync(
x => x.SponsorId == item.SponsorId
&& x.FeaturedEventId == item.FeaturedEventId);
var result = await UpdateAsync<SponsorFeaturedEvent>(item, oldItem);
RunCustomLogicAfterUpdate_SponsorFeaturedEvent(newItem: item, oldItem: oldItem, result: result);
return result;
}
public async Task<IRepositoryActionResult<SponsorFeaturedEvent>> Delete_SponsorFeaturedEventAsync(int sponsorId, int featuredEventId)
{
return await DeleteAsync<SponsorFeaturedEvent>(_ctx.SponsorFeaturedEvents.Where(
x => x.SponsorId == sponsorId
&& x.FeaturedEventId == featuredEventId).FirstOrDefault());
}
public async Task<IRepositoryActionResult<SponsorFeaturedEvent>> DeleteAsync(SponsorFeaturedEvent item)
{
return await DeleteAsync<SponsorFeaturedEvent>(_ctx.SponsorFeaturedEvents.Where(
x => x.SponsorId == item.SponsorId
&& x.FeaturedEventId == item.FeaturedEventId).FirstOrDefault());
}
partial void RunCustomLogicAfterInsert_SponsorFeaturedEvent(SponsorFeaturedEvent item, IRepositoryActionResult<SponsorFeaturedEvent> result);
partial void RunCustomLogicAfterUpdate_SponsorFeaturedEvent(SponsorFeaturedEvent newItem, SponsorFeaturedEvent oldItem, IRepositoryActionResult<SponsorFeaturedEvent> result);
partial void RunCustomLogicOnGetQueryableByPK_SponsorFeaturedEvent(ref IQueryable<SponsorFeaturedEvent> qryItem, int sponsorId, int featuredEventId, int numChildLevels);
partial void RunCustomLogicOnGetEntityByPK_SponsorFeaturedEvent(ref SponsorFeaturedEvent dbItem, int sponsorId, int featuredEventId, int numChildLevels);
#endregion SponsorFeaturedEvent
#region SponsorType
public async Task<IRepositoryActionResult<SponsorType>> InsertAsync(SponsorType item)
{
var result = await InsertAsync<SponsorType>(item);
RunCustomLogicAfterInsert_SponsorType(item, result);
return result;
}
public IQueryable<SponsorType> GetQueryable_SponsorType()
{
return _ctx.Set<SponsorType>();
}
public async Task<SponsorType> Get_SponsorTypeAsync(int sponsorTypeId, int numChildLevels)
{
var qryItem = GetQueryable_SponsorType().AsNoTracking();
RunCustomLogicOnGetQueryableByPK_SponsorType(ref qryItem, sponsorTypeId, numChildLevels);
var dbItem = await qryItem.Where(x => x.SponsorTypeId == sponsorTypeId).FirstOrDefaultAsync();
if (!(dbItem is null))
{
RunCustomLogicOnGetEntityByPK_SponsorType(ref dbItem, sponsorTypeId, numChildLevels);
}
return dbItem;
}
public async Task<SponsorType> GetFirstOrDefaultAsync(SponsorType item)
{
return await _ctx.SponsorTypes.Where(x => x.SponsorTypeId == item.SponsorTypeId).FirstOrDefaultAsync();
}
public async Task<IRepositoryActionResult<SponsorType>> UpdateAsync(SponsorType item)
{
var oldItem = await _ctx.SponsorTypes.FirstOrDefaultAsync(x => x.SponsorTypeId == item.SponsorTypeId);
var result = await UpdateAsync<SponsorType>(item, oldItem);
RunCustomLogicAfterUpdate_SponsorType(newItem: item, oldItem: oldItem, result: result);
return result;
}
public async Task<IRepositoryActionResult<SponsorType>> Delete_SponsorTypeAsync(int sponsorTypeId)
{
return await DeleteAsync<SponsorType>(_ctx.SponsorTypes.Where(x => x.SponsorTypeId == sponsorTypeId).FirstOrDefault());
}
public async Task<IRepositoryActionResult<SponsorType>> DeleteAsync(SponsorType item)
{
return await DeleteAsync<SponsorType>(_ctx.SponsorTypes.Where(x => x.SponsorTypeId == item.SponsorTypeId).FirstOrDefault());
}
partial void RunCustomLogicAfterInsert_SponsorType(SponsorType item, IRepositoryActionResult<SponsorType> result);
partial void RunCustomLogicAfterUpdate_SponsorType(SponsorType newItem, SponsorType oldItem, IRepositoryActionResult<SponsorType> result);
partial void RunCustomLogicOnGetQueryableByPK_SponsorType(ref IQueryable<SponsorType> qryItem, int sponsorTypeId, int numChildLevels);
partial void RunCustomLogicOnGetEntityByPK_SponsorType(ref SponsorType dbItem, int sponsorTypeId, int numChildLevels);
#endregion SponsorType
#region UserProfile
public async Task<IRepositoryActionResult<UserProfile>> InsertAsync(UserProfile item)
{
var result = await InsertAsync<UserProfile>(item);
RunCustomLogicAfterInsert_UserProfile(item, result);
return result;
}
public IQueryable<UserProfile> GetQueryable_UserProfile()
{
return _ctx.Set<UserProfile>();
}
public async Task<UserProfile> Get_UserProfileAsync(int userProfileId, int numChildLevels)
{
var qryItem = GetQueryable_UserProfile().AsNoTracking();
RunCustomLogicOnGetQueryableByPK_UserProfile(ref qryItem, userProfileId, numChildLevels);
var dbItem = await qryItem.Where(x => x.UserProfileId == userProfileId).FirstOrDefaultAsync();
if (!(dbItem is null))
{
RunCustomLogicOnGetEntityByPK_UserProfile(ref dbItem, userProfileId, numChildLevels);
}
return dbItem;
}
public async Task<UserProfile> GetFirstOrDefaultAsync(UserProfile item)
{
return await _ctx.UserProfiles.Where(x => x.UserProfileId == item.UserProfileId).FirstOrDefaultAsync();
}
public async Task<IRepositoryActionResult<UserProfile>> UpdateAsync(UserProfile item)
{
var oldItem = await _ctx.UserProfiles.FirstOrDefaultAsync(x => x.UserProfileId == item.UserProfileId);
var result = await UpdateAsync<UserProfile>(item, oldItem);
RunCustomLogicAfterUpdate_UserProfile(newItem: item, oldItem: oldItem, result: result);
return result;
}
public async Task<IRepositoryActionResult<UserProfile>> Delete_UserProfileAsync(int userProfileId)
{
return await DeleteAsync<UserProfile>(_ctx.UserProfiles.Where(x => x.UserProfileId == userProfileId).FirstOrDefault());
}
public async Task<IRepositoryActionResult<UserProfile>> DeleteAsync(UserProfile item)
{
return await DeleteAsync<UserProfile>(_ctx.UserProfiles.Where(x => x.UserProfileId == item.UserProfileId).FirstOrDefault());
}
partial void RunCustomLogicAfterInsert_UserProfile(UserProfile item, IRepositoryActionResult<UserProfile> result);
partial void RunCustomLogicAfterUpdate_UserProfile(UserProfile newItem, UserProfile oldItem, IRepositoryActionResult<UserProfile> result);
partial void RunCustomLogicOnGetQueryableByPK_UserProfile(ref IQueryable<UserProfile> qryItem, int userProfileId, int numChildLevels);
partial void RunCustomLogicOnGetEntityByPK_UserProfile(ref UserProfile dbItem, int userProfileId, int numChildLevels);
#endregion UserProfile
}
}
| 36.912963 | 200 | 0.776066 | [
"Apache-2.0"
] | MSCTek/ConferenceMate | src/MSC.ConferenceMate.Repository/Repositories/CMRepositoryBase.cs | 59,799 | C# |
using Hyperledger.Aries.Decorators.Attachments;
using Hyperledger.Aries.Extensions;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Xunit;
using Hyperledger.Aries.Features.DidExchange;
using Hyperledger.Aries.Agents;
namespace Hyperledger.Aries.Tests.Decorators
{
public class AttachmentDecoratorTests
{
[Fact]
public void ExtractAttachDecorator()
{
var json = "{\"@id\":\"123\",\"@type\":\"did:sov:BzCbsNYhMrjHiqZDTUASHg;spec/connections/1.0/request\",\"~attach\":[]}";
var message = JsonConvert.DeserializeObject<ConnectionRequestMessage>(json,
new AgentMessageReader<ConnectionRequestMessage>());
var decorator = message.GetDecorator<AttachDecorator>("attach");
Assert.NotNull(decorator);
}
[Fact]
public void ExtractAttachDecoratorReturnsNull()
{
var json = "{\"@id\":\"123\",\"@type\":\"did:sov:BzCbsNYhMrjHiqZDTUASHg;spec/connections/1.0/request\"}";
var message = JsonConvert.DeserializeObject<ConnectionRequestMessage>(json,
new AgentMessageReader<ConnectionRequestMessage>());
var decorator = message.FindDecorator<AttachDecorator>("attach");
Assert.Null(decorator);
}
[Fact]
public void ExtractDecoratorAndAttachment()
{
var message = new ConnectionRequestMessage();
message.AddAttachment(new Attachment {Nickname = "file1"});
var jobj = JObject.Parse(message.ToJson());
Assert.NotNull(jobj["~attach"]);
Assert.Equal("file1", jobj["~attach"].First["nickname"]);
}
[Fact]
public void GetAttachmentFromDecorator()
{
var json = "{\"@id\":\"1\",\"@type\":\"did:sov:BzCbsNYhMrjHiqZDTUASHg;spec/connections/1.0/request\",\"~attach\":[{\"nickname\":\"file1\"}]}";
var message = JsonConvert.DeserializeObject<ConnectionRequestMessage>(json,
new AgentMessageReader<ConnectionRequestMessage>());
var decorator = message.GetDecorator<AttachDecorator>("attach");
Assert.NotNull(decorator);
var file = message.GetAttachment("file1");
Assert.NotNull(file);
var file2 = message.GetAttachment("invalid");
Assert.Null(file2);
}
[Fact]
public void RemoveAttachmentFromMessage()
{
var json = "{\"@id\":\"1\",\"@type\":\"did:sov:BzCbsNYhMrjHiqZDTUASHg;spec/connections/1.0/request\",\"~attach\":[{\"nickname\":\"file1\"}]}";
var message = JsonConvert.DeserializeObject<ConnectionRequestMessage>(json,
new AgentMessageReader<ConnectionRequestMessage>());
var decorator = message.GetDecorator<AttachDecorator>("attach");
Assert.NotNull(decorator);
var file = message.GetAttachment("file1");
Assert.NotNull(file);
message.RemoveAttachment("file1");
var file2 = message.GetAttachment("file1");
Assert.Null(file2);
}
}
}
| 34.866667 | 154 | 0.613448 | [
"Apache-2.0"
] | AYCH-Inc/aych.hyperdnet | test/Hyperledger.Aries.Tests/Decorators/AttachmentDecoratorTests.cs | 3,140 | C# |
using hw.DebugFormatter;
using hw.UnitTest;
using Reni.Parser;
// ReSharper disable StringIndexOfIsCultureSpecific.1
namespace ReniUI.Test
{
[UnitTest]
public sealed class ThenElseMatching : DependenceProvider
{
[UnitTest]
public void Matching()
{
const string text = @"1 then 2 else 3";
var compiler = CompilerBrowser.FromText(text);
var thenToken = compiler.Locate(text.IndexOf("then"));
var elseToken = compiler.Locate(text.IndexOf("else"));
(elseToken.Master == thenToken.Master)
.Assert
(
() =>
"elseToken.Master= " +
$"{elseToken.Master.Anchor.SourceParts.DumpSource()}\n\n" +
$"thenToken.Master = {thenToken.Master.Anchor.SourceParts.DumpSource()}"
);
(elseToken.Index == 1).Assert();
(thenToken.Index == 0).Assert();
}
[UnitTest]
public void NestedMatching()
{
const string text = @"1 then 2 then 333 else 3";
var compiler = CompilerBrowser.FromText(text);
var thenToken = compiler.Locate(text.IndexOf("then"));
var elseToken = compiler.Locate(text.IndexOf("else"));
(elseToken.Master == thenToken.Master).Assert();
(elseToken.Index == 1).Assert();
(thenToken.Index == 0).Assert();
}
}
} | 34.55814 | 96 | 0.541723 | [
"MIT"
] | hahoyer/reni.cs | src/ReniUI/Test/ThenElseMatching.cs | 1,486 | C# |
namespace SKIT.FlurlHttpClient.Wechat.Api.Models
{
/// <summary>
/// <para>表示 [POST] /card/code/update 接口的请求。</para>
/// </summary>
public class CardCodeUpdateRequest : WechatApiRequest
{
/// <summary>
/// 获取或设置卡券模板编号。
/// </summary>
[Newtonsoft.Json.JsonProperty("card_id")]
[System.Text.Json.Serialization.JsonPropertyName("card_id")]
public string? CardId { get; set; }
/// <summary>
/// 获取或设置原卡券 Code。
/// </summary>
[Newtonsoft.Json.JsonProperty("code")]
[System.Text.Json.Serialization.JsonPropertyName("code")]
public string OldCardCode { get; set; } = string.Empty;
/// <summary>
/// 获取或设置新卡券 Code。
/// </summary>
[Newtonsoft.Json.JsonProperty("new_code")]
[System.Text.Json.Serialization.JsonPropertyName("new_code")]
public string NewCardCode { get; set; } = string.Empty;
}
}
| 31.933333 | 69 | 0.588727 | [
"MIT"
] | ZUOXIANGE/DotNetCore.SKIT.FlurlHttpClient.Wechat | src/SKIT.FlurlHttpClient.Wechat.Api/Models/Card/Code/CardCodeUpdateRequest.cs | 1,036 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace General.Librerias.EntidadesNegocio
{
public class beCaptcha
{
public string Codigo { get; set; }
public byte[] Imagen { get; set; }
}
}
| 19.466667 | 44 | 0.691781 | [
"MIT"
] | ecruzado/pcu | General.Librerias.EntidadesNegocio/beCaptcha.cs | 294 | C# |
using System.Collections.Generic;
using Chinook.Domain.Converters;
using Chinook.Domain.Entities;
namespace Chinook.Domain.ApiModels
{
public class AlbumApiModel : BaseApiModel, IConvertModel<Album>
{
public string Title { get; set; }
public int ArtistId { get; set; }
public string ArtistName { get; set; }
public ArtistApiModel Artist { get; set; }
public IList<TrackApiModel> Tracks { get; set; }
public Album Convert() =>
new()
{
Id = Id,
ArtistId = ArtistId,
Title = Title ?? string.Empty
};
}
} | 25.96 | 67 | 0.57319 | [
"MIT"
] | cwoodruff/Chinook5WebAPI | Chinook/Chinook.Domain/ApiModels/AlbumApiModel.cs | 651 | 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("Task1")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Home")]
[assembly: AssemblyProduct("Task1")]
[assembly: AssemblyCopyright("Copyright © Home 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("59650d7f-90a3-4a90-9165-fecc5de6a72d")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.594595 | 84 | 0.744069 | [
"MIT"
] | DimitarDKirov/Data-Bases | 10. ADO.NET/Homework/HomeworkADONET - Solution/Task1/Properties/AssemblyInfo.cs | 1,394 | C# |
namespace IDEIMusic.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class somechanges : DbMigration
{
public override void Up()
{
}
public override void Down()
{
}
}
}
| 16.529412 | 50 | 0.540925 | [
"MIT"
] | Thaenor/ARQSI_TP2 | IDEIMusic/IDEIMusic/Migrations/201412041858339_somechanges.cs | 281 | C# |
using System;
using Tweetinvi.Models;
namespace Tweetinvi.Events
{
public enum UserBlockedRaisedInResultOf
{
/// <summary>
/// This case should not happen and is here in case Twitter changes when they trigger the Blocked event.
/// If you happen to receive this mode, please report to Tweetinvi your case ideally with the associated json.
/// </summary>
Unknown = 0,
/// <summary>
/// The account user has blocked another user
/// </summary>
AccountUserBlockingAnotherUser,
}
/// <summary>
/// Event information when a user is blocked.
/// </summary>
public class UserBlockedEvent : BaseAccountActivityEventArgs<UserBlockedRaisedInResultOf>
{
public UserBlockedEvent(AccountActivityEvent<Tuple<IUser, IUser>> eventInfo) : base(eventInfo)
{
BlockedBy = eventInfo.Args.Item1;
BlockedUser = eventInfo.Args.Item2;
InResultOf = GetInResultOf();
}
/// <summary>
/// The user who got blocked
/// </summary>
public IUser BlockedUser { get; }
/// <summary>
/// The user who blocked
/// </summary>
public IUser BlockedBy { get; }
private UserBlockedRaisedInResultOf GetInResultOf()
{
if (BlockedBy.Id == AccountUserId)
{
return UserBlockedRaisedInResultOf.AccountUserBlockingAnotherUser;
}
return UserBlockedRaisedInResultOf.Unknown;
}
}
}
| 28.87037 | 118 | 0.602309 | [
"MIT"
] | IEvangelist/tweetinvi | src/Tweetinvi.Core/Public/Events/AccountActivity/UserBlockedEvent.cs | 1,561 | C# |
using Helpers;
using System;
using System.Windows.Forms;
using System.Linq;
using TaleWorlds.Core;
using TaleWorlds.CampaignSystem;
using TaleWorlds.CampaignSystem.SandBox.GameComponents;
namespace BannerlordTweaks
{
public class TweakedPregnancyModel : DefaultPregnancyModel
{
public override float StillbirthProbability => Settings.Instance.NoStillbirthsTweakEnabled
? -1
: base.StillbirthProbability;
public override float MaternalMortalityProbabilityInLabor => Settings.Instance.NoMaternalMortalityTweakEnabled
? -1
: base.MaternalMortalityProbabilityInLabor;
public override float DeliveringTwinsProbability => Settings.Instance.TwinsProbabilityTweakEnabled
? Settings.Instance.TwinsProbability
: base.DeliveringTwinsProbability;
public override float DeliveringFemaleOffspringProbability => Settings.Instance.FemaleOffspringProbabilityTweakEnabled
? Settings.Instance.FemaleOffspringProbability
: base.DeliveringFemaleOffspringProbability;
public override float PregnancyDurationInDays => Settings.Instance.PregnancyDurationTweakEnabled
? Settings.Instance.PregnancyDuration
: base.PregnancyDurationInDays;
public override float CharacterFertilityProbability => Settings.Instance.CharacterFertilityProbabilityTweakEnabled
? Settings.Instance.CharacterFertilityProbability
: base.CharacterFertilityProbability;
public override float GetDailyChanceOfPregnancyForHero(Hero hero)
{
try
{
// Changed to message rather than exception.
// if (hero == null) throw new ArgumentNullException(nameof(hero));
if (hero == null)
{
InformationManager.DisplayMessage(new InformationMessage($"An error occurred during GetDailyChanceOfPregnancyForHero. (No hero)"));
// Debug
// InformationManager.DisplayMessage(new InformationMessage("Hero is:" + hero.Name + "\nSpouse is:" + hero.Spouse.Name + "\nSpouse's Spouse is:" + hero.Spouse.Spouse.Name));
return 0;
}
if (!Settings.Instance.DailyChancePregnancyTweakEnabled)
return base.GetDailyChanceOfPregnancyForHero(hero);
float num = 0.0f;
if (!Settings.Instance.PlayerCharacterFertileEnabled && HeroIsMainOrSpouseOfMain(hero))
{
return num;
}
if (Settings.Instance.MaxChildrenTweakEnabled && hero.Children != null && hero.Children.Any() && hero.Children.Count >= Settings.Instance.MaxChildren)
{
return num;
}
if (hero.Spouse != null && hero.IsFertile && IsHeroAgeSuitableForPregnancy(hero))
{
ExplainedNumber bonuses = new ExplainedNumber(1f, null);
PerkHelper.AddPerkBonusForCharacter(DefaultPerks.Medicine.PerfectHealth, hero.Clan.Leader.CharacterObject, false, ref bonuses);
num = (float)((6.5 - ((double)hero.Age - Settings.Instance.MinPregnancyAge) * 0.23) * 0.02) * bonuses.ResultNumber;
}
if (hero.Children == null || !hero.Children.Any())
num *= 3f;
else if (hero.Children.Count > 1)
num *= 2f;
return num;
}
catch (Exception ex)
{
MessageBox.Show($"An error occurred during GetDailyChanceOfPregnancyForHero. Reverting to original behavior... \n\nException:\n{ex.Message}\n\n{ex.InnerException?.Message}\n\n{ex.InnerException?.Message}");
return 0;
}
}
private bool IsHeroAgeSuitableForPregnancy(Hero hero)
{
if (!hero.IsFemale)
return true;
return (double)hero.Age >= Settings.Instance.MinPregnancyAge && (double)hero.Age <= Settings.Instance.MaxPregnancyAge;
}
private bool HeroIsMainOrSpouseOfMain(Hero hero)
{
if (hero == Hero.MainHero)
return true;
if (hero.Spouse == Hero.MainHero)
return true;
return false;
}
}
}
| 41.28972 | 222 | 0.616342 | [
"MIT"
] | cnedwin/Bannerlord.BannerlordTweaks | TweakedPregnancyModel.cs | 4,420 | C# |
// Fill out your copyright notice in the Description page of Project Settings.
using UnrealBuildTool;
using System.Collections.Generic;
public class TempleRunnerEditorTarget : TargetRules
{
public TempleRunnerEditorTarget(TargetInfo Target) : base(Target)
{
Type = TargetType.Editor;
ExtraModuleNames.AddRange( new string[] { "TempleRunner" } );
}
}
| 24 | 78 | 0.775 | [
"MIT"
] | Domekabc/Polygon-lato2019-projekt | TempleRunner/Source/TempleRunnerEditor.Target.cs | 360 | C# |
// dnlib: See LICENSE.txt for more info
using System;
using System.Collections.Generic;
using System.IO;
using dnlib.IO;
using dnlib.DotNet.Pdb;
using dnlib.PE;
using dnlib.W32Resources;
using dnlib.DotNet.MD;
using System.Diagnostics;
namespace dnlib.DotNet.Writer {
/// <summary>
/// Common module writer options base class
/// </summary>
public class ModuleWriterOptionsBase {
IModuleWriterListener listener;
PEHeadersOptions peHeadersOptions;
Cor20HeaderOptions cor20HeaderOptions;
MetaDataOptions metaDataOptions;
ILogger logger;
ILogger metaDataLogger;
Win32Resources win32Resources;
StrongNameKey strongNameKey;
StrongNamePublicKey strongNamePublicKey;
bool delaySign;
/// <summary>
/// Gets/sets the listener
/// </summary>
public IModuleWriterListener Listener {
get { return listener; }
set { listener = value; }
}
/// <summary>
/// Gets/sets the logger. If this is <c>null</c>, any errors result in a
/// <see cref="ModuleWriterException"/> being thrown. To disable this behavior, either
/// create your own logger or use <see cref="DummyLogger.NoThrowInstance"/>.
/// </summary>
public ILogger Logger {
get { return logger; }
set { logger = value; }
}
/// <summary>
/// Gets/sets the <see cref="MetaData"/> writer logger. If this is <c>null</c>, use
/// <see cref="Logger"/>.
/// </summary>
public ILogger MetaDataLogger {
get { return metaDataLogger; }
set { metaDataLogger = value; }
}
/// <summary>
/// Gets/sets the <see cref="PEHeaders"/> options. This is never <c>null</c>.
/// </summary>
public PEHeadersOptions PEHeadersOptions {
get { return peHeadersOptions ?? (peHeadersOptions = new PEHeadersOptions()); }
set { peHeadersOptions = value; }
}
/// <summary>
/// Gets/sets the <see cref="ImageCor20Header"/> options. This is never <c>null</c>.
/// </summary>
public Cor20HeaderOptions Cor20HeaderOptions {
get { return cor20HeaderOptions ?? (cor20HeaderOptions = new Cor20HeaderOptions()); }
set { cor20HeaderOptions = value; }
}
/// <summary>
/// Gets/sets the <see cref="MetaData"/> options. This is never <c>null</c>.
/// </summary>
public MetaDataOptions MetaDataOptions {
get { return metaDataOptions ?? (metaDataOptions = new MetaDataOptions()); }
set { metaDataOptions = value; }
}
/// <summary>
/// Gets/sets the Win32 resources. If this is <c>null</c>, use the module's
/// Win32 resources if any.
/// </summary>
public Win32Resources Win32Resources {
get { return win32Resources; }
set { win32Resources = value; }
}
/// <summary>
/// true to delay sign the assembly. Initialize <see cref="StrongNamePublicKey"/> to the
/// public key to use, and don't initialize <see cref="StrongNameKey"/>. To generate the
/// public key from your strong name key file, execute <c>sn -p mykey.snk mypublickey.snk</c>
/// </summary>
public bool DelaySign {
get { return delaySign; }
set { delaySign = value; }
}
/// <summary>
/// Gets/sets the strong name key. When you enhance strong name sign an assembly,
/// this instance's HashAlgorithm must be initialized to its public key's HashAlgorithm.
/// You should call <see cref="InitializeStrongNameSigning(ModuleDef,StrongNameKey)"/>
/// to initialize this property if you use normal strong name signing.
/// You should call <see cref="InitializeEnhancedStrongNameSigning(ModuleDef,StrongNameKey,StrongNamePublicKey)"/>
/// or <see cref="InitializeEnhancedStrongNameSigning(ModuleDef,StrongNameKey,StrongNamePublicKey,StrongNameKey,StrongNamePublicKey)"/>
/// to initialize this property if you use enhanced strong name signing.
/// </summary>
public StrongNameKey StrongNameKey {
get { return strongNameKey; }
set { strongNameKey = value; }
}
/// <summary>
/// Gets/sets the new public key that should be used. If this is <c>null</c>, use
/// the public key generated from <see cref="StrongNameKey"/>. If it is also <c>null</c>,
/// use the module's Assembly's public key.
/// You should call <see cref="InitializeEnhancedStrongNameSigning(ModuleDef,StrongNameKey,StrongNamePublicKey)"/>
/// or <see cref="InitializeEnhancedStrongNameSigning(ModuleDef,StrongNameKey,StrongNamePublicKey,StrongNameKey,StrongNamePublicKey)"/>
/// to initialize this property if you use enhanced strong name signing.
/// </summary>
public StrongNamePublicKey StrongNamePublicKey {
get { return strongNamePublicKey; }
set { strongNamePublicKey = value; }
}
/// <summary>
/// <c>true</c> if method bodies can be shared (two or more method bodies can share the
/// same RVA), <c>false</c> if method bodies can't be shared. Don't enable it if there
/// must be a 1:1 relationship with method bodies and their RVAs.
/// </summary>
public bool ShareMethodBodies { get; set; }
/// <summary>
/// <c>true</c> if the PE header CheckSum field should be updated, <c>false</c> if the
/// CheckSum field isn't updated.
/// </summary>
public bool AddCheckSum { get; set; }
/// <summary>
/// <c>true</c> if it's a 64-bit module, <c>false</c> if it's a 32-bit or AnyCPU module.
/// </summary>
public bool Is64Bit {
get {
if (!PEHeadersOptions.Machine.HasValue)
return false;
return PEHeadersOptions.Machine == Machine.IA64 ||
PEHeadersOptions.Machine == Machine.AMD64 ||
PEHeadersOptions.Machine == Machine.ARM64;
}
}
/// <summary>
/// Gets/sets the module kind
/// </summary>
public ModuleKind ModuleKind { get; set; }
/// <summary>
/// <c>true</c> if it should be written as an EXE file, <c>false</c> if it should be
/// written as a DLL file.
/// </summary>
public bool IsExeFile {
get {
return ModuleKind != ModuleKind.Dll &&
ModuleKind != ModuleKind.NetModule;
}
}
/// <summary>
/// Set it to <c>true</c> to enable writing a PDB file. Default is <c>false</c> (a PDB file
/// won't be written to disk).
/// </summary>
public bool WritePdb { get; set; }
/// <summary>
/// PDB file name. If it's <c>null</c> a PDB file with the same name as the output assembly
/// will be created but with a PDB extension. <see cref="WritePdb"/> must be <c>true</c> or
/// this property is ignored.
/// </summary>
public string PdbFileName { get; set; }
/// <summary>
/// PDB stream. If this is initialized, then you should also set <see cref="PdbFileName"/>
/// to the name of the PDB file since the file name must be written to the PE debug directory.
/// <see cref="WritePdb"/> must be <c>true</c> or this property is ignored.
/// </summary>
public Stream PdbStream { get; set; }
/// <summary>
/// If <see cref="PdbFileName"/> or <see cref="PdbStream"/> aren't enough, this can be used
/// to create a new <see cref="ISymbolWriter2"/> instance. <see cref="WritePdb"/> must be
/// <c>true</c> or this property is ignored.
/// </summary>
public CreatePdbSymbolWriterDelegate CreatePdbSymbolWriter { get; set; }
/// <summary>
/// Default constructor
/// </summary>
protected ModuleWriterOptionsBase() {
ShareMethodBodies = true;
ModuleKind = ModuleKind.Windows;
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="module">The module</param>
protected ModuleWriterOptionsBase(ModuleDef module)
: this(module, null) {
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="module">The module</param>
/// <param name="listener">Module writer listener</param>
protected ModuleWriterOptionsBase(ModuleDef module, IModuleWriterListener listener) {
this.listener = listener;
ShareMethodBodies = true;
MetaDataOptions.MetaDataHeaderOptions.VersionString = module.RuntimeVersion;
ModuleKind = module.Kind;
PEHeadersOptions.Machine = module.Machine;
PEHeadersOptions.Characteristics = module.Characteristics;
PEHeadersOptions.DllCharacteristics = module.DllCharacteristics;
if (module.Kind == ModuleKind.Windows)
PEHeadersOptions.Subsystem = Subsystem.WindowsGui;
else
PEHeadersOptions.Subsystem = Subsystem.WindowsCui;
PEHeadersOptions.NumberOfRvaAndSizes = 0x10;
Cor20HeaderOptions.Flags = module.Cor20HeaderFlags;
if (module.Assembly != null && !PublicKeyBase.IsNullOrEmpty2(module.Assembly.PublicKey))
Cor20HeaderOptions.Flags |= ComImageFlags.StrongNameSigned;
if (module.Cor20HeaderRuntimeVersion != null) {
Cor20HeaderOptions.MajorRuntimeVersion = (ushort)(module.Cor20HeaderRuntimeVersion.Value >> 16);
Cor20HeaderOptions.MinorRuntimeVersion = (ushort)module.Cor20HeaderRuntimeVersion.Value;
}
else if (module.IsClr1x) {
Cor20HeaderOptions.MajorRuntimeVersion = 2;
Cor20HeaderOptions.MinorRuntimeVersion = 0;
}
else {
Cor20HeaderOptions.MajorRuntimeVersion = 2;
Cor20HeaderOptions.MinorRuntimeVersion = 5;
}
if (module.TablesHeaderVersion != null) {
MetaDataOptions.TablesHeapOptions.MajorVersion = (byte)(module.TablesHeaderVersion.Value >> 8);
MetaDataOptions.TablesHeapOptions.MinorVersion = (byte)module.TablesHeaderVersion.Value;
}
else if (module.IsClr1x) {
// Generics aren't supported
MetaDataOptions.TablesHeapOptions.MajorVersion = 1;
MetaDataOptions.TablesHeapOptions.MinorVersion = 0;
}
else {
// Generics are supported
MetaDataOptions.TablesHeapOptions.MajorVersion = 2;
MetaDataOptions.TablesHeapOptions.MinorVersion = 0;
}
// Some tools crash if #GUID is missing so always create it by default
MetaDataOptions.Flags |= MetaDataFlags.AlwaysCreateGuidHeap;
var modDefMD = module as ModuleDefMD;
if (modDefMD != null) {
var ntHeaders = modDefMD.MetaData.PEImage.ImageNTHeaders;
PEHeadersOptions.TimeDateStamp = ntHeaders.FileHeader.TimeDateStamp;
PEHeadersOptions.MajorLinkerVersion = ntHeaders.OptionalHeader.MajorLinkerVersion;
PEHeadersOptions.MinorLinkerVersion = ntHeaders.OptionalHeader.MinorLinkerVersion;
PEHeadersOptions.ImageBase = ntHeaders.OptionalHeader.ImageBase;
AddCheckSum = ntHeaders.OptionalHeader.CheckSum != 0;
}
if (Is64Bit) {
PEHeadersOptions.Characteristics &= ~Characteristics._32BitMachine;
PEHeadersOptions.Characteristics |= Characteristics.LargeAddressAware;
}
else
PEHeadersOptions.Characteristics |= Characteristics._32BitMachine;
}
/// <summary>
/// Initializes <see cref="StrongNameKey"/> and <see cref="StrongNamePublicKey"/>
/// for normal strong name signing.
/// </summary>
/// <param name="module">Module</param>
/// <param name="signatureKey">Signature strong name key pair</param>
public void InitializeStrongNameSigning(ModuleDef module, StrongNameKey signatureKey) {
StrongNameKey = signatureKey;
StrongNamePublicKey = null;
if (module.Assembly != null)
module.Assembly.CustomAttributes.RemoveAll("System.Reflection.AssemblySignatureKeyAttribute");
}
/// <summary>
/// Initializes <see cref="StrongNameKey"/> and <see cref="StrongNamePublicKey"/>
/// for enhanced strong name signing (without key migration). See
/// http://msdn.microsoft.com/en-us/library/hh415055.aspx
/// </summary>
/// <param name="module">Module</param>
/// <param name="signatureKey">Signature strong name key pair</param>
/// <param name="signaturePubKey">Signature public key</param>
public void InitializeEnhancedStrongNameSigning(ModuleDef module, StrongNameKey signatureKey, StrongNamePublicKey signaturePubKey) {
InitializeStrongNameSigning(module, signatureKey);
StrongNameKey.HashAlgorithm = signaturePubKey.HashAlgorithm;
}
/// <summary>
/// Initializes <see cref="StrongNameKey"/> and <see cref="StrongNamePublicKey"/>
/// for enhanced strong name signing (with key migration). See
/// http://msdn.microsoft.com/en-us/library/hh415055.aspx
/// </summary>
/// <param name="module">Module</param>
/// <param name="signatureKey">Signature strong name key pair</param>
/// <param name="signaturePubKey">Signature public key</param>
/// <param name="identityKey">Identity strong name key pair</param>
/// <param name="identityPubKey">Identity public key</param>
public void InitializeEnhancedStrongNameSigning(ModuleDef module, StrongNameKey signatureKey, StrongNamePublicKey signaturePubKey, StrongNameKey identityKey, StrongNamePublicKey identityPubKey) {
StrongNameKey = signatureKey;
StrongNameKey.HashAlgorithm = signaturePubKey.HashAlgorithm;
StrongNamePublicKey = identityPubKey;
if (module.Assembly != null)
module.Assembly.UpdateOrCreateAssemblySignatureKeyAttribute(identityPubKey, identityKey, signaturePubKey);
}
}
/// <summary>
/// Creates a new <see cref="ISymbolWriter2"/> instance
/// </summary>
/// <param name="writer">Module writer</param>
/// <returns>A new <see cref="ISymbolWriter2"/> instance</returns>
public delegate ISymbolWriter2 CreatePdbSymbolWriterDelegate(ModuleWriterBase writer);
/// <summary>
/// Module writer base class
/// </summary>
public abstract class ModuleWriterBase : IMetaDataListener, ILogger {
/// <summary>Default alignment of all constants</summary>
protected internal const uint DEFAULT_CONSTANTS_ALIGNMENT = 8;
/// <summary>Default alignment of all method bodies</summary>
protected const uint DEFAULT_METHODBODIES_ALIGNMENT = 4;
/// <summary>Default alignment of all .NET resources</summary>
protected const uint DEFAULT_NETRESOURCES_ALIGNMENT = 8;
/// <summary>Default alignment of the .NET metadata</summary>
protected const uint DEFAULT_METADATA_ALIGNMENT = 4;
/// <summary>Default Win32 resources alignment</summary>
protected internal const uint DEFAULT_WIN32_RESOURCES_ALIGNMENT = 8;
/// <summary>Default strong name signature alignment</summary>
protected const uint DEFAULT_STRONGNAMESIG_ALIGNMENT = 16;
/// <summary>Default COR20 header alignment</summary>
protected const uint DEFAULT_COR20HEADER_ALIGNMENT = 4;
/// <summary>Default debug directory alignment</summary>
protected const uint DEFAULT_DEBUGDIRECTORY_ALIGNMENT = 4;
/// <summary>See <see cref="DestinationStream"/></summary>
protected Stream destStream;
/// <summary>See <see cref="Constants"/></summary>
protected UniqueChunkList<ByteArrayChunk> constants;
/// <summary>See <see cref="MethodBodies"/></summary>
protected MethodBodyChunks methodBodies;
/// <summary>See <see cref="NetResources"/></summary>
protected NetResources netResources;
/// <summary>See <see cref="MetaData"/></summary>
protected MetaData metaData;
/// <summary>See <see cref="Win32Resources"/></summary>
protected Win32ResourcesChunk win32Resources;
/// <summary>Offset where the module is written. Usually 0.</summary>
protected long destStreamBaseOffset;
IModuleWriterListener listener;
/// <summary>Debug directory</summary>
protected DebugDirectory debugDirectory;
string createdPdbFileName;
/// <summary>
/// Strong name signature
/// </summary>
protected StrongNameSignature strongNameSignature;
/// <summary>
/// Returns the module writer options
/// </summary>
public abstract ModuleWriterOptionsBase TheOptions { get; }
/// <summary>
/// Gets/sets the module writer listener
/// </summary>
protected IModuleWriterListener Listener {
get { return listener ?? DummyModuleWriterListener.Instance; }
set { listener = value; }
}
/// <summary>
/// Gets the destination stream
/// </summary>
public Stream DestinationStream {
get { return destStream; }
}
/// <summary>
/// Gets the constants
/// </summary>
public UniqueChunkList<ByteArrayChunk> Constants {
get { return constants; }
}
/// <summary>
/// Gets the method bodies
/// </summary>
public MethodBodyChunks MethodBodies {
get { return methodBodies; }
}
/// <summary>
/// Gets the .NET resources
/// </summary>
public NetResources NetResources {
get { return netResources; }
}
/// <summary>
/// Gets the .NET metadata
/// </summary>
public MetaData MetaData {
get { return metaData; }
}
/// <summary>
/// Gets the Win32 resources or <c>null</c> if there's none
/// </summary>
public Win32ResourcesChunk Win32Resources {
get { return win32Resources; }
}
/// <summary>
/// Gets the strong name signature or <c>null</c> if there's none
/// </summary>
public StrongNameSignature StrongNameSignature {
get { return strongNameSignature; }
}
/// <summary>
/// Gets all <see cref="PESection"/>s
/// </summary>
public abstract List<PESection> Sections { get; }
/// <summary>
/// Gets the <c>.text</c> section
/// </summary>
public abstract PESection TextSection { get; }
/// <summary>
/// Gets the <c>.rsrc</c> section or <c>null</c> if there's none
/// </summary>
public abstract PESection RsrcSection { get; }
/// <summary>
/// Gets the debug directory or <c>null</c> if there's none
/// </summary>
public DebugDirectory DebugDirectory {
get { return debugDirectory; }
}
/// <summary>
/// <c>true</c> if <c>this</c> is a <see cref="NativeModuleWriter"/>, <c>false</c> if
/// <c>this</c> is a <see cref="ModuleWriter"/>.
/// </summary>
public bool IsNativeWriter {
get { return this is NativeModuleWriter; }
}
/// <summary>
/// Writes the module to a file
/// </summary>
/// <param name="fileName">File name. The file will be truncated if it exists.</param>
public void Write(string fileName) {
using (var dest = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite)) {
dest.SetLength(0);
try {
Write(dest);
}
catch {
// Writing failed. Delete the file since it's useless.
dest.Close();
DeleteFileNoThrow(fileName);
throw;
}
}
}
static void DeleteFileNoThrow(string fileName) {
if (string.IsNullOrEmpty(fileName))
return;
try {
File.Delete(fileName);
}
catch {
}
}
/// <summary>
/// Writes the module to a <see cref="Stream"/>
/// </summary>
/// <param name="dest">Destination stream</param>
public void Write(Stream dest) {
if (TheOptions.DelaySign) {
Debug.Assert(TheOptions.StrongNamePublicKey != null, "Options.StrongNamePublicKey must be initialized when delay signing the assembly");
Debug.Assert(TheOptions.StrongNameKey == null, "Options.StrongNameKey must be null when delay signing the assembly");
TheOptions.Cor20HeaderOptions.Flags &= ~ComImageFlags.StrongNameSigned;
}
else if (TheOptions.StrongNameKey != null || TheOptions.StrongNamePublicKey != null)
TheOptions.Cor20HeaderOptions.Flags |= ComImageFlags.StrongNameSigned;
Listener = TheOptions.Listener ?? DummyModuleWriterListener.Instance;
destStream = dest;
destStreamBaseOffset = destStream.Position;
Listener.OnWriterEvent(this, ModuleWriterEvent.Begin);
var imageLength = WriteImpl();
destStream.Position = destStreamBaseOffset + imageLength;
Listener.OnWriterEvent(this, ModuleWriterEvent.End);
}
/// <summary>
/// Returns the module that is written
/// </summary>
public abstract ModuleDef Module { get; }
/// <summary>
/// Writes the module to <see cref="destStream"/>. <see cref="Listener"/> and
/// <see cref="destStream"/> have been initialized when this method is called.
/// </summary>
/// <returns>Number of bytes written</returns>
protected abstract long WriteImpl();
/// <summary>
/// Creates the strong name signature if the module has one of the strong name flags
/// set or wants to sign the assembly.
/// </summary>
protected void CreateStrongNameSignature() {
if (TheOptions.DelaySign && TheOptions.StrongNamePublicKey != null) {
int len = TheOptions.StrongNamePublicKey.CreatePublicKey().Length - 0x20;
strongNameSignature = new StrongNameSignature(len > 0 ? len : 0x80);
}
else if (TheOptions.StrongNameKey != null)
strongNameSignature = new StrongNameSignature(TheOptions.StrongNameKey.SignatureSize);
else if (Module.Assembly != null && !PublicKeyBase.IsNullOrEmpty2(Module.Assembly.PublicKey)) {
int len = Module.Assembly.PublicKey.Data.Length - 0x20;
strongNameSignature = new StrongNameSignature(len > 0 ? len : 0x80);
}
else if (((TheOptions.Cor20HeaderOptions.Flags ?? Module.Cor20HeaderFlags) & ComImageFlags.StrongNameSigned) != 0)
strongNameSignature = new StrongNameSignature(0x80);
}
/// <summary>
/// Creates the .NET metadata chunks (constants, method bodies, .NET resources,
/// the metadata, and Win32 resources)
/// </summary>
/// <param name="module"></param>
protected void CreateMetaDataChunks(ModuleDef module) {
constants = new UniqueChunkList<ByteArrayChunk>();
methodBodies = new MethodBodyChunks(TheOptions.ShareMethodBodies);
netResources = new NetResources(DEFAULT_NETRESOURCES_ALIGNMENT);
metaData = MetaData.Create(module, constants, methodBodies, netResources, TheOptions.MetaDataOptions);
metaData.Logger = TheOptions.MetaDataLogger ?? this;
metaData.Listener = this;
// StrongNamePublicKey is used if the user wants to override the assembly's
// public key or when enhanced strong naming the assembly.
var pk = TheOptions.StrongNamePublicKey;
if (pk != null)
metaData.AssemblyPublicKey = pk.CreatePublicKey();
else if (TheOptions.StrongNameKey != null)
metaData.AssemblyPublicKey = TheOptions.StrongNameKey.PublicKey;
var w32Resources = GetWin32Resources();
if (w32Resources != null)
win32Resources = new Win32ResourcesChunk(w32Resources);
}
/// <summary>
/// Gets the Win32 resources that should be written to the new image or <c>null</c> if none
/// </summary>
protected abstract Win32Resources GetWin32Resources();
/// <summary>
/// Calculates <see cref="RVA"/> and <see cref="FileOffset"/> of all <see cref="IChunk"/>s
/// </summary>
/// <param name="chunks">All chunks</param>
/// <param name="offset">Starting file offset</param>
/// <param name="rva">Starting RVA</param>
/// <param name="fileAlignment">File alignment</param>
/// <param name="sectionAlignment">Section alignment</param>
protected void CalculateRvasAndFileOffsets(List<IChunk> chunks, FileOffset offset, RVA rva, uint fileAlignment, uint sectionAlignment) {
foreach (var chunk in chunks) {
chunk.SetOffset(offset, rva);
offset += chunk.GetFileLength();
rva += chunk.GetVirtualSize();
offset = offset.AlignUp(fileAlignment);
rva = rva.AlignUp(sectionAlignment);
}
}
/// <summary>
/// Writes all chunks to <paramref name="writer"/>
/// </summary>
/// <param name="writer">The writer</param>
/// <param name="chunks">All chunks</param>
/// <param name="offset">File offset of first chunk</param>
/// <param name="fileAlignment">File alignment</param>
protected void WriteChunks(BinaryWriter writer, List<IChunk> chunks, FileOffset offset, uint fileAlignment) {
foreach (var chunk in chunks) {
chunk.VerifyWriteTo(writer);
offset += chunk.GetFileLength();
var newOffset = offset.AlignUp(fileAlignment);
writer.WriteZeros((int)(newOffset - offset));
offset = newOffset;
}
}
/// <summary>
/// Strong name sign the assembly
/// </summary>
/// <param name="snSigOffset">Strong name signature offset</param>
protected void StrongNameSign(long snSigOffset) {
var snSigner = new StrongNameSigner(destStream, destStreamBaseOffset);
snSigner.WriteSignature(TheOptions.StrongNameKey, snSigOffset);
}
bool CanWritePdb() {
return TheOptions.WritePdb && Module.PdbState != null;
}
/// <summary>
/// Creates the debug directory if a PDB file should be written
/// </summary>
protected void CreateDebugDirectory() {
if (CanWritePdb())
debugDirectory = new DebugDirectory();
}
/// <summary>
/// Write the PDB file. The caller should send the PDB events before and after calling this
/// method.
/// </summary>
protected void WritePdbFile() {
if (!CanWritePdb())
return;
if (debugDirectory == null)
throw new InvalidOperationException("debugDirectory is null but WritePdb is true");
var pdbState = Module.PdbState;
if (pdbState == null) {
Error("TheOptions.WritePdb is true but module has no PdbState");
debugDirectory.DontWriteAnything = true;
return;
}
var symWriter = GetSymbolWriter2();
if (symWriter == null) {
Error("Could not create a PDB symbol writer. A Windows OS might be required.");
debugDirectory.DontWriteAnything = true;
return;
}
var pdbWriter = new PdbWriter(symWriter, pdbState, metaData);
try {
pdbWriter.Logger = TheOptions.Logger;
pdbWriter.Write();
debugDirectory.Data = pdbWriter.GetDebugInfo(out debugDirectory.debugDirData);
debugDirectory.TimeDateStamp = GetTimeDateStamp();
pdbWriter.Dispose();
}
catch {
pdbWriter.Dispose();
DeleteFileNoThrow(createdPdbFileName);
throw;
}
}
uint GetTimeDateStamp() {
var td = TheOptions.PEHeadersOptions.TimeDateStamp;
if (td.HasValue)
return (uint)td;
TheOptions.PEHeadersOptions.TimeDateStamp = PEHeadersOptions.CreateNewTimeDateStamp();
return (uint)TheOptions.PEHeadersOptions.TimeDateStamp;
}
ISymbolWriter2 GetSymbolWriter2() {
if (TheOptions.CreatePdbSymbolWriter != null) {
var writer = TheOptions.CreatePdbSymbolWriter(this);
if (writer != null)
return writer;
}
if (TheOptions.PdbStream != null) {
return SymbolWriterCreator.Create(TheOptions.PdbStream,
TheOptions.PdbFileName ??
GetStreamName(TheOptions.PdbStream) ??
GetDefaultPdbFileName());
}
if (!string.IsNullOrEmpty(TheOptions.PdbFileName)) {
createdPdbFileName = TheOptions.PdbFileName;
return SymbolWriterCreator.Create(createdPdbFileName);
}
createdPdbFileName = GetDefaultPdbFileName();
if (createdPdbFileName == null)
return null;
return SymbolWriterCreator.Create(createdPdbFileName);
}
static string GetStreamName(Stream stream) {
var fs = stream as FileStream;
return fs == null ? null : fs.Name;
}
string GetDefaultPdbFileName() {
var destFileName = GetStreamName(destStream);
if (string.IsNullOrEmpty(destFileName)) {
Error("TheOptions.WritePdb is true but it's not possible to guess the default PDB file name. Set PdbFileName to the name of the PDB file.");
return null;
}
return Path.ChangeExtension(destFileName, "pdb");
}
/// <inheritdoc/>
void IMetaDataListener.OnMetaDataEvent(MetaData metaData, MetaDataEvent evt) {
switch (evt) {
case MetaDataEvent.BeginCreateTables:
Listener.OnWriterEvent(this, ModuleWriterEvent.MDBeginCreateTables);
break;
case MetaDataEvent.AllocateTypeDefRids:
Listener.OnWriterEvent(this, ModuleWriterEvent.MDAllocateTypeDefRids);
break;
case MetaDataEvent.AllocateMemberDefRids:
Listener.OnWriterEvent(this, ModuleWriterEvent.MDAllocateMemberDefRids);
break;
case MetaDataEvent.AllocateMemberDefRids0:
Listener.OnWriterEvent(this, ModuleWriterEvent.MDAllocateMemberDefRids0);
break;
case MetaDataEvent.AllocateMemberDefRids1:
Listener.OnWriterEvent(this, ModuleWriterEvent.MDAllocateMemberDefRids1);
break;
case MetaDataEvent.AllocateMemberDefRids2:
Listener.OnWriterEvent(this, ModuleWriterEvent.MDAllocateMemberDefRids2);
break;
case MetaDataEvent.AllocateMemberDefRids3:
Listener.OnWriterEvent(this, ModuleWriterEvent.MDAllocateMemberDefRids3);
break;
case MetaDataEvent.AllocateMemberDefRids4:
Listener.OnWriterEvent(this, ModuleWriterEvent.MDAllocateMemberDefRids4);
break;
case MetaDataEvent.MemberDefRidsAllocated:
Listener.OnWriterEvent(this, ModuleWriterEvent.MDMemberDefRidsAllocated);
break;
case MetaDataEvent.InitializeTypeDefsAndMemberDefs0:
Listener.OnWriterEvent(this, ModuleWriterEvent.MDInitializeTypeDefsAndMemberDefs0);
break;
case MetaDataEvent.InitializeTypeDefsAndMemberDefs1:
Listener.OnWriterEvent(this, ModuleWriterEvent.MDInitializeTypeDefsAndMemberDefs1);
break;
case MetaDataEvent.InitializeTypeDefsAndMemberDefs2:
Listener.OnWriterEvent(this, ModuleWriterEvent.MDInitializeTypeDefsAndMemberDefs2);
break;
case MetaDataEvent.InitializeTypeDefsAndMemberDefs3:
Listener.OnWriterEvent(this, ModuleWriterEvent.MDInitializeTypeDefsAndMemberDefs3);
break;
case MetaDataEvent.InitializeTypeDefsAndMemberDefs4:
Listener.OnWriterEvent(this, ModuleWriterEvent.MDInitializeTypeDefsAndMemberDefs4);
break;
case MetaDataEvent.MemberDefsInitialized:
Listener.OnWriterEvent(this, ModuleWriterEvent.MDMemberDefsInitialized);
break;
case MetaDataEvent.BeforeSortTables:
Listener.OnWriterEvent(this, ModuleWriterEvent.MDBeforeSortTables);
break;
case MetaDataEvent.MostTablesSorted:
Listener.OnWriterEvent(this, ModuleWriterEvent.MDMostTablesSorted);
break;
case MetaDataEvent.WriteTypeDefAndMemberDefCustomAttributes0:
Listener.OnWriterEvent(this, ModuleWriterEvent.MDWriteTypeDefAndMemberDefCustomAttributes0);
break;
case MetaDataEvent.WriteTypeDefAndMemberDefCustomAttributes1:
Listener.OnWriterEvent(this, ModuleWriterEvent.MDWriteTypeDefAndMemberDefCustomAttributes1);
break;
case MetaDataEvent.WriteTypeDefAndMemberDefCustomAttributes2:
Listener.OnWriterEvent(this, ModuleWriterEvent.MDWriteTypeDefAndMemberDefCustomAttributes2);
break;
case MetaDataEvent.WriteTypeDefAndMemberDefCustomAttributes3:
Listener.OnWriterEvent(this, ModuleWriterEvent.MDWriteTypeDefAndMemberDefCustomAttributes3);
break;
case MetaDataEvent.WriteTypeDefAndMemberDefCustomAttributes4:
Listener.OnWriterEvent(this, ModuleWriterEvent.MDWriteTypeDefAndMemberDefCustomAttributes4);
break;
case MetaDataEvent.MemberDefCustomAttributesWritten:
Listener.OnWriterEvent(this, ModuleWriterEvent.MDMemberDefCustomAttributesWritten);
break;
case MetaDataEvent.BeginAddResources:
Listener.OnWriterEvent(this, ModuleWriterEvent.MDBeginAddResources);
break;
case MetaDataEvent.EndAddResources:
Listener.OnWriterEvent(this, ModuleWriterEvent.MDEndAddResources);
break;
case MetaDataEvent.BeginWriteMethodBodies:
Listener.OnWriterEvent(this, ModuleWriterEvent.MDBeginWriteMethodBodies);
break;
case MetaDataEvent.WriteMethodBodies0:
Listener.OnWriterEvent(this, ModuleWriterEvent.MDWriteMethodBodies0);
break;
case MetaDataEvent.WriteMethodBodies1:
Listener.OnWriterEvent(this, ModuleWriterEvent.MDWriteMethodBodies1);
break;
case MetaDataEvent.WriteMethodBodies2:
Listener.OnWriterEvent(this, ModuleWriterEvent.MDWriteMethodBodies2);
break;
case MetaDataEvent.WriteMethodBodies3:
Listener.OnWriterEvent(this, ModuleWriterEvent.MDWriteMethodBodies3);
break;
case MetaDataEvent.WriteMethodBodies4:
Listener.OnWriterEvent(this, ModuleWriterEvent.MDWriteMethodBodies4);
break;
case MetaDataEvent.WriteMethodBodies5:
Listener.OnWriterEvent(this, ModuleWriterEvent.MDWriteMethodBodies5);
break;
case MetaDataEvent.WriteMethodBodies6:
Listener.OnWriterEvent(this, ModuleWriterEvent.MDWriteMethodBodies6);
break;
case MetaDataEvent.WriteMethodBodies7:
Listener.OnWriterEvent(this, ModuleWriterEvent.MDWriteMethodBodies7);
break;
case MetaDataEvent.WriteMethodBodies8:
Listener.OnWriterEvent(this, ModuleWriterEvent.MDWriteMethodBodies8);
break;
case MetaDataEvent.WriteMethodBodies9:
Listener.OnWriterEvent(this, ModuleWriterEvent.MDWriteMethodBodies9);
break;
case MetaDataEvent.EndWriteMethodBodies:
Listener.OnWriterEvent(this, ModuleWriterEvent.MDEndWriteMethodBodies);
break;
case MetaDataEvent.OnAllTablesSorted:
Listener.OnWriterEvent(this, ModuleWriterEvent.MDOnAllTablesSorted);
break;
case MetaDataEvent.EndCreateTables:
Listener.OnWriterEvent(this, ModuleWriterEvent.MDEndCreateTables);
break;
default:
break;
}
}
ILogger GetLogger() {
return TheOptions.Logger ?? DummyLogger.ThrowModuleWriterExceptionOnErrorInstance;
}
/// <inheritdoc/>
void ILogger.Log(object sender, LoggerEvent loggerEvent, string format, params object[] args) {
GetLogger().Log(this, loggerEvent, format, args);
}
/// <inheritdoc/>
bool ILogger.IgnoresEvent(LoggerEvent loggerEvent) {
return GetLogger().IgnoresEvent(loggerEvent);
}
/// <summary>
/// Logs an error message
/// </summary>
/// <param name="format">Format</param>
/// <param name="args">Format args</param>
protected void Error(string format, params object[] args) {
GetLogger().Log(this, LoggerEvent.Error, format, args);
}
/// <summary>
/// Logs a warning message
/// </summary>
/// <param name="format">Format</param>
/// <param name="args">Format args</param>
protected void Warning(string format, params object[] args) {
GetLogger().Log(this, LoggerEvent.Warning, format, args);
}
}
}
| 35.534483 | 197 | 0.723435 | [
"MIT"
] | CodeShark-Dev/dnlib | src/DotNet/Writer/ModuleWriterBase.cs | 32,976 | C# |
namespace System
{
[H5.Convention(Member = H5.ConventionMember.Field | H5.ConventionMember.Method, Notation = H5.Notation.CamelCase)]
[H5.External]
[H5.Constructor("Number")]
[H5.Reflectable]
#pragma warning disable CS0659 // Type overrides Object.Equals(object o) but does not override Object.GetHashCode()
public struct Int16 : IComparable, IComparable<short>, IEquatable<short>, IFormattable
{
private extern Int16(int i);
[H5.InlineConst]
public const short MinValue = -32768;
[H5.InlineConst]
public const short MaxValue = 32767;
[H5.Template("System.Int16.parse({s})")]
public static extern short Parse(string s);
[H5.Template("System.Int16.parse({s}, {radix})")]
public static extern short Parse(string s, int radix);
[H5.Template("System.Int16.tryParse({s}, {result})")]
public static extern bool TryParse(string s, out short result);
[H5.Template("System.Int16.tryParse({s}, {result}, {radix})")]
public static extern bool TryParse(string s, out short result, int radix);
public extern string ToString(int radix);
[H5.Template("System.Int16.format({this}, {format})")]
public extern string Format(string format);
[H5.Template("System.Int16.format({this}, {format}, {provider})")]
public extern string Format(string format, IFormatProvider provider);
[H5.Template("System.Int16.format({this}, {format})")]
public extern string ToString(string format);
[H5.Template("System.Int16.format({this}, {format}, {provider})")]
public extern string ToString(string format, IFormatProvider provider);
[H5.Template("H5.compare({this}, {other})")]
public extern int CompareTo(short other);
[H5.Template("H5.compare({this}, {obj})")]
public extern int CompareTo(object obj);
[H5.Template("{this} === {other}")]
public extern bool Equals(short other);
[H5.Template("System.Int16.equals({this}, {other})")]
public override extern bool Equals(object other);
}
#pragma warning restore CS0659 // Type overrides Object.Equals(object o) but does not override Object.GetHashCode()
} | 39.508772 | 118 | 0.655861 | [
"Apache-2.0"
] | curiosity-ai/h5 | H5/H5/System/Int16.cs | 2,252 | C# |
namespace CreativeTim.Argon.DotNetCore.Free.Models.Cms
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
public partial class HostingModel : BaseModelEntity
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public HostingModel()
{
HistoryPurchaseHostings = new HashSet<HistoryPurchaseHostingModel>();
Purchases = new HashSet<PurchaseModel>();
}
[StringLength(1000)]
public string HostingIp { get; set; }
[StringLength(1000)]
public string HostingName { get; set; }
[StringLength(1000)]
public string LinkLogin { get; set; }
[StringLength(1000)]
public string UserName { get; set; }
[StringLength(1000)]
public string Password { get; set; }
[StringLength(1000)]
public string Vendor { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<HistoryPurchaseHostingModel> HistoryPurchaseHostings { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<PurchaseModel> Purchases { get; set; }
}
}
| 33.022222 | 128 | 0.687079 | [
"MIT"
] | ngocbauofficial/dependencycore | CreativeTim.Argon.DotNetCore.Free/Models/Cms/HostingModel.cs | 1,486 | C# |
using System;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Text;
using System.IO;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
using Cupscale.ImageUtils;
using Cupscale.IO;
using Cupscale.Main;
using Cupscale.OS;
using Cupscale.UI;
using Cyotek.Windows.Forms;
using HTAlt.WinForms;
using ImageMagick;
using Paths = Cupscale.IO.Paths;
namespace Cupscale.Forms
{
public partial class ModelComparisonForm : Form
{
public string currentSourcePath;
public bool cutoutMode;
public ModelComparisonForm()
{
InitializeComponent();
}
private void ModelComparisonForm_Load(object sender, EventArgs e)
{
UIHelpers.InitCombox(compositionMode, 0);
UIHelpers.InitCombox(comparisonMode, 0);
UIHelpers.InitCombox(scaleFactor, 2);
UIHelpers.InitCombox(cropMode, 0);
if (ModelComparisonTool.compositionModeComboxIndex >= 0)
compositionMode.SelectedIndex = ModelComparisonTool.compositionModeComboxIndex;
if (ModelComparisonTool.comparisonModeComboxIndex >= 0)
comparisonMode.SelectedIndex = ModelComparisonTool.comparisonModeComboxIndex;
if (ModelComparisonTool.scaleComboxIndex >= 0)
scaleFactor.SelectedIndex = ModelComparisonTool.scaleComboxIndex;
if (ModelComparisonTool.cropModeComboxIndex >= 0)
cropMode.SelectedIndex = ModelComparisonTool.cropModeComboxIndex;
if (!string.IsNullOrWhiteSpace(ModelComparisonTool.lastCompositionModels))
modelPathsBox.Text = ModelComparisonTool.lastCompositionModels;
}
private void addModelBtn_Click(object sender, EventArgs e)
{
using (var modelForm = new ModelSelectForm(null, 0))
{
if (modelForm.ShowDialog() == DialogResult.OK)
modelPathsBox.AppendText(modelForm.selectedModel + Environment.NewLine);
}
}
private async void runBtn_Click(object sender, EventArgs e)
{
if(PreviewUI.previewImg.Image == null || !File.Exists(Paths.tempImgPath))
{
Program.ShowMessage("No image loaded!", "Error");
return;
}
Enabled = false;
cutoutMode = cropMode.SelectedIndex == 1;
if (cutoutMode)
{
PreviewUI.SaveCurrentCutout();
currentSourcePath = Path.Combine(Paths.previewPath, "preview.png");
}
else
{
currentSourcePath = Paths.tempImgPath;
}
string[] lines = Regex.Split(modelPathsBox.Text, "\r\n|\r|\n");
if(comparisonMode.SelectedIndex == 0)
{
string outpath = Path.Combine(Paths.imgOutPath, "!Original.png");
await ImageProcessing.ConvertImage(currentSourcePath, GetSaveFormat(), false, ImageProcessing.ExtMode.UseNew, false, outpath);
await ProcessImage(outpath, "Original");
}
for (int i = 0; i < lines.Length; i++)
{
if (!File.Exists(lines[i]))
continue;
ModelData mdl = new ModelData(lines[i], null, ModelData.ModelMode.Single);
await DoUpscale(i, mdl, !cutoutMode);
}
bool vert = compositionMode.SelectedIndex == 1;
MagickImage merged = ImgUtils.MergeImages(Directory.GetFiles(Paths.imgOutPath, "*.png", SearchOption.AllDirectories), vert, true);
string mergedPath = Path.Combine(Paths.imgOutPath, Path.GetFileNameWithoutExtension(Program.lastImgPath) + "-composition");
mergedPath = Path.ChangeExtension(mergedPath, GetSaveExt());
merged.Write(mergedPath);
await Upscale.CopyImagesTo(Program.lastImgPath.GetParentDir());
IOUtils.ClearDir(Paths.previewPath);
Enabled = true;
Program.ShowMessage("Saved model composition to " + Program.lastImgPath.GetParentDir() + "\\" + Path.GetFileName(mergedPath), "Message");
}
static ImageProcessing.Format GetSaveFormat()
{
ImageProcessing.Format saveFormat = ImageProcessing.Format.PngFast;
if (Config.GetInt("previewFormat") == 1)
saveFormat = ImageProcessing.Format.Jpeg;
if (Config.GetInt("previewFormat") == 2)
saveFormat = ImageProcessing.Format.Weppy;
return saveFormat;
}
static string GetSaveExt ()
{
string ext = "png";
if (Config.GetInt("previewFormat") == 1)
ext = "jpg";
if (Config.GetInt("previewFormat") == 2)
ext = "webp";
return ext;
}
async Task DoUpscale (int index, ModelData mdl, bool fullImage)
{
if (PreviewUI.previewImg.Image == null)
{
Program.ShowMessage("Please load an image first!", "Error");
return;
}
Program.mainForm.SetBusy(true);
Upscale.currentMode = Upscale.UpscaleMode.Composition;
//await ImageProcessing.PreProcessImages(Paths.previewPath, !bool.Parse(Config.Get("alpha")));
//if (cutoutMode)
//currentSourcePath += ".png";
string outImg = null;
try
{
bool useNcnn = (Config.Get("cudaFallback").GetInt() == 2 || Config.Get("cudaFallback").GetInt() == 3);
bool useCpu = (Config.Get("cudaFallback").GetInt() == 1);
ESRGAN.Backend backend = ESRGAN.Backend.CUDA;
if (useCpu) backend = ESRGAN.Backend.CPU;
if (useNcnn) backend = ESRGAN.Backend.NCNN;
string inpath = Paths.previewPath;
if (fullImage) inpath = Paths.tempImgPath.GetParentDir();
await ESRGAN.DoUpscale(inpath, Paths.compositionOut, mdl, Config.Get("tilesize"), Config.GetBool("alpha"), ESRGAN.PreviewMode.None, backend);
if (backend == ESRGAN.Backend.NCNN)
outImg = Directory.GetFiles(Paths.compositionOut, "*.png*", SearchOption.AllDirectories)[0];
else
outImg = Directory.GetFiles(Paths.compositionOut, "*.tmp", SearchOption.AllDirectories)[0];
await Upscale.PostprocessingSingle(outImg, false);
await ProcessImage(PreviewUI.lastOutfile, mdl.model1Name);
IOUtils.TryCopy(PreviewUI.lastOutfile, Path.Combine(Paths.imgOutPath, $"{index}-{mdl.model1Name}.png"), true);
}
catch (Exception e)
{
if (e.StackTrace.Contains("Index"))
Program.ShowMessage("The upscale process seems to have exited before completion!", "Error");
Logger.ErrorMessage("An error occured during upscaling:", e);
Program.mainForm.SetProgress(0f, "Cancelled.");
}
Program.mainForm.SetProgress(0, "Done.");
Program.mainForm.SetBusy(false);
}
async Task ProcessImage (string path, string text)
{
int scale = scaleFactor.GetInt();
Image source = ImgUtils.GetImage(currentSourcePath);
int newWidth = source.Width * scale;
Logger.Log($"int newWidth ({newWidth}) = source.Width({source.Width}) * scale({scale});");
Upscale.Filter filter = Upscale.Filter.Bicubic;
if(Program.currentFilter == FilterType.Point)
filter = Upscale.Filter.NearestNeighbor;
Logger.Log("Scaling image for composition...");
await Task.Delay(1);
ImgSharpUtils.ResizeImageAdvanced(path, newWidth, Upscale.ScaleMode.PixelsWidth, filter, false);
AddText(path, text);
}
void AddText(string path, string text)
{
Logger.Log("Adding text: " + text);
int footerHeight = 45;
Image baseImg = ImgUtils.GetImage(path);
Logger.Log($"baseImg: {baseImg.Width}x{baseImg.Height}");
int heightWithFooter = baseImg.Height + footerHeight;
Bitmap img = new Bitmap(baseImg.Width, heightWithFooter);
Logger.Log($"img: {img.Width}x{img.Height}");
using (Graphics graphics = Graphics.FromImage(img))
{
graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
graphics.SmoothingMode = SmoothingMode.HighQuality;
graphics.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
graphics.CompositingQuality = CompositingQuality.HighQuality;
graphics.FillRectangle(new SolidBrush(Color.FromArgb(22, 22, 22)), 0, 0, baseImg.Width, heightWithFooter);
graphics.DrawImage(baseImg, 0, 0, baseImg.Width, baseImg.Height);
GraphicsPath p = new GraphicsPath();
int fontSize = 19;
SizeF s = new Size(999999999, 99999999);
Font font = new Font("Times New Roman", graphics.DpiY * fontSize / 72);
int cf = 0, lf = 0;
while (s.Width >= img.Width)
{
fontSize--;
font = new Font(FontFamily.GenericSansSerif, graphics.DpiY * fontSize / 72, FontStyle.Regular);
s = graphics.MeasureString(text, font, new SizeF(), new StringFormat(), out cf, out lf);
}
StringFormat stringFormat = new StringFormat();
//stringFormat.Alignment = StringAlignment.Center;
double a = graphics.DpiY * fontSize / 72;
//stringFormat.LineAlignment = StringAlignment.Center;
//Brush textBrush = Brushes.White;
//graphics.DrawString(text, font, textBrush, new Rectangle(0, img.Height, img.Width, footerHeight - 0), stringFormat);
graphics.DrawString(text, font, Brushes.White, new PointF(0, img.Height - footerHeight));
}
Logger.Log("Saving img with size " + img.Width + "x" + img.Height);
img.Save(path);
}
private void cancelBtn_Click(object sender, EventArgs e)
{
ModelComparisonTool.lastCompositionModels = modelPathsBox.Text;
Close();
}
private void ModelComparisonForm_FormClosing(object sender, FormClosingEventArgs e)
{
ModelComparisonTool.lastCompositionModels = modelPathsBox.Text;
ModelComparisonTool.comparisonModeComboxIndex = comparisonMode.SelectedIndex;
ModelComparisonTool.compositionModeComboxIndex = compositionMode.SelectedIndex;
ModelComparisonTool.scaleComboxIndex = scaleFactor.SelectedIndex;
ModelComparisonTool.cropModeComboxIndex = cropMode.SelectedIndex;
}
}
}
| 44.745968 | 157 | 0.599892 | [
"MIT"
] | yggdrasil75/cupscale | Code/Forms/ModelComparisonForm.cs | 11,099 | C# |
namespace Genbox.VelcroPhysics.Shared
{
public class GraphNode<T>
{
public GraphNode(T item = default)
{
Item = item;
}
/// <summary>The item.</summary>
public T Item { get; set; }
/// <summary>The next item in the list.</summary>
public GraphNode<T> Next { get; set; }
/// <summary>The previous item in the list.</summary>
public GraphNode<T> Prev { get; set; }
internal void Invalidate()
{
Next = null;
Prev = null;
}
public void Clear()
{
Item = default;
Invalidate();
}
}
} | 22.741935 | 62 | 0.462411 | [
"MIT"
] | D31m05z/VelcroPhysics | src/VelcroPhysics/Shared/GraphNode.cs | 677 | 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("Colosseum.iOS")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Colosseum.iOS")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("72bdc44f-c588-44f3-b6df-9aace7daafdd")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.810811 | 84 | 0.744103 | [
"Apache-2.0"
] | AsfendTheMVP/Colosseum | Colosseum/Colosseum/Colosseum.iOS/Properties/AssemblyInfo.cs | 1,402 | C# |
using MainArc.Ddomain;
using System;
using System.Collections.Generic;
using System.Text;
namespace MainArc.Application.ViewModel
{
public class CourseViewModel
{
public IEnumerable<Course> Courses { get; set; }
}
}
| 18.307692 | 56 | 0.722689 | [
"MIT"
] | anas-dev-92/MainArch | MainArc/MainArc.Application/ViewModel/CourseViewModel.cs | 240 | C# |
using System;
using System.Threading.Tasks;
using Telegram.Bot.Tests.Integ.Framework;
using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums;
namespace Telegram.Bot.Tests.Integ.Admin_Bot
{
public class ChatMemberAdministrationTestFixture
{
public Chat RegularMemberChat { get; }
public int RegularMemberUserId { get; }
public string RegularMemberUserName { get; }
public string GroupInviteLink { get; set; }
public ChatMemberAdministrationTestFixture(TestsFixture testsFixture)
{
string collectionName = Constants.TestCollections.ChatMemberAdministration;
RegularMemberChat = GetChat(testsFixture, collectionName).GetAwaiter().GetResult();
testsFixture.SendTestCollectionNotificationAsync(
collectionName,
$"Chosen regular member is @{RegularMemberChat.Username.Replace("_", @"\_")}"
).GetAwaiter().GetResult();
RegularMemberUserId = (int)RegularMemberChat.Id;
RegularMemberUserName = RegularMemberChat.Username;
}
private static async Task<Chat> GetChat(TestsFixture testsFixture, string collectionName)
{
Chat chat;
int.TryParse(ConfigurationProvider.TestConfigurations.RegularGroupMemberId, out int userId);
if (userId is default)
{
await testsFixture.UpdateReceiver.DiscardNewUpdatesAsync();
string botUserName = testsFixture.BotUser.Username;
await testsFixture.SendTestCollectionNotificationAsync(collectionName,
$"No value is set for `{nameof(ConfigurationProvider.TestConfigurations.RegularGroupMemberId)}` " +
$"in test settings. A non-admin chat member should send /test command in private chat with " +
$"@{botUserName.Replace("_", @"\_")}."
);
chat = await testsFixture.GetChatFromTesterAsync(ChatType.Private);
}
else
{
chat = await testsFixture.BotClient.GetChatAsync(userId);
}
if (chat.Username is default)
{
await testsFixture.SendTestCollectionNotificationAsync(collectionName,
$"[{chat.FirstName}](tg://user?id={chat.Id}) doesn't have a username.\n" +
"❎ Failing tests...");
throw new ArgumentNullException(nameof(chat.Username), "Chat member doesn't have a username");
}
return chat;
}
}
}
| 37.608696 | 119 | 0.623892 | [
"MIT"
] | Akshay-Gupta/Telegram.Bot | test/Telegram.Bot.Tests.Integ/Admin Bot/ChatMemberAdministrationTestFixture.cs | 2,599 | C# |
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using TestHelpers;
namespace LinqAF.Tests
{
[TestClass]
public class ContainsTests
{
[TestMethod]
public void InstanceExtensionNoOverlap()
{
Dictionary<MethodInfo, List<MethodInfo>> instOverlaps, extOverlaps;
Helper.GetOverlappingMethods(typeof(Impl.IContains<>), out instOverlaps, out extOverlaps);
if (instOverlaps.Count > 0)
{
var failure = new StringBuilder();
foreach (var kv in instOverlaps)
{
failure.AppendLine("For " + kv.Key);
failure.AppendLine(
LinqAFString.Join("\t -", kv.Value.Select(x => x.ToString() + "\n"))
);
Assert.Fail(failure.ToString());
}
}
if (extOverlaps.Count > 0)
{
var failure = new StringBuilder();
foreach (var kv in extOverlaps)
{
failure.AppendLine("For " + kv.Key);
failure.AppendLine(
LinqAFString.Join("\t -", kv.Value.Select(x => x.ToString() + "\n"))
);
Assert.Fail(failure.ToString());
}
}
}
[TestMethod]
public void Universal()
{
var enums = Helper.AllEnumerables();
foreach (var e in enums)
{
System.Collections.Generic.List<string> missing;
if (!Helper.Implements(e, typeof(Impl.IContains<>), out missing))
{
Assert.Fail($"{e.Name} does not implement IContains ({string.Join(", ", missing)})");
}
}
}
class _IntComparer : IEqualityComparer<int>
{
public bool Equals(int x, int y) => x == y;
public int GetHashCode(int obj) => obj;
}
[TestMethod]
public void Chaining()
{
foreach (var e in Helper.GetEnumerables(new[] { 2, 4, 6 }))
{
Assert.IsTrue(e.Contains(4));
Assert.IsFalse(e.Contains(5));
Assert.IsTrue(e.Contains(4, new _IntComparer()));
Assert.IsFalse(e.Contains(5, new _IntComparer()));
}
}
[TestMethod]
public void Chaining_Weird()
{
var empty = Enumerable.Empty<int>();
var emptyOrdered = empty.OrderBy(x => x);
var groupByDefault = new[] { 1, 1, 2, 2, 3, 3 }.GroupBy(x => x);
var groupBySpecific = new[] { "hello", "HELLO", "world", "WORLD", "foo", "FOO" }.GroupBy(x => x, StringComparer.OrdinalIgnoreCase);
var lookupDefault = new int[] { 1, 1, 2, 2, 3, 3 }.ToLookup(x => x);
var lookupSpecific = new int[] { 1, 1, 2, 2, 3, 3 }.ToLookup(x => x, new _IntComparer());
var range = Enumerable.Range(1, 5);
var repeat = Enumerable.Repeat("foo", 5);
var reverseRange = Enumerable.Range(1, 5).Reverse();
var oneItemDefault = Enumerable.Empty<int>().DefaultIfEmpty();
var oneItemSpecific = Enumerable.Empty<int>().DefaultIfEmpty(4);
var oneItemDefaultOrdered = oneItemDefault.OrderBy(x => x);
var oneItemSpecificOrdered = oneItemSpecific.OrderBy(x => x);
// empty
{
Assert.IsFalse(empty.Contains(1));
Assert.IsFalse(empty.Contains(1, new _IntComparer()));
}
// emptyOrdered
{
Assert.IsFalse(emptyOrdered.Contains(1));
Assert.IsFalse(emptyOrdered.Contains(1, new _IntComparer()));
}
// groupByDefault
{
Assert.IsFalse(groupByDefault.Contains(groupByDefault.First()));
Assert.IsFalse(groupByDefault.Contains(groupByDefault.First(), null));
}
// groupBySpecific
{
Assert.IsFalse(groupBySpecific.Contains(groupBySpecific.First()));
Assert.IsFalse(groupBySpecific.Contains(groupBySpecific.First(), null));
}
// lookupDefault
{
Assert.IsFalse(lookupDefault.Contains(lookupDefault.First()));
Assert.IsFalse(lookupDefault.Contains(lookupDefault.First(), null));
}
// lookupSpecific
{
Assert.IsFalse(lookupSpecific.Contains(lookupDefault.First()));
Assert.IsFalse(lookupSpecific.Contains(lookupDefault.First(), null));
}
// range
{
Assert.IsTrue(range.Contains(4));
Assert.IsTrue(range.Contains(4, new _IntComparer()));
}
// repeat
{
Assert.IsTrue(repeat.Contains("foo"));
Assert.IsTrue(repeat.Contains("FOO", StringComparer.InvariantCultureIgnoreCase));
}
// reverseRange
{
Assert.IsTrue(reverseRange.Contains(4));
Assert.IsTrue(reverseRange.Contains(4, new _IntComparer()));
}
// oneItemDefault
{
Assert.IsTrue(oneItemDefault.Contains(0));
Assert.IsTrue(oneItemDefault.Contains(0, new _IntComparer()));
}
// oneItemSpecific
{
Assert.IsTrue(oneItemSpecific.Contains(4));
Assert.IsTrue(oneItemSpecific.Contains(4, new _IntComparer()));
}
// oneItemDefaultOrdered
{
Assert.IsTrue(oneItemDefaultOrdered.Contains(0));
Assert.IsTrue(oneItemDefaultOrdered.Contains(0, new _IntComparer()));
}
// oneItemSpecificOrdered
{
Assert.IsTrue(oneItemSpecificOrdered.Contains(4));
Assert.IsTrue(oneItemSpecificOrdered.Contains(4, new _IntComparer()));
}
}
[TestMethod]
public void Chaining_Dictionary()
{
var dict = new System.Collections.Generic.Dictionary<int, int> { [1] = 2, [3] = 4 };
var sortedDict = new System.Collections.Generic.SortedDictionary<int, int> { [1] = 2, [3] = 4 };
Assert.IsTrue(dict.Contains(dict.First()));
Assert.IsTrue(dict.Contains(dict.First(), null));
Assert.IsTrue(sortedDict.Contains(sortedDict.First()));
Assert.IsTrue(sortedDict.Contains(sortedDict.First(), null));
}
[TestMethod]
public void Malformed()
{
foreach (var e in Helper.GetMalformedEnumerables<string>())
{
try { e.Contains(""); Assert.Fail(); } catch (ArgumentException exc) { Assert.AreEqual("source", exc.ParamName); }
try { e.Contains("", StringComparer.InvariantCultureIgnoreCase); Assert.Fail(); } catch (ArgumentException exc) { Assert.AreEqual("source", exc.ParamName); }
}
}
[TestMethod]
public void Malformed_Weird()
{
var empty = new EmptyEnumerable<int>();
var emptyOrdered = new EmptyOrderedEnumerable<int>();
var groupByDefault = new GroupByDefaultEnumerable<int, int, int, EmptyEnumerable<int>, EmptyEnumerator<int>>();
var groupBySpecific = new GroupBySpecificEnumerable<int, int, int, EmptyEnumerable<int>, EmptyEnumerator<int>>();
var lookupDefault = new LookupDefaultEnumerable<int, int>();
var lookupSpecific = new LookupSpecificEnumerable<int, int>();
var range = new RangeEnumerable();
var repeat = new RepeatEnumerable<int>();
var reverseRange = new ReverseRangeEnumerable();
var oneItemDefault = new OneItemDefaultEnumerable<int>();
var oneItemSpecific = new OneItemSpecificEnumerable<int>();
var oneItemDefaultOrdered = new OneItemDefaultOrderedEnumerable<int>();
var oneItemSpecificOrdered = new OneItemSpecificOrderedEnumerable<int>();
// empty
{
try { empty.Contains(1); Assert.Fail(); } catch (ArgumentException exc) { Assert.AreEqual("source", exc.ParamName); }
try { empty.Contains(1, new _IntComparer()); Assert.Fail(); } catch (ArgumentException exc) { Assert.AreEqual("source", exc.ParamName); }
}
// emptyOrdered
{
try { emptyOrdered.Contains(1); Assert.Fail(); } catch (ArgumentException exc) { Assert.AreEqual("source", exc.ParamName); }
try { emptyOrdered.Contains(1, new _IntComparer()); Assert.Fail(); } catch (ArgumentException exc) { Assert.AreEqual("source", exc.ParamName); }
}
// groupByDefault
{
try { groupByDefault.Contains(new GroupingEnumerable<int, int>()); Assert.Fail(); } catch (ArgumentException exc) { Assert.AreEqual("source", exc.ParamName); }
try { groupByDefault.Contains(new GroupingEnumerable<int, int>(), null); Assert.Fail(); } catch (ArgumentException exc) { Assert.AreEqual("source", exc.ParamName); }
}
// groupBySpecific
{
try { groupBySpecific.Contains(new GroupingEnumerable<int, int>()); Assert.Fail(); } catch (ArgumentException exc) { Assert.AreEqual("source", exc.ParamName); }
try { groupBySpecific.Contains(new GroupingEnumerable<int, int>(), null); Assert.Fail(); } catch (ArgumentException exc) { Assert.AreEqual("source", exc.ParamName); }
}
// lookupDefault
{
try { lookupDefault.Contains(new GroupingEnumerable<int, int>()); Assert.Fail(); } catch (ArgumentException exc) { Assert.AreEqual("source", exc.ParamName); }
try { lookupDefault.Contains(new GroupingEnumerable<int, int>(), null); Assert.Fail(); } catch (ArgumentException exc) { Assert.AreEqual("source", exc.ParamName); }
}
// lookupSpecific
{
try { lookupSpecific.Contains(new GroupingEnumerable<int, int>()); Assert.Fail(); } catch (ArgumentException exc) { Assert.AreEqual("source", exc.ParamName); }
try { lookupSpecific.Contains(new GroupingEnumerable<int, int>(), null); Assert.Fail(); } catch (ArgumentException exc) { Assert.AreEqual("source", exc.ParamName); }
}
// range
{
try { range.Contains(1); Assert.Fail(); } catch (ArgumentException exc) { Assert.AreEqual("source", exc.ParamName); }
try { range.Contains(1, new _IntComparer()); Assert.Fail(); } catch (ArgumentException exc) { Assert.AreEqual("source", exc.ParamName); }
}
// repeat
{
try { repeat.Contains(1); Assert.Fail(); } catch (ArgumentException exc) { Assert.AreEqual("source", exc.ParamName); }
try { repeat.Contains(1, new _IntComparer()); Assert.Fail(); } catch (ArgumentException exc) { Assert.AreEqual("source", exc.ParamName); }
}
// reverseRange
{
try { reverseRange.Contains(1); Assert.Fail(); } catch (ArgumentException exc) { Assert.AreEqual("source", exc.ParamName); }
try { reverseRange.Contains(1, new _IntComparer()); Assert.Fail(); } catch (ArgumentException exc) { Assert.AreEqual("source", exc.ParamName); }
}
// oneItemDefault
{
try { oneItemDefault.Contains(1); Assert.Fail(); } catch (ArgumentException exc) { Assert.AreEqual("source", exc.ParamName); }
try { oneItemDefault.Contains(1, new _IntComparer()); Assert.Fail(); } catch (ArgumentException exc) { Assert.AreEqual("source", exc.ParamName); }
}
// oneItemSpecific
{
try { oneItemSpecific.Contains(1); Assert.Fail(); } catch (ArgumentException exc) { Assert.AreEqual("source", exc.ParamName); }
try { oneItemSpecific.Contains(1, new _IntComparer()); Assert.Fail(); } catch (ArgumentException exc) { Assert.AreEqual("source", exc.ParamName); }
}
// oneItemDefaultOrdered
{
try { oneItemDefaultOrdered.Contains(1); Assert.Fail(); } catch (ArgumentException exc) { Assert.AreEqual("source", exc.ParamName); }
try { oneItemDefaultOrdered.Contains(1, new _IntComparer()); Assert.Fail(); } catch (ArgumentException exc) { Assert.AreEqual("source", exc.ParamName); }
}
// oneItemSpecificOrdered
{
try { oneItemSpecificOrdered.Contains(1); Assert.Fail(); } catch (ArgumentException exc) { Assert.AreEqual("source", exc.ParamName); }
try { oneItemSpecificOrdered.Contains(1, new _IntComparer()); Assert.Fail(); } catch (ArgumentException exc) { Assert.AreEqual("source", exc.ParamName); }
}
}
}
}
| 44.496644 | 182 | 0.559578 | [
"Apache-2.0"
] | kevin-montrose/LinqAF | LinqAF.Tests/ContainsTests.cs | 13,262 | C# |
// <copyright file="MessageArgsMsTest.cs" company="Automate The Planet Ltd.">
// Copyright 2016 Automate The Planet Ltd.
// Licensed under the Apache License, Version 2.0 (the "License");
// You may not use this file except in compliance with the License.
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
// <author>Anton Angelov</author>
// <site>http://automatetheplanet.com/</site>
using System;
using System.IO;
using System.Text;
namespace MSBuildTcpIPLogger
{
public class MessageArgsMsTest : BaseMessageArgs
{
public string TestListContent { get; set; }
public string ResultsFilePath { get; set; }
public string TestListPath { get; set; }
public string ListName { get; set; }
public MessageArgsMsTest(Command command, string projectPath, IpAddressSettings ipAddressSettings, string workingDir, string testListContent, string testListName, string resultsFilePath)
: base(command, projectPath, ipAddressSettings, workingDir)
{
TestListContent = testListContent;
ResultsFilePath = resultsFilePath;
ListName = testListName;
}
public MessageArgsMsTest()
{
}
public string CreateTestList()
{
TestListPath = String.Empty;
if (!String.IsNullOrEmpty(TestListContent))
{
TestListPath = Path.GetTempFileName();
var sw = new StreamWriter(TestListPath, false, Encoding.UTF8);
TestListContent = TestListContent.TrimStart('?');
sw.WriteLine(TestListContent);
sw.Close();
sw = new StreamWriter(@"E:\AutomationTestAssistant\ServerAgent\bin\Release\testList.xml", false, Encoding.UTF8);
sw.WriteLine(TestListContent);
sw.Close();
}
return TestListPath;
}
}
}
| 38.033333 | 194 | 0.656442 | [
"Apache-2.0"
] | FrancielleWN/AutomateThePlanet-Learning-Series | CSharp-Series/MSBuildTcpIPLogger/MessageArgsMsTest.cs | 2,284 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Xamarin.Forms;
namespace XamarinFormsShared.WinPhone
{
public partial class MainPage : PhoneApplicationPage
{
public MainPage()
{
InitializeComponent();
Forms.Init();
Content = XamarinFormsShared.App.GetMainPage().ConvertPageToUIElement(this);
}
}
}
| 19.888889 | 80 | 0.739292 | [
"MIT"
] | HolisticWare/HolisticWare.Core | samples/XamarinFormsShared/XamarinFormsShared.WinPhone/MainPage.xaml.cs | 539 | C# |
#nullable enable
using System.Collections.Generic;
using Edanoue.Logging.Interfaces;
using Edanoue.Logging.Internal;
using UnityEngine;
using ILogger = Edanoue.Logging.Interfaces.ILogger;
namespace Edanoue.Logging
{
using Extra = KeyValuePair<string, object>;
/// <summary>
/// Utility functions at module level.
/// Basically delegate everything to the root logger.
/// </summary>
public static class Logging
{
/// <summary>
/// Return a logger with the specified name or, if name is None, return a logger which is the root logger of the
/// hierarchy.
/// <param name="name">
/// If specified, the name is typically a dot-separated hierarchical
/// name like "a", "a.b" or "a.b.c.d". Choice of these names is entirely up to the developer who is using logging.
/// </param>
/// <returns>logger</returns>
/// </summary>
public static ILogger GetLogger(string name)
{
if (string.IsNullOrEmpty(name) || name == CONST.ROOT_LOGGER_NAME)
return Manager.Root;
return Manager.GetLogger(name);
}
/// <summary>
/// Return a logger with the specified class, creating it if necessary.
/// </summary>
/// <note>
/// GetLogger<"MyClass">() is same to GetLogger("MyNamespace.MyClass")
/// </note>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static ILogger GetLogger<T>()
{
// Get Type fullname
var name = typeof(T).FullName;
// Replace nested type separator "+" to "."
name = name.Replace("+", CONST.NAME_SEPARATOR);
return Manager.GetLogger(name);
}
/// <summary>
/// Return a logger with the specified class, creating it if necessary.
/// </summary>
/// <note>
/// GetLogger<"MyClass">("Foo") is same to GetLogger("MyNamespace.MyClass.Foo")
/// </note>
/// <param name="childName">child logger name</param>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static ILogger GetLogger<T>(string childName)
{
// Get Type fullname
var name = typeof(T).FullName;
// Replace nested type separator "+" to "."
name = name.Replace("+", CONST.NAME_SEPARATOR);
// Add name
name += $"{CONST.NAME_SEPARATOR}{childName}";
return Manager.GetLogger(name);
}
/// <summary>
/// Set the logging level of root logger
/// </summary>
/// <param name="level"></param>
public static void SetLevel(LogLevel level)
{
Manager.Root.SetLevel(level);
}
/// <summary>
/// Log message with severity "Debug" on root logger.
/// </summary>
/// <param name="message"></param>
public static void Debug(string message)
{
Manager.Root.Debug(message);
}
/// <summary>
/// Log message with severity "Debug" on root logger
/// with UnityEngine.Object context
/// </summary>
/// <param name="message"></param>
/// <param name="context"></param>
public static void Debug(string message, Object context)
{
Manager.Root.Debug(message, new Extra(CONST.UNITY_CONTEXT_KEY, context));
}
/// <summary>
/// Log message with severity "Info" on root logger.
/// </summary>
/// <param name="message"></param>
public static void Info(string message)
{
Manager.Root.Info(message);
}
/// <summary>
/// Log message with severity "Info" on root logger.
/// </summary>
/// <param name="message"></param>
/// <param name="context"></param>
public static void Info(string message, Object context)
{
Manager.Root.Info(message, new Extra(CONST.UNITY_CONTEXT_KEY, context));
}
/// <summary>
/// Log message with severity "Warning" on root logger.
/// </summary>
/// <param name="message"></param>
public static void Warning(string message)
{
Manager.Root.Warning(message);
}
/// <summary>
/// Log message with severity "Warning" on root logger.
/// </summary>
/// <param name="message"></param>
/// <param name="context"></param>
public static void Warning(string message, Object context)
{
Manager.Root.Warning(message, new Extra(CONST.UNITY_CONTEXT_KEY, context));
}
/// <summary>
/// Log message with severity "Error" on root logger.
/// </summary>
/// <param name="message"></param>
public static void Error(string message)
{
Manager.Root.Error(message);
}
/// <summary>
/// Log message with severity "Error" on root logger.
/// </summary>
/// <param name="message"></param>
/// <param name="context"></param>
public static void Error(string message, Object context)
{
Manager.Root.Error(message, new Extra(CONST.UNITY_CONTEXT_KEY, context));
}
/// <summary>
/// Log message with severity "Critical" on root logger.
/// </summary>
/// <param name="message"></param>
public static void Critical(string message)
{
Manager.Root.Critical(message);
}
/// <summary>
/// Log message with severity "Critical" on root logger.
/// </summary>
/// <param name="message"></param>
/// <param name="context"></param>
public static void Critical(string message, Object context)
{
Manager.Root.Critical(message, new Extra(CONST.UNITY_CONTEXT_KEY, context));
}
/// <summary>
/// Log message with the integer severity level on root logger.
/// </summary>
/// <param name="level"></param>
/// <param name="message"></param>
public static void Log(int level, string message)
{
Manager.Root.Log(level, message);
}
/// <summary>
/// Log message with the integer severity level on root logger.
/// </summary>
/// <param name="level">user defined level</param>
/// <param name="message"></param>
/// <param name="context"></param>
public static void Log(int level, string message, Object context)
{
Manager.Root.Log(level, message, new Extra(CONST.UNITY_CONTEXT_KEY, context));
}
/// <summary>
/// Is root logger enabled for level?
/// </summary>
/// <param name="level"></param>
/// <returns></returns>
public static bool IsEnabledFor(int level)
{
return Manager.Root.IsEnabledFor(level);
}
public static bool IsEnabledFor(LogLevel level)
{
return IsEnabledFor((int) level);
}
/// <summary>
/// Add the specified handler to root logger.
/// </summary>
/// <param name="handler"></param>
public static void AddHandler(IHandler handler)
{
Manager.Root.AddHandler(handler);
}
}
} | 33.720721 | 122 | 0.54662 | [
"MIT"
] | edanoue/UnityLogging | Runtime/Logging.cs | 7,486 | C# |
using System;
using Marten.Internal;
using Marten.Linq.Fields;
using Marten.Linq.SqlGeneration;
using NSubstitute;
using Shouldly;
using Weasel.Postgresql;
using Xunit;
namespace DocumentDbTests.Reading.Linq.Internals
{
public class DummyStatement: Statement
{
public DummyStatement() : base(Substitute.For<IFieldMapping>())
{
}
protected override void configure(CommandBuilder builder)
{
throw new NotSupportedException();
}
}
public class StatementTests
{
[Fact]
public void appending_child_converts_to_CTE()
{
var root = new DummyStatement();
var descendent = new DummyStatement();
root.InsertAfter(descendent);
root.Next.ShouldBe(descendent);
descendent.Previous.ShouldBe(root);
}
}
public class when_inserting_a_statement_before_an_unattached_statement
{
private DummyStatement original;
private DummyStatement newRoot;
public when_inserting_a_statement_before_an_unattached_statement()
{
var session = Substitute.For<IMartenSession>();
session.NextTempTableName().Returns("NextTempTable");
original = new DummyStatement
{
Mode = StatementMode.Select
};
newRoot = new DummyStatement();
original.InsertBefore(newRoot);
}
[Fact]
public void relationships()
{
newRoot.Next.ShouldBe(original);
original.Previous.ShouldBe(newRoot);
}
[Fact]
public void new_root_is_top()
{
newRoot.Previous.ShouldBeNull();
original.Top().ShouldBe(newRoot);
newRoot.Top().ShouldBe(newRoot);
}
[Fact]
public void original_is_current()
{
original.Current().ShouldBe(original);
newRoot.Current().ShouldBe(original);
}
}
public class when_inserting_statement_in_front_of_statement_that_is_not_the_top
{
private DummyStatement root = new DummyStatement();
private DummyStatement original = new DummyStatement();
private DummyStatement inserted = new DummyStatement();
public when_inserting_statement_in_front_of_statement_that_is_not_the_top()
{
var session = Substitute.For<IMartenSession>();
session.NextTempTableName().Returns("NextTempTable");
root.InsertAfter(original);
inserted = new DummyStatement();
original.InsertBefore(inserted);
}
[Fact]
public void relationships()
{
root.Next.ShouldBe(inserted);
inserted.Previous.ShouldBe(root);
inserted.Next.ShouldBe(original);
original.Previous.ShouldBe(inserted);
}
[Fact]
public void root_is_still_top()
{
original.Top().ShouldBe(root);
inserted.Top().ShouldBe(root);
}
[Fact]
public void original_is_current()
{
original.Current().ShouldBe(original);
inserted.Current().ShouldBe(original);
}
}
}
| 25.192308 | 83 | 0.597557 | [
"MIT"
] | Rob89/marten | src/DocumentDbTests/Reading/Linq/Internals/StatementTests.cs | 3,275 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace ImageFramework.ImageLoader
{
internal static class Dll
{
public const string DllFilePath = @"DxImageLoader.dll";
[DllImport(DllFilePath, CallingConvention = CallingConvention.Cdecl)]
public static extern int image_open(string filename);
[DllImport(DllFilePath, CallingConvention = CallingConvention.Cdecl)]
public static extern int image_allocate(uint format, int width, int height, int depth, int layer, int mipmap);
[DllImport(DllFilePath, CallingConvention = CallingConvention.Cdecl)]
public static extern void image_release(int id);
[DllImport(DllFilePath, CallingConvention = CallingConvention.Cdecl)]
public static extern void image_info(int id, out uint format, out uint originalFormat,
out int nLayer, out int nMipmaps);
[DllImport(DllFilePath, CallingConvention = CallingConvention.Cdecl)]
public static extern void image_info_mipmap(int id, int mipmap, out int width, out int height, out int depth);
[DllImport(DllFilePath, CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr image_get_mipmap(int id, int layer, int mipmap, out uint size);
[DllImport(DllFilePath, CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool image_save(int id, string filename, string extension, uint format, int quality);
[DllImport(DllFilePath, CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr get_export_formats(string extension, out int nFormats);
[DllImport(DllFilePath, CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr get_error(out int length);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
public delegate uint ProgressDelegate([MarshalAs(UnmanagedType.R4)] float progress, [MarshalAs(UnmanagedType.LPStr)] string description);
[DllImport(DllFilePath, CallingConvention = CallingConvention.Cdecl)]
public static extern void set_progress_callback([MarshalAs(UnmanagedType.FunctionPtr)] ProgressDelegate pDelegate);
public static string GetError()
{
var ptr = get_error(out var length);
return ptr.Equals(IntPtr.Zero) ? "" : Marshal.PtrToStringAnsi(ptr, length);
}
[DllImport("kernel32.dll", EntryPoint = "CopyMemory", SetLastError = false)]
public static extern void CopyMemory(IntPtr dest, IntPtr src, uint count);
}
}
| 45.898305 | 145 | 0.727105 | [
"MIT"
] | gaybro8777/ImageViewer | ImageFramework/ImageLoader/Dll.cs | 2,710 | 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("Task 07-Magic Nums")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Task 07-Magic Nums")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("d32c2fb8-004a-4634-bcc5-679576e9a6f3")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.081081 | 84 | 0.74308 | [
"MIT"
] | ewgeni-dinew/01.Programming-Fundamentals | 13. String and Text/Task 07-Magic Nums/Properties/AssemblyInfo.cs | 1,412 | C# |
using System.Collections.Generic;
using System.IO.Abstractions.TestingHelpers;
using Moq;
using SpruceJS.Core;
using SpruceJS.Core.Config.Files;
using SpruceJS.Core.Modules.Exceptions;
using Xunit;
namespace SpruceJS.Tests.Core
{
public class SpruceBuilderExceptionTests
{
[Fact]
public void OutputThrowsModuleKeyDoesNotExistException()
{
var fileconfigMock = new Mock<IFileConfig>();
fileconfigMock.Setup(i => i.Modules).Returns(new[] { @"c:\a.js", @"c:\b.js" });
var fileSystem = new MockFileSystem(new Dictionary<string, MockFileData> {
{ @"c:\a.js", new MockFileData("define('a', ['c'], function () { var enginetests1 = 123; });") },
{ @"c:\b.js", new MockFileData("define('b', function () { var enginetests2 = 456; });") }
});
var engine = new SpruceBuilder(fileconfigMock.Object, fileSystem) { Minify = false };
engine.LoadModule(@"c:\a.js");
Assert.Throws<ModuleKeyDoesNotExistException>(
() => { engine.GetOutput(); }
);
}
[Fact]
public void MinifiedOutputThrowsModuleKeyDoesNotExistException()
{
var fileconfigMock = new Mock<IFileConfig>();
fileconfigMock.Setup(i => i.Modules).Returns(new[] { @"c:\a.js", @"c:\b.js" });
var fileSystem = new MockFileSystem(new Dictionary<string, MockFileData> {
{ @"c:\a.js", new MockFileData("define('a', ['c'], function () { var enginetests1 = 123; });") },
{ @"c:\b.js", new MockFileData("define('b', function () { var enginetests2 = 456; });") }
});
var engine = new SpruceBuilder(fileconfigMock.Object, fileSystem) { Minify = true };
engine.LoadModule(@"c:\a.js");
Assert.Throws<ModuleKeyDoesNotExistException>(
() => { engine.GetOutput(); }
);
}
[Fact]
public void OutputThrowsModuleKeyNotUniqueException()
{
var fileconfigMock = new Mock<IFileConfig>();
fileconfigMock.Setup(i => i.Modules).Returns(new[] { @"c:\a.js", @"c:\b.js" });
var fileSystem = new MockFileSystem(new Dictionary<string, MockFileData> {
{ @"c:\a.js", new MockFileData("define('a', function () { var enginetests1 = 123; });") },
{ @"c:\b.js", new MockFileData("define('a', function () { var enginetests2 = 456; });") }
});
var engine = new SpruceBuilder(fileconfigMock.Object, fileSystem) { Minify = false };
engine.LoadModule(@"c:\a.js");
Assert.Throws<ModuleKeyNotUniqueException>(
() => { engine.GetOutput(); }
);
}
[Fact]
public void MinifiedOutputThrowsModuleKeyNotUniqueException()
{
var fileconfigMock = new Mock<IFileConfig>();
fileconfigMock.Setup(i => i.Modules).Returns(new[] { @"c:\a.js", @"c:\b.js" });
var fileSystem = new MockFileSystem(new Dictionary<string, MockFileData> {
{ @"c:\a.js", new MockFileData("define('a', ['c'], function () { var enginetests1 = 123; });") },
{ @"c:\b.js", new MockFileData("define('a', function () { var enginetests2 = 456; });") }
});
var engine = new SpruceBuilder(fileconfigMock.Object, fileSystem) { Minify = true };
engine.LoadModule(@"c:\a.js");
Assert.Throws<ModuleKeyNotUniqueException>(
() => { engine.GetOutput(); }
);
}
[Fact]
public void OutputThrowsModuleKeyCircularReferenceException()
{
var fileconfigMock = new Mock<IFileConfig>();
fileconfigMock.Setup(i => i.Modules).Returns(new[] { @"c:\a.js", @"c:\b.js" });
var fileSystem = new MockFileSystem(new Dictionary<string, MockFileData> {
{ @"c:\a.js", new MockFileData("define('a', ['b'], function () { var enginetests1 = 123; });") },
{ @"c:\b.js", new MockFileData("define('b', ['a'], function () { var enginetests2 = 456; });") }
});
var engine = new SpruceBuilder(fileconfigMock.Object, fileSystem) { Minify = false };
engine.LoadModule(@"c:\a.js");
Assert.Throws<ModuleKeyCircularReferenceException>(
() => { engine.GetOutput(); }
);
}
[Fact]
public void MinifiedOutputModuleKeyCircularReferenceException()
{
var fileconfigMock = new Mock<IFileConfig>();
fileconfigMock.Setup(i => i.Modules).Returns(new[] { @"c:\a.js", @"c:\b.js" });
var fileSystem = new MockFileSystem(new Dictionary<string, MockFileData> {
{ @"c:\a.js", new MockFileData("define('a', ['b'], function () { var enginetests1 = 123; });") },
{ @"c:\b.js", new MockFileData("define('b', ['a'], function () { var enginetests2 = 456; });") }
});
var engine = new SpruceBuilder(fileconfigMock.Object, fileSystem) { Minify = true };
engine.LoadModule(@"c:\a.js");
Assert.Throws<ModuleKeyCircularReferenceException>(
() => { engine.GetOutput(); }
);
}
[Fact]
public void NamelessModulesNotThrowsException()
{
var fileconfigMock = new Mock<IFileConfig>();
fileconfigMock.Setup(i => i.Modules).Returns(new[] { @"c:\a.js", @"c:\b.js" });
var fileSystem = new MockFileSystem(new Dictionary<string, MockFileData> {
{ @"c:\a.js", new MockFileData("define(function () { var enginetests1 = 123; });") },
{ @"c:\b.js", new MockFileData("define([], function () { var enginetests2 = 456; });") }
});
var engine = new SpruceBuilder(fileconfigMock.Object, fileSystem) { Minify = true };
Assert.DoesNotThrow(
() => { engine.GetOutput(); }
);
}
[Fact]
public void OutputThrowsNotValidModuleException()
{
var fileconfigMock = new Mock<IFileConfig>();
fileconfigMock.Setup(i => i.Modules).Returns(new[] { @"c:\a.js", @"c:\b.js" });
var fileSystem = new MockFileSystem(new Dictionary<string, MockFileData> {
{ @"c:\a.js", new MockFileData("define(function () { var enginetests1 = 123; });") },
{ @"c:\b.js", new MockFileData("define();") }
});
var engine = new SpruceBuilder(fileconfigMock.Object, fileSystem) { Minify = true };
Assert.Throws<ModuleNotValidException>(
() => { engine.GetOutput(); }
);
}
}
}
| 36.182927 | 102 | 0.623525 | [
"Apache-2.0"
] | whoknewdk/SpruceJS | src/Tests/SpruceJS.Tests/Core/SpruceBuilderExceptionTests.cs | 5,936 | C# |
//-----------------------------------------------------------------------
// <copyright file="jet_convert.cs" company="Microsoft Corporation">
// Copyright (c) Microsoft Corporation.
// </copyright>
//-----------------------------------------------------------------------
#if !MANAGEDESENT_ON_WSA // Not exposed in MSDK
namespace Microsoft.Isam.Esent.Interop
{
using System;
/// <summary>
/// Conversion options for <see cref="Api.JetCompact"/>. This feature
/// was discontinued in Windows Server 2003.
/// </summary>
[Obsolete("Not available in Windows Server 2003 and up.")]
public abstract class JET_CONVERT
{
}
}
#endif // !MANAGEDESENT_ON_WSA | 33.904762 | 75 | 0.521067 | [
"MIT"
] | Bhaskers-Blu-Org2/ManagedEsent | EsentInterop/jet_convert.cs | 714 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations.Internal;
using Microsoft.EntityFrameworkCore.Update;
using Microsoft.EntityFrameworkCore.Utilities;
namespace Microsoft.EntityFrameworkCore.Migrations.Operations
{
/// <summary>
/// A <see cref="MigrationOperation" /> for updating seed data in an existing table.
/// </summary>
[DebuggerDisplay("UPDATE {Table}")]
public class UpdateDataOperation : MigrationOperation, ITableMigrationOperation
{
/// <summary>
/// The name of the table in which data will be updated.
/// </summary>
public virtual string Table { get; set; } = null!;
/// <summary>
/// The schema that contains the table, or <see langword="null" /> if the default schema should be used.
/// </summary>
public virtual string? Schema { get; set; }
/// <summary>
/// A list of column names that represent the columns that will be used to identify
/// the rows that should be updated.
/// </summary>
public virtual string[] KeyColumns { get; set; } = null!;
/// <summary>
/// A list of store types for the columns that will be used to identify
/// the rows that should be updated.
/// </summary>
public virtual string[]? KeyColumnTypes { get; set; }
/// <summary>
/// The rows to be updated, represented as a list of key value arrays where each
/// value in the array corresponds to a column in the <see cref="KeyColumns" /> property.
/// </summary>
public virtual object?[,] KeyValues { get; set; } = null!;
/// <summary>
/// A list of column names that represent the columns that contain data to be updated.
/// </summary>
public virtual string[] Columns { get; set; } = null!;
/// <summary>
/// A list of store types for the columns in which data will be updated.
/// </summary>
public virtual string[]? ColumnTypes { get; set; }
/// <summary>
/// The data to be updated, represented as a list of value arrays where each
/// value in the array corresponds to a column in the <see cref="Columns" /> property.
/// </summary>
public virtual object?[,] Values { get; set; } = null!;
/// <summary>
/// Generates the commands that correspond to this operation.
/// </summary>
/// <returns> The commands that correspond to this operation. </returns>
[Obsolete]
public virtual IEnumerable<ModificationCommand> GenerateModificationCommands(IModel? model)
{
Check.DebugAssert(
KeyColumns.Length == KeyValues.GetLength(1),
$"The number of key values doesn't match the number of keys (${KeyColumns.Length})"
);
Check.DebugAssert(
Columns.Length == Values.GetLength(1),
$"The number of values doesn't match the number of keys (${Columns.Length})"
);
Check.DebugAssert(
KeyValues.GetLength(0) == Values.GetLength(0),
$"The number of key values doesn't match the number of values (${KeyValues.GetLength(0)})"
);
var table = model?.GetRelationalModel().FindTable(Table, Schema);
var keyProperties =
table != null ? MigrationsModelDiffer.GetMappedProperties(table, KeyColumns) : null;
var properties =
table != null ? MigrationsModelDiffer.GetMappedProperties(table, Columns) : null;
for (var i = 0; i < KeyValues.GetLength(0); i++)
{
var keys = new ColumnModification[KeyColumns.Length];
for (var j = 0; j < KeyColumns.Length; j++)
{
keys[j] = new ColumnModification(
KeyColumns[j],
originalValue: null,
value: KeyValues[i, j],
property: keyProperties?[j],
columnType: KeyColumnTypes?[j],
isRead: false,
isWrite: false,
isKey: true,
isCondition: true,
sensitiveLoggingEnabled: false
);
}
var modifications = new ColumnModification[Columns.Length];
for (var j = 0; j < Columns.Length; j++)
{
modifications[j] = new ColumnModification(
Columns[j],
originalValue: null,
value: Values[i, j],
property: properties?[j],
columnType: ColumnTypes?[j],
isRead: false,
isWrite: true,
isKey: true,
isCondition: false,
sensitiveLoggingEnabled: false
);
}
yield return new ModificationCommand(
Table,
Schema,
keys.Concat(modifications).ToArray(),
sensitiveLoggingEnabled: false
);
}
}
}
}
| 41.897059 | 116 | 0.538961 | [
"Apache-2.0"
] | belav/efcore | src/EFCore.Relational/Migrations/Operations/UpdateDataOperation.cs | 5,698 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Logging;
namespace SoundPlugin
{
public class SoundManager
{
private Dictionary<Source, Sound> oneTimeSounds = new Dictionary<Source, Sound>();
private OpenALManager openALManager;
internal SoundManager(OpenALManager openALManager)
{
this.openALManager = openALManager;
}
public Source streamPlayAndForgetSound(Stream soundStream)
{
Source source = openALManager.getSource();
if (source != null)
{
Sound sound = openALManager.createStreamingSound(soundStream);
oneTimeSounds.Add(source, sound);
source.PlaybackFinished += source_PlaybackFinished;
source.playSound(sound);
return source;
}
else
{
Log.Error("Ran out of sources trying to play sound.");
}
return null;
}
public double getDuration(Stream soundStream)
{
AudioCodec codec = openALManager.createAudioCodec(soundStream);
double duration = codec.Duration;
openALManager.destroyAudioCodec(codec);
return duration;
}
/// <summary>
/// Open a capture device, you must dispose it when you are done.
/// </summary>
/// <returns>A new open capture device.</returns>
public CaptureDevice openCaptureDevice(BufferFormat format = BufferFormat.Stereo16, int bufferSeconds = 5, int rate = 44100)
{
return openALManager.createCaptureDevice(format, bufferSeconds, rate);
}
void source_PlaybackFinished(Source source)
{
source.PlaybackFinished -= source_PlaybackFinished;
Sound sound = oneTimeSounds[source];
openALManager.destroySound(sound);
oneTimeSounds.Remove(source);
}
}
}
| 32.734375 | 133 | 0.583771 | [
"MIT"
] | AnomalousMedical/Engine | SoundPlugin/Plugin/SoundManager.cs | 2,097 | 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.Identity.UI.UIFrameworkAttribute("Bootstrap4")]
[assembly: System.Reflection.AssemblyCompanyAttribute("CompleteApp.Api")]
[assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")]
[assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")]
[assembly: System.Reflection.AssemblyProductAttribute("CompleteApp.Api")]
[assembly: System.Reflection.AssemblyTitleAttribute("CompleteApp.Api")]
[assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")]
// Generated by the MSBuild WriteCodeFragment class.
| 43 | 80 | 0.663256 | [
"MIT"
] | fesnarriaga/courses | desenvolvedor-io/04_rest-aspnet-core-webapi/04_CompleteApp/CompleteApp/src/CompleteApp.Api/obj/Debug/net5.0/CompleteApp.Api.AssemblyInfo.cs | 1,075 | C# |
using UnityEngine;
using Random = UnityEngine.Random;
[RequireComponent(typeof(CarController))]
public class CarAudio : MonoBehaviour
{
// This script reads some of the car's current properties and plays sounds accordingly.
// The engine sound can be a simple single clip which is looped and pitched, or it
// can be a crossfaded blend of four clips which represent the timbre of the engine
// at different RPM and Throttle state.
// the engine clips should all be a steady pitch, not rising or falling.
// when using four channel engine crossfading, the four clips should be:
// lowAccelClip : The engine at low revs, with throttle open (i.e. begining acceleration at very low speed)
// highAccelClip : Thenengine at high revs, with throttle open (i.e. accelerating, but almost at max speed)
// lowDecelClip : The engine at low revs, with throttle at minimum (i.e. idling or engine-braking at very low speed)
// highDecelClip : Thenengine at high revs, with throttle at minimum (i.e. engine-braking at very high speed)
// For proper crossfading, the clips pitches should all match, with an octave offset between low and high.
public enum DriveMode
{
AI,
Human
}
public enum EngineAudioOptions // Options for the engine audio
{
Simple, // Simple style audio
FourChannel // four Channel audio
}
public EngineAudioOptions engineSoundStyle = EngineAudioOptions.FourChannel;// Set the default audio options to be four channel
public DriveMode driveMode = DriveMode.AI;
public AudioClip lowAccelClip; // Audio clip for low acceleration
public AudioClip lowDecelClip; // Audio clip for low deceleration
public AudioClip highAccelClip; // Audio clip for high acceleration
public AudioClip highDecelClip; // Audio clip for high deceleration
public float pitchMultiplier = 1f; // Used for altering the pitch of audio clips
public float lowPitchMin = 1f; // The lowest possible pitch for the low sounds
public float lowPitchMax = 6f; // The highest possible pitch for the low sounds
public float highPitchMultiplier = 0.25f; // Used for altering the pitch of high sounds
public float maxRolloffDistance = 500; // The maximum distance where rollof starts to take place
public float dopplerLevel = 1; // The mount of doppler effect used in the audio
public bool useDoppler = true; // Toggle for using doppler
private AudioSource m_LowAccel; // Source for the low acceleration sounds
private AudioSource m_LowDecel; // Source for the low deceleration sounds
private AudioSource m_HighAccel; // Source for the high acceleration sounds
private AudioSource m_HighDecel; // Source for the high deceleration sounds
private bool m_StartedSound; // flag for knowing if we have started sounds
private CarController m_CarController; // Reference to car we are controlling
private PlayerVehicle playerVehicle;
private void StartSound()
{
// get the carcontroller ( this will not be null as we have require component)
if (driveMode == DriveMode.AI)
{
m_CarController = GetComponent<CarController>();
}
else
{
playerVehicle = GetComponent<PlayerVehicle>();
}
// setup the simple audio source
m_HighAccel = SetUpEngineAudioSource(highAccelClip);
// if we have four channel audio setup the four audio sources
if (engineSoundStyle == EngineAudioOptions.FourChannel)
{
m_LowAccel = SetUpEngineAudioSource(lowAccelClip);
m_LowDecel = SetUpEngineAudioSource(lowDecelClip);
m_HighDecel = SetUpEngineAudioSource(highDecelClip);
}
// flag that we have started the sounds playing
m_StartedSound = true;
}
private void StopSound()
{
//Destroy all audio sources on this object:
foreach (var source in GetComponents<AudioSource>())
{
Destroy(source);
}
m_StartedSound = false;
}
// Update is called once per frame
private void Update()
{
// get the distance to main camera
float camDist = (Camera.main.transform.position - transform.position).sqrMagnitude;
// stop sound if the object is beyond the maximum roll off distance
if (m_StartedSound && camDist > maxRolloffDistance * maxRolloffDistance)
{
StopSound();
}
// start the sound if not playing and it is nearer than the maximum distance
if (!m_StartedSound && camDist < maxRolloffDistance * maxRolloffDistance)
{
StartSound();
}
if (m_StartedSound)
{
float pitch = 0;
if (driveMode == DriveMode.AI)
{
// The pitch is interpolated between the min and max values, according to the car's revs.
pitch = ULerp(lowPitchMin, lowPitchMax, m_CarController.Revs);
}
else
{
pitch = ULerp(lowPitchMin, lowPitchMax, playerVehicle.GetThrottle());
}
// clamp to minimum pitch (note, not clamped to max for high revs while burning out)
pitch = Mathf.Min(lowPitchMax, pitch);
if (engineSoundStyle == EngineAudioOptions.Simple)
{
// for 1 channel engine sound, it's oh so simple:
m_HighAccel.pitch = pitch * pitchMultiplier * highPitchMultiplier;
m_HighAccel.dopplerLevel = useDoppler ? dopplerLevel : 0;
m_HighAccel.volume = 1;
}
else
{
// for 4 channel engine sound, it's a little more complex:
// adjust the pitches based on the multipliers
m_LowAccel.pitch = pitch * pitchMultiplier;
m_LowDecel.pitch = pitch * pitchMultiplier;
m_HighAccel.pitch = pitch * highPitchMultiplier * pitchMultiplier;
m_HighDecel.pitch = pitch * highPitchMultiplier * pitchMultiplier;
float accFade = 0;
float highFade = 0;
if (driveMode == DriveMode.AI)
{
// get values for fading the sounds based on the acceleration
accFade = Mathf.Abs(m_CarController.AccelInput);
highFade = Mathf.InverseLerp(0.2f, 0.8f, m_CarController.Revs);
}
else
{
accFade = Mathf.Abs(playerVehicle.GetThrottle());
highFade = Mathf.InverseLerp(0.2f, 0.8f, playerVehicle.GetThrottle());
}
float decFade = 1 - accFade;
// get the high fade value based on the cars revs
float lowFade = 1 - highFade;
// adjust the values to be more realistic
highFade = 1 - ((1 - highFade) * (1 - highFade));
lowFade = 1 - ((1 - lowFade) * (1 - lowFade));
accFade = 1 - ((1 - accFade) * (1 - accFade));
decFade = 1 - ((1 - decFade) * (1 - decFade));
// adjust the source volumes based on the fade values
m_LowAccel.volume = lowFade * accFade;
m_LowDecel.volume = lowFade * decFade;
m_HighAccel.volume = highFade * accFade;
m_HighDecel.volume = highFade * decFade;
// adjust the doppler levels
m_HighAccel.dopplerLevel = useDoppler ? dopplerLevel : 0;
m_LowAccel.dopplerLevel = useDoppler ? dopplerLevel : 0;
m_HighDecel.dopplerLevel = useDoppler ? dopplerLevel : 0;
m_LowDecel.dopplerLevel = useDoppler ? dopplerLevel : 0;
}
}
}
// sets up and adds new audio source to the gane object
private AudioSource SetUpEngineAudioSource(AudioClip clip)
{
// create the new audio source component on the game object and set up its properties
AudioSource source = gameObject.AddComponent<AudioSource>();
source.spatialBlend = 1;
source.clip = clip;
source.volume = 0;
source.loop = true;
// start the clip from a random point
source.time = Random.Range(0f, clip.length);
source.Play();
source.minDistance = 5;
source.maxDistance = maxRolloffDistance;
source.dopplerLevel = 0;
return source;
}
// unclamped versions of Lerp and Inverse Lerp, to allow value to exceed the from-to range
private static float ULerp(float from, float to, float value)
{
return (1.0f - value) * from + value * to;
}
}
| 42.086364 | 137 | 0.591965 | [
"MIT"
] | archx64/AutonomousDrivingSimulator | Car/Scripts/CarAudio.cs | 9,259 | C# |
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
namespace EmployeeDetails
{
class Crud
{
public static List<Employee> EmployeeList = new List<Employee>();
Employee employee = new Employee();
Validate validate = new Validate();
public void Create()
{
Console.WriteLine("Enter Employee Details");
Console.WriteLine("======================");
FromFirst:
Console.WriteLine("Enter The Employee Id :");
ReId:
string employeeId = Console.ReadLine();
var isvalidId = validate.ValidateId(employeeId);
if (isvalidId)
{
employee.EmployeeId = employeeId;
}
else
{
goto ReId;
}
Console.WriteLine("Enter The Employee Name :");
ReName:
string employeeName = Console.ReadLine();
var isvalidName = validate.ValidateName(employeeName);
if (isvalidName)
{
employee.EmployeeName = employeeName;
}
else
{
goto ReName;
}
Console.WriteLine("Enter The Employee Date Of Birth :");
ReDob:
string dateOfBirth = Console.ReadLine();
var isvalidBirth =validate.ValidateBirth( dateOfBirth);
if (isvalidBirth)
{
employee. DateOfBirth =Convert.ToDateTime( dateOfBirth);
}
else
{
goto ReDob;
}
Console.WriteLine("Enter The Employee Date Of Joining :");
ReDoj:
string dateOfJoining = Console.ReadLine();
string dateBirth =Convert.ToString( employee.DateOfBirth);
var isvalidJoining = validate.ValidateJoining(dateOfJoining,dateBirth);
if (isvalidJoining)
{
employee.DateOfJoining =Convert.ToDateTime( dateOfJoining);
}
else
{
goto ReDoj;
}
Console.WriteLine("Enter 10 Digit Mobile No : ");
ReMobile:
string mobileNo = Console.ReadLine();
var isvalidNo = validate.ValidateMobile(mobileNo);
if (isvalidNo)
{
employee.MobileNumber= Convert.ToInt64(mobileNo);
}
else
{
goto ReMobile;
}
Console.WriteLine("Enter New Mail ID:");
ReMail:
string eMail = Console.ReadLine();
var isvalidMail = validate.ValidateMail(eMail);
if (isvalidMail)
{
employee.EMail = eMail;
}
else
{
goto ReMail;
}
try
{
if (EmployeeList.Exists(Employee => Employee.EmployeeId == employee.EmployeeId))
{
throw new AlreadyExistException();
}
else
{
EmployeeList.Add(employee);
Console.WriteLine("Successfully created");
}
}
catch (AlreadyExistException Exception) {
Console.WriteLine(Exception.Message);
goto FromFirst;
}
}
public static void Read()
{
if (EmployeeList.Count > 0)
{
for (int i = 0; i < EmployeeList.Count; i++)
{
Console.WriteLine(" -----------------");
Console.WriteLine("| Employee detail |");
Console.WriteLine(" -----------------");
Console.WriteLine("Employee Name :{0}\nEmployee Id :{1}\nEmployee DOB :{2}\nEmployee DOJ :{3}\nEmployee Mobile Number:{4} ", EmployeeList[i].EmployeeName, EmployeeList[i].EmployeeId, EmployeeList[i].DateOfBirth.ToShortDateString(), EmployeeList[i].DateOfJoining.ToShortDateString(), EmployeeList[i].MobileNumber);
}
}
else {
Console.WriteLine();
Console.WriteLine("No Records Found");
}
}
public void Update(List<Employee> EmployeeList,Employee UpdateEmployee)
{
bool isupdated = false;
int ModifyNumber=0;
Console.WriteLine("Chose Option for Modify Employee Detail:");
Console.WriteLine("1.Id \n2.Name \n3.dob \n4.Doj \n5.mobilenumber \n6.email ");
try
{
ModifyNumber = Convert.ToInt32(Console.ReadLine());
}
catch (Exception exception)
{
Console.WriteLine(exception.Message);
}
switch (ModifyNumber)
{
case 1:
Console.WriteLine("Enter New Employee Id:");
ReId:
string employeeId = Console.ReadLine();
var isvalidId = validate.ValidateId(employeeId);
if (isvalidId)
{
UpdateEmployee.EmployeeId = employeeId;
isupdated = true;
}
else {
goto ReId;
}
break;
case 2:
Console.WriteLine("Enter New Employee Name:");
ReName:
string employeeName = Console.ReadLine();
var isvalidName = validate.ValidateName(employeeName);
if (isvalidName)
{
UpdateEmployee.EmployeeName = employeeName;
isupdated = true;
}
else
{
goto ReName;
}
break;
case 3:
Console.WriteLine("Enter New Date Of Birth:");
ReDob:
string dateOfBirth =Console.ReadLine();
var isvalidBirth = validate.ValidateBirth(dateOfBirth);
if (isvalidBirth)
{
UpdateEmployee.DateOfBirth = Convert.ToDateTime(dateOfBirth);
isupdated = true;
}
else
{
goto ReDob;
}
break;
case 4:
Console.WriteLine("Enter New Date Of Joining:");
ReDoj:
string dateOfJoining = Console.ReadLine();
string dateBirth = Convert.ToString(employee.DateOfBirth);
var isvalidJoining = validate.ValidateJoining(dateOfJoining, dateBirth);
if (isvalidJoining)
{
UpdateEmployee.DateOfJoining = Convert.ToDateTime(dateOfJoining);
isupdated = true;
}
else
{
goto ReDoj;
}
break;
case 5:
Console.WriteLine("Enter New Mobile Number:");
ReMobile:
string mobileNumber = Console.ReadLine();
var isvalidNo = validate.ValidateMobile(mobileNumber);
if (isvalidNo)
{
UpdateEmployee.MobileNumber = Convert.ToInt64(mobileNumber);
isupdated = true;
}
else
{
goto ReMobile;
}
break;
case 6:
Console.WriteLine("Enter New Mail ID:");
ReMail:
string eMail = Console.ReadLine();
var isvalidMail = validate.ValidateMail(eMail);
if (isvalidMail)
{
UpdateEmployee.EMail = eMail;
isupdated = true;
}
else
{
goto ReMail;
}
break;
}
if (isupdated)
{
Console.WriteLine("successfully updated");
}
else
{
Console.WriteLine("employee not found");
}
}
public static void Delete(List<Employee> EmployeeList, Employee DeleteEmployee)
{
bool isremoved = false;
EmployeeList.Remove(DeleteEmployee);
isremoved = true;
if (isremoved)
{
Console.WriteLine("\nsuccessfully Removed");
}
else {
Console.WriteLine("\nemployee not found");
}
}
}
} | 33.246575 | 334 | 0.415019 | [
"MIT"
] | ajaybharathi0820/EmployeeDetails | Employee/Crud.cs | 9,710 | C# |
using rover.Interfaces;
using System;
using System.Collections.Generic;
using System.Text;
namespace rover.Classes
{
class Position : IPosition
{
public void PrintPosition(Common common)
{
char dir = 'N';
if (common.facing == 1)
{
dir = 'N';
}
else if (common.facing == 2)
{
dir = 'E';
}
else if (common.facing == 3)
{
dir = 'S';
}
else if (common.facing == 4)
{
dir = 'W';
}
if(common.x<= 5 && common.y <= 5)
{
Console.WriteLine(common.x + " " + common.y + " " + dir);
}
}
public Common SetPosition(int x, int y, int facing )
{
Common common = new Common();
common.x = x;
common.y = y;
common.facing = facing;
return common;
}
}
}
| 22.347826 | 73 | 0.395914 | [
"MIT"
] | PersistentGaneshGadekar/rover | rover/Classes/Position.cs | 1,030 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using W_ORM.Layout.Attributes;
namespace W_ORM.MSSQL.Attributes
{
[AttributeUsage(AttributeTargets.Property, Inherited = false, AllowMultiple = false)]
public class NVARCHAR : BaseAttribute
{
public NVARCHAR(int maxLength = 4000) : base("Type","NVARCHAR")
{
this.maxLength = maxLength;
}
private int maxLength;
public int MaxLength
{
get { return maxLength; }
set { maxLength = value; }
}
public override object TypeId => 1000;
}
}
| 24.703704 | 89 | 0.632684 | [
"MIT"
] | bhdryrdm/W-ORM | W-ORM/W-ORM.MSSQL/Attributes/NVARCHAR.cs | 669 | C# |
using System.Collections.Generic;
namespace AdventOfCode
{
public interface ISolver
{
public int Day { get; }
public string Title { get; }
public void Setup();
public IEnumerable<string> Solve();
}
}
| 18.923077 | 43 | 0.609756 | [
"MIT"
] | Abzylicious/advent-of-code-2020 | AdventOfCode/ISolver.cs | 248 | C# |
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using CA.LoopControlPluginBase;
namespace CA_DataUploaderLib
{
public sealed class PluginsCommandHandler : IPluginCommandHandler
{
private readonly CommandHandler cmd;
private readonly List<Action> removeCommandActions = new List<Action>();
private readonly List<EventHandler<NewVectorReceivedArgs>> subscribedNewVectorReceivedEvents = new List<EventHandler<NewVectorReceivedArgs>>();
public PluginsCommandHandler(CommandHandler cmd)
{
this.cmd = cmd;
}
public event EventHandler<NewVectorReceivedArgs> NewVectorReceived
{
add { cmd.NewVectorReceived += value; subscribedNewVectorReceivedEvents.Add(value); }
remove { cmd.NewVectorReceived -= value; subscribedNewVectorReceivedEvents.Remove(value); }
}
public void AddCommand(string name, Func<List<string>, bool> func) => removeCommandActions.Add(cmd.AddCommand(name, func));
public void Execute(string command, bool addToCommandHistory) => cmd.Execute(command, addToCommandHistory);
public async Task<NewVectorReceivedArgs> When(Predicate<NewVectorReceivedArgs> condition, CancellationToken token)
{
var tcs = new TaskCompletionSource<NewVectorReceivedArgs>();
NewVectorReceived += OnNewValue;
try
{
using (CancellationTokenRegistration cancellationTokenRegistration = token.Register(OnCancelled))
return await tcs.Task;
}
finally
{
NewVectorReceived -= OnNewValue;
}
void OnCancelled() => tcs.TrySetCanceled(token);
void OnNewValue(object sender, NewVectorReceivedArgs e)
{
if (condition(e)) tcs.TrySetResult(e);
}
}
public void Dispose()
{// class is sealed without unmanaged resources, no need for the full disposable pattern.
foreach (var subscribedEvent in subscribedNewVectorReceivedEvents.ToArray())
NewVectorReceived -= subscribedEvent;
foreach (var removeAction in removeCommandActions)
removeAction();
}
}
} | 41.928571 | 151 | 0.653322 | [
"MIT"
] | copenhagenatomics/CA_DataUploader | CA_DataUploaderLib/PluginsCommandHandler.cs | 2,348 | C# |
using Moq;
using Ocelot.Infrastructure;
using Ocelot.Logging;
using Ocelot.Provider.Kubernetes;
using Ocelot.ServiceDiscovery.Providers;
using Ocelot.Values;
using Shouldly;
using System;
using System.Collections.Generic;
using System.Text;
using TestStack.BDDfy;
using Xunit;
namespace Ocelot.UnitTests.Kubernetes
{
public class PollingKubeServiceDiscoveryProviderTests
{
private readonly int _delay;
private PollKube _provider;
private readonly List<Service> _services;
private readonly Mock<IOcelotLoggerFactory> _factory;
private readonly Mock<IOcelotLogger> _logger;
private readonly Mock<IServiceDiscoveryProvider> _kubeServiceDiscoveryProvider;
private List<Service> _result;
public PollingKubeServiceDiscoveryProviderTests()
{
_services = new List<Service>();
_delay = 1;
_factory = new Mock<IOcelotLoggerFactory>();
_logger = new Mock<IOcelotLogger>();
_factory.Setup(x => x.CreateLogger<PollKube>()).Returns(_logger.Object);
_kubeServiceDiscoveryProvider = new Mock<IServiceDiscoveryProvider>();
}
[Fact]
public void should_return_service_from_kube()
{
var service = new Service("", new ServiceHostAndPort("", 0), "", "", new List<string>());
this.Given(x => GivenKubeReturns(service))
.When(x => WhenIGetTheServices(1))
.Then(x => ThenTheCountIs(1))
.BDDfy();
}
private void GivenKubeReturns(Service service)
{
_services.Add(service);
_kubeServiceDiscoveryProvider.Setup(x => x.Get()).ReturnsAsync(_services);
}
private void ThenTheCountIs(int count)
{
_result.Count.ShouldBe(count);
}
private void WhenIGetTheServices(int expected)
{
_provider = new PollKube(_delay, _factory.Object, _kubeServiceDiscoveryProvider.Object);
var result = Wait.WaitFor(3000).Until(() => {
try
{
_result = _provider.Get().GetAwaiter().GetResult();
if (_result.Count == expected)
{
return true;
}
return false;
}
catch (Exception)
{
return false;
}
});
result.ShouldBeTrue();
}
}
}
| 30.686747 | 101 | 0.576757 | [
"MIT"
] | akasexdev/Ocelot | test/Ocelot.UnitTests/Kubernetes/PollingKubeServiceDiscoveryProviderTests.cs | 2,549 | C# |
namespace Pic.Plugin.GeneratorCtrl
{
partial class FindAndReplaceForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.label1 = new System.Windows.Forms.Label();
this.lblReplaceWith = new System.Windows.Forms.Label();
this.txtLookFor = new System.Windows.Forms.TextBox();
this.txtReplaceWith = new System.Windows.Forms.TextBox();
this.btnFindNext = new System.Windows.Forms.Button();
this.bnReplace = new System.Windows.Forms.Button();
this.btnReplaceAll = new System.Windows.Forms.Button();
this.chkMatchWholeWord = new System.Windows.Forms.CheckBox();
this.chkMatchCase = new System.Windows.Forms.CheckBox();
this.btnHighlightAll = new System.Windows.Forms.Button();
this.bnCancel = new System.Windows.Forms.Button();
this.btnFindPrevious = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(12, 9);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(56, 13);
this.label1.TabIndex = 0;
this.label1.Text = "Fi&nd what:";
//
// lblReplaceWith
//
this.lblReplaceWith.AutoSize = true;
this.lblReplaceWith.Location = new System.Drawing.Point(12, 35);
this.lblReplaceWith.Name = "lblReplaceWith";
this.lblReplaceWith.Size = new System.Drawing.Size(72, 13);
this.lblReplaceWith.TabIndex = 2;
this.lblReplaceWith.Text = "Re&place with:";
//
// txtLookFor
//
this.txtLookFor.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.txtLookFor.Location = new System.Drawing.Point(90, 6);
this.txtLookFor.Name = "txtLookFor";
this.txtLookFor.Size = new System.Drawing.Size(232, 20);
this.txtLookFor.TabIndex = 1;
//
// txtReplaceWith
//
this.txtReplaceWith.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.txtReplaceWith.Location = new System.Drawing.Point(90, 32);
this.txtReplaceWith.Name = "txtReplaceWith";
this.txtReplaceWith.Size = new System.Drawing.Size(232, 20);
this.txtReplaceWith.TabIndex = 3;
//
// btnFindNext
//
this.btnFindNext.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.btnFindNext.Location = new System.Drawing.Point(247, 80);
this.btnFindNext.Name = "btnFindNext";
this.btnFindNext.Size = new System.Drawing.Size(75, 23);
this.btnFindNext.TabIndex = 6;
this.btnFindNext.Text = "&Find next";
this.btnFindNext.UseVisualStyleBackColor = true;
this.btnFindNext.Click += new System.EventHandler(this.OnBnClickFindNext);
//
// bnReplace
//
this.bnReplace.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.bnReplace.Location = new System.Drawing.Point(77, 110);
this.bnReplace.Name = "bnReplace";
this.bnReplace.Size = new System.Drawing.Size(75, 23);
this.bnReplace.TabIndex = 7;
this.bnReplace.Text = "&Replace";
this.bnReplace.UseVisualStyleBackColor = true;
this.bnReplace.Click += new System.EventHandler(this.OnBnClickReplace);
//
// btnReplaceAll
//
this.btnReplaceAll.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.btnReplaceAll.Location = new System.Drawing.Point(157, 110);
this.btnReplaceAll.Name = "btnReplaceAll";
this.btnReplaceAll.Size = new System.Drawing.Size(84, 23);
this.btnReplaceAll.TabIndex = 9;
this.btnReplaceAll.Text = "Replace &All";
this.btnReplaceAll.UseVisualStyleBackColor = true;
this.btnReplaceAll.Click += new System.EventHandler(this.OnBnClickReplaceAll);
//
// chkMatchWholeWord
//
this.chkMatchWholeWord.AutoSize = true;
this.chkMatchWholeWord.Location = new System.Drawing.Point(178, 58);
this.chkMatchWholeWord.Name = "chkMatchWholeWord";
this.chkMatchWholeWord.Size = new System.Drawing.Size(113, 17);
this.chkMatchWholeWord.TabIndex = 5;
this.chkMatchWholeWord.Text = "Match &whole word";
this.chkMatchWholeWord.UseVisualStyleBackColor = true;
//
// chkMatchCase
//
this.chkMatchCase.AutoSize = true;
this.chkMatchCase.Location = new System.Drawing.Point(90, 58);
this.chkMatchCase.Name = "chkMatchCase";
this.chkMatchCase.Size = new System.Drawing.Size(82, 17);
this.chkMatchCase.TabIndex = 4;
this.chkMatchCase.Text = "Match &case";
this.chkMatchCase.UseVisualStyleBackColor = true;
//
// btnHighlightAll
//
this.btnHighlightAll.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.btnHighlightAll.Location = new System.Drawing.Point(16, 80);
this.btnHighlightAll.Name = "btnHighlightAll";
this.btnHighlightAll.Size = new System.Drawing.Size(136, 23);
this.btnHighlightAll.TabIndex = 8;
this.btnHighlightAll.Text = "Find && highlight &all";
this.btnHighlightAll.UseVisualStyleBackColor = true;
this.btnHighlightAll.Visible = false;
this.btnHighlightAll.Click += new System.EventHandler(this.OnBnClickHighlightAll);
//
// bnCancel
//
this.bnCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.bnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.bnCancel.Location = new System.Drawing.Point(247, 110);
this.bnCancel.Name = "bnCancel";
this.bnCancel.Size = new System.Drawing.Size(75, 23);
this.bnCancel.TabIndex = 6;
this.bnCancel.Text = "Cancel";
this.bnCancel.UseVisualStyleBackColor = true;
this.bnCancel.Click += new System.EventHandler(this.OnCancel);
//
// btnFindPrevious
//
this.btnFindPrevious.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.btnFindPrevious.Location = new System.Drawing.Point(157, 80);
this.btnFindPrevious.Name = "btnFindPrevious";
this.btnFindPrevious.Size = new System.Drawing.Size(84, 23);
this.btnFindPrevious.TabIndex = 6;
this.btnFindPrevious.Text = "Find pre&vious";
this.btnFindPrevious.UseVisualStyleBackColor = true;
this.btnFindPrevious.Click += new System.EventHandler(this.OnBnClickFindPrevious);
//
// FindAndReplaceForm
//
this.AcceptButton = this.bnReplace;
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.CancelButton = this.bnCancel;
this.ClientSize = new System.Drawing.Size(334, 145);
this.Controls.Add(this.chkMatchCase);
this.Controls.Add(this.chkMatchWholeWord);
this.Controls.Add(this.btnReplaceAll);
this.Controls.Add(this.bnReplace);
this.Controls.Add(this.btnHighlightAll);
this.Controls.Add(this.bnCancel);
this.Controls.Add(this.btnFindPrevious);
this.Controls.Add(this.btnFindNext);
this.Controls.Add(this.txtReplaceWith);
this.Controls.Add(this.txtLookFor);
this.Controls.Add(this.lblReplaceWith);
this.Controls.Add(this.label1);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "FindAndReplaceForm";
this.ShowIcon = false;
this.Text = "Find and replace";
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.OnFormClocsing);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label lblReplaceWith;
private System.Windows.Forms.TextBox txtLookFor;
private System.Windows.Forms.TextBox txtReplaceWith;
private System.Windows.Forms.Button btnFindNext;
private System.Windows.Forms.Button bnReplace;
private System.Windows.Forms.Button btnReplaceAll;
private System.Windows.Forms.CheckBox chkMatchWholeWord;
private System.Windows.Forms.CheckBox chkMatchCase;
private System.Windows.Forms.Button btnHighlightAll;
private System.Windows.Forms.Button bnCancel;
private System.Windows.Forms.Button btnFindPrevious;
}
} | 49.52093 | 166 | 0.629379 | [
"MIT"
] | treeDiM/PackLib4ES | Sources/Libraries/Pic.Plugin.GeneratorCtrl/FindAndReplaceForm.Designer.cs | 10,649 | C# |
using System;
using NetRuntimeSystem = System;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.ComponentModel;
using System.Reflection;
using System.Collections.Generic;
using NetOffice;
namespace NetOffice.PublisherApi
{
///<summary>
/// DispatchInterface Plate
/// SupportByVersion Publisher, 14,15,16
///</summary>
[SupportByVersionAttribute("Publisher", 14,15,16)]
[EntityTypeAttribute(EntityType.IsDispatchInterface)]
public class Plate : COMObject
{
#pragma warning disable
#region Type Information
private static Type _type;
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public static Type LateBindingApiWrapperType
{
get
{
if (null == _type)
_type = typeof(Plate);
return _type;
}
}
#endregion
#region Construction
///<param name="factory">current used factory core</param>
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
public Plate(Core factory, ICOMObject parentObject, object comProxy) : base(factory, parentObject, comProxy)
{
}
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public Plate(ICOMObject parentObject, object comProxy) : base(parentObject, comProxy)
{
}
///<param name="factory">current used factory core</param>
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
///<param name="comProxyType">Type of inner wrapped COM proxy"</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public Plate(Core factory, ICOMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(factory, parentObject, comProxy, comProxyType)
{
}
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
///<param name="comProxyType">Type of inner wrapped COM proxy"</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public Plate(ICOMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(parentObject, comProxy, comProxyType)
{
}
///<param name="replacedObject">object to replaced. replacedObject are not usable after this action</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public Plate(ICOMObject replacedObject) : base(replacedObject)
{
}
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public Plate() : base()
{
}
/// <param name="progId">registered ProgID</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public Plate(string progId) : base(progId)
{
}
#endregion
#region Properties
/// <summary>
/// SupportByVersion Publisher 14, 15, 16
/// Get/Set
/// </summary>
[SupportByVersionAttribute("Publisher", 14,15,16)]
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public Int32 Angle
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "Angle", paramsArray);
return NetRuntimeSystem.Convert.ToInt32(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "Angle", paramsArray);
}
}
/// <summary>
/// SupportByVersion Publisher 14, 15, 16
/// Get
/// </summary>
[SupportByVersionAttribute("Publisher", 14,15,16)]
public NetOffice.PublisherApi.Application Application
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "Application", paramsArray);
NetOffice.PublisherApi.Application newObject = Factory.CreateKnownObjectFromComProxy(this,returnItem,NetOffice.PublisherApi.Application.LateBindingApiWrapperType) as NetOffice.PublisherApi.Application;
return newObject;
}
}
/// <summary>
/// SupportByVersion Publisher 14, 15, 16
/// Get
/// </summary>
[SupportByVersionAttribute("Publisher", 14,15,16)]
public NetOffice.PublisherApi.ColorFormat Color
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "Color", paramsArray);
NetOffice.PublisherApi.ColorFormat newObject = Factory.CreateKnownObjectFromComProxy(this,returnItem,NetOffice.PublisherApi.ColorFormat.LateBindingApiWrapperType) as NetOffice.PublisherApi.ColorFormat;
return newObject;
}
}
/// <summary>
/// SupportByVersion Publisher 14, 15, 16
/// Get/Set
/// </summary>
[SupportByVersionAttribute("Publisher", 14,15,16)]
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public Int32 Frequency
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "Frequency", paramsArray);
return NetRuntimeSystem.Convert.ToInt32(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "Frequency", paramsArray);
}
}
/// <summary>
/// SupportByVersion Publisher 14, 15, 16
/// Get
/// </summary>
[SupportByVersionAttribute("Publisher", 14,15,16)]
public Int32 Index
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "Index", paramsArray);
return NetRuntimeSystem.Convert.ToInt32(returnItem);
}
}
/// <summary>
/// SupportByVersion Publisher 14, 15, 16
/// Get/Set
/// </summary>
[SupportByVersionAttribute("Publisher", 14,15,16)]
public Int32 Luminance
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "Luminance", paramsArray);
return NetRuntimeSystem.Convert.ToInt32(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "Luminance", paramsArray);
}
}
/// <summary>
/// SupportByVersion Publisher 14, 15, 16
/// Get
/// </summary>
[SupportByVersionAttribute("Publisher", 14,15,16)]
public string Name
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "Name", paramsArray);
return NetRuntimeSystem.Convert.ToString(returnItem);
}
}
/// <summary>
/// SupportByVersion Publisher 14, 15, 16
/// Get
/// Unknown COM Proxy
/// </summary>
[SupportByVersionAttribute("Publisher", 14,15,16)]
public object Parent
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "Parent", paramsArray);
ICOMObject newObject = Factory.CreateObjectFromComProxy(this,returnItem);
return newObject;
}
}
/// <summary>
/// SupportByVersion Publisher 14, 15, 16
/// Get
/// </summary>
[SupportByVersionAttribute("Publisher", 14,15,16)]
public bool InUse
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "InUse", paramsArray);
return NetRuntimeSystem.Convert.ToBoolean(returnItem);
}
}
/// <summary>
/// SupportByVersion Publisher 14, 15, 16
/// Get
/// </summary>
[SupportByVersionAttribute("Publisher", 14,15,16)]
public NetOffice.PublisherApi.Enums.PbInkName InkName
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "InkName", paramsArray);
int intReturnItem = NetRuntimeSystem.Convert.ToInt32(returnItem);
return (NetOffice.PublisherApi.Enums.PbInkName)intReturnItem;
}
}
#endregion
#region Methods
/// <summary>
/// SupportByVersion Publisher 14, 15, 16
///
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
[SupportByVersionAttribute("Publisher", 14,15,16)]
public void Delete10()
{
object[] paramsArray = null;
Invoker.Method(this, "Delete10", paramsArray);
}
/// <summary>
/// SupportByVersion Publisher 14, 15, 16
///
/// </summary>
/// <param name="plateReplaceWith">optional object PlateReplaceWith</param>
/// <param name="replaceTint">optional NetOffice.PublisherApi.Enums.PbReplaceTint ReplaceTint = 0</param>
[SupportByVersionAttribute("Publisher", 14,15,16)]
public void Delete(object plateReplaceWith, object replaceTint)
{
object[] paramsArray = Invoker.ValidateParamsArray(plateReplaceWith, replaceTint);
Invoker.Method(this, "Delete", paramsArray);
}
/// <summary>
/// SupportByVersion Publisher 14, 15, 16
///
/// </summary>
[CustomMethodAttribute]
[SupportByVersionAttribute("Publisher", 14,15,16)]
public void Delete()
{
object[] paramsArray = null;
Invoker.Method(this, "Delete", paramsArray);
}
/// <summary>
/// SupportByVersion Publisher 14, 15, 16
///
/// </summary>
/// <param name="plateReplaceWith">optional object PlateReplaceWith</param>
[CustomMethodAttribute]
[SupportByVersionAttribute("Publisher", 14,15,16)]
public void Delete(object plateReplaceWith)
{
object[] paramsArray = Invoker.ValidateParamsArray(plateReplaceWith);
Invoker.Method(this, "Delete", paramsArray);
}
/// <summary>
/// SupportByVersion Publisher 14, 15, 16
///
/// </summary>
[SupportByVersionAttribute("Publisher", 14,15,16)]
public void ConvertToProcess()
{
object[] paramsArray = null;
Invoker.Method(this, "ConvertToProcess", paramsArray);
}
#endregion
#pragma warning restore
}
} | 29.02994 | 205 | 0.690594 | [
"MIT"
] | brunobola/NetOffice | Source/Publisher/DispatchInterfaces/Plate.cs | 9,698 | C# |
using System.Threading;
using System.Threading.Tasks;
using Application.Exceptions;
using Application.Interfaces.Persistence.Main;
using Application.Modules.Containers.Models;
using Domain.Entities;
using Mapster;
using MediatR;
namespace Application.Modules.Containers.Queries
{
public class GetContainerByIdQuery : IRequest<ContainerDto>
{
public GetContainerByIdQuery(int containerId)
{
ContainerId = containerId;
}
public int ContainerId { get; set; }
}
public class GetContainerByIdQueryHandler : IRequestHandler<GetContainerByIdQuery, ContainerDto>
{
private readonly IMainAsyncRepository<Container> _repository;
public GetContainerByIdQueryHandler(IMainAsyncRepository<Container> repository)
{
_repository = repository;
}
public async Task<ContainerDto> Handle(GetContainerByIdQuery request, CancellationToken cancellationToken)
{
var container = await _repository.GetByIdAsync(request.ContainerId);
if (container is null)
throw new NotFoundException(nameof(Container), request.ContainerId);
return container.Adapt<ContainerDto>();
}
}
} | 30.219512 | 114 | 0.706215 | [
"MIT"
] | kerem-acer/basic-cms | src/Application/Modules/Containers/Queries/GetContainerByIdQuery.cs | 1,239 | C# |
namespace Merchello.Core.Models
{
using System;
using System.Runtime.Serialization;
using Merchello.Core.Models.EntityBase;
/// <summary>
/// Defines a note.
/// </summary>
public interface INote : IEntity
{
/// <summary>
/// Gets or sets the entity key related to the note
/// </summary>
[DataMember]
Guid EntityKey { get; set; }
/// <summary>
/// Gets or sets the entity type field key.
/// </summary>
[DataMember]
Guid EntityTfKey { get; set; }
/// <summary>
/// Gets or sets the author.
/// </summary>
[DataMember]
string Author { get; set; }
/// <summary>
/// Gets or sets the message.
/// </summary>
[DataMember]
string Message { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the not is for internal use only.
/// </summary>
[DataMember]
bool InternalOnly { get; set; }
}
} | 23.795455 | 85 | 0.518625 | [
"MIT"
] | ryanology/Merchello | src/Merchello.Core/Models/Interfaces/INote.cs | 1,049 | C# |
using SmartSql.Reflection.TypeConstants;
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Reflection;
using System.Reflection.Emit;
using System.Text;
using SmartSql.Utils;
namespace SmartSql.Reflection.PropertyAccessor
{
public class EmitSetAccessorFactory : ISetAccessorFactory
{
public static readonly ISetAccessorFactory Instance = new EmitSetAccessorFactory();
private EmitSetAccessorFactory()
{
}
public Action<object, object> Create(Type targetType, string propertyName)
{
var propertyInfo = targetType.GetProperty(propertyName);
return Create(propertyInfo);
}
public Action<object, object> Create(PropertyInfo propertyInfo)
{
return CacheUtil<EmitSetAccessorFactory, PropertyInfo, Action<object, object>>
.GetOrAdd(propertyInfo, CreateImpl);
}
private Action<object, object> CreateImpl(PropertyInfo propertyInfo)
{
var dynamicMethod = new DynamicMethod("Set_" + Guid.NewGuid().ToString("N"), null, new[] { CommonType.Object, CommonType.Object }, propertyInfo.DeclaringType, true);
var ilGen = dynamicMethod.GetILGenerator();
ilGen.LoadArg(0);
ilGen.LoadArg(1);
if (propertyInfo.PropertyType.IsValueType)
{
ilGen.Unbox(propertyInfo.PropertyType);
ilGen.LoadValueIndirect(propertyInfo.PropertyType);
}
ilGen.Call(propertyInfo.SetMethod);
ilGen.Return();
return (Action<object, object>)dynamicMethod.CreateDelegate(typeof(Action<object, object>));
}
}
}
| 36.041667 | 177 | 0.658382 | [
"Apache-2.0"
] | Ahoo-Wang/SmartSql | src/SmartSql/Reflection/PropertyAccessor/EmitSetAccessorFactory.cs | 1,732 | C# |
#region Copyright
//
// DotNetNuke® - https://www.dnnsoftware.com
// Copyright (c) 2002-2018
// by DotNetNuke Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and
// to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions
// of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
#endregion
#region Usings
using System;
#endregion
namespace DotNetNuke.Services.Scheduling
{
public class PurgeScheduleHistory : SchedulerClient
{
public PurgeScheduleHistory(ScheduleHistoryItem objScheduleHistoryItem)
{
ScheduleHistoryItem = objScheduleHistoryItem;
}
public override void DoWork()
{
try
{
//notification that the event is progressing
Progressing();
SchedulingProvider.Instance().PurgeScheduleHistory();
//update the result to success since no exception was thrown
ScheduleHistoryItem.Succeeded = true;
ScheduleHistoryItem.AddLogNote("Schedule history purged.");
}
catch (Exception exc)
{
ScheduleHistoryItem.Succeeded = false;
ScheduleHistoryItem.AddLogNote("Schedule history purge failed." + exc);
ScheduleHistoryItem.Succeeded = false;
//notification that we have errored
Errored(ref exc);
//log the exception
Exceptions.Exceptions.LogException(exc);
}
}
}
} | 38.539683 | 116 | 0.671746 | [
"MIT"
] | Mhtshum/Dnn.Platform | DNN Platform/Library/Services/Scheduling/PurgeScheduleHistory.cs | 2,429 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the rds-2014-10-31.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.RDS.Model
{
/// <summary>
/// Available option.
/// </summary>
public partial class OptionGroupOption
{
private int? _defaultPort;
private string _description;
private string _engineName;
private string _majorEngineVersion;
private string _minimumRequiredMinorEngineVersion;
private string _name;
private List<OptionGroupOptionSetting> _optionGroupOptionSettings = new List<OptionGroupOptionSetting>();
private List<OptionVersion> _optionGroupOptionVersions = new List<OptionVersion>();
private List<string> _optionsConflictsWith = new List<string>();
private List<string> _optionsDependedOn = new List<string>();
private bool? _permanent;
private bool? _persistent;
private bool? _portRequired;
private bool? _requiresAutoMinorEngineVersionUpgrade;
private bool? _supportsOptionVersionDowngrade;
private bool? _vpcOnly;
/// <summary>
/// Gets and sets the property DefaultPort.
/// <para>
/// If the option requires a port, specifies the default port for the option.
/// </para>
/// </summary>
public int DefaultPort
{
get { return this._defaultPort.GetValueOrDefault(); }
set { this._defaultPort = value; }
}
// Check to see if DefaultPort property is set
internal bool IsSetDefaultPort()
{
return this._defaultPort.HasValue;
}
/// <summary>
/// Gets and sets the property Description.
/// <para>
/// The description of the option.
/// </para>
/// </summary>
public string Description
{
get { return this._description; }
set { this._description = value; }
}
// Check to see if Description property is set
internal bool IsSetDescription()
{
return this._description != null;
}
/// <summary>
/// Gets and sets the property EngineName.
/// <para>
/// The name of the engine that this option can be applied to.
/// </para>
/// </summary>
public string EngineName
{
get { return this._engineName; }
set { this._engineName = value; }
}
// Check to see if EngineName property is set
internal bool IsSetEngineName()
{
return this._engineName != null;
}
/// <summary>
/// Gets and sets the property MajorEngineVersion.
/// <para>
/// Indicates the major engine version that the option is available for.
/// </para>
/// </summary>
public string MajorEngineVersion
{
get { return this._majorEngineVersion; }
set { this._majorEngineVersion = value; }
}
// Check to see if MajorEngineVersion property is set
internal bool IsSetMajorEngineVersion()
{
return this._majorEngineVersion != null;
}
/// <summary>
/// Gets and sets the property MinimumRequiredMinorEngineVersion.
/// <para>
/// The minimum required engine version for the option to be applied.
/// </para>
/// </summary>
public string MinimumRequiredMinorEngineVersion
{
get { return this._minimumRequiredMinorEngineVersion; }
set { this._minimumRequiredMinorEngineVersion = value; }
}
// Check to see if MinimumRequiredMinorEngineVersion property is set
internal bool IsSetMinimumRequiredMinorEngineVersion()
{
return this._minimumRequiredMinorEngineVersion != null;
}
/// <summary>
/// Gets and sets the property Name.
/// <para>
/// The name of the option.
/// </para>
/// </summary>
public string Name
{
get { return this._name; }
set { this._name = value; }
}
// Check to see if Name property is set
internal bool IsSetName()
{
return this._name != null;
}
/// <summary>
/// Gets and sets the property OptionGroupOptionSettings.
/// <para>
/// The option settings that are available (and the default value) for each option in
/// an option group.
/// </para>
/// </summary>
public List<OptionGroupOptionSetting> OptionGroupOptionSettings
{
get { return this._optionGroupOptionSettings; }
set { this._optionGroupOptionSettings = value; }
}
// Check to see if OptionGroupOptionSettings property is set
internal bool IsSetOptionGroupOptionSettings()
{
return this._optionGroupOptionSettings != null && this._optionGroupOptionSettings.Count > 0;
}
/// <summary>
/// Gets and sets the property OptionGroupOptionVersions.
/// <para>
/// The versions that are available for the option.
/// </para>
/// </summary>
public List<OptionVersion> OptionGroupOptionVersions
{
get { return this._optionGroupOptionVersions; }
set { this._optionGroupOptionVersions = value; }
}
// Check to see if OptionGroupOptionVersions property is set
internal bool IsSetOptionGroupOptionVersions()
{
return this._optionGroupOptionVersions != null && this._optionGroupOptionVersions.Count > 0;
}
/// <summary>
/// Gets and sets the property OptionsConflictsWith.
/// <para>
/// The options that conflict with this option.
/// </para>
/// </summary>
public List<string> OptionsConflictsWith
{
get { return this._optionsConflictsWith; }
set { this._optionsConflictsWith = value; }
}
// Check to see if OptionsConflictsWith property is set
internal bool IsSetOptionsConflictsWith()
{
return this._optionsConflictsWith != null && this._optionsConflictsWith.Count > 0;
}
/// <summary>
/// Gets and sets the property OptionsDependedOn.
/// <para>
/// The options that are prerequisites for this option.
/// </para>
/// </summary>
public List<string> OptionsDependedOn
{
get { return this._optionsDependedOn; }
set { this._optionsDependedOn = value; }
}
// Check to see if OptionsDependedOn property is set
internal bool IsSetOptionsDependedOn()
{
return this._optionsDependedOn != null && this._optionsDependedOn.Count > 0;
}
/// <summary>
/// Gets and sets the property Permanent.
/// <para>
/// Permanent options can never be removed from an option group. An option group containing
/// a permanent option can't be removed from a DB instance.
/// </para>
/// </summary>
public bool Permanent
{
get { return this._permanent.GetValueOrDefault(); }
set { this._permanent = value; }
}
// Check to see if Permanent property is set
internal bool IsSetPermanent()
{
return this._permanent.HasValue;
}
/// <summary>
/// Gets and sets the property Persistent.
/// <para>
/// Persistent options can't be removed from an option group while DB instances are associated
/// with the option group. If you disassociate all DB instances from the option group,
/// your can remove the persistent option from the option group.
/// </para>
/// </summary>
public bool Persistent
{
get { return this._persistent.GetValueOrDefault(); }
set { this._persistent = value; }
}
// Check to see if Persistent property is set
internal bool IsSetPersistent()
{
return this._persistent.HasValue;
}
/// <summary>
/// Gets and sets the property PortRequired.
/// <para>
/// Specifies whether the option requires a port.
/// </para>
/// </summary>
public bool PortRequired
{
get { return this._portRequired.GetValueOrDefault(); }
set { this._portRequired = value; }
}
// Check to see if PortRequired property is set
internal bool IsSetPortRequired()
{
return this._portRequired.HasValue;
}
/// <summary>
/// Gets and sets the property RequiresAutoMinorEngineVersionUpgrade.
/// <para>
/// If true, you must enable the Auto Minor Version Upgrade setting for your DB instance
/// before you can use this option. You can enable Auto Minor Version Upgrade when you
/// first create your DB instance, or by modifying your DB instance later.
/// </para>
/// </summary>
public bool RequiresAutoMinorEngineVersionUpgrade
{
get { return this._requiresAutoMinorEngineVersionUpgrade.GetValueOrDefault(); }
set { this._requiresAutoMinorEngineVersionUpgrade = value; }
}
// Check to see if RequiresAutoMinorEngineVersionUpgrade property is set
internal bool IsSetRequiresAutoMinorEngineVersionUpgrade()
{
return this._requiresAutoMinorEngineVersionUpgrade.HasValue;
}
/// <summary>
/// Gets and sets the property SupportsOptionVersionDowngrade.
/// <para>
/// If true, you can change the option to an earlier version of the option. This only
/// applies to options that have different versions available.
/// </para>
/// </summary>
public bool SupportsOptionVersionDowngrade
{
get { return this._supportsOptionVersionDowngrade.GetValueOrDefault(); }
set { this._supportsOptionVersionDowngrade = value; }
}
// Check to see if SupportsOptionVersionDowngrade property is set
internal bool IsSetSupportsOptionVersionDowngrade()
{
return this._supportsOptionVersionDowngrade.HasValue;
}
/// <summary>
/// Gets and sets the property VpcOnly.
/// <para>
/// If true, you can only use this option with a DB instance that is in a VPC.
/// </para>
/// </summary>
public bool VpcOnly
{
get { return this._vpcOnly.GetValueOrDefault(); }
set { this._vpcOnly = value; }
}
// Check to see if VpcOnly property is set
internal bool IsSetVpcOnly()
{
return this._vpcOnly.HasValue;
}
}
} | 33.936963 | 113 | 0.591776 | [
"Apache-2.0"
] | ChristopherButtars/aws-sdk-net | sdk/src/Services/RDS/Generated/Model/OptionGroupOption.cs | 11,844 | C# |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
using System;
using System.Collections.Generic;
using Aliyun.Acs.Core.Transform;
using Aliyun.Acs.adb.Model.V20190315;
namespace Aliyun.Acs.adb.Transform.V20190315
{
public class BindDBResourcePoolWithUserResponseUnmarshaller
{
public static BindDBResourcePoolWithUserResponse Unmarshall(UnmarshallerContext _ctx)
{
BindDBResourcePoolWithUserResponse bindDBResourcePoolWithUserResponse = new BindDBResourcePoolWithUserResponse();
bindDBResourcePoolWithUserResponse.HttpResponse = _ctx.HttpResponse;
bindDBResourcePoolWithUserResponse.RequestId = _ctx.StringValue("BindDBResourcePoolWithUser.RequestId");
return bindDBResourcePoolWithUserResponse;
}
}
}
| 38.175 | 117 | 0.772757 | [
"Apache-2.0"
] | AxiosCros/aliyun-openapi-net-sdk | aliyun-net-sdk-adb/Adb/Transform/V20190315/BindDBResourcePoolWithUserResponseUnmarshaller.cs | 1,527 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the fms-2018-01-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Amazon.FMS.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.FMS.Model.Internal.MarshallTransformations
{
/// <summary>
/// AppsListData Marshaller
/// </summary>
public class AppsListDataMarshaller : IRequestMarshaller<AppsListData, JsonMarshallerContext>
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="requestObject"></param>
/// <param name="context"></param>
/// <returns></returns>
public void Marshall(AppsListData requestObject, JsonMarshallerContext context)
{
if(requestObject.IsSetAppsList())
{
context.Writer.WritePropertyName("AppsList");
context.Writer.WriteArrayStart();
foreach(var requestObjectAppsListListValue in requestObject.AppsList)
{
context.Writer.WriteObjectStart();
var marshaller = AppMarshaller.Instance;
marshaller.Marshall(requestObjectAppsListListValue, context);
context.Writer.WriteObjectEnd();
}
context.Writer.WriteArrayEnd();
}
if(requestObject.IsSetCreateTime())
{
context.Writer.WritePropertyName("CreateTime");
context.Writer.Write(requestObject.CreateTime);
}
if(requestObject.IsSetLastUpdateTime())
{
context.Writer.WritePropertyName("LastUpdateTime");
context.Writer.Write(requestObject.LastUpdateTime);
}
if(requestObject.IsSetListId())
{
context.Writer.WritePropertyName("ListId");
context.Writer.Write(requestObject.ListId);
}
if(requestObject.IsSetListName())
{
context.Writer.WritePropertyName("ListName");
context.Writer.Write(requestObject.ListName);
}
if(requestObject.IsSetListUpdateToken())
{
context.Writer.WritePropertyName("ListUpdateToken");
context.Writer.Write(requestObject.ListUpdateToken);
}
if(requestObject.IsSetPreviousAppsList())
{
context.Writer.WritePropertyName("PreviousAppsList");
context.Writer.WriteObjectStart();
foreach (var requestObjectPreviousAppsListKvp in requestObject.PreviousAppsList)
{
context.Writer.WritePropertyName(requestObjectPreviousAppsListKvp.Key);
var requestObjectPreviousAppsListValue = requestObjectPreviousAppsListKvp.Value;
context.Writer.WriteArrayStart();
foreach(var requestObjectPreviousAppsListValueListValue in requestObjectPreviousAppsListValue)
{
context.Writer.WriteObjectStart();
var marshaller = AppMarshaller.Instance;
marshaller.Marshall(requestObjectPreviousAppsListValueListValue, context);
context.Writer.WriteObjectEnd();
}
context.Writer.WriteArrayEnd();
}
context.Writer.WriteObjectEnd();
}
}
/// <summary>
/// Singleton Marshaller.
/// </summary>
public readonly static AppsListDataMarshaller Instance = new AppsListDataMarshaller();
}
} | 37.301587 | 115 | 0.595532 | [
"Apache-2.0"
] | philasmar/aws-sdk-net | sdk/src/Services/FMS/Generated/Model/Internal/MarshallTransformations/AppsListDataMarshaller.cs | 4,700 | C# |
using System;
using System.Collections.Generic;
using InfectedRose.Luz;
using InfectedRose.Lvl;
namespace InfectedRose.Utilities
{
public static class LuzFileExtensions
{
public static uint GenerateChecksum(this LuzFile @this, List<LvlFile> scenes)
{
if (@this.Scenes.Length != scenes.Count)
{
throw new ArgumentOutOfRangeException(nameof(scenes), "The count of scenes has to equal the count of scenes in this luz file.");
}
uint value = ushort.MaxValue; // For checksum calculations
uint total = ushort.MaxValue; // Sum of all changes applied to value
var zoneLayer = new ChecksumLayer
{
Id = uint.MaxValue,
Layer = default,
Revision = @this.RevisionNumber
};
zoneLayer.Apply(ref value, ref total);
for (var index = 0; index < scenes.Count; index++)
{
var scene = scenes[index];
var lvl = @this.Scenes[index];
//
// Get revision
//
var revision = scene.LevelInfo?.RevisionNumber ?? scene.OldLevelHeader.Revision;
//
// Get layer
//
var sceneLayer = new ChecksumLayer
{
Id = lvl.SceneId,
Layer = lvl.LayerId,
Revision = revision
};
sceneLayer.Apply(ref value, ref total);
}
//
// Get final checksum
//
var lower = (ushort) ((value & ushort.MaxValue) + (value >> 16));
var upper = (ushort) ((total & ushort.MaxValue) + (total >> 16));
//
// The checksum has two parts, one for the 'total', and one for the 'value', these combine to form a 32bit value
//
return (uint) (upper << 16 | lower);
}
}
} | 30.794118 | 144 | 0.481375 | [
"MIT"
] | UchuServer/InfectedRose | InfectedRose.Utilities/Extensions/LuzFileExtensions.cs | 2,094 | C# |
namespace PythonSharp.Tests.Commands
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using PythonSharp.Commands;
using PythonSharp.Expressions;
using PythonSharp.Language;
using PythonSharp.Tests.Classes;
[TestClass]
public class SetAttributeCommandTests
{
[TestMethod]
public void SetAttributeInDynamicObject()
{
BindingEnvironment environment = new BindingEnvironment();
DefinedClass klass = new DefinedClass("Spam");
DynamicObject dynobj = new DynamicObject(klass);
environment.SetValue("foo", dynobj);
SetAttributeCommand command = new SetAttributeCommand(new NameExpression("foo"), "one", new ConstantExpression(1));
command.Execute(environment);
Assert.IsTrue(dynobj.HasValue("one"));
Assert.AreEqual(1, dynobj.GetValue("one"));
}
[TestMethod]
public void SetAttributeInNativeObject()
{
BindingEnvironment environment = new BindingEnvironment();
Person adam = new Person();
environment.SetValue("adam", adam);
SetAttributeCommand command = new SetAttributeCommand(new NameExpression("adam"), "FirstName", new ConstantExpression("Adam"));
command.Execute(environment);
Assert.AreEqual("Adam", adam.FirstName);
}
}
}
| 33.021277 | 140 | 0.62951 | [
"MIT"
] | ajlopez/PythonSharp | Src/PythonSharp.Tests/Commands/SetAttributeCommandTests.cs | 1,554 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
namespace SIPSorcery.GB28181.Persistence {
public abstract class QueryProvider : IQueryProvider {
protected QueryProvider() { }
IQueryable<S> IQueryProvider.CreateQuery<S>(Expression expression) {
return new Query<S>(this, expression);
}
IQueryable IQueryProvider.CreateQuery(Expression expression) {
Type elementType = TypeSystem.GetElementType(expression.Type);
try {
return (IQueryable)Activator.CreateInstance(typeof(Query<>).MakeGenericType(elementType), new object[] { this, expression });
}
catch (TargetInvocationException tie) {
throw tie.InnerException;
}
}
S IQueryProvider.Execute<S>(Expression expression) {
return (S)this.Execute(expression);
}
object IQueryProvider.Execute(Expression expression) {
return this.Execute(expression);
}
public abstract string GetQueryText(Expression expression);
public abstract object Execute(Expression expression);
}
}
| 30.341463 | 141 | 0.656752 | [
"BSD-2-Clause"
] | 7956968/gb28181-sip | SIPSorcery.28181/Persistence/LINQtoData/QueryProvider.cs | 1,246 | C# |
namespace NightLight
{
interface ITool
{
/// <summary>
/// Sets up the tool
/// </summary>
/// <param name="target">The targets IP address</param>
/// <param name="port">The targets port</param>
/// <param name="connections">Amount of connections that should be connected to the target. Can also be used as amount of packets</param>
/// <param name="timeout">The maximum time the tool is allowed to run. When the timeout is done, the tool would stop running</param>
void Init(string target, int port, int connections, int timeout);
/// <summary>
/// Starts the tool
/// </summary>
void Start();
/// <summary>
/// Gets a bool on wether the tool is timed out and should be terminated
/// </summary>
bool IsTimedOut { get; }
/// <summary>
/// Aborts the tools run-time
/// </summary>
void Abort();
/// <summary>
/// Gets the status to the console when it is cycled each 100ms from the GUI thread
/// </summary>
/// <returns>Returns a string that shall be written to the console of the tools state</returns>
string GetStatus();
}
}
| 35.555556 | 146 | 0.561719 | [
"Unlicense"
] | Taco-Gestapo/project-breakfast | ITool.cs | 1,282 | 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.Synapse.V20210401Preview.Outputs
{
[OutputType]
public sealed class WorkspaceRepositoryConfigurationResponse
{
/// <summary>
/// Account name
/// </summary>
public readonly string? AccountName;
/// <summary>
/// Collaboration branch
/// </summary>
public readonly string? CollaborationBranch;
/// <summary>
/// GitHub Enterprise host name. For example: https://github.mydomain.com
/// </summary>
public readonly string? HostName;
/// <summary>
/// The last commit ID
/// </summary>
public readonly string? LastCommitId;
/// <summary>
/// VSTS project name
/// </summary>
public readonly string? ProjectName;
/// <summary>
/// Repository name
/// </summary>
public readonly string? RepositoryName;
/// <summary>
/// Root folder to use in the repository
/// </summary>
public readonly string? RootFolder;
/// <summary>
/// The VSTS tenant ID
/// </summary>
public readonly string? TenantId;
/// <summary>
/// Type of workspace repositoryID configuration. Example WorkspaceVSTSConfiguration, WorkspaceGitHubConfiguration
/// </summary>
public readonly string? Type;
[OutputConstructor]
private WorkspaceRepositoryConfigurationResponse(
string? accountName,
string? collaborationBranch,
string? hostName,
string? lastCommitId,
string? projectName,
string? repositoryName,
string? rootFolder,
string? tenantId,
string? type)
{
AccountName = accountName;
CollaborationBranch = collaborationBranch;
HostName = hostName;
LastCommitId = lastCommitId;
ProjectName = projectName;
RepositoryName = repositoryName;
RootFolder = rootFolder;
TenantId = tenantId;
Type = type;
}
}
}
| 28.905882 | 122 | 0.584453 | [
"Apache-2.0"
] | sebtelko/pulumi-azure-native | sdk/dotnet/Synapse/V20210401Preview/Outputs/WorkspaceRepositoryConfigurationResponse.cs | 2,457 | C# |
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace WebAssembly.Instructions;
/// <summary>
/// Tests the <see cref="Int64CountOneBits"/> instruction.
/// </summary>
[TestClass]
public class Int64CountOneBitsTests
{
/// <summary>
/// Tests compilation and execution of the <see cref="Int64CountOneBits"/> instruction.
/// </summary>
[TestMethod]
public void Int64CountOneBits_Compiled()
{
var exports = CompilerTestBase<long>.CreateInstance(
new LocalGet(0),
new Int64CountOneBits(),
new End());
//Test cases from https://github.com/WebAssembly/spec/blob/f1b89dfaf379060c7e35eb90b7daeb14d4ade3f7/test/core/i64.wast
Assert.AreEqual(64, exports.Test(-1));
Assert.AreEqual(0, exports.Test(0));
Assert.AreEqual(1, exports.Test(0x00008000));
Assert.AreEqual(4, exports.Test(unchecked((long)0x8000800080008000)));
Assert.AreEqual(63, exports.Test(0x7fffffffffffffff));
Assert.AreEqual(32, exports.Test(unchecked((long)0xAAAAAAAA55555555)));
Assert.AreEqual(32, exports.Test(unchecked((long)0x99999999AAAAAAAA)));
Assert.AreEqual(48, exports.Test(unchecked((long)0xDEADBEEFDEADBEEF)));
}
}
| 37.606061 | 126 | 0.688961 | [
"Apache-2.0"
] | munik/dotnet-webassembly | WebAssembly.Tests/Instructions/Int64CountOneBitsTests.cs | 1,243 | 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("RavenUnity")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("RavenUnity")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("3d6b0d26-9c50-4729-a352-c9ea46a40a46")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.648649 | 84 | 0.744436 | [
"MIT"
] | mzandvliet/RavenUnity | Properties/AssemblyInfo.cs | 1,396 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Media;
using Microsoft.VisualStudio.Text.Classification;
using Microsoft.VisualStudio.Utilities;
namespace SemanticHighlighter
{
[Export(typeof(EditorFormatDefinition))]
[ClassificationType(ClassificationTypeNames = FormatConstants.Brace)]
[Name(FormatConstants.Brace)]
[UserVisible(true)]
[Order(After = Priority.High)]
internal sealed class AbmesBraceFormat : ClassificationFormatDefinition
{
public AbmesBraceFormat()
{
DisplayName = "Abmes Brace";
ForegroundColor = Colors.Blue;
}
}
[Export(typeof(EditorFormatDefinition))]
[ClassificationType(ClassificationTypeNames = FormatConstants.Bracket)]
[Name(FormatConstants.Bracket)]
[UserVisible(true)]
[Order(After = Priority.High)]
internal sealed class AbmesBracketFormat : ClassificationFormatDefinition
{
public AbmesBracketFormat()
{
DisplayName = "Abmes Bracket";
ForegroundColor = Colors.Red;
}
}
[Export(typeof(EditorFormatDefinition))]
[ClassificationType(ClassificationTypeNames = FormatConstants.Parenthesis)]
[Name(FormatConstants.Parenthesis)]
[UserVisible(true)]
[Order(After = Priority.High)]
internal sealed class AbmesParenthesisFormat : ClassificationFormatDefinition
{
public AbmesParenthesisFormat()
{
DisplayName = "Abmes Parenthesis";
ForegroundColor = Colors.Red;
}
}
[Export(typeof(EditorFormatDefinition))]
[ClassificationType(ClassificationTypeNames = FormatConstants.Colon)]
[Name(FormatConstants.Colon)]
[UserVisible(true)]
[Order(After = Priority.High)]
internal sealed class AbmesColonFormat : ClassificationFormatDefinition
{
public AbmesColonFormat()
{
DisplayName = "Abmes Colon";
ForegroundColor = Colors.Red;
}
}
[Export(typeof(EditorFormatDefinition))]
[ClassificationType(ClassificationTypeNames = FormatConstants.Semicolon)]
[Name(FormatConstants.Semicolon)]
[UserVisible(true)]
[Order(After = Priority.High)]
internal sealed class AbmesSemicolonFormat : ClassificationFormatDefinition
{
public AbmesSemicolonFormat()
{
DisplayName = "Abmes Semicolon";
ForegroundColor = Colors.Red;
}
}
[Export(typeof(EditorFormatDefinition))]
[ClassificationType(ClassificationTypeNames = FormatConstants.Comma)]
[Name(FormatConstants.Comma)]
[UserVisible(true)]
[Order(After = Priority.High)]
internal sealed class AbmesCommaFormat : ClassificationFormatDefinition
{
public AbmesCommaFormat()
{
DisplayName = "Abmes Comma";
ForegroundColor = Colors.Red;
}
}
[Export(typeof(EditorFormatDefinition))]
[ClassificationType(ClassificationTypeNames = FormatConstants.AngleBracket)]
[Name(FormatConstants.AngleBracket)]
[UserVisible(true)]
[Order(After = Priority.High)]
internal sealed class AbmesAngleBracketFormat : ClassificationFormatDefinition
{
public AbmesAngleBracketFormat()
{
DisplayName = "Abmes Angle Bracket";
ForegroundColor = Colors.Red;
}
}
}
| 31.288288 | 82 | 0.683271 | [
"MIT"
] | abmes/SemanticHighlighter | SemanticHighlighter/AbmesClassifierFormats.cs | 3,475 | C# |
using System;
using System.Collections;
using System.Diagnostics;
using System.Linq;
using System.Linq.Expressions;
using FluentAssertions.Common;
using FluentAssertions.Equivalency;
using FluentAssertions.Execution;
namespace FluentAssertions.Collections
{
/// <summary>
/// Contains a number of methods to assert that an <see cref="IEnumerable"/> is in the expected state.
/// </summary>
[DebuggerNonUserCode]
public class NonGenericCollectionAssertions : CollectionAssertions<IEnumerable, NonGenericCollectionAssertions>
{
public NonGenericCollectionAssertions(IEnumerable collection) : base(collection)
{
}
/// <summary>
/// Asserts that the number of items in the collection matches the supplied <paramref name="expected" /> amount.
/// </summary>
/// <param name="expected">The expected number of items in the collection.</param>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <paramref name="because" />.
/// </param>
public AndConstraint<NonGenericCollectionAssertions> HaveCount(int expected, string because = "", params object[] becauseArgs)
{
if (Subject is null)
{
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:collection} to contain {0} item(s){reason}, but found <null>.", expected);
}
int actualCount = GetMostLocalCount();
Execute.Assertion
.ForCondition(actualCount == expected)
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:collection} to contain {0} item(s){reason}, but found {1}.", expected, actualCount);
return new AndConstraint<NonGenericCollectionAssertions>(this);
}
/// <summary>
/// Asserts that the number of items in the collection does not match the supplied <paramref name="unexpected" /> amount.
/// </summary>
/// <param name="unexpected">The unexpected number of items in the collection.</param>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <paramref name="because" />.
/// </param>
public AndConstraint<NonGenericCollectionAssertions> NotHaveCount(int unexpected, string because = "", params object[] becauseArgs)
{
if (Subject is null)
{
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:collection} to not contain {0} item(s){reason}, but found <null>.", unexpected);
}
int actualCount = GetMostLocalCount();
Execute.Assertion
.ForCondition(actualCount != unexpected)
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:collection} to not contain {0} item(s){reason}, but found {1}.", unexpected, actualCount);
return new AndConstraint<NonGenericCollectionAssertions>(this);
}
/// <summary>
/// Asserts that the number of items in the collection is greater than the supplied <paramref name="expected" /> amount.
/// </summary>
/// <param name="expected">The number to which the actual number items in the collection will be compared.</param>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <paramref name="because" />.
/// </param>
public AndConstraint<NonGenericCollectionAssertions> HaveCountGreaterThan(int expected, string because = "", params object[] becauseArgs)
{
if (Subject is null)
{
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:collection} to contain more than {0} item(s){reason}, but found <null>.", expected);
}
int actualCount = GetMostLocalCount();
Execute.Assertion
.ForCondition(actualCount > expected)
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:collection} to contain more than {0} item(s){reason}, but found {1}.", expected, actualCount);
return new AndConstraint<NonGenericCollectionAssertions>(this);
}
/// <summary>
/// Asserts that the number of items in the collection is greater or equal to the supplied <paramref name="expected" /> amount.
/// </summary>
/// <param name="expected">The number to which the actual number items in the collection will be compared.</param>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <paramref name="because" />.
/// </param>
public AndConstraint<NonGenericCollectionAssertions> HaveCountGreaterOrEqualTo(int expected, string because = "", params object[] becauseArgs)
{
if (Subject is null)
{
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:collection} to contain at least {0} item(s){reason}, but found <null>.", expected);
}
int actualCount = GetMostLocalCount();
Execute.Assertion
.ForCondition(actualCount >= expected)
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:collection} to contain at least {0} item(s){reason}, but found {1}.", expected, actualCount);
return new AndConstraint<NonGenericCollectionAssertions>(this);
}
/// <summary>
/// Asserts that the number of items in the collection is less than the supplied <paramref name="expected" /> amount.
/// </summary>
/// <param name="expected">The number to which the actual number items in the collection will be compared.</param>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <paramref name="because" />.
/// </param>
public AndConstraint<NonGenericCollectionAssertions> HaveCountLessThan(int expected, string because = "", params object[] becauseArgs)
{
if (Subject is null)
{
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:collection} to contain fewer than {0} item(s){reason}, but found <null>.", expected);
}
int actualCount = GetMostLocalCount();
Execute.Assertion
.ForCondition(actualCount < expected)
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:collection} to contain fewer than {0} item(s){reason}, but found {1}.", expected, actualCount);
return new AndConstraint<NonGenericCollectionAssertions>(this);
}
/// <summary>
/// Asserts that the number of items in the collection is less or equal to the supplied <paramref name="expected" /> amount.
/// </summary>
/// <param name="expected">The number to which the actual number items in the collection will be compared.</param>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <paramref name="because" />.
/// </param>
public AndConstraint<NonGenericCollectionAssertions> HaveCountLessOrEqualTo(int expected, string because = "", params object[] becauseArgs)
{
if (Subject is null)
{
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:collection} to contain at most {0} item(s){reason}, but found <null>.", expected);
}
int actualCount = GetMostLocalCount();
Execute.Assertion
.ForCondition(actualCount <= expected)
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:collection} to contain at most {0} item(s){reason}, but found {1}.", expected, actualCount);
return new AndConstraint<NonGenericCollectionAssertions>(this);
}
/// <summary>
/// Asserts that the number of items in the collection matches a condition stated by the <paramref name="countPredicate"/>.
/// </summary>
/// <param name="countPredicate">A predicate that yields the number of items that is expected to be in the collection.</param>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <paramref name="because" />.
/// </param>
public AndConstraint<NonGenericCollectionAssertions> HaveCount(Expression<Func<int, bool>> countPredicate, string because = "",
params object[] becauseArgs)
{
Guard.ThrowIfArgumentIsNull(countPredicate, nameof(countPredicate), "Cannot compare collection count against a <null> predicate.");
if (Subject is null)
{
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:collection} to contain {0} items{reason}, but found {1}.", countPredicate.Body, Subject);
}
Func<int, bool> compiledPredicate = countPredicate.Compile();
int actualCount = GetMostLocalCount();
if (!compiledPredicate(actualCount))
{
Execute.Assertion
.BecauseOf(because, becauseArgs)
.FailWith("Expected {context:collection} {0} to have a count {1}{reason}, but count is {2}.",
Subject, countPredicate.Body, actualCount);
}
return new AndConstraint<NonGenericCollectionAssertions>(this);
}
private int GetMostLocalCount()
{
if (Subject is ICollection castSubject)
{
return castSubject.Count;
}
else
{
return Subject.Cast<object>().Count();
}
}
/// <summary>
/// Asserts that the current collection contains the specified <paramref name="expected"/> object. Elements are compared
/// using their <see cref="object.Equals(object)" /> implementation.
/// </summary>
/// <param name="expected">An object, or <see cref="IEnumerable"/> of objects that are expected to be in the collection.</param>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <paramref name="because" />.
/// </param>
public AndConstraint<NonGenericCollectionAssertions> Contain(object expected, string because = "",
params object[] becauseArgs)
{
if (expected is IEnumerable enumerable)
{
return base.Contain(enumerable, because, becauseArgs);
}
return base.Contain(new[] { expected }, because, becauseArgs);
}
/// <summary>
/// Asserts that the current collection does not contain the supplied <paramref name="unexpected" /> item.
/// Elements are compared using their <see cref="object.Equals(object)" /> implementation.
/// </summary>
/// <param name="unexpected">The element that is not expected to be in the collection</param>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <paramref name="because" />.
/// </param>
public AndConstraint<NonGenericCollectionAssertions> NotContain(object unexpected, string because = "",
params object[] becauseArgs)
{
if (unexpected is IEnumerable enumerable)
{
return base.NotContain(enumerable, because, becauseArgs);
}
return base.NotContain(new[] { unexpected }, because, becauseArgs);
}
}
}
| 49.715719 | 150 | 0.610562 | [
"Apache-2.0"
] | Jacksondr5/fluentassertions | Src/FluentAssertions/Collections/NonGenericCollectionAssertions.cs | 14,867 | C# |
// Copyright (c) 2019 .NET Foundation and Contributors. All rights reserved.
// 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 full license information.
using System;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Reactive;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using Android.Preferences;
using Android.Runtime;
namespace ReactiveUI
{
/// <summary>
/// This is a PreferenceFragment that is both an Activity and has ReactiveObject powers
/// (i.e. you can call RaiseAndSetIfChanged).
/// </summary>
/// <typeparam name="TViewModel">The view model type.</typeparam>
[SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1402:FileMayOnlyContainASingleType", Justification = "Classes with the same class names within.")]
public class ReactivePreferenceFragment<TViewModel> : ReactivePreferenceFragment, IViewFor<TViewModel>, ICanActivate
where TViewModel : class
{
private TViewModel _viewModel;
/// <summary>
/// Initializes a new instance of the <see cref="ReactivePreferenceFragment{TViewModel}"/> class.
/// </summary>
protected ReactivePreferenceFragment()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ReactivePreferenceFragment{TViewModel}"/> class.
/// </summary>
/// <param name="handle">The handle.</param>
/// <param name="ownership">The ownership.</param>
protected ReactivePreferenceFragment(IntPtr handle, JniHandleOwnership ownership)
: base(handle, ownership)
{
}
/// <inheritdoc/>
public TViewModel ViewModel
{
get => _viewModel;
set => this.RaiseAndSetIfChanged(ref _viewModel, value);
}
/// <inheritdoc/>
object IViewFor.ViewModel
{
get => _viewModel;
set => _viewModel = (TViewModel)value;
}
}
/// <summary>
/// This is a PreferenceFragment that is both an Activity and has ReactiveObject powers
/// (i.e. you can call RaiseAndSetIfChanged).
/// </summary>
[SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1402:FileMayOnlyContainASingleType", Justification = "Classes with the same class names within.")]
public class ReactivePreferenceFragment : PreferenceFragment, IReactiveNotifyPropertyChanged<ReactivePreferenceFragment>, IReactiveObject, IHandleObservableErrors
{
private readonly Subject<Unit> _activated = new Subject<Unit>();
private readonly Subject<Unit> _deactivated = new Subject<Unit>();
/// <summary>
/// Initializes a new instance of the <see cref="ReactivePreferenceFragment"/> class.
/// </summary>
protected ReactivePreferenceFragment()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ReactivePreferenceFragment"/> class.
/// </summary>
/// <param name="handle">The handle.</param>
/// <param name="ownership">The ownership.</param>
protected ReactivePreferenceFragment(IntPtr handle, JniHandleOwnership ownership)
: base(handle, ownership)
{
}
/// <inheritdoc/>
public event PropertyChangingEventHandler PropertyChanging
{
add => PropertyChangingEventManager.AddHandler(this, value);
remove => PropertyChangingEventManager.RemoveHandler(this, value);
}
/// <inheritdoc/>
public event PropertyChangedEventHandler PropertyChanged
{
add => PropertyChangedEventManager.AddHandler(this, value);
remove => PropertyChangedEventManager.RemoveHandler(this, value);
}
/// <inheritdoc />
public IObservable<IReactivePropertyChangedEventArgs<ReactivePreferenceFragment>> Changing => this.GetChangingObservable();
/// <inheritdoc />
public IObservable<IReactivePropertyChangedEventArgs<ReactivePreferenceFragment>> Changed => this.GetChangedObservable();
/// <inheritdoc/>
public IObservable<Exception> ThrownExceptions => this.GetThrownExceptionsObservable();
/// <summary>
/// Gets a signal when the fragment is activated.
/// </summary>
public IObservable<Unit> Activated => _activated.AsObservable();
/// <summary>
/// Gets a signal when the fragment is deactivated.
/// </summary>
public IObservable<Unit> Deactivated => _deactivated.AsObservable();
/// <inheritdoc/>
public IDisposable SuppressChangeNotifications() => IReactiveObjectExtensions.SuppressChangeNotifications(this);
/// <inheritdoc/>
void IReactiveObject.RaisePropertyChanged(PropertyChangedEventArgs args)
{
PropertyChangedEventManager.DeliverEvent(this, args);
}
/// <inheritdoc/>
void IReactiveObject.RaisePropertyChanging(PropertyChangingEventArgs args)
{
PropertyChangingEventManager.DeliverEvent(this, args);
}
/// <inheritdoc/>
public override void OnPause()
{
base.OnPause();
_deactivated.OnNext(Unit.Default);
}
/// <inheritdoc/>
public override void OnResume()
{
base.OnResume();
_activated.OnNext(Unit.Default);
}
/// <inheritdoc/>
protected override void Dispose(bool disposing)
{
if (disposing)
{
_activated?.Dispose();
_deactivated?.Dispose();
}
base.Dispose(disposing);
}
}
}
| 36.222222 | 166 | 0.640423 | [
"MIT"
] | InitialForce/ReactiveUI | src/ReactiveUI/Platforms/android/ReactivePreferenceFragment.cs | 5,870 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Azure;
using Azure.Core;
using Azure.Core.Pipeline;
using Azure.ResourceManager.Core;
using Azure.ResourceManager.WebPubSub.Models;
namespace Azure.ResourceManager.WebPubSub
{
internal partial class WebPubSubPrivateEndpointConnectionsRestOperations
{
private readonly string _userAgent;
private readonly HttpPipeline _pipeline;
private readonly Uri _endpoint;
private readonly string _apiVersion;
/// <summary> The ClientDiagnostics is used to provide tracing support for the client library. </summary>
internal ClientDiagnostics ClientDiagnostics { get; }
/// <summary> Initializes a new instance of WebPubSubPrivateEndpointConnectionsRestOperations. </summary>
/// <param name="clientDiagnostics"> The handler for diagnostic messaging in the client. </param>
/// <param name="pipeline"> The HTTP pipeline for sending and receiving REST requests and responses. </param>
/// <param name="applicationId"> The application id to use for user agent. </param>
/// <param name="endpoint"> server parameter. </param>
/// <param name="apiVersion"> Api Version. </param>
/// <exception cref="ArgumentNullException"> <paramref name="apiVersion"/> is null. </exception>
public WebPubSubPrivateEndpointConnectionsRestOperations(ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, string applicationId, Uri endpoint = null, string apiVersion = default)
{
_endpoint = endpoint ?? new Uri("https://management.azure.com");
_apiVersion = apiVersion ?? "2021-10-01";
ClientDiagnostics = clientDiagnostics;
_pipeline = pipeline;
_userAgent = Core.HttpMessageUtilities.GetUserAgentName(this, applicationId);
}
internal HttpMessage CreateListRequest(string subscriptionId, string resourceGroupName, string resourceName)
{
var message = _pipeline.CreateMessage();
var request = message.Request;
request.Method = RequestMethod.Get;
var uri = new RawRequestUriBuilder();
uri.Reset(_endpoint);
uri.AppendPath("/subscriptions/", false);
uri.AppendPath(subscriptionId, true);
uri.AppendPath("/resourceGroups/", false);
uri.AppendPath(resourceGroupName, true);
uri.AppendPath("/providers/Microsoft.SignalRService/webPubSub/", false);
uri.AppendPath(resourceName, true);
uri.AppendPath("/privateEndpointConnections", false);
uri.AppendQuery("api-version", _apiVersion, true);
request.Uri = uri;
request.Headers.Add("Accept", "application/json");
message.SetProperty("SDKUserAgent", _userAgent);
return message;
}
/// <summary> List private endpoint connections. </summary>
/// <param name="subscriptionId"> Gets subscription Id which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
/// <param name="resourceGroupName"> The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. </param>
/// <param name="resourceName"> The name of the resource. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="resourceName"/> is null. </exception>
public async Task<Response<PrivateEndpointConnectionList>> ListAsync(string subscriptionId, string resourceGroupName, string resourceName, CancellationToken cancellationToken = default)
{
if (subscriptionId == null)
{
throw new ArgumentNullException(nameof(subscriptionId));
}
if (resourceGroupName == null)
{
throw new ArgumentNullException(nameof(resourceGroupName));
}
if (resourceName == null)
{
throw new ArgumentNullException(nameof(resourceName));
}
using var message = CreateListRequest(subscriptionId, resourceGroupName, resourceName);
await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
switch (message.Response.Status)
{
case 200:
{
PrivateEndpointConnectionList value = default;
using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false);
value = PrivateEndpointConnectionList.DeserializePrivateEndpointConnectionList(document.RootElement);
return Response.FromValue(value, message.Response);
}
default:
throw await ClientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false);
}
}
/// <summary> List private endpoint connections. </summary>
/// <param name="subscriptionId"> Gets subscription Id which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
/// <param name="resourceGroupName"> The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. </param>
/// <param name="resourceName"> The name of the resource. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="resourceName"/> is null. </exception>
public Response<PrivateEndpointConnectionList> List(string subscriptionId, string resourceGroupName, string resourceName, CancellationToken cancellationToken = default)
{
if (subscriptionId == null)
{
throw new ArgumentNullException(nameof(subscriptionId));
}
if (resourceGroupName == null)
{
throw new ArgumentNullException(nameof(resourceGroupName));
}
if (resourceName == null)
{
throw new ArgumentNullException(nameof(resourceName));
}
using var message = CreateListRequest(subscriptionId, resourceGroupName, resourceName);
_pipeline.Send(message, cancellationToken);
switch (message.Response.Status)
{
case 200:
{
PrivateEndpointConnectionList value = default;
using var document = JsonDocument.Parse(message.Response.ContentStream);
value = PrivateEndpointConnectionList.DeserializePrivateEndpointConnectionList(document.RootElement);
return Response.FromValue(value, message.Response);
}
default:
throw ClientDiagnostics.CreateRequestFailedException(message.Response);
}
}
internal HttpMessage CreateGetRequest(string subscriptionId, string resourceGroupName, string resourceName, string privateEndpointConnectionName)
{
var message = _pipeline.CreateMessage();
var request = message.Request;
request.Method = RequestMethod.Get;
var uri = new RawRequestUriBuilder();
uri.Reset(_endpoint);
uri.AppendPath("/subscriptions/", false);
uri.AppendPath(subscriptionId, true);
uri.AppendPath("/resourceGroups/", false);
uri.AppendPath(resourceGroupName, true);
uri.AppendPath("/providers/Microsoft.SignalRService/webPubSub/", false);
uri.AppendPath(resourceName, true);
uri.AppendPath("/privateEndpointConnections/", false);
uri.AppendPath(privateEndpointConnectionName, true);
uri.AppendQuery("api-version", _apiVersion, true);
request.Uri = uri;
request.Headers.Add("Accept", "application/json");
message.SetProperty("SDKUserAgent", _userAgent);
return message;
}
/// <summary> Get the specified private endpoint connection. </summary>
/// <param name="subscriptionId"> Gets subscription Id which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
/// <param name="resourceGroupName"> The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. </param>
/// <param name="resourceName"> The name of the resource. </param>
/// <param name="privateEndpointConnectionName"> The name of the private endpoint connection. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="resourceName"/> or <paramref name="privateEndpointConnectionName"/> is null. </exception>
public async Task<Response<PrivateEndpointConnectionData>> GetAsync(string subscriptionId, string resourceGroupName, string resourceName, string privateEndpointConnectionName, CancellationToken cancellationToken = default)
{
if (subscriptionId == null)
{
throw new ArgumentNullException(nameof(subscriptionId));
}
if (resourceGroupName == null)
{
throw new ArgumentNullException(nameof(resourceGroupName));
}
if (resourceName == null)
{
throw new ArgumentNullException(nameof(resourceName));
}
if (privateEndpointConnectionName == null)
{
throw new ArgumentNullException(nameof(privateEndpointConnectionName));
}
using var message = CreateGetRequest(subscriptionId, resourceGroupName, resourceName, privateEndpointConnectionName);
await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
switch (message.Response.Status)
{
case 200:
{
PrivateEndpointConnectionData value = default;
using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false);
value = PrivateEndpointConnectionData.DeserializePrivateEndpointConnectionData(document.RootElement);
return Response.FromValue(value, message.Response);
}
case 404:
return Response.FromValue((PrivateEndpointConnectionData)null, message.Response);
default:
throw await ClientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false);
}
}
/// <summary> Get the specified private endpoint connection. </summary>
/// <param name="subscriptionId"> Gets subscription Id which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
/// <param name="resourceGroupName"> The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. </param>
/// <param name="resourceName"> The name of the resource. </param>
/// <param name="privateEndpointConnectionName"> The name of the private endpoint connection. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="resourceName"/> or <paramref name="privateEndpointConnectionName"/> is null. </exception>
public Response<PrivateEndpointConnectionData> Get(string subscriptionId, string resourceGroupName, string resourceName, string privateEndpointConnectionName, CancellationToken cancellationToken = default)
{
if (subscriptionId == null)
{
throw new ArgumentNullException(nameof(subscriptionId));
}
if (resourceGroupName == null)
{
throw new ArgumentNullException(nameof(resourceGroupName));
}
if (resourceName == null)
{
throw new ArgumentNullException(nameof(resourceName));
}
if (privateEndpointConnectionName == null)
{
throw new ArgumentNullException(nameof(privateEndpointConnectionName));
}
using var message = CreateGetRequest(subscriptionId, resourceGroupName, resourceName, privateEndpointConnectionName);
_pipeline.Send(message, cancellationToken);
switch (message.Response.Status)
{
case 200:
{
PrivateEndpointConnectionData value = default;
using var document = JsonDocument.Parse(message.Response.ContentStream);
value = PrivateEndpointConnectionData.DeserializePrivateEndpointConnectionData(document.RootElement);
return Response.FromValue(value, message.Response);
}
case 404:
return Response.FromValue((PrivateEndpointConnectionData)null, message.Response);
default:
throw ClientDiagnostics.CreateRequestFailedException(message.Response);
}
}
internal HttpMessage CreateUpdateRequest(string subscriptionId, string resourceGroupName, string resourceName, string privateEndpointConnectionName, PrivateEndpointConnectionData parameters)
{
var message = _pipeline.CreateMessage();
var request = message.Request;
request.Method = RequestMethod.Put;
var uri = new RawRequestUriBuilder();
uri.Reset(_endpoint);
uri.AppendPath("/subscriptions/", false);
uri.AppendPath(subscriptionId, true);
uri.AppendPath("/resourceGroups/", false);
uri.AppendPath(resourceGroupName, true);
uri.AppendPath("/providers/Microsoft.SignalRService/webPubSub/", false);
uri.AppendPath(resourceName, true);
uri.AppendPath("/privateEndpointConnections/", false);
uri.AppendPath(privateEndpointConnectionName, true);
uri.AppendQuery("api-version", _apiVersion, true);
request.Uri = uri;
request.Headers.Add("Accept", "application/json");
request.Headers.Add("Content-Type", "application/json");
var content = new Utf8JsonRequestContent();
content.JsonWriter.WriteObjectValue(parameters);
request.Content = content;
message.SetProperty("SDKUserAgent", _userAgent);
return message;
}
/// <summary> Update the state of specified private endpoint connection. </summary>
/// <param name="subscriptionId"> Gets subscription Id which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
/// <param name="resourceGroupName"> The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. </param>
/// <param name="resourceName"> The name of the resource. </param>
/// <param name="privateEndpointConnectionName"> The name of the private endpoint connection. </param>
/// <param name="parameters"> The resource of private endpoint and its properties. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="resourceName"/>, <paramref name="privateEndpointConnectionName"/> or <paramref name="parameters"/> is null. </exception>
public async Task<Response<PrivateEndpointConnectionData>> UpdateAsync(string subscriptionId, string resourceGroupName, string resourceName, string privateEndpointConnectionName, PrivateEndpointConnectionData parameters, CancellationToken cancellationToken = default)
{
if (subscriptionId == null)
{
throw new ArgumentNullException(nameof(subscriptionId));
}
if (resourceGroupName == null)
{
throw new ArgumentNullException(nameof(resourceGroupName));
}
if (resourceName == null)
{
throw new ArgumentNullException(nameof(resourceName));
}
if (privateEndpointConnectionName == null)
{
throw new ArgumentNullException(nameof(privateEndpointConnectionName));
}
if (parameters == null)
{
throw new ArgumentNullException(nameof(parameters));
}
using var message = CreateUpdateRequest(subscriptionId, resourceGroupName, resourceName, privateEndpointConnectionName, parameters);
await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
switch (message.Response.Status)
{
case 200:
{
PrivateEndpointConnectionData value = default;
using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false);
value = PrivateEndpointConnectionData.DeserializePrivateEndpointConnectionData(document.RootElement);
return Response.FromValue(value, message.Response);
}
default:
throw await ClientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false);
}
}
/// <summary> Update the state of specified private endpoint connection. </summary>
/// <param name="subscriptionId"> Gets subscription Id which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
/// <param name="resourceGroupName"> The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. </param>
/// <param name="resourceName"> The name of the resource. </param>
/// <param name="privateEndpointConnectionName"> The name of the private endpoint connection. </param>
/// <param name="parameters"> The resource of private endpoint and its properties. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="resourceName"/>, <paramref name="privateEndpointConnectionName"/> or <paramref name="parameters"/> is null. </exception>
public Response<PrivateEndpointConnectionData> Update(string subscriptionId, string resourceGroupName, string resourceName, string privateEndpointConnectionName, PrivateEndpointConnectionData parameters, CancellationToken cancellationToken = default)
{
if (subscriptionId == null)
{
throw new ArgumentNullException(nameof(subscriptionId));
}
if (resourceGroupName == null)
{
throw new ArgumentNullException(nameof(resourceGroupName));
}
if (resourceName == null)
{
throw new ArgumentNullException(nameof(resourceName));
}
if (privateEndpointConnectionName == null)
{
throw new ArgumentNullException(nameof(privateEndpointConnectionName));
}
if (parameters == null)
{
throw new ArgumentNullException(nameof(parameters));
}
using var message = CreateUpdateRequest(subscriptionId, resourceGroupName, resourceName, privateEndpointConnectionName, parameters);
_pipeline.Send(message, cancellationToken);
switch (message.Response.Status)
{
case 200:
{
PrivateEndpointConnectionData value = default;
using var document = JsonDocument.Parse(message.Response.ContentStream);
value = PrivateEndpointConnectionData.DeserializePrivateEndpointConnectionData(document.RootElement);
return Response.FromValue(value, message.Response);
}
default:
throw ClientDiagnostics.CreateRequestFailedException(message.Response);
}
}
internal HttpMessage CreateDeleteRequest(string subscriptionId, string resourceGroupName, string resourceName, string privateEndpointConnectionName)
{
var message = _pipeline.CreateMessage();
var request = message.Request;
request.Method = RequestMethod.Delete;
var uri = new RawRequestUriBuilder();
uri.Reset(_endpoint);
uri.AppendPath("/subscriptions/", false);
uri.AppendPath(subscriptionId, true);
uri.AppendPath("/resourceGroups/", false);
uri.AppendPath(resourceGroupName, true);
uri.AppendPath("/providers/Microsoft.SignalRService/webPubSub/", false);
uri.AppendPath(resourceName, true);
uri.AppendPath("/privateEndpointConnections/", false);
uri.AppendPath(privateEndpointConnectionName, true);
uri.AppendQuery("api-version", _apiVersion, true);
request.Uri = uri;
request.Headers.Add("Accept", "application/json");
message.SetProperty("SDKUserAgent", _userAgent);
return message;
}
/// <summary> Delete the specified private endpoint connection. </summary>
/// <param name="subscriptionId"> Gets subscription Id which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
/// <param name="resourceGroupName"> The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. </param>
/// <param name="resourceName"> The name of the resource. </param>
/// <param name="privateEndpointConnectionName"> The name of the private endpoint connection. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="resourceName"/> or <paramref name="privateEndpointConnectionName"/> is null. </exception>
public async Task<Response> DeleteAsync(string subscriptionId, string resourceGroupName, string resourceName, string privateEndpointConnectionName, CancellationToken cancellationToken = default)
{
if (subscriptionId == null)
{
throw new ArgumentNullException(nameof(subscriptionId));
}
if (resourceGroupName == null)
{
throw new ArgumentNullException(nameof(resourceGroupName));
}
if (resourceName == null)
{
throw new ArgumentNullException(nameof(resourceName));
}
if (privateEndpointConnectionName == null)
{
throw new ArgumentNullException(nameof(privateEndpointConnectionName));
}
using var message = CreateDeleteRequest(subscriptionId, resourceGroupName, resourceName, privateEndpointConnectionName);
await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
switch (message.Response.Status)
{
case 200:
case 202:
case 204:
return message.Response;
default:
throw await ClientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false);
}
}
/// <summary> Delete the specified private endpoint connection. </summary>
/// <param name="subscriptionId"> Gets subscription Id which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
/// <param name="resourceGroupName"> The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. </param>
/// <param name="resourceName"> The name of the resource. </param>
/// <param name="privateEndpointConnectionName"> The name of the private endpoint connection. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="resourceName"/> or <paramref name="privateEndpointConnectionName"/> is null. </exception>
public Response Delete(string subscriptionId, string resourceGroupName, string resourceName, string privateEndpointConnectionName, CancellationToken cancellationToken = default)
{
if (subscriptionId == null)
{
throw new ArgumentNullException(nameof(subscriptionId));
}
if (resourceGroupName == null)
{
throw new ArgumentNullException(nameof(resourceGroupName));
}
if (resourceName == null)
{
throw new ArgumentNullException(nameof(resourceName));
}
if (privateEndpointConnectionName == null)
{
throw new ArgumentNullException(nameof(privateEndpointConnectionName));
}
using var message = CreateDeleteRequest(subscriptionId, resourceGroupName, resourceName, privateEndpointConnectionName);
_pipeline.Send(message, cancellationToken);
switch (message.Response.Status)
{
case 200:
case 202:
case 204:
return message.Response;
default:
throw ClientDiagnostics.CreateRequestFailedException(message.Response);
}
}
internal HttpMessage CreateListNextPageRequest(string nextLink, string subscriptionId, string resourceGroupName, string resourceName)
{
var message = _pipeline.CreateMessage();
var request = message.Request;
request.Method = RequestMethod.Get;
var uri = new RawRequestUriBuilder();
uri.Reset(_endpoint);
uri.AppendRawNextLink(nextLink, false);
request.Uri = uri;
request.Headers.Add("Accept", "application/json");
message.SetProperty("SDKUserAgent", _userAgent);
return message;
}
/// <summary> List private endpoint connections. </summary>
/// <param name="nextLink"> The URL to the next page of results. </param>
/// <param name="subscriptionId"> Gets subscription Id which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
/// <param name="resourceGroupName"> The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. </param>
/// <param name="resourceName"> The name of the resource. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="nextLink"/>, <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="resourceName"/> is null. </exception>
public async Task<Response<PrivateEndpointConnectionList>> ListNextPageAsync(string nextLink, string subscriptionId, string resourceGroupName, string resourceName, CancellationToken cancellationToken = default)
{
if (nextLink == null)
{
throw new ArgumentNullException(nameof(nextLink));
}
if (subscriptionId == null)
{
throw new ArgumentNullException(nameof(subscriptionId));
}
if (resourceGroupName == null)
{
throw new ArgumentNullException(nameof(resourceGroupName));
}
if (resourceName == null)
{
throw new ArgumentNullException(nameof(resourceName));
}
using var message = CreateListNextPageRequest(nextLink, subscriptionId, resourceGroupName, resourceName);
await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
switch (message.Response.Status)
{
case 200:
{
PrivateEndpointConnectionList value = default;
using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false);
value = PrivateEndpointConnectionList.DeserializePrivateEndpointConnectionList(document.RootElement);
return Response.FromValue(value, message.Response);
}
default:
throw await ClientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false);
}
}
/// <summary> List private endpoint connections. </summary>
/// <param name="nextLink"> The URL to the next page of results. </param>
/// <param name="subscriptionId"> Gets subscription Id which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
/// <param name="resourceGroupName"> The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. </param>
/// <param name="resourceName"> The name of the resource. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="nextLink"/>, <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="resourceName"/> is null. </exception>
public Response<PrivateEndpointConnectionList> ListNextPage(string nextLink, string subscriptionId, string resourceGroupName, string resourceName, CancellationToken cancellationToken = default)
{
if (nextLink == null)
{
throw new ArgumentNullException(nameof(nextLink));
}
if (subscriptionId == null)
{
throw new ArgumentNullException(nameof(subscriptionId));
}
if (resourceGroupName == null)
{
throw new ArgumentNullException(nameof(resourceGroupName));
}
if (resourceName == null)
{
throw new ArgumentNullException(nameof(resourceName));
}
using var message = CreateListNextPageRequest(nextLink, subscriptionId, resourceGroupName, resourceName);
_pipeline.Send(message, cancellationToken);
switch (message.Response.Status)
{
case 200:
{
PrivateEndpointConnectionList value = default;
using var document = JsonDocument.Parse(message.Response.ContentStream);
value = PrivateEndpointConnectionList.DeserializePrivateEndpointConnectionList(document.RootElement);
return Response.FromValue(value, message.Response);
}
default:
throw ClientDiagnostics.CreateRequestFailedException(message.Response);
}
}
}
}
| 58.5 | 275 | 0.641595 | [
"MIT"
] | AntonioVT/azure-sdk-for-net | sdk/webpubsub/Azure.ResourceManager.WebPubSub/src/Generated/RestOperations/WebPubSubPrivateEndpointConnectionsRestOperations.cs | 33,345 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Harmony;
namespace MechEngineer
{
internal static class HarmonyExtensions
{
internal static void Patch(this HarmonyInstance @this, Type type)
{
var parentMethodInfos = type.GetHarmonyMethods();
if (parentMethodInfos == null || !parentMethodInfos.Any())
{
return;
}
var info = HarmonyMethod.Merge(parentMethodInfos);
var processor = new PatchProcessor(@this, type, info);
processor.Patch();
}
}
}
| 25.08 | 73 | 0.606061 | [
"Unlicense"
] | adammartinez271828/MechEngineer | source/Misc/HarmonyExtensions.cs | 629 | C# |
namespace System.Runtime.CompilerServices;
internal static class IsExternalInit { }
| 28 | 42 | 0.845238 | [
"MIT"
] | xiaomi7732/CodeSaar | CodeNameK/src/CodeWithSaar.PathUtility/src/IsExternalInit.cs | 84 | C# |
// ============================================================
//
// Astramed
// SoftGears.CMS.Web
// LoginModel.cs
//
// Created by: ykorshev
// at 21.06.2013 10:32
//
// ============================================================
namespace CityPlace.Web.Models.Account
{
/// <summary>
/// Модель авторизации на сайте
/// </summary>
public class LoginModel
{
/// <summary>
/// Емейл
/// </summary>
public string Email { get; set; }
/// <summary>
/// Пароль
/// </summary>
public string Password { get; set; }
/// <summary>
/// Запомнить меня
/// </summary>
public bool RememberMe { get; set; }
}
} | 22.242424 | 64 | 0.408719 | [
"MIT"
] | softgears/CityPlace | CityPlace.Web/Models/Account/LoginModel.cs | 784 | C# |
using System.Data.Entity;
using StudentSystem.Persistence.Migrations;
namespace StudentSystem.Persistence
{
public class DbConfig
{
public static void RegisterDb()
{
Database.SetInitializer(new MigrateDatabaseToLatestVersion<StudentSystemDbContext, Configuration>());
}
}
} | 23.142857 | 113 | 0.703704 | [
"MIT"
] | chunk1ty/student-system | src/StudentSystem.Persistence/DbConfig.cs | 326 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.