content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2
values |
|---|---|---|---|---|---|---|---|---|
using Nest;
using System;
using System.Collections.Generic;
using System.Linq;
namespace RimDev.Filter.Nest
{
public static class QueryContainerDescriptorExtensions
{
public static QueryContainer Filter<T>(
this QueryContainerDescriptor<T> value,
object filter,
IDictionary<Type, Func<object, string>> filterValueFormatters = null)
where T : class
{
if (filter == null)
{
return value;
}
var mustQueries = FilterLogic.GenerateMustQueriesFromFilter<T>(filter, filterValueFormatters);
if (mustQueries.Any())
{
return value.Bool(x =>
x.Must(mustQueries));
}
return value;
}
}
} | 25.34375 | 106 | 0.554871 | [
"MIT"
] | billboga/filter | src/Filter.Nest/QueryContainerDescriptorExtensions.cs | 813 | C# |
using GameEstate.Core;
using System.Collections.Generic;
using System.IO;
namespace GameEstate.Formats.Valve.Blocks
{
/// <summary>
/// "NTRO" block. CResourceIntrospectionManifest.
/// </summary>
public class NTRO : Block
{
public enum DataType
{
Struct = 1,
Enum = 2, // TODO: not verified with resourceinfo
ExternalReference = 3,
String4 = 4, // TODO: not verified with resourceinfo
SByte = 10,
Byte = 11,
Int16 = 12,
UInt16 = 13,
Int32 = 14,
UInt32 = 15,
Int64 = 16, // TODO: not verified with resourceinfo
UInt64 = 17,
Float = 18,
Matrix2x4 = 21, // TODO: FourVectors2D
Vector = 22,
Vector4D = 23,
Quaternion = 25,
Fltx4 = 27,
Color = 28, // TODO: not verified with resourceinfo
Boolean = 30,
String = 31,
Matrix3x4 = 33,
Matrix3x4a = 36,
CTransform = 40,
Vector4D_44 = 44,
}
public class ResourceDiskStruct
{
public class Field
{
public string FieldName { get; set; }
public short Count { get; set; }
public short OnDiskOffset { get; set; }
public List<byte> Indirections { get; private set; } = new List<byte>();
public uint TypeData { get; set; }
public DataType Type { get; set; }
public ushort Unknown { get; set; }
public void WriteText(IndentedTextWriter w)
{
w.WriteLine("CResourceDiskStructField {"); w.Indent++;
w.WriteLine($"CResourceString m_pFieldName = \"{FieldName}\"");
w.WriteLine($"int16 m_nCount = {Count}");
w.WriteLine($"int16 m_nOnDiskOffset = {OnDiskOffset}");
w.WriteLine($"uint8[{Indirections.Count}] m_Indirection = ["); w.Indent++;
foreach (var dep in Indirections)
w.WriteLine("{0:D2}", dep);
w.Indent--; w.WriteLine("]");
w.WriteLine($"uint32 m_nTypeData = 0x{TypeData:X8}");
w.WriteLine($"int16 m_nType = {(int)Type}");
w.Indent--; w.WriteLine("}");
}
}
public uint IntrospectionVersion { get; set; }
public uint Id { get; set; }
public string Name { get; set; }
public uint DiskCrc { get; set; }
public int UserVersion { get; set; }
public ushort DiskSize { get; set; }
public ushort Alignment { get; set; }
public uint BaseStructId { get; set; }
public byte StructFlags { get; set; }
public ushort Unknown { get; set; }
public byte Unknown2 { get; set; }
public List<Field> FieldIntrospection { get; private set; } = new List<Field>();
public void WriteText(IndentedTextWriter w)
{
w.WriteLine("CResourceDiskStruct {"); w.Indent++;
w.WriteLine($"uint32 m_nIntrospectionVersion = 0x{IntrospectionVersion:X8}");
w.WriteLine($"uint32 m_nId = 0x{Id:X8}");
w.WriteLine($"CResourceString m_pName = \"{Name}\"");
w.WriteLine($"uint32 m_nDiskCrc = 0x{DiskCrc:X8}");
w.WriteLine($"int32 m_nUserVersion = {UserVersion}");
w.WriteLine($"uint16 m_nDiskSize = 0x{DiskSize:X4}");
w.WriteLine($"uint16 m_nAlignment = 0x{Alignment:X4}");
w.WriteLine($"uint32 m_nBaseStructId = 0x{BaseStructId:X8}");
w.WriteLine($"Struct m_FieldIntrospection[{FieldIntrospection.Count}] = ["); w.Indent++;
foreach (var field in FieldIntrospection)
field.WriteText(w);
w.Indent--; w.WriteLine("]");
w.WriteLine($"uint8 m_nStructFlags = 0x{StructFlags:X2}");
w.Indent--; w.WriteLine("}");
}
}
public class ResourceDiskEnum
{
public class Value
{
public string EnumValueName { get; set; }
public int EnumValue { get; set; }
public void WriteText(IndentedTextWriter w)
{
w.WriteLine("CResourceDiskEnumValue {"); w.Indent++;
w.WriteLine("CResourceString m_pEnumValueName = \"{EnumValueName}\"");
w.WriteLine("int32 m_nEnumValue = {EnumValue}");
w.Indent--; w.WriteLine("}");
}
}
public uint IntrospectionVersion { get; set; }
public uint Id { get; set; }
public string Name { get; set; }
public uint DiskCrc { get; set; }
public int UserVersion { get; set; }
public List<Value> EnumValueIntrospection { get; private set; } = new List<Value>();
public void WriteText(IndentedTextWriter w)
{
w.WriteLine("CResourceDiskEnum {"); w.Indent++;
w.WriteLine($"uint32 m_nIntrospectionVersion = 0x{IntrospectionVersion:X8}");
w.WriteLine($"uint32 m_nId = 0x{Id:X8}");
w.WriteLine($"CResourceString m_pName = \"{Name}\"");
w.WriteLine($"uint32 m_nDiskCrc = 0x{DiskCrc:X8}");
w.WriteLine($"int32 m_nUserVersion = {UserVersion}");
w.WriteLine($"Struct m_EnumValueIntrospection[{EnumValueIntrospection.Count}] = ["); w.Indent++;
foreach (var value in EnumValueIntrospection)
value.WriteText(w);
w.Indent--; w.WriteLine("]");
w.Indent--; w.WriteLine("}");
}
}
public uint IntrospectionVersion { get; private set; }
public List<ResourceDiskStruct> ReferencedStructs { get; } = new List<ResourceDiskStruct>();
public List<ResourceDiskEnum> ReferencedEnums { get; } = new List<ResourceDiskEnum>();
public override void Read(BinaryPak parent, BinaryReader r)
{
r.Position(Offset);
IntrospectionVersion = r.ReadUInt32();
ReadStructs(r);
r.BaseStream.Position = Offset + 12; // skip 3 ints
ReadEnums(r);
}
void ReadStructs(BinaryReader r)
{
var entriesOffset = r.ReadUInt32();
var entriesCount = r.ReadUInt32();
if (entriesCount == 0)
return;
r.BaseStream.Position += entriesOffset - 8; // offset minus 2 ints we just read
for (var i = 0; i < entriesCount; i++)
{
var diskStruct = new ResourceDiskStruct
{
IntrospectionVersion = r.ReadUInt32(),
Id = r.ReadUInt32(),
Name = r.ReadO32UTF8(),
DiskCrc = r.ReadUInt32(),
UserVersion = r.ReadInt32(),
DiskSize = r.ReadUInt16(),
Alignment = r.ReadUInt16(),
BaseStructId = r.ReadUInt32()
};
var fieldsOffset = r.ReadUInt32();
var fieldsSize = r.ReadUInt32();
if (fieldsSize > 0)
{
var prev = r.BaseStream.Position;
r.BaseStream.Position += fieldsOffset - 8; // offset minus 2 ints we just read
for (var y = 0; y < fieldsSize; y++)
{
var field = new ResourceDiskStruct.Field
{
FieldName = r.ReadO32UTF8(),
Count = r.ReadInt16(),
OnDiskOffset = r.ReadInt16()
};
var indirectionOffset = r.ReadUInt32();
var indirectionSize = r.ReadUInt32();
if (indirectionSize > 0)
{
// jump to indirections
var prev2 = r.BaseStream.Position;
r.BaseStream.Position += indirectionOffset - 8; // offset minus 2 ints we just read
for (var x = 0; x < indirectionSize; x++)
field.Indirections.Add(r.ReadByte());
r.BaseStream.Position = prev2;
}
field.TypeData = r.ReadUInt32();
field.Type = (DataType)r.ReadInt16();
field.Unknown = r.ReadUInt16();
diskStruct.FieldIntrospection.Add(field);
}
r.BaseStream.Position = prev;
}
diskStruct.StructFlags = r.ReadByte();
diskStruct.Unknown = r.ReadUInt16();
diskStruct.Unknown2 = r.ReadByte();
ReferencedStructs.Add(diskStruct);
}
}
void ReadEnums(BinaryReader r)
{
var entriesOffset = r.ReadUInt32();
var entriesCount = r.ReadUInt32();
if (entriesCount == 0)
return;
r.BaseStream.Position += entriesOffset - 8; // offset minus 2 ints we just read
for (var i = 0; i < entriesCount; i++)
{
var diskEnum = new ResourceDiskEnum
{
IntrospectionVersion = r.ReadUInt32(),
Id = r.ReadUInt32(),
Name = r.ReadO32UTF8(),
DiskCrc = r.ReadUInt32(),
UserVersion = r.ReadInt32()
};
var fieldsOffset = r.ReadUInt32();
var fieldsSize = r.ReadUInt32();
if (fieldsSize > 0)
{
var prev = r.BaseStream.Position;
r.BaseStream.Position += fieldsOffset - 8; // offset minus 2 ints we just read
for (var y = 0; y < fieldsSize; y++)
diskEnum.EnumValueIntrospection.Add(new ResourceDiskEnum.Value
{
EnumValueName = r.ReadO32UTF8(),
EnumValue = r.ReadInt32()
});
r.BaseStream.Position = prev;
}
ReferencedEnums.Add(diskEnum);
}
}
public override void WriteText(IndentedTextWriter w)
{
w.WriteLine("CResourceIntrospectionManifest {"); w.Indent++;
w.WriteLine($"uint32 m_nIntrospectionVersion = 0x{IntrospectionVersion:x8}");
w.WriteLine($"Struct m_ReferencedStructs[{ReferencedStructs.Count}] = ["); w.Indent++;
foreach (var refStruct in ReferencedStructs)
refStruct.WriteText(w);
w.Indent--; w.WriteLine("]");
w.WriteLine($"Struct m_ReferencedEnums[{ReferencedEnums.Count}] = ["); w.Indent++;
foreach (var refEnum in ReferencedEnums)
refEnum.WriteText(w);
w.Indent--; w.WriteLine("]");
w.Indent--; w.WriteLine("}");
}
}
}
| 43.154412 | 113 | 0.475975 | [
"MIT"
] | smorey2/GameEstate | src/GameEstate.Formats/Formats/Valve/Blocks/NTRO.cs | 11,738 | C# |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="AutoWorkspace.cs" company="WildGums">
// Copyright (c) 2008 - 2014 WildGums. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Orc.WorkspaceManagement.Behaviors
{
using System.Windows;
public class AutoWorkspace : WorkspaceBehaviorBase<FrameworkElement>
{
#region Properties
public bool PersistSize
{
get { return (bool)GetValue(PersistSizeProperty); }
set { SetValue(PersistSizeProperty, value); }
}
public static readonly DependencyProperty PersistSizeProperty =
DependencyProperty.Register(nameof(PersistSize), typeof(bool), typeof(AutoWorkspace), new PropertyMetadata(true));
public bool PersistGridSettings
{
get { return (bool)GetValue(PersistGridSettingsProperty); }
set { SetValue(PersistGridSettingsProperty, value); }
}
public static readonly DependencyProperty PersistGridSettingsProperty =
DependencyProperty.Register(nameof(PersistGridSettings), typeof(bool), typeof(AutoWorkspace), new PropertyMetadata(true));
#endregion
#region Methods
protected override void SaveSettings(IWorkspace workspace, string prefix)
{
if (PersistSize)
{
AssociatedObject.SaveSizeToWorkspace(workspace, prefix);
}
if (PersistGridSettings)
{
AssociatedObject.SaveGridValuesToWorkspace(workspace, prefix);
}
}
protected override void LoadSettings(IWorkspace workspace, string prefix)
{
if (PersistSize)
{
AssociatedObject.LoadSizeFromWorkspace(workspace, prefix);
}
if (PersistGridSettings)
{
AssociatedObject.LoadGridValuesFromWorkspace(workspace, prefix);
}
}
#endregion
}
}
| 33.523077 | 134 | 0.554842 | [
"MIT"
] | WildGums/Orc.WorkspaceManagement | src/Orc.WorkspaceManagement.Xaml/Behaviors/AutoWorkspace.cs | 2,181 | C# |
using System;
using Microsoft.Extensions.DependencyInjection;
namespace Nybus.Container
{
public class ServiceProviderScope : IScope
{
private readonly IServiceScope _scope;
public ServiceProviderScope(IServiceScope scope)
{
_scope = scope ?? throw new ArgumentNullException(nameof(scope));
}
public void Dispose()
{
_scope.Dispose();
}
public T Resolve<T>()
{
return _scope.ServiceProvider.GetRequiredService<T>();
}
public void Release<T>(T component) { }
}
} | 22.333333 | 77 | 0.600332 | [
"MIT"
] | Kralizek/NybusLegacyAdapter | src/Nybus.Legacy.NetExtensions.Adapters/Container/ServiceProviderScope.cs | 605 | C# |
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Tencent is pleased to support the open source community by making behaviac available.
//
// Copyright (C) 2015 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at http://opensource.org/licenses/BSD-3-Clause
//
// Unless required by applicable law or agreed to in writing, software distributed under the License is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and limitations under the License.
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
using System;
using System.Collections;
using System.Collections.Generic;
namespace behaviac
{
public class DecoratorAlwaysRunning : DecoratorNode
{
public DecoratorAlwaysRunning()
{
}
~DecoratorAlwaysRunning()
{
}
protected override void load(int version, string agentType, List<property_t> properties)
{
base.load(version, agentType, properties);
}
public override bool IsValid(Agent pAgent, BehaviorTask pTask)
{
if (!(pTask.GetNode() is DecoratorAlwaysRunning))
{
return false;
}
return base.IsValid(pAgent, pTask);
}
protected override BehaviorTask createTask()
{
DecoratorAlwaysRunningTask pTask = new DecoratorAlwaysRunningTask();
return pTask;
}
class DecoratorAlwaysRunningTask : DecoratorTask
{
public DecoratorAlwaysRunningTask() : base()
{
}
protected override void addChild(BehaviorTask pBehavior)
{
base.addChild(pBehavior);
}
public override void copyto(BehaviorTask target)
{
base.copyto(target);
}
public override void save(ISerializableNode node)
{
base.save(node);
}
public override void load(ISerializableNode node)
{
base.load(node);
}
protected override EBTStatus decorate(EBTStatus status)
{
return EBTStatus.BT_RUNNING;
}
}
}
} | 32.592593 | 113 | 0.55303 | [
"BSD-3-Clause"
] | Manistein/behaviac | integration/BattleCityDemo/Assets/Scripts/behaviac/BehaviorTree/Nodes/Decorators/Decoratoralwaysrunning.cs | 2,640 | C# |
//
// Authors:
// Marek Habersack grendel@twistedcode.net
//
// Copyright (c) 2010, Novell, Inc (http://novell.com/)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in
// the documentation and/or other materials provided with the distribution.
// * Neither the name of Novell, Inc nor names of the contributors may be used to endorse or promote products derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
using System;
using System.Text;
namespace CaptainHook.Mail
{
public class TemplateFragmentPlainText : TemplateFragment
{
public string Data {
get { return Builder.ToString (); }
}
public TemplateFragmentPlainText ()
{}
public TemplateFragmentPlainText (string inputFile)
{
if (String.IsNullOrEmpty (inputFile))
throw new ArgumentNullException ("inputFile");
this.InFile = inputFile;
}
public override string ToString ()
{
var sb = new StringBuilder ();
sb.AppendFormat ("{0}: ", typeof (TemplateFragmentPlainText).FullName);
string[] lines = Data.Split (new char[] {'\n'});
foreach (string line in lines)
sb.AppendFormat ("\t'{0}'\n", line);
return sb.ToString ();
}
}
}
| 37.904762 | 183 | 0.731575 | [
"MIT"
] | Skye-D/CaptainHook | CaptainHook/Mail/TemplateFragmentPlainText.cs | 2,388 | C# |
using FluentAssertions;
using Xunit;
namespace Scrima.OData.Tests
{
public class RawParserTests
{
[Theory]
[InlineData("?$filter=name eq 'Jon'&$count=true&$search=myvalue&$orderby=name asc&$top=10&$skip=5&$skiptoken=mytoken")]
[InlineData("$filter=name eq 'Jon'&$count=true&$search=myvalue&$orderby=name asc&$top=10&$skip=5&$skiptoken=mytoken")]
public void Should_ParseRawString_When_AllParametersProvided(string rawQueryString)
{
var rawQueryParsed = ODataRawQueryOptions.ParseRawQuery(rawQueryString);
rawQueryParsed.Should().NotBeNull();
rawQueryParsed.Count.Should().Be("true");
rawQueryParsed.Filter.Should().Be("name eq 'Jon'");
rawQueryParsed.Search.Should().Be("myvalue");
rawQueryParsed.OrderBy.Should().Be("name asc");
rawQueryParsed.Top.Should().Be("10");
rawQueryParsed.Skip.Should().Be("5");
rawQueryParsed.SkipToken.Should().Be("mytoken");
}
[Theory]
[InlineData("?$filter=name eq 'Jon'")]
[InlineData("$filter=name eq 'Jon'")]
public void Should_ParseRawString_When_SomeValueEmpty(string rawQueryString)
{
var rawQueryParsed = ODataRawQueryOptions.ParseRawQuery(rawQueryString);
rawQueryParsed.Should().NotBeNull();
rawQueryParsed.Filter.Should().Be("name eq 'Jon'");
rawQueryParsed.Count.Should().BeNull();
rawQueryParsed.Search.Should().BeNull();
rawQueryParsed.OrderBy.Should().BeNull();
rawQueryParsed.Top.Should().BeNull();
rawQueryParsed.Skip.Should().BeNull();
rawQueryParsed.SkipToken.Should().BeNull();
}
}
}
| 41.186047 | 127 | 0.626765 | [
"MIT"
] | YoioReloaded/scrima-dotnet | test/Scrima.OData.Tests/RawParserTests.cs | 1,773 | C# |
#pragma warning disable 108 // new keyword hiding
#pragma warning disable 114 // new keyword hiding
namespace Windows.Management.Policies
{
#if __ANDROID__ || __IOS__ || NET46 || __WASM__
[global::Uno.NotImplemented]
#endif
public partial class NamedPolicy
{
#if __ANDROID__ || __IOS__ || NET46 || __WASM__
[global::Uno.NotImplemented]
public static global::Windows.Management.Policies.NamedPolicyData GetPolicyFromPath( string area, string name)
{
throw new global::System.NotImplementedException("The member NamedPolicyData NamedPolicy.GetPolicyFromPath(string area, string name) is not implemented in Uno.");
}
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__
[global::Uno.NotImplemented]
public static global::Windows.Management.Policies.NamedPolicyData GetPolicyFromPathForUser( global::Windows.System.User user, string area, string name)
{
throw new global::System.NotImplementedException("The member NamedPolicyData NamedPolicy.GetPolicyFromPathForUser(User user, string area, string name) is not implemented in Uno.");
}
#endif
}
}
| 41.807692 | 183 | 0.768169 | [
"Apache-2.0"
] | nv-ksavaria/Uno | src/Uno.UWP/Generated/3.0.0.0/Windows.Management.Policies/NamedPolicy.cs | 1,087 | C# |
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Social.Network.Domain.Commands;
using Social.Network.Domain.Models;
using Social.Network.Domain.Models.Auths;
using Social.Network.Domain.Queries;
using Social.Network.Domain.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
namespace Social.Network.Api.Controllers
{
[Authorize]
[ApiController]
[Route("api/v1/[controller]")]
public class SocialNetworkController : ControllerBase
{
#region Private Members
/// <summary>
/// A single instance from <see cref="ILogger"/>
/// </summary>
private readonly ILogger<SocialNetworkController> logger;
/// <summary>
/// A single instance from <see cref="IQueryRepository"/>
/// </summary>
private readonly IQueryRepository query;
/// <summary>
/// A single instance from <see cref="ICommandRepository"/>
/// </summary>
private readonly ICommandRepository command;
/// <summary>
/// A single instance from <see cref="IUserService"/>
/// </summary>
private readonly IUserService user;
#endregion
#region Constructor
/// <summary>
/// Default constructor
/// </summary>
/// <param name="logger"></param>
/// <param name="query"></param>
/// <param name="command"></param>
public SocialNetworkController(ILogger<SocialNetworkController> logger, IQueryRepository query, ICommandRepository command, IUserService user)
{
this.logger = logger;
this.query = query;
this.command = command;
this.user = user;
}
#endregion
[AllowAnonymous]
[HttpPost("Authenticate")]
public IActionResult Authenticate(AuthRequest model)
{
var response = user.Authenticate(model);
if (response == null)
return BadRequest(new { message = "Username or password is incorrect" });
return Ok(response);
}
[HttpGet, Route("Users")]
public ActionResult FetchUsers()
{
return Ok(query.GetUsers());
}
[HttpGet, Route("People")]
public ActionResult FetchPeople()
{
//var reqAt = DateTime.Now;
//var result = query.GetPeople();
//var response = new RestResponse<People>()
//{
// Message = "Success",
// StatusCode = (int)HttpStatusCode.OK,
// Data = result.ToList(),
// RequestAt = reqAt,
// ResponseAt = DateTime.Now,
//};
return Ok(query.GetPeople());
}
[HttpGet, Route("Channels")]
public ActionResult FetchChannels()
{
//var reqAt = DateTime.Now;
//var result = query.GetChannels();
//var response = new RestResponse<Channels>()
//{
// Message = "Success",
// StatusCode = (int)HttpStatusCode.OK,
// Data = result.ToList(),
// RequestAt = reqAt,
// ResponseAt = DateTime.Now,
//};
return Ok(query.GetChannels());
}
[HttpGet, Route("Activities")]
public ActionResult FetchActivities()
{
//var reqAt = DateTime.Now;
//var result = query.GetActivities();
//var response = new RestResponse<Activities>()
//{
// Message = "Success",
// StatusCode = (int)HttpStatusCode.OK,
// Data = result.ToList(),
// RequestAt = reqAt,
// ResponseAt = DateTime.Now,
//};
return Ok(query.GetActivities());
}
[HttpGet, Route("Documents")]
public ActionResult FetchDocuments()
{
//var reqAt = DateTime.Now;
//var result = query.GetDocuments();
//var response = new RestResponse<Documents>()
//{
// Message = "Success",
// StatusCode = (int)HttpStatusCode.OK,
// Data = result.ToList(),
// RequestAt = reqAt,
// ResponseAt = DateTime.Now,
//};
return Ok(query.GetDocuments());
}
[HttpGet, Route("Videos")]
public ActionResult FetchVideos()
{
//var reqAt = DateTime.Now;
//var result = query.GetVideos();
//var response = new RestResponse<Videos>()
//{
// Message = "Success",
// StatusCode = (int)HttpStatusCode.OK,
// Data = result.ToList(),
// RequestAt = reqAt,
// ResponseAt = DateTime.Now,
//};
return Ok(query.GetVideos());
}
}
}
| 28.994286 | 150 | 0.527 | [
"MIT"
] | muhammad-hari/social-network-page | Social.Network.Api/Social.Network.Api/Controllers/SocialNetworkController.cs | 5,076 | C# |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace CoinBot.Core
{
public class MarketManager
{
/// <summary>
/// The <see cref="IMarketClient"/>s.
/// </summary>
private readonly List<IMarketClient> _clients;
private readonly IReadOnlyDictionary<string, Exchange> _exchanges;
/// <summary>
/// The <see cref="ILogger"/>.
/// </summary>
private readonly ILogger _logger;
/// <summary>
/// The tick interval <see cref="TimeSpan"/>.
/// </summary>
private readonly TimeSpan _tickInterval;
/// <summary>
/// The <see cref="Timer"/>.
/// </summary>
private Timer _timer;
public MarketManager(IOptions<MarketManagerSettings> settings, IEnumerable<IMarketClient> clients, ILogger logger)
{
this._clients = clients.ToList() ?? throw new ArgumentNullException(nameof(clients));
this._logger = logger ?? throw new ArgumentNullException(nameof(logger));
this._tickInterval = TimeSpan.FromMinutes(settings.Value.RefreshInterval);
this._exchanges = new ReadOnlyDictionary<string, Exchange>(this._clients.ToDictionary(client => client.Name, client => new Exchange
{
Lock = new ReaderWriterLockSlim()
}));
}
public IEnumerable<MarketSummaryDto> Get(Currency currency)
{
List<MarketSummaryDto> results = new List<MarketSummaryDto>();
foreach (KeyValuePair<string, Exchange> row in this._exchanges)
{
string name = row.Key;
Exchange exchange = row.Value;
// Enter read lock with a timeout of 3 seconds to continue to the next exchange.
if (!exchange.Lock.TryEnterReadLock(TimeSpan.FromSeconds(3)))
{
this._logger.LogWarning(0, $"The '{name}' exchange was locked for more than 3 seconds.");
continue;
}
try
{
if (exchange.Markets == null)
continue;
IEnumerable<MarketSummaryDto> markets = exchange.Markets.Where(m =>
{
// TODO FIX EMPTY CURRENCIES
if (m.BaseCurrrency == null || m.MarketCurrency == null)
return false;
if (m.BaseCurrrency?.Symbol.Equals(currency.Symbol, StringComparison.OrdinalIgnoreCase) != false ||
m.MarketCurrency?.Symbol.Equals(currency.Symbol, StringComparison.OrdinalIgnoreCase) != false)
return true;
return false;
});
results.AddRange(markets);
}
finally
{
exchange.Lock.ExitReadLock();
}
}
return results;
}
public IEnumerable<MarketSummaryDto> GetPair(Currency currency1, Currency currency2)
{
List<MarketSummaryDto> results = new List<MarketSummaryDto>();
foreach (KeyValuePair<string, Exchange> row in this._exchanges)
{
string name = row.Key;
Exchange exchange = row.Value;
// Enter read lock with a timeout of 3 seconds to continue to the next exchange.
if (!exchange.Lock.TryEnterReadLock(TimeSpan.FromSeconds(3)))
{
this._logger.LogWarning(0, $"The '{name}' exchange was locked for more than 3 seconds.");
continue;
}
try
{
if (exchange.Markets == null)
continue;
IEnumerable<MarketSummaryDto> markets = exchange.Markets.Where(m =>
{
// TODO FIX EMPTY CURRENCIES
if (m.BaseCurrrency == null || m.MarketCurrency == null)
return false;
if ((m.BaseCurrrency?.Symbol.Equals(currency1.Symbol, StringComparison.OrdinalIgnoreCase) != false &&
m.MarketCurrency?.Symbol.Equals(currency2.Symbol, StringComparison.OrdinalIgnoreCase) != false) ||
(m.BaseCurrrency?.Symbol.Equals(currency2.Symbol, StringComparison.OrdinalIgnoreCase) != false &&
m.MarketCurrency?.Symbol.Equals(currency1.Symbol, StringComparison.OrdinalIgnoreCase) != false))
return true;
return false;
});
results.AddRange(markets);
}
finally
{
exchange.Lock.ExitReadLock();
}
}
return results;
}
public void Start()
{
// start a timer to fire the tickFunction
this._timer = new Timer(
async state => await this.Tick(),
null,
TimeSpan.FromSeconds(0),
Timeout.InfiniteTimeSpan);
}
public void Stop()
{
// stop the timer
this._timer.Dispose();
this._timer = null;
}
private Task Tick()
{
try
{
this.Update();
}
catch (Exception e)
{
this._logger.LogError(new EventId(e.HResult), e, e.Message);
}
finally
{
// and reset the timer
this._timer.Change(this._tickInterval, TimeSpan.Zero);
}
return Task.CompletedTask;
}
/// <summary>
/// Updates the markets.
/// </summary>
/// <returns></returns>
private void Update()
{
Parallel.ForEach(this._clients, client =>
{
if (this._exchanges.TryGetValue(client.Name, out Exchange exchange))
{
this._logger.LogInformation($"Start updating exchange '{client.Name}'.");
Stopwatch watch = new Stopwatch();
watch.Start();
IReadOnlyCollection<MarketSummaryDto> markets;
try
{
markets = client.Get().Result;
}
catch (Exception e)
{
this._logger.LogError(0, e, $"An error occurred while fetching results from the exchange '{client.Name}'.");
exchange.Lock.EnterWriteLock();
try
{
// Remove out-of-date market summaries
exchange.Markets = null;
}
finally
{
exchange.Lock.ExitWriteLock();
}
return;
}
// Update market summaries
exchange.Lock.EnterWriteLock();
try
{
exchange.Markets = markets;
watch.Stop();
this._logger.LogInformation($"Finished updating exchange '{client.Name}' in {watch.ElapsedMilliseconds}ms.");
}
finally
{
exchange.Lock.ExitWriteLock();
}
}
else
this._logger.LogWarning(0, $"Couldn't find exchange {client.Name}.");
});
}
private class Exchange
{
public ReaderWriterLockSlim Lock;
public IReadOnlyCollection<MarketSummaryDto> Markets;
}
}
}
| 26.755459 | 137 | 0.653501 | [
"MIT"
] | rroslund/CoinBot | src/CoinBot.Core/MarketManager.cs | 6,129 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using Google.Cloud.Firestore;
using Newtonsoft.Json;
using AkshaySDemoGoogleFireStoreDB.Models;
using System.Threading.Tasks;
using System.Linq;
using Google.Cloud.Firestore.V1;
namespace AkshaySDemoGoogleFireStoreDB.DataAccess
{
public class ChefDataAccessLayer
{
public static string GoogleApisOAuthJsonString { get; set; }
FirestoreDb fireStoreDB;
public ChefDataAccessLayer()
{
FirestoreClientBuilder firestoreClientBuilder = new FirestoreClientBuilder();
firestoreClientBuilder.JsonCredentials = GoogleApisOAuthJsonString;
FirestoreClient firestoreClient = firestoreClientBuilder.Build();
fireStoreDB = FirestoreDb.Create("akshaysdemo", firestoreClient);
}
public async Task<List<Chef>> GetAllChefs()
{
try
{
Query chefQuery = fireStoreDB.Collection("chefs");
QuerySnapshot chefQuerySnapshot = await chefQuery.GetSnapshotAsync();
List<Chef> lstChefs = new List<Chef>();
foreach(DocumentSnapshot documentSnapshot in chefQuerySnapshot.Documents)
{
if(documentSnapshot.Exists)
{
Dictionary<string, object> name = documentSnapshot.ToDictionary();
string json = JsonConvert.SerializeObject(name);
Chef newChef = JsonConvert.DeserializeObject<Chef>(json);
newChef.ID = documentSnapshot.Id;
lstChefs.Add(newChef);
}
}
return lstChefs;
}
catch
{
throw;
}
}
public async void AddChef(Chef chef)
{
try
{
CollectionReference chefsRef = fireStoreDB.Collection("chefs");
await chefsRef.AddAsync(chef);
}
catch
{
throw;
}
}
public async void UpdateChef(Chef chef)
{
try
{
DocumentReference chefRef = fireStoreDB.Collection("chefs").Document(chef.ID.ToString());
await chefRef.SetAsync(chef, SetOptions.Overwrite);
}
catch
{
throw;
}
}
public async Task<Chef> GetChefData(int id)
{
try
{
DocumentReference docRef = fireStoreDB.Collection("chefs").Document(id.ToString());
DocumentSnapshot snapshot = await docRef.GetSnapshotAsync();
if (snapshot.Exists)
{
Chef chef = snapshot.ConvertTo<Chef>();
chef.ID = snapshot.Id;
return chef;
}
else
{
return new Chef();
}
}
catch
{
throw;
}
}
public async void DeleteChef(int id)
{
try
{
DocumentReference chefRef = fireStoreDB.Collection("chefs").Document(id.ToString());
await chefRef.DeleteAsync();
}
catch
{
throw;
}
}
public async Task<List<Country>> GetCountryData()
{
try
{
Query countriesQuery = fireStoreDB.Collection("countries");
QuerySnapshot countriesQuerySnapshot = await countriesQuery.GetSnapshotAsync();
List<Country> lstCountries = new List<Country>();
foreach (DocumentSnapshot documentSnapshot in countriesQuerySnapshot.Documents)
{
if (documentSnapshot.Exists)
{
Dictionary<string, object> country = documentSnapshot.ToDictionary();
string json = JsonConvert.SerializeObject(country);
Country newCountry = JsonConvert.DeserializeObject<Country>(json);
lstCountries.Add(newCountry);
}
}
return lstCountries;
}
catch
{
throw;
}
}
}
}
| 31.676056 | 105 | 0.502223 | [
"Apache-2.0"
] | akshays2112/AkshaySDemo | AkshaySDemoGoogleFireStoreDB/DataAccess/ChefDataAccessLayer.cs | 4,500 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using OpenTelemetry.Resources;
using System.Diagnostics;
namespace OpenTelemetry.Exporter.AzureMonitor.Demo.Tracing
{
public static class DemoTrace
{
public static readonly ActivitySource source = new ActivitySource("DemoSource");
public static void Main()
{
var resource = OpenTelemetry.Resources.Resources.CreateServiceResource("my-service", "roleinstance1", "my-namespace");
using var tracerProvider = OpenTelemetry.Sdk.CreateTracerProviderBuilder()
.SetResource(resource)
.AddSource("Demo.DemoServer")
.AddSource("Demo.DemoClient")
.AddAzureMonitorTraceExporter(o => {
o.ConnectionString = $"InstrumentationKey=Ikey;";
})
.Build();
using (var sample = new InstrumentationWithActivitySource())
{
sample.Start();
System.Console.WriteLine("Press ENTER to stop.");
System.Console.ReadLine();
}
}
}
}
| 33.4 | 130 | 0.60479 | [
"MIT"
] | augustoproiete-forks/Azure--azure-sdk-for-net | sdk/monitor/OpenTelemetry.Exporter.AzureMonitor/tests/OpenTelemetry.Exporter.AzureMonitor.Demo.Tracing/DemoTrace.cs | 1,169 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using System.Reflection.Emit;
using Microsoft.Azure.WebJobs.Script.Binding;
namespace Microsoft.Azure.WebJobs.Script.Description
{
[DebuggerDisplay("{Name} ({Metadata.ScriptType})")]
public class FunctionDescriptor
{
// For unit tests.
internal FunctionDescriptor()
{
}
public FunctionDescriptor(
string name,
IFunctionInvoker invoker,
FunctionMetadata metadata,
Collection<ParameterDescriptor> parameters,
Collection<CustomAttributeBuilder> attributes,
Collection<FunctionBinding> inputBindings,
Collection<FunctionBinding> outputBindings)
{
Name = name;
Invoker = invoker;
Parameters = parameters;
CustomAttributes = attributes;
Metadata = metadata;
InputBindings = inputBindings;
OutputBindings = outputBindings;
TriggerParameter = Parameters?.FirstOrDefault(p => p.IsTrigger);
TriggerBinding = InputBindings?.SingleOrDefault(p => p.Metadata.IsTrigger);
HttpTriggerAttribute = GetTriggerAttributeOrNull<HttpTriggerAttribute>();
}
public string Name { get; internal set; }
public Collection<ParameterDescriptor> Parameters { get; }
public Collection<CustomAttributeBuilder> CustomAttributes { get; }
public IFunctionInvoker Invoker { get; internal set; }
public FunctionMetadata Metadata { get; internal set; }
public Collection<FunctionBinding> InputBindings { get; }
public Collection<FunctionBinding> OutputBindings { get; }
public ParameterDescriptor TriggerParameter { get; }
public FunctionBinding TriggerBinding { get; }
public virtual HttpTriggerAttribute HttpTriggerAttribute { get; }
private TAttribute GetTriggerAttributeOrNull<TAttribute>()
{
var extensionBinding = TriggerBinding as ExtensionBinding;
if (extensionBinding != null)
{
return extensionBinding.Attributes.OfType<TAttribute>().SingleOrDefault();
}
return default(TAttribute);
}
}
}
| 33.324324 | 95 | 0.65734 | [
"Apache-2.0",
"MIT"
] | Minh12349/azure-functions-host | src/WebJobs.Script/Description/FunctionDescriptor.cs | 2,468 | C# |
using System;
using System.Diagnostics.CodeAnalysis;
using Zilon.Core.Schemes;
using Zilon.Core.Tactics;
using Zilon.Core.World;
namespace Zilon.Core.Tests.Common
{
[ExcludeFromCodeCoverage]
public class TestMaterializedSectorNode : ISectorNode
{
public TestMaterializedSectorNode(ISectorSubScheme sectorScheme)
{
SectorScheme = sectorScheme ?? throw new ArgumentNullException(nameof(sectorScheme));
}
public IBiome Biome { get; }
public ISector Sector { get; }
public ISectorSubScheme SectorScheme { get; }
public SectorNodeState State => SectorNodeState.SectorMaterialized;
public void BindSchemeInfo(IBiome biom, ISectorSubScheme sectorScheme)
{
throw new NotImplementedException();
}
public void MaterializeSector(ISector sector)
{
throw new NotImplementedException();
}
}
} | 28.484848 | 97 | 0.679787 | [
"MIT"
] | kreghek/Zilon_Roguelike | Zilon.Core/Zilon.Core.Tests.Common/TestMaterializedSectorNode.cs | 942 | C# |
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OSB
{
public class Binding
{
[JsonProperty("instance_id")]
public string InstanceId { get; set; }
[JsonProperty("binding_id")]
public string BindingId { get; set; }
[JsonProperty("service_id")]
public string ServiceId { get; set; }
[JsonProperty("plan_id")]
public string PlanId { get; set; }
}
}
| 24.772727 | 47 | 0.616514 | [
"MIT"
] | Azure-Samples/service-fabric-service-catalog | SFServiceCatalog/OSBClient/Binding.cs | 547 | C# |
using Amphisbaena.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Linq;
using System.Threading.Tasks;
namespace Amphisbaena.Tests.Complex {
[TestClass]
public sealed class FactoryTest {
#region Public
[TestMethod]
public async Task ComplexAggregation() {
int[] data = Enumerable
.Range(0, 1000)
.ToArray();
int expected = data.Sum();
int actual = await data
.ToChannelReader()
.ToBatch((batch, item, index) => batch.Count < 100)
.ForEach(batch => batch.Sum(), new ChannelParallelOptions() { DegreeOfParallelism = 4 })
.Aggregate((s, a) => s + a);
Assert.AreEqual(expected, actual);
}
[TestMethod("Detach even")]
public async Task DetachTest() {
int[] data = Enumerable
.Range(0, 10)
.ToArray();
int expected = data
.Select(x => x % 2 == 0 ? -x : x)
.Sum();
int sumOdd = await data
.ToChannelReader()
.Detach(out var even, item => item % 2 == 0)
.Aggregate((s, a) => s + a);
int sumEven = await even
.Aggregate(0, (s, a) => s - a);
Assert.AreEqual(expected, sumOdd + sumEven);
}
[TestMethod("Attach even")]
public async Task AttachTest() {
int[] data = Enumerable
.Range(0, 100)
.ToArray();
int expected = data.Sum(item => item * 3);
int actual = await data
.ToChannelReader()
.Attach(data
.ToChannelReader()
.Select(item => item * 2))
.Aggregate((s, a) => s + a);
Assert.AreEqual(expected, actual);
}
[TestMethod("Detach Attach")]
public async Task DetachAttach() {
int[] data = Enumerable
.Range(0, 10)
.ToArray();
int expected = data
.Select(x => x % 2 == 0 ? -x : x)
.Sum(item => item);
int actual = await data
.ToChannelReader()
.DetachAttach(
item => item % 2 == 0,
reader => reader.Select(x => -x)
)
.Aggregate((s, a) => s + a);
Assert.AreEqual(expected, actual);
}
#endregion Public
}
}
| 23.51087 | 96 | 0.541378 | [
"MIT"
] | Dmitry-Bychenko/Amphisbaena | Amphisbaena.Tests/Complex/Test.Complex.Aggregations.cs | 2,165 | C# |
using System;
using System.Collections.Generic;
using ModestTree;
namespace Zenject
{
[NoReflectionBaking]
public class ResolveProvider : IProvider
{
readonly object _identifier;
readonly DiContainer _container;
readonly Type _contractType;
readonly bool _isOptional;
readonly InjectSources _source;
readonly bool _matchAll;
public ResolveProvider(
Type contractType, DiContainer container, object identifier,
bool isOptional, InjectSources source, bool matchAll)
{
_contractType = contractType;
_identifier = identifier;
_container = container;
_isOptional = isOptional;
_source = source;
_matchAll = matchAll;
}
public bool IsCached
{
get { return false; }
}
public bool TypeVariesBasedOnMemberType
{
get { return false; }
}
public Type GetInstanceType(InjectContext context)
{
return _contractType;
}
public void GetAllInstancesWithInjectSplit(
InjectContext context, List<TypeValuePair> args, out Action injectAction, List<object> buffer)
{
Assert.IsEmpty(args);
Assert.IsNotNull(context);
Assert.That(_contractType.DerivesFromOrEqual(context.MemberType));
injectAction = null;
if (_matchAll)
{
_container.ResolveAll(GetSubContext(context), buffer);
}
else
{
buffer.Add(_container.Resolve(GetSubContext(context)));
}
}
InjectContext GetSubContext(InjectContext parent)
{
var subContext = parent.CreateSubContext(_contractType, _identifier);
subContext.SourceType = _source;
subContext.Optional = _isOptional;
return subContext;
}
}
}
| 27.040541 | 106 | 0.584708 | [
"MIT"
] | 0007berd/MergeTest | Assets/Plugins/Zenject/Source/Providers/ResolveProvider.cs | 2,001 | C# |
using System;
namespace AGXUnity
{
/// <summary>
/// Simulation step callback functions.
/// </summary>
public class StepCallbackFunctions
{
/// <summary>
/// Step callback signature: void callback()
/// </summary>
public delegate void StepCallbackDef();
/// <summary>
/// Before native simulation.stepForward is called. This callback is
/// fired before the native transforms are written so feel free to
/// change and use Unity object transforms.
/// </summary>
public StepCallbackDef PreStepForward;
/// <summary>
/// After PreStepForward, before native simulation.stepForward is called.
/// Synchronize all native transforms during this callback.
/// </summary>
public StepCallbackDef PreSynchronizeTransforms;
/// <summary>
/// Callback after native simulation.stepForward is done and before any
/// other post callbacks. Write back transforms from the simulation to
/// the Unity objects during this call.
/// </summary>
public StepCallbackDef PostSynchronizeTransforms;
/// <summary>
/// After PostSynchronizeTransforms where the Unity objects have the
/// transforms of the simulation step. During this callback it's possible
/// to use "all" data from the simulation.
/// </summary>
public StepCallbackDef PostStepForward;
/// <summary>
/// Simulation step event - pre-collide.
/// </summary>
public StepCallbackDef SimulationPreCollide;
/// <summary>
/// Simulation step event - pre.
/// </summary>
public StepCallbackDef SimulationPre;
/// <summary>
/// Simulation step event - post.
/// </summary>
public StepCallbackDef SimulationPost;
/// <summary>
/// Simulation step event - last.
/// </summary>
public StepCallbackDef SimulationLast;
/// <summary>
/// Internal preparation callbacks.
/// </summary>
public StepCallbackDef _Internal_PrePre;
/// <summary>
/// Internal preparation callbacks.
/// </summary>
public StepCallbackDef _Internal_PrePost;
public void OnInitialize( agxSDK.Simulation simulation )
{
m_simulationStepEvents = new SimulationStepEvents( this );
simulation.add( m_simulationStepEvents );
}
public void OnDestroy( agxSDK.Simulation simulation )
{
if ( m_simulationStepEvents == null )
return;
simulation.remove( m_simulationStepEvents );
m_simulationStepEvents.Dispose();
m_simulationStepEvents = null;
}
private SimulationStepEvents m_simulationStepEvents = null;
private class SimulationStepEvents : agxSDK.StepEventListener
{
private StepCallbackFunctions m_functions = null;
public SimulationStepEvents( StepCallbackFunctions functions )
: base( (int)ActivationMask.ALL )
{
m_functions = functions;
}
public sealed override void preCollide( double time )
{
Invoke( m_functions.SimulationPreCollide );
}
public sealed override void pre( double time )
{
Invoke( m_functions.SimulationPre, m_functions._Internal_PrePre );
}
public sealed override void post( double time )
{
Invoke( m_functions.SimulationPost, m_functions._Internal_PrePost );
}
public sealed override void last( double time )
{
Invoke( m_functions.SimulationLast );
}
private void Invoke( StepCallbackDef callbacks, StepCallbackDef internalPre = null )
{
if ( callbacks != null || internalPre != null ) {
BeginManagedCallbacks();
internalPre?.Invoke();
callbacks?.Invoke();
EndManagedCallbacks();
}
}
private void BeginManagedCallbacks()
{
agx.agxSWIG.setEntityCreationThreadSafe( true );
}
private void EndManagedCallbacks()
{
agx.agxSWIG.setEntityCreationThreadSafe( false );
}
}
}
}
| 28.056338 | 90 | 0.654869 | [
"Apache-2.0"
] | Algoryx/AGXUnity | AGXUnity/StepCallbackFunctions.cs | 3,986 | C# |
using System;
namespace Elsa.Attributes
{
[AttributeUsage(AttributeTargets.Property)]
public class ActivityInputObjectAttribute : Attribute
{
/// <summary>
/// A category to group these property with - will be overidden by any inputs that specify their own category.
/// </summary>
public string? Category { get; set; }
}
} | 28.615385 | 118 | 0.66129 | [
"MIT"
] | sfmskywalker/Flowsharp | src/core/Elsa.Abstractions/Attributes/ActivityInputObjectAttribute.cs | 372 | C# |
using System;
using Bunit;
using FluentAssertions;
using NUnit.Framework;
namespace MudBlazor.UnitTests.Components
{
[TestFixture]
public class ProgressTests : BunitTest
{
/// <summary>
/// Value is converted from the min - max range into 0 - 100 percent range
/// </summary>
[Test]
public void Progress_Should_ConvertValueRangeToPercent()
{
var comp = Context.RenderComponent<MudProgressLinear>(x =>
{
x.Add(y => y.Min, -500);
x.Add(y => y.Max, 500);
x.Add(y => y.Value, -400);
x.Add(y => y.BufferValue, 400);
});
Console.WriteLine(comp.Markup);
// checking range conversion
comp.Instance.GetValuePercent().Should().Be(10);
comp.Instance.GetBufferPercent().Should().Be(90);
// checking cut-off at min and max
comp.SetParam(x => x.Min, 0.0);
comp.Instance.GetValuePercent().Should().Be(0);
comp.SetParam(x => x.Min, -500.0);
comp.SetParam(x => x.Max, 0.0);
comp.Instance.GetBufferPercent().Should().Be(100);
comp.SetParam(x => x.Min, 0.0);
comp.SetParam(x => x.Max, 100.0);
comp.SetParam(x => x.Value, 100.0);
comp.Instance.GetValuePercent().Should().Be(100);
comp.SetParam(x => x.Value, -2.0);
comp.SetParam(x => x.Min, -7.0);
comp.SetParam(x => x.Max, 7.0);
comp.SetParam(x => x.Buffer, false);
var percent = (-2 - (-7)) / 14.0 * 100;
comp.Instance.GetValuePercent().Should().Be(percent);
comp.Find("div.mud-progress-linear-bar").MarkupMatches(
$"<div class=\"mud-progress-linear-bar mud-default mud-progress-linear-bar-1-determinate\" style=\"transform: translateX(-{Math.Round(100 - percent)}%);\"></div>");
}
}
}
| 39.7 | 180 | 0.533501 | [
"MIT"
] | AssayNet/MudBlazor | src/MudBlazor.UnitTests/Components/ProgressTests.cs | 1,987 | C# |
namespace Entitas
{
/// Implement this interface if you want to create a system which should
/// execute cleanup logic after execution.
public interface ICleanupSystem : ISystem
{
void Cleanup();
}
} | 25.333333 | 76 | 0.671053 | [
"MIT"
] | kubagdynia/TanmaNabu | TanmaNabu/Core/Entitas/Systems/Interfaces/ICleanupSystem.cs | 230 | C# |
#region Apache License
//
// 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.
//
#endregion
using System;
using System.IO;
using log4net;
using log4net.Core;
namespace log4net.Layout
{
/// <summary>
/// Adapts any <see cref="ILayout"/> to a <see cref="IRawLayout"/>
/// </summary>
/// <remarks>
/// <para>
/// Where an <see cref="IRawLayout"/> is required this adapter
/// allows a <see cref="ILayout"/> to be specified.
/// </para>
/// </remarks>
/// <author>Nicko Cadell</author>
/// <author>Gert Driesen</author>
public class Layout2RawLayoutAdapter : IRawLayout
{
#region Member Variables
/// <summary>
/// The layout to adapt
/// </summary>
private ILayout m_layout;
#endregion
#region Constructors
/// <summary>
/// Construct a new adapter
/// </summary>
/// <param name="layout">the layout to adapt</param>
/// <remarks>
/// <para>
/// Create the adapter for the specified <paramref name="layout"/>.
/// </para>
/// </remarks>
public Layout2RawLayoutAdapter(ILayout layout)
{
m_layout = layout;
}
#endregion
#region Implementation of IRawLayout
/// <summary>
/// Format the logging event as an object.
/// </summary>
/// <param name="loggingEvent">The event to format</param>
/// <returns>returns the formatted event</returns>
/// <remarks>
/// <para>
/// Format the logging event as an object.
/// </para>
/// <para>
/// Uses the <see cref="ILayout"/> object supplied to
/// the constructor to perform the formatting.
/// </para>
/// </remarks>
virtual public object Format(LoggingEvent loggingEvent)
{
using StringWriter writer = new StringWriter(System.Globalization.CultureInfo.InvariantCulture);
m_layout.Format(writer, loggingEvent);
return writer.ToString();
}
#endregion
}
}
| 27.085106 | 99 | 0.686567 | [
"Apache-2.0"
] | 13thirteen/logging-log4net | src/log4net/Layout/Layout2RawLayoutAdapter.cs | 2,546 | C# |
#region License
// Copyright (c) 2007 James Newton-King
//
// 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
using System;
using System.Collections.Generic;
using Newtonsoft.JsonV4.Linq;
using Newtonsoft.JsonV4.Serialization;
using Newtonsoft.JsonV4.Tests.TestObjects;
using Newtonsoft.JsonV4.Utilities;
#if !NETFX_CORE
using NUnit.Framework;
#else
using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
using TestFixture = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute;
using Test = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute;
#endif
using System.Reflection;
namespace Newtonsoft.JsonV4.Tests.Serialization
{
[TestFixture]
public class CamelCasePropertyNamesContractResolverTests : TestFixtureBase
{
[Test]
public void JsonConvertSerializerSettings()
{
Person person = new Person();
person.BirthDate = new DateTime(2000, 11, 20, 23, 55, 44, DateTimeKind.Utc);
person.LastModified = new DateTime(2000, 11, 20, 23, 55, 44, DateTimeKind.Utc);
person.Name = "Name!";
string json = JsonConvert.SerializeObject(person, Formatting.Indented, new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
});
Assert.AreEqual(@"{
""name"": ""Name!"",
""birthDate"": ""2000-11-20T23:55:44Z"",
""lastModified"": ""2000-11-20T23:55:44Z""
}", json);
Person deserializedPerson = JsonConvert.DeserializeObject<Person>(json, new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
});
Assert.AreEqual(person.BirthDate, deserializedPerson.BirthDate);
Assert.AreEqual(person.LastModified, deserializedPerson.LastModified);
Assert.AreEqual(person.Name, deserializedPerson.Name);
json = JsonConvert.SerializeObject(person, Formatting.Indented);
Assert.AreEqual(@"{
""Name"": ""Name!"",
""BirthDate"": ""2000-11-20T23:55:44Z"",
""LastModified"": ""2000-11-20T23:55:44Z""
}", json);
}
[Test]
public void JTokenWriter()
{
JsonIgnoreAttributeOnClassTestClass ignoreAttributeOnClassTestClass = new JsonIgnoreAttributeOnClassTestClass();
ignoreAttributeOnClassTestClass.Field = int.MinValue;
JsonSerializer serializer = new JsonSerializer();
serializer.ContractResolver = new CamelCasePropertyNamesContractResolver();
JTokenWriter writer = new JTokenWriter();
serializer.Serialize(writer, ignoreAttributeOnClassTestClass);
JObject o = (JObject)writer.Token;
JProperty p = o.Property("theField");
Assert.IsNotNull(p);
Assert.AreEqual(int.MinValue, (int)p.Value);
string json = o.ToString();
}
#if !(NETFX_CORE || PORTABLE || PORTABLE40)
#pragma warning disable 618
[Test]
public void MemberSearchFlags()
{
PrivateMembersClass privateMembersClass = new PrivateMembersClass("PrivateString!", "InternalString!");
string json = JsonConvert.SerializeObject(privateMembersClass, Formatting.Indented, new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver { DefaultMembersSearchFlags = BindingFlags.NonPublic | BindingFlags.Instance }
});
Assert.AreEqual(@"{
""_privateString"": ""PrivateString!"",
""i"": 0,
""_internalString"": ""InternalString!""
}", json);
PrivateMembersClass deserializedPrivateMembersClass = JsonConvert.DeserializeObject<PrivateMembersClass>(@"{
""_privateString"": ""Private!"",
""i"": -2,
""_internalString"": ""Internal!""
}", new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver { DefaultMembersSearchFlags = BindingFlags.NonPublic | BindingFlags.Instance }
});
Assert.AreEqual("Private!", ReflectionUtils.GetMemberValue(typeof(PrivateMembersClass).GetField("_privateString", BindingFlags.Instance | BindingFlags.NonPublic), deserializedPrivateMembersClass));
Assert.AreEqual("Internal!", ReflectionUtils.GetMemberValue(typeof(PrivateMembersClass).GetField("_internalString", BindingFlags.Instance | BindingFlags.NonPublic), deserializedPrivateMembersClass));
// readonly
Assert.AreEqual(0, ReflectionUtils.GetMemberValue(typeof(PrivateMembersClass).GetField("i", BindingFlags.Instance | BindingFlags.NonPublic), deserializedPrivateMembersClass));
}
#pragma warning restore 618
#endif
[Test]
public void BlogPostExample()
{
Product product = new Product
{
ExpiryDate = new DateTime(2010, 12, 20, 18, 1, 0, DateTimeKind.Utc),
Name = "Widget",
Price = 9.99m,
Sizes = new[] { "Small", "Medium", "Large" }
};
string json =
JsonConvert.SerializeObject(
product,
Formatting.Indented,
new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }
);
//{
// "name": "Widget",
// "expiryDate": "\/Date(1292868060000)\/",
// "price": 9.99,
// "sizes": [
// "Small",
// "Medium",
// "Large"
// ]
//}
Assert.AreEqual(@"{
""name"": ""Widget"",
""expiryDate"": ""2010-12-20T18:01:00Z"",
""price"": 9.99,
""sizes"": [
""Small"",
""Medium"",
""Large""
]
}", json);
}
#if !(NET35 || NET20 || PORTABLE40)
[Test]
public void DynamicCamelCasePropertyNames()
{
dynamic o = new TestDynamicObject();
o.Text = "Text!";
o.Integer = int.MaxValue;
string json = JsonConvert.SerializeObject(o, Formatting.Indented,
new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
});
Assert.AreEqual(@"{
""explicit"": false,
""text"": ""Text!"",
""integer"": 2147483647,
""int"": 0,
""childObject"": null
}", json);
}
#endif
[Test]
public void DictionaryCamelCasePropertyNames()
{
Dictionary<string, string> values = new Dictionary<string, string>
{
{ "First", "Value1!" },
{ "Second", "Value2!" }
};
string json = JsonConvert.SerializeObject(values, Formatting.Indented,
new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
});
Assert.AreEqual(@"{
""first"": ""Value1!"",
""second"": ""Value2!""
}", json);
}
}
} | 36.283186 | 211 | 0.628902 | [
"MIT"
] | woodp/Newtonsoft.Json | Src/Newtonsoft.Json.Tests/Serialization/CamelCasePropertyNamesContractResolverTests.cs | 8,200 | C# |
/*
Copyright 2020 George Lasry, Nils Kopal, CrypTool project
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using CrypTool.CrypAnalysisViewControl;
using CrypTool.PluginBase;
using CrypTool.PluginBase.Miscellaneous;
using EnigmaAnalyzerLib;
using EnigmaAnalyzerLib.Common;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Windows.Controls;
using System.Windows.Threading;
using static CrypTool.EnigmaAnalyzer.EnigmaAnalyzer;
using static EnigmaAnalyzerLib.Key;
namespace CrypTool.EnigmaAnalyzer
{
[Author("George Lasry, Nils Kopal", "george.lasry@CrypTool.org", "CrypTool project", "http://www.CrypTool.org")]
[PluginInfo("CrypTool.EnigmaAnalyzer.Properties.Resources", "PluginCaption", "PluginTooltip", "EnigmaAnalyzer/DetailedDescription/doc.xml",
"EnigmaAnalyzer/Images/Enigma.png")]
[ComponentCategory(ComponentCategory.CryptanalysisSpecific)]
public class EnigmaAnalyzer : ICrypComponent
{
public delegate void OnNewBestKey(NewBestKeyEventArgs args);
public delegate void OnNewBestPlaintext(NewBestPlaintextEventArgs args);
public delegate void OnNewBestlistEntry(NewBestListEntryArgs args);
public delegate void OnNewCryptanalysisStep(NewCryptanalysisStepArgs args);
private const string ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private const int MAX_BESTLIST_ENTRIES = 100;
private readonly EnigmaAnalyzerSettings _settings = new EnigmaAnalyzerSettings();
private readonly AssignmentPresentation _presentation = new AssignmentPresentation();
private readonly IList<UnknownToken> _unknownList = new List<UnknownToken>();
private readonly IList<UnknownToken> _lowerList = new List<UnknownToken>();
private string _ciphertext = string.Empty;
private string _crib = string.Empty;
private string _plaintext = string.Empty;
private string _key = string.Empty;
private string _plugsInput = string.Empty;
private UiResultReporter _resultReporter = null;
public ISettings Settings => _settings;
public UserControl Presentation => _presentation;
[PropertyInfo(Direction.InputData, "CiphertextCaption", "CiphertextTooltip", true)]
public string Ciphertext
{
get => _ciphertext;
set => _ciphertext = value;
}
[PropertyInfo(Direction.InputData, "CribCaption", "CribTooltip", false)]
public string Crib
{
get => _crib;
set => _crib = value;
}
[PropertyInfo(Direction.InputData, "PlugsInputCaption", "PlugsInputTooltip", false)]
public string PlugsInput
{
get => _plugsInput;
set => _plugsInput = value;
}
[PropertyInfo(Direction.OutputData, "PlaintextCaption", "PlaintextTooltip", true)]
public string Plaintext
{
get => _plaintext;
set
{
_plaintext = value;
OnPropertyChanged("Plaintext");
}
}
[PropertyInfo(Direction.OutputData, "KeyCaption", "KeyTooltip", true)]
public string Key
{
get => _key;
set
{
_key = value;
OnPropertyChanged("Key");
}
}
public event StatusChangedEventHandler OnPluginStatusChanged;
public event PluginProgressChangedEventHandler OnPluginProgressChanged;
public event GuiLogNotificationEventHandler OnGuiLogNotificationOccured;
public event PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// Format the string to contain only alphabet characters in upper case
/// </summary>
/// <param name="text">The string to be prepared</param>
/// <returns>The properly formated string to be processed direct by the encryption function</returns>
public string PreFormatInput(string text)
{
StringBuilder result = new StringBuilder();
bool newToken = true;
_unknownList.Clear();
_lowerList.Clear();
for (int i = 0; i < text.Length; i++)
{
if (ALPHABET.Contains(char.ToUpper(text[i])))
{
newToken = true;
if (text[i] == char.ToLower(text[i])) //Solution for preserve FIXME underconstruction
{
if (_settings.UnknownSymbolHandling == 1)
{
_lowerList.Add(new UnknownToken(text[i], result.Length));
}
else
{
_lowerList.Add(new UnknownToken(text[i], i));
}
} //underconstruction end
result.Append(char.ToUpper(text[i])); // FIXME: shall save positions of lowercase letters
}
else if (_settings.UnknownSymbolHandling != 1) // 1 := remove
{
// 0 := preserve, 2 := replace by X
char symbol = _settings.UnknownSymbolHandling == 0 ? text[i] : 'X';
if (newToken)
{
_unknownList.Add(new UnknownToken(symbol, i));
newToken = false;
}
else
{
_unknownList.Last().Text += symbol;
}
}
}
return result.ToString().ToUpper();
}
/// <summary>
/// Formats the string processed by the encryption for presentation according
/// to the settings given
/// </summary>
/// <param name="text">The encrypted text</param>
/// <returns>The formatted text for output</returns>
public string PostFormatOutput(string text)
{
StringBuilder workstring = new StringBuilder(text);
foreach (UnknownToken token in _unknownList)
{
workstring.Insert(token.Position, token.Text);
}
foreach (UnknownToken token in _lowerList) //Solution for preserve FIXME underconstruction
{
char help = workstring[token.Position];
workstring.Remove(token.Position, 1);
workstring.Insert(token.Position, char.ToLower(help));
} //underconstruction end
switch (_settings.CaseHandling)
{
default:
case 0: // preserve
// FIXME: shall restore lowercase letters
return workstring.ToString();
case 1: // upper
return workstring.ToString().ToUpper();
case 2: // lower
return workstring.ToString().ToLower();
}
}
public void PreExecution()
{
}
public void PostExecution()
{
}
public void Execute()
{
// reset presentation
_presentation.Dispatcher.Invoke(DispatcherPriority.Normal, (SendOrPostCallback)delegate
{
_presentation.BestList.Clear();
}, null);
UpdateStartTime(DateTime.Now);
_resultReporter = new UiResultReporter(this);
_resultReporter.OnGuiLogNotificationOccured += OnGuiLogNotificationOccured;
_resultReporter.OnPluginProgressChanged += OnPluginProgressChanged;
_resultReporter.OnNewBestlistEntry += _resultReporter_OnNewBestlistEntry;
_resultReporter.OnNewCryptanalysisStep += _resultReporter_OnNewCryptanalysisStep;
switch (_settings.AnalysisMode)
{
case AnalysisMode.BOMBE:
try
{
NewCryptanalysisStepArgs step = new NewCryptanalysisStepArgs("Turing Bombe");
_resultReporter_OnNewCryptanalysisStep(step);
OnNewAnalysisMode(step);
PerformTuringBombeAnalysis();
}
catch (Exception ex)
{
GuiLogMessage(string.Format("Exception occured during Turing bombe analysis: {0}", ex.Message), NotificationLevel.Error);
}
finally
{
//inform cryptanalysis threads to stop
_resultReporter.ShouldTerminate = true;
}
break;
case AnalysisMode.IC_SEARCH:
{
NewCryptanalysisStepArgs step = new NewCryptanalysisStepArgs("IoC Search");
_resultReporter_OnNewCryptanalysisStep(step);
OnNewAnalysisMode(step);
PerformICTrigramSearch(true);
}
break;
case AnalysisMode.TRIGRAM_SEARCH:
{
NewCryptanalysisStepArgs step = new NewCryptanalysisStepArgs("Trigram Search");
_resultReporter_OnNewCryptanalysisStep(step);
OnNewAnalysisMode(step);
PerformICTrigramSearch(false);
}
break;
case AnalysisMode.HILLCLIMBING:
{
NewCryptanalysisStepArgs step = new NewCryptanalysisStepArgs("Hillclimbing");
_resultReporter_OnNewCryptanalysisStep(step);
OnNewAnalysisMode(step);
PerformHillclimbingSimulatedAnnealing(HcSaRunnable.Mode.HC);
}
break;
case AnalysisMode.SIMULATED_ANNEALING:
{
NewCryptanalysisStepArgs step = new NewCryptanalysisStepArgs("Simulated Annealing");
_resultReporter_OnNewCryptanalysisStep(step);
OnNewAnalysisMode(step);
PerformHillclimbingSimulatedAnnealing(HcSaRunnable.Mode.SA);
}
break;
case AnalysisMode.GILLOGLY:
{
NewCryptanalysisStepArgs step = new NewCryptanalysisStepArgs("Gillogly");
_resultReporter_OnNewCryptanalysisStep(step);
OnNewAnalysisMode(step);
PerformGilloglyAttack();
}
break;
default:
throw new NotImplementedException(string.Format("Cryptanalysis mode {0} not implemented", _settings.AnalysisMode));
}
}
private void OnNewSearchSpace(Key from, Key to)
{
Presentation.Dispatcher.Invoke(DispatcherPriority.Normal, (SendOrPostCallback)delegate
{
try
{
_presentation.SearchFrom.Value = string.Format("{0}", from.getKeystringShort());
_presentation.SearchTo.Value = string.Format("{0}", to.getKeystringShort());
}
catch (Exception)
{
//do nothing
}
}, null);
}
private void OnNewAnalysisMode(NewCryptanalysisStepArgs args)
{
Presentation.Dispatcher.Invoke(DispatcherPriority.Normal, (SendOrPostCallback)delegate
{
try
{
_presentation.AnalysisMode.Value = args.Step;
}
catch (Exception)
{
//do nothing
}
}, null);
}
private void _resultReporter_OnNewCryptanalysisStep(NewCryptanalysisStepArgs args)
{
Presentation.Dispatcher.Invoke(DispatcherPriority.Normal, (SendOrPostCallback)delegate
{
try
{
_presentation.AnalysisStep.Value = args.Step;
}
catch (Exception)
{
//do nothing
}
}, null);
}
private void _resultReporter_OnNewBestlistEntry(NewBestListEntryArgs args)
{
Presentation.Dispatcher.Invoke(DispatcherPriority.Normal, (SendOrPostCallback)delegate
{
try
{
if (_presentation.BestList.Count > 0 && args.ResultEntry.Value <= _presentation.BestList.Last().Value)
{
return;
}
//Insert new entry at correct place to sustain order of list:
int insertIndex = _presentation.BestList.TakeWhile(e => e.Value > args.ResultEntry.Value).Count();
_presentation.BestList.Insert(insertIndex, args.ResultEntry);
if (_presentation.BestList.Count > MAX_BESTLIST_ENTRIES)
{
_presentation.BestList.RemoveAt(MAX_BESTLIST_ENTRIES);
}
int ranking = 1;
foreach (BestListEntry e in _presentation.BestList)
{
e.Ranking = ranking;
ranking++;
}
//if we have a new number 1, we output it
if (args.ResultEntry.Ranking == 1)
{
Plaintext = args.ResultEntry.Text;
Key = args.ResultEntry.Key;
}
}
catch (Exception)
{
//do nothing
}
}, null);
}
/// <summary>
/// Performs a cryptanalysis using the Turing bombe algorithm
/// </summary>
private void PerformTuringBombeAnalysis()
{
//parameters for Turing bombe analysis
string crib = Crib;
short[] ciphertext = new short[MAXLEN];
string strciphertext = Regex.Replace(Ciphertext != null ? Ciphertext.ToUpper() : string.Empty, "[^A-Z]", "");
int clen;
bool range = true;
Key lowKey = new Key();
Key highKey = new Key();
Key key = new Key();
string indicatorS = "";
string indicatorMessageKeyS = "";
int hc_sa_cycles = 2;
int right_ring_sampling = 1;
MRingScope middle_ring_scope = MRingScope.ALL;
string crib_position = _settings.CribPositionFrom + "-" + _settings.CribPositionTo;
int threads = _settings.CoresUsed + 1;
//convert ciphertext to numerical representation
clen = EnigmaUtils.getText(strciphertext, ciphertext);
//validate/format parameters
if (_settings.CribPositionTo < _settings.CribPositionFrom)
{
GuiLogMessage("Crib position invalid. The position 'from' has to be smaller or equal to the position 'to'", NotificationLevel.Error);
return;
}
if (string.IsNullOrEmpty(crib))
{
GuiLogMessage("No crib given. Turing bombe can not work without any crib", NotificationLevel.Error);
return;
}
if (string.IsNullOrEmpty(strciphertext))
{
GuiLogMessage("Empty ciphertext given. Turing bombe can not work without any ciphertext to analyze", NotificationLevel.Error);
return;
}
if (!CheckRanges())
{
return;
}
SetPlugs(lowKey, highKey, key);
//convert and check key range
GenerateRangeStrings(out string rangeLowS, out string rangeHighS);
int result = setRange(lowKey, highKey, rangeLowS, rangeHighS, _settings.Model);
if (result != 1)
{
GuiLogMessage(string.Format("Invalid key range: {0}-{1} - Invalid key format, or first key has a higher value than the last key", rangeLowS, rangeHighS), NotificationLevel.Error);
return;
}
OnNewSearchSpace(lowKey, highKey);
//analysis objects
BombeSearch bombeSearch = new BombeSearch();
EnigmaStats enigmaStats = new EnigmaStats();
//load correct language
LoadAnalysisLanguage(enigmaStats);
//perform Turing bombe analysis
try
{
bombeSearch.bombeSearch(crib, ciphertext, clen, range, lowKey, highKey, key, indicatorS, indicatorMessageKeyS, hc_sa_cycles,
right_ring_sampling, middle_ring_scope, false, crib_position, threads, enigmaStats, _resultReporter);
}
catch (Exception ex)
{
GuiLogMessage(string.Format("Exception occured during execution of turing bombe analysis: {0}", ex.Message), NotificationLevel.Error);
}
}
/// <summary>
/// Performs a cryptanalysis using ic and trigram search
/// </summary>
/// <param name="findSettingsIc"></param>
private void PerformICTrigramSearch(bool findSettingsIc)
{
//parameters
short[] ciphertext = new short[MAXLEN];
string strciphertext = Regex.Replace(Ciphertext != null ? Ciphertext.ToUpper() : string.Empty, "[^A-Z]", "");
int clen;
Key lowKey = new Key();
Key highKey = new Key();
string indicatorS = "";
string indicatorMessageKeyS = "";
int hc_sa_cycles = 2;
int right_ring_sampling = 1;
MRingScope middle_ring_scope = MRingScope.ALL;
int threads = _settings.CoresUsed + 1;
//check, if we have plugs
if (!findSettingsIc)
{
if (string.IsNullOrEmpty(PlugsInput))
{
GuiLogMessage("No plugs given. Trigram search can not work without any plugs", NotificationLevel.Error);
return;
}
}
//convert ciphertext to numerical representation
clen = EnigmaUtils.getText(strciphertext, ciphertext);
//validate/format parameters
if (string.IsNullOrEmpty(strciphertext))
{
GuiLogMessage("Empty ciphertext given. Cryptanalysis can not work without any ciphertext to analyze", NotificationLevel.Error);
return;
}
if (!CheckRanges())
{
return;
}
SetPlugs(lowKey, highKey, null);
//convert and check key range
GenerateRangeStrings(out string rangeLowS, out string rangeHighS);
int result = setRange(lowKey, highKey, rangeLowS, rangeHighS, _settings.Model);
if (result != 1)
{
GuiLogMessage(string.Format("Invalid key range: {0}-{1} - Invalid key format, or first key has a higher value than the last key", rangeLowS, rangeHighS), NotificationLevel.Error);
return;
}
OnNewSearchSpace(lowKey, highKey);
//analysis objects
TrigramICSearch trigramICSearch = new TrigramICSearch();
EnigmaStats enigmaStats = new EnigmaStats();
//load correct language
LoadAnalysisLanguage(enigmaStats);
//perform hill climbing
try
{
trigramICSearch.searchTrigramIC(lowKey, highKey, findSettingsIc, middle_ring_scope, right_ring_sampling, false, hc_sa_cycles, 0,
threads, ciphertext, clen, indicatorS, indicatorMessageKeyS, enigmaStats, _resultReporter);
}
catch (Exception ex)
{
GuiLogMessage(string.Format("Exception occured during execution of cryptanalysis: {0}", ex.Message), NotificationLevel.Error);
}
}
/// <summary>
/// Sets plugs of lowKey, highKey, and key
/// </summary>
/// <param name="lowKey"></param>
/// <param name="highKey"></param>
/// <param name="key"></param>
private void SetPlugs(Key lowKey, Key highKey, Key key)
{
if (!string.IsNullOrEmpty(PlugsInput))
{
lowKey.setStecker(PlugsInput);
highKey.setStecker(PlugsInput);
if (key != null)
{
key.setStecker(PlugsInput);
}
}
}
/// <summary>
/// Performs a cryptanalysis using (an improved version of) Gillogly's original attack
/// </summary>
/// <param name="findSettingsIc"></param>
private void PerformGilloglyAttack()
{
//parameters
short[] ciphertext = new short[MAXLEN];
string strciphertext = Regex.Replace(Ciphertext != null ? Ciphertext.ToUpper() : string.Empty, "[^A-Z]", "");
int clen;
Key lowKey = new Key();
Key highKey = new Key();
int hc_sa_cycles = 2;
int right_ring_sampling = 1;
int threads = _settings.CoresUsed + 1;
//convert ciphertext to numerical representation
clen = EnigmaUtils.getText(strciphertext, ciphertext);
//validate/format parameters
if (string.IsNullOrEmpty(strciphertext))
{
GuiLogMessage("Empty ciphertext given. Cryptanalysis can not work without any ciphertext to analyze", NotificationLevel.Error);
return;
}
if (!CheckRanges())
{
return;
}
SetPlugs(lowKey, highKey, null);
//convert and check key range
GenerateRangeStrings(out string rangeLowS, out string rangeHighS);
int result = setRange(lowKey, highKey, rangeLowS, rangeHighS, _settings.Model);
if (result != 1)
{
GuiLogMessage(string.Format("Invalid key range: {0}-{1} - Invalid key format, or first key has a higher value than the last key", rangeLowS, rangeHighS), NotificationLevel.Error);
return;
}
OnNewSearchSpace(lowKey, highKey);
//analysis objects
GilloglyAttack gilloglyAttack = new GilloglyAttack();
EnigmaStats enigmaStats = new EnigmaStats();
//load correct language
LoadAnalysisLanguage(enigmaStats);
//perform hill climbing
try
{
gilloglyAttack.PerformAttack(lowKey, highKey, right_ring_sampling, hc_sa_cycles,
threads, ciphertext, clen, enigmaStats, _resultReporter);
}
catch (Exception ex)
{
GuiLogMessage(string.Format("Exception occured during execution of cryptanalysis: {0}", ex.Message), NotificationLevel.Error);
}
}
/// <summary>
/// Performs a cryptanalysis using hill climbing or simulated annealing
/// </summary>
private void PerformHillclimbingSimulatedAnnealing(HcSaRunnable.Mode mode)
{
//parameters
short[] ciphertext = new short[MAXLEN];
string strciphertext = Regex.Replace(Ciphertext != null ? Ciphertext.ToUpper() : string.Empty, "[^A-Z]", "");
int clen;
bool range = true;
int strength = 1;
Key lowKey = new Key();
Key highKey = new Key();
Key key = new Key();
int hc_sa_cycles = 2;
int right_ring_sampling = 1;
MRingScope middle_ring_scope = MRingScope.ALL;
int threads = _settings.CoresUsed + 1;
//convert ciphertext to numerical representation
clen = EnigmaUtils.getText(strciphertext, ciphertext);
//validate/format parameters
if (string.IsNullOrEmpty(strciphertext))
{
GuiLogMessage("Empty ciphertext given. Cryptanalysis can not work without any ciphertext to analyze", NotificationLevel.Error);
return;
}
if (!CheckRanges())
{
return;
}
SetPlugs(lowKey, highKey, key);
//convert and check key range
GenerateRangeStrings(out string rangeLowS, out string rangeHighS);
int result = setRange(lowKey, highKey, rangeLowS, rangeHighS, _settings.Model);
if (result != 1)
{
GuiLogMessage(string.Format("Invalid key range: {0}-{1} - Invalid key format, or first key has a higher value than the last key", rangeLowS, rangeHighS), NotificationLevel.Error);
return;
}
OnNewSearchSpace(lowKey, highKey);
//analysis objects
HillClimb hillClimb = new HillClimb();
EnigmaStats enigmaStats = new EnigmaStats();
//load correct language
LoadAnalysisLanguage(enigmaStats);
//perform hill climbing
try
{
hillClimb.hillClimbRange(range ? lowKey : key, range ? highKey : key, hc_sa_cycles, threads, 0,
middle_ring_scope, right_ring_sampling, ciphertext, clen, mode, strength, enigmaStats, _resultReporter);
}
catch (Exception ex)
{
GuiLogMessage(string.Format("Exception occured during execution of cryptanalysis: {0}", ex.Message), NotificationLevel.Error);
}
}
/// <summary>
/// Lets enigmaStats load the defined analysis language
/// </summary>
/// <param name="enigmaStats"></param>
private void LoadAnalysisLanguage(EnigmaStats enigmaStats)
{
switch (_settings.AnalysisLanguage)
{
case Language.ENGLISH:
enigmaStats.loadBidictFromResources(EnigmaAnalyzerLib.Properties.Resources.english_logbigrams);
enigmaStats.loadTridictFromResource(EnigmaAnalyzerLib.Properties.Resources.english_logtrigrams);
break;
case Language.GERMAN:
default:
enigmaStats.loadBidictFromResources(EnigmaAnalyzerLib.Properties.Resources.german_logbigrams);
enigmaStats.loadTridictFromResource(EnigmaAnalyzerLib.Properties.Resources.german_logtrigrams);
break;
//todo: add french and italian resources
}
}
/// <summary>
/// Checks, if search ranges are valid, e.g. if left rotor from <= left rotor to
/// </summary>
/// <returns></returns>
private bool CheckRanges()
{
//rotor settings
if (_settings.Model == Model.M4 && _settings.GreekRotorFrom > _settings.GreekRotorTo)
{
GuiLogMessage(string.Format("Invalid key range: Greek rotor 'from' has to be smaller or equal to Greek rotor 'to'"), NotificationLevel.Error);
return false;
}
if (_settings.LeftRotorFrom > _settings.LeftRotorTo)
{
GuiLogMessage(string.Format("Invalid key range: left rotor 'from' has to be smaller or equal to left rotor 'to'"), NotificationLevel.Error);
return false;
}
if (_settings.MiddleRotorFrom > _settings.MiddleRotorTo)
{
GuiLogMessage(string.Format("Invalid key range: middle rotor 'from' has to be smaller or equal to middle rotor 'to'"), NotificationLevel.Error);
return false;
}
if (_settings.RightRotorFrom > _settings.RightRotorTo)
{
GuiLogMessage(string.Format("Invalid key range: middle rotor 'from' has to be smaller or equal to middle rotor 'to'"), NotificationLevel.Error);
return false;
}
//ring settings
if (_settings.Model == Model.M4 && _settings.GreekRingFrom > _settings.GreekRingTo)
{
GuiLogMessage(string.Format("Invalid key range: Greek ring 'from' has to be smaller or equal to Greek ring 'to'"), NotificationLevel.Error);
return false;
}
if (_settings.LeftRingFrom > _settings.LeftRingTo)
{
GuiLogMessage(string.Format("Invalid key range: left ring 'from' has to be smaller or equal to left ring 'to'"), NotificationLevel.Error);
return false;
}
if (_settings.MiddleRingFrom > _settings.MiddleRingTo)
{
GuiLogMessage(string.Format("Invalid key range: middle ring 'from' has to be smaller or equal to middle ring 'to'"), NotificationLevel.Error);
return false;
}
if (_settings.RightRingFrom > _settings.RightRingTo)
{
GuiLogMessage(string.Format("Invalid key range: middle ring 'from' has to be smaller or equal to middle ring 'to'"), NotificationLevel.Error);
return false;
}
//rotor positions
if (_settings.Model == Model.M4 && _settings.GreekRotorPositionFrom > _settings.GreekRotorPositionTo)
{
GuiLogMessage(string.Format("Invalid key range: Greek rotor position 'from' has to be smaller or equal to Greek rotor position 'to'"), NotificationLevel.Error);
return false;
}
if (_settings.LeftRotorPositionFrom > _settings.LeftRotorPositionTo)
{
GuiLogMessage(string.Format("Invalid key range: left rotor position 'from' has to be smaller or equal to left rotor position 'to'"), NotificationLevel.Error);
return false;
}
if (_settings.MiddleRotorPositionFrom > _settings.MiddleRotorPositionTo)
{
GuiLogMessage(string.Format("Invalid key range: middle rotor position 'from' has to be smaller or equal to middle rotor position 'to'"), NotificationLevel.Error);
return false;
}
if (_settings.RightRotorPositionFrom > _settings.RightRotorPositionTo)
{
GuiLogMessage(string.Format("Invalid key range: middle rotor position 'from' has to be smaller or equal to middle rotor position 'to'"), NotificationLevel.Error);
return false;
}
return true;
}
/// <summary>
/// Generates range strings for the enigma anylsis based on the settings
/// </summary>
/// <param name="rangeLowS"></param>
/// <param name="rangeHighS"></param>
private void GenerateRangeStrings(out string rangeLowS, out string rangeHighS)
{
/*
case Model.M3:
fminS = "B:111:AAA:AAA";
tmaxS = "C:888:ZZZ:ZZZ";
break;
case Model.M4:
fminS = "B:B111:AAAA:AAAA";
tmaxS = "C:G888:ZZZZ:ZZZZ";
break;
case Model.H:
default:
fminS = "A:111:AAA:AAA";
tmaxS = "C:555:ZZZ:ZZZ";
break;
*/
switch (_settings.Model)
{
case Model.M4:
//M4 has 4 rotors
rangeLowS = string.Format("{0}:{1}{2}{3}{4}:{5}{6}{7}{8}:{9}{10}{11}{12}",
EnigmaAnalyzerSettings.GetReflectString(_settings.ReflectorFrom),
EnigmaAnalyzerSettings.GetRotorString(_settings.GreekRotorFrom),
EnigmaAnalyzerSettings.GetRotorString(_settings.LeftRotorFrom),
EnigmaAnalyzerSettings.GetRotorString(_settings.MiddleRotorFrom),
EnigmaAnalyzerSettings.GetRotorString(_settings.RightRotorFrom),
EnigmaAnalyzerSettings.GetRotorRingPositionString(_settings.GreekRingFrom),
EnigmaAnalyzerSettings.GetRotorRingPositionString(_settings.LeftRingFrom),
EnigmaAnalyzerSettings.GetRotorRingPositionString(_settings.MiddleRingFrom),
EnigmaAnalyzerSettings.GetRotorRingPositionString(_settings.RightRingFrom),
EnigmaAnalyzerSettings.GetRotorRingPositionString(_settings.GreekRotorPositionFrom),
EnigmaAnalyzerSettings.GetRotorRingPositionString(_settings.LeftRotorPositionFrom),
EnigmaAnalyzerSettings.GetRotorRingPositionString(_settings.MiddleRotorPositionFrom),
EnigmaAnalyzerSettings.GetRotorRingPositionString(_settings.RightRotorPositionFrom));
rangeHighS = string.Format("{0}:{1}{2}{3}{4}:{5}{6}{7}{8}:{9}{10}{11}{12}",
EnigmaAnalyzerSettings.GetReflectString(_settings.ReflectorTo),
EnigmaAnalyzerSettings.GetRotorString(_settings.GreekRotorTo),
EnigmaAnalyzerSettings.GetRotorString(_settings.LeftRotorTo),
EnigmaAnalyzerSettings.GetRotorString(_settings.MiddleRotorTo),
EnigmaAnalyzerSettings.GetRotorString(_settings.RightRotorTo),
EnigmaAnalyzerSettings.GetRotorRingPositionString(_settings.GreekRingTo),
EnigmaAnalyzerSettings.GetRotorRingPositionString(_settings.LeftRingTo),
EnigmaAnalyzerSettings.GetRotorRingPositionString(_settings.MiddleRingTo),
EnigmaAnalyzerSettings.GetRotorRingPositionString(_settings.RightRingTo),
EnigmaAnalyzerSettings.GetRotorRingPositionString(_settings.GreekRotorPositionTo),
EnigmaAnalyzerSettings.GetRotorRingPositionString(_settings.LeftRotorPositionTo),
EnigmaAnalyzerSettings.GetRotorRingPositionString(_settings.MiddleRotorPositionTo),
EnigmaAnalyzerSettings.GetRotorRingPositionString(_settings.RightRotorPositionTo));
break;
default:
//all other have 3 rotors
rangeLowS = string.Format("{0}:{1}{2}{3}:{4}{5}{6}:{7}{8}{9}",
EnigmaAnalyzerSettings.GetReflectString(_settings.ReflectorFrom),
EnigmaAnalyzerSettings.GetRotorString(_settings.LeftRotorFrom),
EnigmaAnalyzerSettings.GetRotorString(_settings.MiddleRotorFrom),
EnigmaAnalyzerSettings.GetRotorString(_settings.RightRotorFrom),
EnigmaAnalyzerSettings.GetRotorRingPositionString(_settings.LeftRingFrom),
EnigmaAnalyzerSettings.GetRotorRingPositionString(_settings.MiddleRingFrom),
EnigmaAnalyzerSettings.GetRotorRingPositionString(_settings.RightRingFrom),
EnigmaAnalyzerSettings.GetRotorRingPositionString(_settings.LeftRotorPositionFrom),
EnigmaAnalyzerSettings.GetRotorRingPositionString(_settings.MiddleRotorPositionFrom),
EnigmaAnalyzerSettings.GetRotorRingPositionString(_settings.RightRotorPositionFrom));
rangeHighS = string.Format("{0}:{1}{2}{3}:{4}{5}{6}:{7}{8}{9}",
EnigmaAnalyzerSettings.GetReflectString(_settings.ReflectorTo),
EnigmaAnalyzerSettings.GetRotorString(_settings.LeftRotorTo),
EnigmaAnalyzerSettings.GetRotorString(_settings.MiddleRotorTo),
EnigmaAnalyzerSettings.GetRotorString(_settings.RightRotorTo),
EnigmaAnalyzerSettings.GetRotorRingPositionString(_settings.LeftRingTo),
EnigmaAnalyzerSettings.GetRotorRingPositionString(_settings.MiddleRingTo),
EnigmaAnalyzerSettings.GetRotorRingPositionString(_settings.RightRingTo),
EnigmaAnalyzerSettings.GetRotorRingPositionString(_settings.LeftRotorPositionTo),
EnigmaAnalyzerSettings.GetRotorRingPositionString(_settings.MiddleRotorPositionTo),
EnigmaAnalyzerSettings.GetRotorRingPositionString(_settings.RightRotorPositionTo));
break;
}
}
public void Stop()
{
if (_resultReporter != null)
{
_resultReporter.ShouldTerminate = true;
}
}
public void Initialize()
{
}
public void Dispose()
{
}
private void OnPropertyChanged(string name)
{
EventsHelper.PropertyChanged(PropertyChanged, this, new PropertyChangedEventArgs(name));
}
private void GuiLogMessage(string message, NotificationLevel logLevel)
{
EventsHelper.GuiLogMessage(OnGuiLogNotificationOccured, this, new GuiLogEventArgs(message, this, logLevel));
}
private void ProgressChanged(double value, double max)
{
EventsHelper.ProgressChanged(OnPluginProgressChanged, this, new PluginProgressEventArgs(value, max));
}
public void UpdateStartTime(DateTime startTime)
{
Presentation.Dispatcher.Invoke(DispatcherPriority.Normal, (SendOrPostCallback)delegate
{
try
{
_presentation.StartTime.Value = startTime.ToString();
}
catch (Exception)
{
//do nothing
}
}, null);
}
public void UpdateTimeLeftAndEndTimeLabels(TimeSpan timeLeft)
{
Presentation.Dispatcher.Invoke(DispatcherPriority.Normal, (SendOrPostCallback)delegate
{
try
{
_presentation.TimeLeft.Value = timeLeft.ToString();
_presentation.EndTime.Value = (DateTime.Now + timeLeft).ToString();
}
catch (Exception)
{
//do nothing
}
}, null);
}
}
public class UnknownToken
{
public string Text { get; set; }
public int Position { get; set; }
public UnknownToken(char c, int position)
{
Text = char.ToString(c);
Position = position;
}
public override string ToString()
{
return "[" + Text + "," + Position + "]";
}
}
/// <summary>
/// Single entry of the Bestlist
/// </summary>
public class BestListEntry : ICrypAnalysisResultListEntry, INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private int _ranking;
public int Ranking
{
get => _ranking;
set
{
_ranking = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Ranking)));
}
}
public double Value
{
get;
set;
}
public string Key
{
get;
set;
}
public string Text
{
get;
set;
}
public double ExactValue => Math.Abs(Value);
public string ClipboardValue => ExactValue.ToString();
public string ClipboardKey => Key;
public string ClipboardText => Text;
public string ClipboardEntry =>
Properties.Resources.RankingHeader + " " + Ranking + Environment.NewLine +
Properties.Resources.ValueHeader + " " + ExactValue + Environment.NewLine +
Properties.Resources.KeyHeader + " " + Key + Environment.NewLine +
Properties.Resources.TextHeader + " " + Text;
}
/// <summary>
/// The result reporter ist responsible for receiving new data during the cryptanalysis and
/// then he raises events which are used by the component to output the data to the ui and/or
/// component's outputs
/// </summary>
public class UiResultReporter : ResultReporter
{
private readonly EnigmaAnalyzer _EnigmaAnalyzer;
public event PluginProgressChangedEventHandler OnPluginProgressChanged;
public event GuiLogNotificationEventHandler OnGuiLogNotificationOccured;
public event OnNewBestKey OnNewBestKey;
public event OnNewBestPlaintext OnNewBestPlaintext;
public event OnNewBestlistEntry OnNewBestlistEntry;
public event OnNewCryptanalysisStep OnNewCryptanalysisStep;
private DateTime lastProgressUpdate = DateTime.Now;
private int lastScore = int.MinValue;
private long lastCount = 0;
private const int UPDATE_INTERVAL_SECONDS = 1;
private readonly object _lockObject = new object();
public UiResultReporter(EnigmaAnalyzer EnigmaAnalyzer)
{
_EnigmaAnalyzer = EnigmaAnalyzer;
}
public override void displayBestKey(string key)
{
OnNewBestKey?.Invoke(new NewBestKeyEventArgs(key));
}
public override void displayBestPlaintext(string plaintext)
{
OnNewBestPlaintext?.Invoke(new NewBestPlaintextEventArgs(plaintext));
}
public override void displayProgress(long count, long max)
{
lock (_lockObject)
{
if (DateTime.Now > lastProgressUpdate.AddSeconds(UPDATE_INTERVAL_SECONDS))
{
float speed = (count - lastCount) / (float)UPDATE_INTERVAL_SECONDS;
float totalSeconds = (max - count) / speed;
TimeSpan timeLeft = new TimeSpan(0, 0, 0, (int)totalSeconds);
_EnigmaAnalyzer.UpdateTimeLeftAndEndTimeLabels(timeLeft);
PluginProgressChanged(count, max);
lastProgressUpdate = DateTime.Now;
lastCount = count;
}
}
}
public override void reportResult(Key key, int currScore, string plaintext, string desc, int cribPosition = -1)
{
lock (_lockObject)
{
if (currScore > lastScore)
{
BestListEntry resultEntry = new BestListEntry();
if (cribPosition == -1)
{
resultEntry.Key = key.getKeystringShort();
}
else
{
resultEntry.Key = string.Format("{0}, position={1}", key.getKeystringShort(), cribPosition);
}
resultEntry.Text = plaintext;
resultEntry.Value = currScore;
OnNewBestlistEntry?.Invoke(new NewBestListEntryArgs(resultEntry));
displayBestKey(resultEntry.Key);
displayBestPlaintext(resultEntry.Text);
lastScore = currScore;
}
}
}
public override bool shouldPushResult(int score)
{
return true;
}
public override void WriteException(string message, Exception ex)
{
GuiLogMessage(message, NotificationLevel.Error);
//in case of an exception during the analysis, we stop the analysis process
ShouldTerminate = true;
}
public override void WriteMessage(string message)
{
GuiLogMessage(message, NotificationLevel.Info);
}
public override void WriteWarning(string message)
{
GuiLogMessage(message, NotificationLevel.Warning);
}
private void GuiLogMessage(string message, NotificationLevel logLevel)
{
EventsHelper.GuiLogMessage(OnGuiLogNotificationOccured, _EnigmaAnalyzer, new GuiLogEventArgs(message, _EnigmaAnalyzer, logLevel));
}
private void PluginProgressChanged(double value, double max)
{
EventsHelper.ProgressChanged(OnPluginProgressChanged, _EnigmaAnalyzer, new PluginProgressEventArgs(value, max));
}
public override void UpdateCryptanalysisStep(string step)
{
OnNewCryptanalysisStep?.Invoke(new NewCryptanalysisStepArgs(step));
}
}
public class NewBestKeyEventArgs : EventArgs
{
public string Key
{
get;
private set;
}
public NewBestKeyEventArgs(string key) : base()
{
Key = key;
}
}
public class NewBestPlaintextEventArgs : EventArgs
{
public string Plaintext
{
get;
private set;
}
public NewBestPlaintextEventArgs(string plaintext) : base()
{
Plaintext = plaintext;
}
}
public class NewBestListEntryArgs : EventArgs
{
public BestListEntry ResultEntry
{
get;
private set;
}
public NewBestListEntryArgs(BestListEntry resultEntry) : base()
{
ResultEntry = resultEntry;
}
}
public class NewCryptanalysisStepArgs : EventArgs
{
public string Step
{
get;
private set;
}
public NewCryptanalysisStepArgs(string step) : base()
{
Step = step;
}
}
}
| 40.130658 | 195 | 0.563637 | [
"Apache-2.0"
] | CrypToolProject/CrypTool-2 | CrypPlugins/EnigmaAnalyzer/EnigmaAnalyzer.cs | 46,995 | C# |
//-----------------------------------------------------------------------
// <copyright file="TableAccessPolicyResponse.cs" company="Microsoft">
// Copyright 2012 Microsoft Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
// -----------------------------------------------------------------------------------------
namespace Microsoft.WindowsAzure.Storage.Table.Protocol
{
using System;
using System.IO;
#if !COMMON
using System.Xml.Linq;
#endif
using Microsoft.WindowsAzure.Storage.Shared.Protocol;
/// <summary>
/// Parses the response XML from an operation to set the access policy for a table.
/// </summary>
internal class TableAccessPolicyResponse : AccessPolicyResponseBase<SharedAccessTablePolicy>
{
/// <summary>
/// Initializes a new instance of the TableAccessPolicyResponse class.
/// </summary>
/// <param name="stream">The stream to be parsed.</param>
internal TableAccessPolicyResponse(Stream stream)
: base(stream)
{
}
#if !COMMON
/// <summary>
/// Parses the current element.
/// </summary>
/// <param name="accessPolicyElement">The shared access policy element to parse.</param>
/// <returns>The shared access policy.</returns>
protected override SharedAccessTablePolicy ParseElement(XElement accessPolicyElement)
{
SharedAccessTablePolicy accessPolicy = new SharedAccessTablePolicy();
string sharedAccessStartTimeString = (string)accessPolicyElement.Element(Constants.Start);
if (!string.IsNullOrEmpty(sharedAccessStartTimeString))
{
accessPolicy.SharedAccessStartTime = Uri.UnescapeDataString(sharedAccessStartTimeString).ToUTCTime();
}
string sharedAccessExpiryTimeString = (string)accessPolicyElement.Element(Constants.Expiry);
if (!string.IsNullOrEmpty(sharedAccessExpiryTimeString))
{
accessPolicy.SharedAccessExpiryTime = Uri.UnescapeDataString(sharedAccessExpiryTimeString).ToUTCTime();
}
string permissionsString = (string)accessPolicyElement.Element(Constants.Permission);
if (!string.IsNullOrEmpty(permissionsString))
{
accessPolicy.Permissions = SharedAccessTablePolicy.PermissionsFromString(permissionsString);
}
return accessPolicy;
}
#endif
}
} | 42.589041 | 120 | 0.624317 | [
"Apache-2.0"
] | takekazuomi/azure-sdk-for-net | microsoft-azure-api/Services/Storage/Lib/Common/Table/Protocol/TableAccessPolicyResponse.cs | 3,039 | C# |
using CounterStrike.Models.Guns;
using CounterStrike.Models.Guns.Contracts;
using CounterStrike.Models.Maps;
using CounterStrike.Models.Maps.Contracts;
using CounterStrike.Models.Players;
using CounterStrike.Models.Players.Contracts;
using CounterStrike.Repositories;
using CounterStrike.Utilities.Messages;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CounterStrike.Core.Contracts
{
public class Controller : IController
{
private readonly GunRepository gunRepository;
private readonly PlayerRepository playerRepository;
private readonly IMap map;
public Controller()
{
this.gunRepository = new GunRepository();
this.playerRepository = new PlayerRepository();
this.map = new Map();
}
public string AddGun(string type, string name, int bulletsCount)
{
IGun gun = CreateGun(type, name, bulletsCount);
this.gunRepository.Add(gun);
string msg = string.Format(OutputMessages.SuccessfullyAddedGun, gun.Name);
return msg;
}
public string AddPlayer(string type, string username, int health, int armor, string gunName)
{
IGun gun = this.gunRepository.FindByName(gunName);
if(gun==null)
{
throw new ArgumentException(ExceptionMessages.GunCannotBeFound);
}
IPlayer player = CreatePlayer(type, username, health, armor, gun);
this.playerRepository.Add(player);
string msg = string.Format(OutputMessages.SuccessfullyAddedPlayer, player.Username);
return msg;
}
public string Report()
{
var players = this.playerRepository.Models.OrderBy(p => p.GetType().Name).ThenByDescending(p => p.Health).ThenBy(p => p.Username);
StringBuilder sb = new StringBuilder();
foreach (var p in players)
{
sb.AppendLine(p.ToString());
}
return sb.ToString().Trim();
}
public string StartGame()
{
string result= this.map.Start(this.playerRepository.Models.ToList());
return result;
}
private IGun CreateGun(string type, string name, int bulletsCount)
{
IGun gun = null;
if (type == nameof(Pistol))
gun = new Pistol(name, bulletsCount);
else if (type == nameof(Rifle))
gun = new Rifle(name, bulletsCount);
else
{
throw new ArgumentException(ExceptionMessages.InvalidGunType);
}
return gun;
}
private IPlayer CreatePlayer(string type, string username, int health, int armor, IGun gun)
{
IPlayer player = null;
if (type == nameof(Terrorist))
player = new Terrorist(username, health, armor, gun);
else if (type == nameof(CounterTerrorist))
player = new CounterTerrorist(username, health, armor, gun);
else
{
throw new ArgumentException(ExceptionMessages.InvalidPlayerType);
}
return player;
}
}
}
| 31.865385 | 142 | 0.59475 | [
"MIT"
] | tonchevaAleksandra/C-Sharp-OOP | EXAMS/Exam12April20/Core/Contracts/Controller.cs | 3,316 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace System.IO
{
/// <devdoc>
/// Provides data for the <see cref='System.IO.FileSystemWatcher.Renamed'/> event.
/// </devdoc>
public class RenamedEventArgs : FileSystemEventArgs
{
private readonly string _oldName;
private readonly string _oldFullPath;
/// <devdoc>
/// Initializes a new instance of the <see cref='System.IO.RenamedEventArgs'/> class.
/// </devdoc>
public RenamedEventArgs(WatcherChangeTypes changeType, string directory, string name, string oldName)
: base(changeType, directory, name)
{
_oldName = oldName;
_oldFullPath = Combine(directory, oldName);
}
/// <devdoc>
/// Gets the previous fully qualified path of the affected file or directory.
/// </devdoc>
public string OldFullPath
{
get
{
return _oldFullPath;
}
}
/// <devdoc>
/// Gets the old name of the affected file or directory.
/// </devdoc>
public string OldName
{
get
{
return _oldName;
}
}
}
}
| 29.170213 | 109 | 0.557257 | [
"MIT"
] | 690486439/corefx | src/System.IO.FileSystem.Watcher/src/System/IO/RenamedEventArgs.cs | 1,371 | C# |
using UnityEngine;
public class GrappleImpactSounds : MonoBehaviour
{
public static GrappleImpactSounds instance;
private GameObject player;
private PlayerScript ps;
public AudioSource audioS;
public AudioClip[] clips;
public AudioClip audioMiss;
public bool hasAudioPlayed;
private void Start()
{
player = transform.root.gameObject;
if (player)
{
ps = player.GetComponent<PlayerScript>();
}
instance = this;
}
public void PlayGrappleHitSound()
{
if (!hasAudioPlayed)
{
int rand = Random.Range(0, 2);
audioS.clip = clips[rand];
audioS.Play();
hasAudioPlayed = true;
}
}
public void PlayGrappleMissSound()
{
audioS.clip = audioMiss;
audioS.Play();
}
public void HasLetGoOfGrapple()
{
hasAudioPlayed = false;
}
}
| 19.530612 | 53 | 0.571578 | [
"MIT"
] | johnklima/SkyPortal | Assets/Member Scenes/Christian/FINISHED/Player/GrappleImpactSounds.cs | 957 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace QLNhaHang.Properties
{
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
{
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default
{
get
{
return defaultInstance;
}
}
}
}
| 35.433333 | 151 | 0.581373 | [
"CC0-1.0"
] | shidomusic/SqlServer-With-Winform | Properties/Settings.Designer.cs | 1,065 | C# |
using UnityEngine;
using System.Collections;
using Network;
using Protobuf;
public class TestNetWork : MonoBehaviour
{
public void Start()
{
UserProto proto = new UserProto();
proto.id = 1;
proto.name = "2173";
//string name = "你好";
//proto.name = System.Text.Encoding.UTF8.GetString(System.Text.Encoding.UTF8.GetBytes(name));
//============================================================================序列化
string message = GameSocketInterface.Serialize(proto, "ExampleMessage", UserProto.GetProtoName());
//============================================================================反序列化
UserProto proto1 = new UserProto();
proto1 = GameSocketInterface.deserialize(proto1, message, "ExampleMessage", UserProto.GetProtoName());
Debug.LogError(proto1.name);
}
}
| 32.444444 | 110 | 0.534247 | [
"MIT"
] | 2173/protobuf-for-purejsb | Assets/GameLogicScripts/TestNet/TestNetWork.cs | 894 | C# |
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("RegexAnalyzer.Test")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("RegexAnalyzer.Test")]
[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)]
// 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.3125 | 84 | 0.74062 | [
"MIT"
] | Jac21/CSharpMenagerie | Experiments/Roslyn/RegexAnalyzer/RegexAnalyzer/RegexAnalyzer.Test/Properties/AssemblyInfo.cs | 1,229 | C# |
using System.Threading.Tasks;
using Abp.Application.Services;
using Abp.Application.Services.Dto;
using JiraDashboard.Roles.Dto;
using JiraDashboard.Users.Dto;
namespace JiraDashboard.Users
{
public interface IUserAppService : IAsyncCrudAppService<UserDto, long, PagedResultRequestDto, CreateUserDto, UserDto>
{
Task<ListResultDto<RoleDto>> GetRoles();
Task ChangeLanguage(ChangeUserLanguageDto input);
}
}
| 27.3125 | 121 | 0.775744 | [
"MIT"
] | rajat-chugh/jira-dashboard | aspnet-core/src/JiraDashboard.Application/Users/IUserAppService.cs | 437 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using DG.Tweening;
public class PickPoint : MonoBehaviour
{
[Header("Setting")]
public int maxCandyCnt = 5;
public float purchaseInterval = 10;
public float pickableInterval = 20;
[Range(0, 1)] public float colliderRadius = 0.2f;
public int CandyCnt { get; private set; }
public int purchasingPower { get; private set; }
public bool isPickable { get; private set; }
public delegate void Pickable(int index);
public event Pickable pickableEvent;
public event Pickable unpickableEvent;
private int _index;
public GameObject info;
public GameObject prefab_candy;
public SpriteRenderer candyRender;
private float purchaseTimer;
private float pickableTimer;
private void Start()
{
GetComponent<CircleCollider2D>().radius = colliderRadius;
isPickable = true;
purchasingPower = 1;
CandyCnt = 5;
purchaseTimer = purchaseInterval;
pickableTimer = pickableInterval;
}
private void Update()
{
if(CandyCnt!= maxCandyCnt) {
purchaseTimer -= Time.deltaTime;
if (purchaseTimer < 0) {
if (CandyCnt == 0)
info.SetActive(true);
CandyCnt += MarketPoint.Instance.PurchaseCandy(Mathf.Min(purchasingPower, maxCandyCnt - CandyCnt));
purchaseTimer = purchaseInterval;
StartCoroutine(PurchaseAnim());
}
}
else if(CandyCnt == 0) {
info.SetActive(false);
}
if (!isPickable) {
pickableTimer -= Time.deltaTime;
if (pickableTimer < 0 && CandyCnt > 0) {
isPickable = true;
pickableTimer = pickableInterval;
pickableEvent(_index);
candyRender.DOColor(Color.white, 0.5f);
}
}
}
IEnumerator PurchaseAnim()
{
GameObject go = Instantiate(prefab_candy, transform);
go.transform.localPosition = new Vector3(0,1,0);
yield return new WaitForSeconds(0.5f);
Destroy(go);
}
public int TreatCandy(int cnt)
{
if (!isPickable)
return 0;
int treatCnt = cnt;
if(cnt > CandyCnt) {
treatCnt = CandyCnt;
info.SetActive(false);
}
CandyCnt -= treatCnt;
isPickable = false;
unpickableEvent(_index);
candyRender.DOColor(Color.grey, 0.5f);
return treatCnt;
}
public void RegisterIndex(int index)
{
_index = index;
}
//private void OnDrawGizmos()
//{
// Gizmos.color = Color.red;
// Gizmos.DrawWireSphere(transform.position, colliderRadius);
//}
}
| 27.144231 | 115 | 0.588735 | [
"MIT"
] | wzzwzz687510/HalloweenCandyFactory | Assets/Scripts/PickPoint.cs | 2,825 | C# |
using Xunit;
namespace _349_IntersectionOfTwoArrays
{
class Program
{
static void Main(string[] args)
{
var solution = new Solution();
Assert.Equal(new[] { 2 }, solution.Intersection(new[] { 1, 2, 2, 1 }, new[] { 2, 2 }));
Assert.Equal(new[] { 9,4 }, solution.Intersection(new[] { 4,9,5 }, new[] { 9, 4, 9, 8, 4 }));
}
}
}
| 24.875 | 105 | 0.507538 | [
"MIT"
] | kodoftw/LeetCode | LeetCode/349-IntersectionOfTwoArrays/Program.cs | 400 | C# |
using Microsoft.Xna.Framework;
using SGS.Components;
using SGS.Components.Tasks;
using SGS.Components.World;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SGS.Components.Players
{
public class PlayerHurtEffect
{
private Player player;
private GameWorldArea area;
private Repeat repetition;
public PlayerHurtEffect(Player p, GameWorldArea area)
{
this.player = p;
this.area = area;
this.repetition = Repeat.Task(HurtPlayer).Each(1000);
}
public void Update(GameTime t)
{
this.repetition.Update(t);
}
public void Start()
{
this.repetition.Start();
}
public void Stop()
{
this.repetition.Stop();
}
private void HurtPlayer(GameTime t)
{
this.player.State.Damage(this.area.DegenerationRatio);
}
}
}
| 21.744681 | 66 | 0.592955 | [
"MIT"
] | vitormoura/game-sgs_lab | src/SGS/SGS/Components/Players/PlayerHurtEffect.cs | 1,024 | C# |
// SPDX-License-Identifier: Apache-2.0
// Licensed to the Ed-Fi Alliance under one or more agreements.
// The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0.
// See the LICENSE and NOTICES files in the project root for more information.
using System;
using System.Web.Http;
using MappingEdu.Common;
using MappingEdu.Service.Model.MapNote;
using MappingEdu.Service.SystemItems;
namespace MappingEdu.Web.UI.Controllers.ApiControllers
{
/// <summary>
/// Controller for managing map notes
/// </summary>
[RoutePrefix(Constants.Api.V1.RoutePrefix)]
public class MapNoteController : ControllerBase
{
private readonly IMapNoteService _mapNoteService;
public MapNoteController(IMapNoteService mapNoteService)
{
_mapNoteService = mapNoteService;
}
[Route("MapNotes/{id:guid}")]
[AcceptVerbs("GET")]
public MapNoteViewModel[] Get(Guid id)
{
return _mapNoteService.Get(id);
}
[Route("MapNotes/{id:guid}/{id2:guid}")]
[AcceptVerbs("GET")]
public MapNoteViewModel Get(Guid id, Guid id2)
{
return _mapNoteService.Get(id, id2);
}
[Route("MapNotes/{id:guid}")]
[AcceptVerbs("POST")]
public MapNoteViewModel Post(Guid id, MapNoteCreateModel model)
{
return _mapNoteService.Post(id, model);
}
[Route("MapNotes/{id:guid}/{id2:guid}")]
[AcceptVerbs("PUT")]
public MapNoteViewModel Put(Guid id, Guid id2, MapNoteEditModel model)
{
return _mapNoteService.Put(id, id2, model);
}
[Route("MapNotes/{id:guid}/{id2:guid}")]
[AcceptVerbs("DELETE")]
public void Delete(Guid id, Guid id2)
{
_mapNoteService.Delete(id, id2);
}
}
} | 30.274194 | 86 | 0.62227 | [
"Apache-2.0"
] | Ed-Fi-Exchange-OSS/MappingEDU | src/MappingEdu.Web.UI/Controllers/ApiControllers/MapNoteController.cs | 1,879 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class fruitFlySpawner : MonoBehaviour
{
public static int numberOfAdultFlies;
public int numberOfAdults;
public int numberOfFlies;
public int weekNumber;
private GameObject[] array;
private GameObject[] array1;
// Start is called before the first frame update
void Start()
{
weekNumber = 0;
}
private void Update()
{
numberOfAdults = 0;
numberOfFlies = 0;
}
// Update is called once per frame
void LateUpdate()
{
array = GameObject.FindGameObjectsWithTag("adult");
array1 = GameObject.FindGameObjectsWithTag("fly");
foreach (GameObject a in array)
{
numberOfAdults += 1;
numberOfFlies += 1;
}
foreach (GameObject a in array1)
{
numberOfFlies += 1;
}
weekNumber += 1;
}
}
| 20.979592 | 60 | 0.564202 | [
"CC0-1.0"
] | aLE-xTX/FruitFlies | fruitFlySpawner.cs | 1,028 | C# |
// This file is auto-generated! Edit DelegateFactoryServiceCollectionExtensions.tt instead
using System;
using System.Runtime.CompilerServices;
using Microsoft.Extensions.DependencyInjection;
[assembly: InternalsVisibleTo("GenericFactory.Tests")]
namespace GenericFactory
{
public static class DelegateFactoryServiceCollectionExtensions
{
public static IServiceCollection AddFactory<TService>(this IServiceCollection services, Func<IServiceProvider, TService> factoryFunction)
where TService : class
{
services.AddTransient
<
IFactory<TService>
>(provider => new DelegateFactory<TService>(provider, factoryFunction));
return services;
}
public static IServiceCollection AddFactory<TService, TArg1>(this IServiceCollection services, Func<IServiceProvider, TArg1, TService> factoryFunction)
where TService : class
{
services.AddTransient
<
IFactory<TService, TArg1>
>(provider => new DelegateFactory<TService, TArg1>(provider, factoryFunction));
return services;
}
public static IServiceCollection AddFactory<TService, TArg1, TArg2>(this IServiceCollection services, Func<IServiceProvider, TArg1, TArg2, TService> factoryFunction)
where TService : class
{
services.AddTransient
<
IFactory<TService, TArg1, TArg2>
>(provider => new DelegateFactory<TService, TArg1, TArg2>(provider, factoryFunction));
return services;
}
public static IServiceCollection AddFactory<TService, TArg1, TArg2, TArg3>(this IServiceCollection services, Func<IServiceProvider, TArg1, TArg2, TArg3, TService> factoryFunction)
where TService : class
{
services.AddTransient
<
IFactory<TService, TArg1, TArg2, TArg3>
>(provider => new DelegateFactory<TService, TArg1, TArg2, TArg3>(provider, factoryFunction));
return services;
}
public static IServiceCollection AddFactory<TService, TArg1, TArg2, TArg3, TArg4>(this IServiceCollection services, Func<IServiceProvider, TArg1, TArg2, TArg3, TArg4, TService> factoryFunction)
where TService : class
{
services.AddTransient
<
IFactory<TService, TArg1, TArg2, TArg3, TArg4>
>(provider => new DelegateFactory<TService, TArg1, TArg2, TArg3, TArg4>(provider, factoryFunction));
return services;
}
public static IServiceCollection AddFactory<TService, TArg1, TArg2, TArg3, TArg4, TArg5>(this IServiceCollection services, Func<IServiceProvider, TArg1, TArg2, TArg3, TArg4, TArg5, TService> factoryFunction)
where TService : class
{
services.AddTransient
<
IFactory<TService, TArg1, TArg2, TArg3, TArg4, TArg5>
>(provider => new DelegateFactory<TService, TArg1, TArg2, TArg3, TArg4, TArg5>(provider, factoryFunction));
return services;
}
public static IServiceCollection AddFactory<TService, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6>(this IServiceCollection services, Func<IServiceProvider, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TService> factoryFunction)
where TService : class
{
services.AddTransient
<
IFactory<TService, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6>
>(provider => new DelegateFactory<TService, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6>(provider, factoryFunction));
return services;
}
public static IServiceCollection AddFactory<TService, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TArg7>(this IServiceCollection services, Func<IServiceProvider, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TArg7, TService> factoryFunction)
where TService : class
{
services.AddTransient
<
IFactory<TService, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TArg7>
>(provider => new DelegateFactory<TService, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TArg7>(provider, factoryFunction));
return services;
}
public static IServiceCollection AddFactory<TService, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TArg7, TArg8>(this IServiceCollection services, Func<IServiceProvider, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TArg7, TArg8, TService> factoryFunction)
where TService : class
{
services.AddTransient
<
IFactory<TService, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TArg7, TArg8>
>(provider => new DelegateFactory<TService, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TArg7, TArg8>(provider, factoryFunction));
return services;
}
public static IServiceCollection AddFactory<TService, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TArg7, TArg8, TArg9>(this IServiceCollection services, Func<IServiceProvider, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TArg7, TArg8, TArg9, TService> factoryFunction)
where TService : class
{
services.AddTransient
<
IFactory<TService, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TArg7, TArg8, TArg9>
>(provider => new DelegateFactory<TService, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TArg7, TArg8, TArg9>(provider, factoryFunction));
return services;
}
public static IServiceCollection AddFactory<TService, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TArg7, TArg8, TArg9, TArg10>(this IServiceCollection services, Func<IServiceProvider, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TArg7, TArg8, TArg9, TArg10, TService> factoryFunction)
where TService : class
{
services.AddTransient
<
IFactory<TService, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TArg7, TArg8, TArg9, TArg10>
>(provider => new DelegateFactory<TService, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TArg7, TArg8, TArg9, TArg10>(provider, factoryFunction));
return services;
}
public static IServiceCollection AddFactory<TService, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TArg7, TArg8, TArg9, TArg10, TArg11>(this IServiceCollection services, Func<IServiceProvider, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TArg7, TArg8, TArg9, TArg10, TArg11, TService> factoryFunction)
where TService : class
{
services.AddTransient
<
IFactory<TService, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TArg7, TArg8, TArg9, TArg10, TArg11>
>(provider => new DelegateFactory<TService, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TArg7, TArg8, TArg9, TArg10, TArg11>(provider, factoryFunction));
return services;
}
public static IServiceCollection AddFactory<TService, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TArg7, TArg8, TArg9, TArg10, TArg11, TArg12>(this IServiceCollection services, Func<IServiceProvider, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TArg7, TArg8, TArg9, TArg10, TArg11, TArg12, TService> factoryFunction)
where TService : class
{
services.AddTransient
<
IFactory<TService, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TArg7, TArg8, TArg9, TArg10, TArg11, TArg12>
>(provider => new DelegateFactory<TService, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TArg7, TArg8, TArg9, TArg10, TArg11, TArg12>(provider, factoryFunction));
return services;
}
public static IServiceCollection AddFactory<TService, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TArg7, TArg8, TArg9, TArg10, TArg11, TArg12, TArg13>(this IServiceCollection services, Func<IServiceProvider, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TArg7, TArg8, TArg9, TArg10, TArg11, TArg12, TArg13, TService> factoryFunction)
where TService : class
{
services.AddTransient
<
IFactory<TService, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TArg7, TArg8, TArg9, TArg10, TArg11, TArg12, TArg13>
>(provider => new DelegateFactory<TService, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TArg7, TArg8, TArg9, TArg10, TArg11, TArg12, TArg13>(provider, factoryFunction));
return services;
}
public static IServiceCollection AddFactory<TService, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TArg7, TArg8, TArg9, TArg10, TArg11, TArg12, TArg13, TArg14>(this IServiceCollection services, Func<IServiceProvider, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TArg7, TArg8, TArg9, TArg10, TArg11, TArg12, TArg13, TArg14, TService> factoryFunction)
where TService : class
{
services.AddTransient
<
IFactory<TService, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TArg7, TArg8, TArg9, TArg10, TArg11, TArg12, TArg13, TArg14>
>(provider => new DelegateFactory<TService, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TArg7, TArg8, TArg9, TArg10, TArg11, TArg12, TArg13, TArg14>(provider, factoryFunction));
return services;
}
public static IServiceCollection AddFactory<TService, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TArg7, TArg8, TArg9, TArg10, TArg11, TArg12, TArg13, TArg14, TArg15>(this IServiceCollection services, Func<IServiceProvider, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TArg7, TArg8, TArg9, TArg10, TArg11, TArg12, TArg13, TArg14, TArg15, TService> factoryFunction)
where TService : class
{
services.AddTransient
<
IFactory<TService, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TArg7, TArg8, TArg9, TArg10, TArg11, TArg12, TArg13, TArg14, TArg15>
>(provider => new DelegateFactory<TService, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TArg7, TArg8, TArg9, TArg10, TArg11, TArg12, TArg13, TArg14, TArg15>(provider, factoryFunction));
return services;
}
}
}
| 58.872832 | 367 | 0.659107 | [
"MIT"
] | GediminasMasaitis/DependencyInjection.GenericFactory | src/GenericFactory/DelegateFactoryServiceCollectionExtensions.cs | 10,187 | C# |
// Copyright (c) 2018 FiiiLab Technology Ltd
// Distributed under the MIT software license, see the accompanying
// file LICENSE or or http://www.opensource.org/licenses/mit-license.php.
using FiiiCoin.Wallet.Win.Common;
namespace FiiiCoin.Wallet.Win.Models.UiModels
{
public class ConfirmSendData : NotifyBase
{
private double fee;
public double Fee
{
get { return fee; }
set { fee = value; RaisePropertyChanged("Fee"); }
}
private double amount;
public double Amount
{
get { return amount; }
set { amount = value; RaisePropertyChanged("Amount"); }
}
private string toAddress;
public string ToAddress
{
get { return toAddress; }
set { toAddress = value; RaisePropertyChanged("ToAddress"); }
}
private double arrivalAmount;
public double ArrivalAmount
{
get { return arrivalAmount; }
set { arrivalAmount = value; RaisePropertyChanged("ArrivalAmount"); RaisePropertyChanged("ArrivalAmount"); }
}
}
}
| 26.627907 | 120 | 0.598253 | [
"MIT"
] | ft-john/FiiiCoin | Wallet/FiiiCoin.Wallet.Win/Models/UiModels/ConfirmSendData.cs | 1,147 | C# |
// ★秀丸クラス
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
public sealed partial class HmCustomLivePreviewDynamicLib
{
public sealed partial class Hidemaru
{
public sealed class ExplorerPane
{
static ExplorerPane()
{
SetUnManagedDll();
}
// モードの設定
public static int SetMode(int mode)
{
try
{
int result = pExplorerPane_SetMode(Hidemaru.WindowHandle, (IntPtr)mode);
return result;
}
catch (Exception e)
{
OutputDebugStream(ErrorMsg.MethodNeedExplorerOperation + ":\n" + e.Message);
}
return 0;
}
// モードの取得
public static int GetMode()
{
try
{
int result = pExplorerPane_GetMode(Hidemaru.WindowHandle);
return result;
}
catch (Exception e)
{
OutputDebugStream(ErrorMsg.MethodNeedExplorerOperation + ":\n" + e.Message);
}
return 0;
}
// LoadProjectする
public static int LoadProject(string filepath)
{
try
{
byte[] encode_data = HmOriginalEncodeFunc.EncodeWStringToOriginalEncodeVector(filepath);
int result = pExplorerPane_LoadProject(Hidemaru.WindowHandle, encode_data);
return result;
}
catch (Exception e)
{
OutputDebugStream(ErrorMsg.MethodNeedExplorerOperation + ":\n" + e.Message);
}
return 0;
}
// SaveProjectする
public static int SaveProject(string filepath)
{
try
{
byte[] encode_data = HmOriginalEncodeFunc.EncodeWStringToOriginalEncodeVector(filepath);
int result = pExplorerPane_SaveProject(Hidemaru.WindowHandle, encode_data);
return result;
}
catch (Exception e)
{
OutputDebugStream(ErrorMsg.MethodNeedExplorerOperation + ":\n" + e.Message);
}
return 0;
}
// GetProjectする
public static string GetProject()
{
try
{
IntPtr startpointer = pExplorerPane_GetProject(Hidemaru.WindowHandle);
List<byte> blist = GetPointerToByteArray(startpointer);
string project_name = Hidemaru.HmOriginalDecodeFunc.DecodeOriginalEncodeVector(blist);
if (String.IsNullOrEmpty(project_name))
{
return null;
}
return project_name;
/*
if (hmJSDynamicLib.Hidemaru.Macro.IsExecuting)
{
string cmd = @"dllfuncstr(loaddll(""HmExplorerPane""), ""GetProject"", hidemaruhandle(0))";
string project_name = (string)hmJSDynamicLib.Hidemaru.Macro.Var(cmd);
if (String.IsNullOrEmpty(project_name))
{
return null;
}
return project_name;
}
else
{
string cmd = @"endmacro dllfuncstr(loaddll(""HmExplorerPane""), ""GetProject"", hidemaruhandle(0))";
var result = hmJSDynamicLib.Hidemaru.Macro.ExecEval(cmd);
string project_name = result.Message;
if (String.IsNullOrEmpty(project_name))
{
return null;
}
return result.Message;
}
*/
}
catch (Exception e)
{
OutputDebugStream(ErrorMsg.MethodNeedExplorerOperation + ":\n" + e.Message);
}
return null;
}
private static List<byte> GetPointerToByteArray(IntPtr startpointer)
{
List<byte> blist = new List<byte>();
int index = 0;
while (true)
{
var b = Marshal.ReadByte(startpointer, index);
blist.Add(b);
// 文字列の終端はやはり0
if (b == 0)
{
break;
}
index++;
}
return blist;
}
// GetCurrentDirする
public static string GetCurrentDir()
{
if (version < 885)
{
OutputDebugStream(ErrorMsg.MethodNeedExplorerNotFound + ":\n" + "GetCurrentDir");
return "";
}
try
{
IntPtr startpointer = pExplorerPane_GetCurrentDir(Hidemaru.WindowHandle);
List<byte> blist = GetPointerToByteArray(startpointer);
string currentdir_name = Hidemaru.HmOriginalDecodeFunc.DecodeOriginalEncodeVector(blist);
if (String.IsNullOrEmpty(currentdir_name))
{
return null;
}
return currentdir_name;
/*
if (hmJSDynamicLib.Hidemaru.pExplorerPane_GetCurrentDir != null)
{
if (hmJSDynamicLib.Hidemaru.Macro.IsExecuting)
{
string cmd = @"dllfuncstr(loaddll(""HmExplorerPane""), ""GetCurrentDir"", hidemaruhandle(0))";
string currentdir_name = (string)hmJSDynamicLib.Hidemaru.Macro.Var(cmd);
if (String.IsNullOrEmpty(currentdir_name))
{
return null;
}
return currentdir_name;
}
else
{
string cmd = @"endmacro dllfuncstr(loaddll(""HmExplorerPane""), ""GetCurrentDir"", hidemaruhandle(0))";
var result = hmJSDynamicLib.Hidemaru.Macro.ExecEval(cmd);
string currentdir_name = result.Message;
if (String.IsNullOrEmpty(currentdir_name))
{
return null;
}
return result.Message;
}
}
*/
}
catch (Exception e)
{
OutputDebugStream(ErrorMsg.MethodNeedExplorerOperation + ":\n" + e.Message);
}
return null;
}
// GetUpdated
public static int GetUpdated()
{
try
{
int result = pExplorerPane_GetUpdated(Hidemaru.WindowHandle);
return result;
}
catch (Exception e)
{
OutputDebugStream(ErrorMsg.MethodNeedExplorerOperation + ":\n" + e.Message);
}
return 0;
}
public static IntPtr WindowHandle
{
get
{
return pExplorerPane_GetWindowHandle(Hidemaru.WindowHandle);
}
}
public static IntPtr SendMessage(int commandID)
{
//
// loaddll "HmExplorerPane.dll";
// #h=dllfunc("GetWindowHandle",hidemaruhandle(0));
// #ret=sendmessage(#h,0x111/*WM_COMMAND*/,251,0); //251=1つ上のフォルダ
//
return HmCustomLivePreviewDynamicLib.SendMessage(ExplorerPane.WindowHandle, 0x111, commandID, IntPtr.Zero);
}
}
}
}
| 34.277108 | 131 | 0.432103 | [
"Apache-2.0"
] | komiyamma/hm_customlivepreview | HmCustomLivePreview.src/hmJSStaticLib/ClearScript/hmJSStaticLib/hmCustomLivePreviewHidemaruExplorerPane.cs | 8,625 | C# |
// Copyright (C) 2018 Fievus
//
// This software may be modified and distributed under the terms
// of the MIT license. See the LICENSE file for details.
using Carna;
namespace Charites.Windows.Samples.SimpleLoginDemo.Presentation.Login
{
[Specification("LoginController Spec")]
class LoginControllerSpec
{
[Context]
LoginControllerSpec_LoginPanelLocation LoginPanelLocation { get; }
[Context]
LoginControllerSpec_LoginButtonClick LoginButtonClick { get; }
}
}
| 27 | 74 | 0.723197 | [
"MIT"
] | averrunci/WindowsFormsMvc | Samples/SimpleLoginDemo/SimpleLoginDemo.Presentation.Spec/Login/LoginControllerSpec.cs | 515 | C# |
// ---------------------------------------------------------------------------
// Copyright (c) 2019, The .NET Foundation.
// This software is released under the Apache License, Version 2.0.
// The license and further copyright text can be found in the file LICENSE.md
// at the root directory of the distribution.
// ---------------------------------------------------------------------------
using System;
using System.Windows.Forms;
namespace WinForms.TestHarness
{
internal static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
private static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new FlexForm());
}
}
} | 33.807692 | 80 | 0.508532 | [
"Apache-2.0"
] | kazuyaujihara/Version3-1 | src/TestHarness/WinForms.TestHarness/Program.cs | 856 | C# |
//The MIT License(MIT)
//Copyright(c) 2016 Alberto Rodriguez & LiveCharts Contributors
//Permission is hereby granted, free of charge, to any person obtaining a copy
//of this software and associated documentation files (the "Software"), to deal
//in the Software without restriction, including without limitation the rights
//to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//copies of the Software, and to permit persons to whom the Software is
//furnished to do so, subject to the following conditions:
//The above copyright notice and this permission notice shall be included in all
//copies or substantial portions of the Software.
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
//SOFTWARE.
namespace LiveCharts.Definitions.Series
{
/// <summary>
///
/// </summary>
/// <seealso cref="LiveCharts.Definitions.Series.IGroupedStackedSeriesView" />
/// <seealso cref="LiveCharts.Definitions.Series.IStackModelableSeriesView" />
public interface IStackedColumnSeriesView : IGroupedStackedSeriesView, IStackModelableSeriesView
{
/// <summary>
/// Gets or sets the maximum width of the column.
/// </summary>
/// <value>
/// The maximum width of the column.
/// </value>
double MaxColumnWidth { get; set; }
/// <summary>
/// Gets or sets the column padding.
/// </summary>
/// <value>
/// The column padding.
/// </value>
double ColumnPadding { get; set; }
/// <summary>
/// Gets or sets visibility if value is zero
/// </summary>
bool ShowIfZero { get; set; }
}
} | 40.921569 | 100 | 0.684715 | [
"MIT"
] | patryksojkowski/LiveCharts | Core40/Definitions/Series/IStackedColumnSeriesView.cs | 2,089 | C# |
//////////////////////////////////////////////////////////////////////////////////////////////////
// This is generated code! Do not alter this code because changes you make will be over written
// the next time the code is generated. If you need to change this code, do it via the T4 template
//////////////////////////////////////////////////////////////////////////////////////////////////
using System;
using System.Linq;
using QIQO.Business.Client.Core.UI;
using QIQO.Business.Client.Entities;
namespace QIQO.Business.Client.Wrappers
{
public partial class CommentWrapper : ModelWrapperBase<Comment>
{
public CommentWrapper(Comment model) : base(model)
{
}
public System.Int32 CommentKey
{
get { return GetValue<System.Int32>(); }
set { SetValue(value); }
}
public System.Int32 CommentKeyOriginalValue => GetOriginalValue<System.Int32>(nameof(CommentKey));
public bool CommentKeyIsChanged => GetIsChanged(nameof(CommentKey));
public System.Int32 EntityKey
{
get { return GetValue<System.Int32>(); }
set { SetValue(value); }
}
public System.Int32 EntityKeyOriginalValue => GetOriginalValue<System.Int32>(nameof(EntityKey));
public bool EntityKeyIsChanged => GetIsChanged(nameof(EntityKey));
public System.Int32 EntityTypeKey
{
get { return GetValue<System.Int32>(); }
set { SetValue(value); }
}
public System.Int32 EntityTypeKeyOriginalValue => GetOriginalValue<System.Int32>(nameof(EntityTypeKey));
public bool EntityTypeKeyIsChanged => GetIsChanged(nameof(EntityTypeKey));
public QIQO.Business.Client.Entities.QIQOCommentType CommentType
{
get { return GetValue<QIQO.Business.Client.Entities.QIQOCommentType>(); }
set { SetValue(value); }
}
public QIQO.Business.Client.Entities.QIQOCommentType CommentTypeOriginalValue => GetOriginalValue<QIQO.Business.Client.Entities.QIQOCommentType>(nameof(CommentType));
public bool CommentTypeIsChanged => GetIsChanged(nameof(CommentType));
public System.String CommentValue
{
get { return GetValue<System.String>(); }
set { SetValue(value); }
}
public System.String CommentValueOriginalValue => GetOriginalValue<System.String>(nameof(CommentValue));
public bool CommentValueIsChanged => GetIsChanged(nameof(CommentValue));
public System.String AddedUserID
{
get { return GetValue<System.String>(); }
set { SetValue(value); }
}
public System.String AddedUserIDOriginalValue => GetOriginalValue<System.String>(nameof(AddedUserID));
public bool AddedUserIDIsChanged => GetIsChanged(nameof(AddedUserID));
public System.DateTime AddedDateTime
{
get { return GetValue<System.DateTime>(); }
set { SetValue(value); }
}
public System.DateTime AddedDateTimeOriginalValue => GetOriginalValue<System.DateTime>(nameof(AddedDateTime));
public bool AddedDateTimeIsChanged => GetIsChanged(nameof(AddedDateTime));
public System.String UpdateUserID
{
get { return GetValue<System.String>(); }
set { SetValue(value); }
}
public System.String UpdateUserIDOriginalValue => GetOriginalValue<System.String>(nameof(UpdateUserID));
public bool UpdateUserIDIsChanged => GetIsChanged(nameof(UpdateUserID));
public System.DateTime UpdateDateTime
{
get { return GetValue<System.DateTime>(); }
set { SetValue(value); }
}
public System.DateTime UpdateDateTimeOriginalValue => GetOriginalValue<System.DateTime>(nameof(UpdateDateTime));
public bool UpdateDateTimeIsChanged => GetIsChanged(nameof(UpdateDateTime));
}
}
| 31.633028 | 167 | 0.723898 | [
"MIT"
] | rdrrichards/QIQO.Business.Client.Solution | QIQO.Business.Client.Wrappers/Wrappers/Generated/CommentWrapper.g.cs | 3,448 | C# |
//
// AppKitSynchronizationContext.cs: Default SynchronizationContext for the main UI thread
//
using System.Threading;
using Foundation;
namespace AppKit {
class AppKitSynchronizationContext : SynchronizationContext {
public override SynchronizationContext CreateCopy ()
{
return new AppKitSynchronizationContext ();
}
public override void Post (SendOrPostCallback d, object state)
{
NSRunLoop.Main.BeginInvokeOnMainThread (() => d (state));
}
public override void Send (SendOrPostCallback d, object state)
{
NSRunLoop.Main.InvokeOnMainThread (() => d (state));
}
}
} | 24.04 | 89 | 0.745424 | [
"BSD-3-Clause"
] | bradumbaugh/xamarin-macios | src/AppKit/AppKitSynchronizationContext.cs | 601 | C# |
namespace Book.Views.Samples.Chapter18.Sample04
{
using System.Reactive.Disposables;
using ReactiveUI;
using ViewModels.Samples.Chapter18.Sample04;
public partial class MainView : ReactiveUserControl<MainViewModel>
{
public MainView()
{
InitializeComponent();
this
.WhenActivated(
disposables =>
{
this
.OneWayBind(this.ViewModel, x => x.LeftChild, x => x.leftChildViewModelViewHost.ViewModel)
.DisposeWith(disposables);
this
.OneWayBind(this.ViewModel, x => x.RightChild, x => x.rightChildViewModelViewHost.ViewModel)
.DisposeWith(disposables);
this
.OneWayBind(this.ViewModel, x => x.Messages, x => x.messagesTextBox.Text)
.DisposeWith(disposables);
this
.BindCommand(this.ViewModel, x => x.LoadLeftChildCommand, x => x.loadLeftChildButton)
.DisposeWith(disposables);
this
.BindCommand(this.ViewModel, x => x.UnloadLeftChildCommand, x => x.unloadLeftChildButton)
.DisposeWith(disposables);
this
.BindCommand(this.ViewModel, x => x.LoadRightChildCommand, x => x.loadRightChildButton)
.DisposeWith(disposables);
this
.BindCommand(this.ViewModel, x => x.UnloadRightChildCommand, x => x.unloadRightChildButton)
.DisposeWith(disposables);
});
}
}
} | 44.190476 | 120 | 0.487608 | [
"MIT"
] | AlexejLiebenthal/YouIandReactiveUI | Host.WPF/Views/Samples/Chapter 18/Sample 04/MainView.xaml.cs | 1,856 | C# |
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace PhantomNet.AspNetCore.IdentityAccount
{
[Authorize]
[Route("Accounts")]
public abstract class IdentityAccountsControllerBase : Controller
{
public IActionResult Index()
{
return View();
}
}
}
| 20.875 | 69 | 0.667665 | [
"MIT"
] | green-grass/PhantomNet-IdentityAccount | src/PhantomNet.AspNetCore.IdentityAccount/IdentityAccountsControllerBase.cs | 336 | C# |
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
// Ported from um/ShlObj_core.h in the Windows SDK for Windows 10.0.20348.0
// Original source is Copyright © Microsoft. All rights reserved.
using System.Runtime.InteropServices;
namespace TerraFX.Interop.Windows;
/// <include file='CIDA.xml' path='doc/member[@name="CIDA"]/*' />
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public unsafe partial struct CIDA
{
/// <include file='CIDA.xml' path='doc/member[@name="CIDA.cidl"]/*' />
public uint cidl;
/// <include file='CIDA.xml' path='doc/member[@name="CIDA.aoffset"]/*' />
[NativeTypeName("UINT [1]")]
public fixed uint aoffset[1];
}
| 36.190476 | 145 | 0.706579 | [
"MIT"
] | IngmarBitter/terrafx.interop.windows | sources/Interop/Windows/Windows/um/ShlObj_core/CIDA.cs | 762 | C# |
/*
Copyright (c) Miha Zupan. All rights reserved.
This file is a part of the CAH project by Miha Zupan and Juš Mirtič.
It is licensed under the Simplified BSD License (BSD 2-clause).
For more information visit:
https://github.com/MihaZupan/CAH/blob/master/LICENSE
*/
namespace CAH.Server.Responses.Lobby
{
class CreateGameRoomResponse : IResponse
{
public string Method => Methods.Lobby_CreateGameRoom;
public int GameRoomId;
public CreateGameRoomResponse(int gameRoomId)
{
GameRoomId = gameRoomId;
}
}
}
| 26.909091 | 72 | 0.672297 | [
"BSD-2-Clause"
] | MihaZupan/CAH | src/CAH.Server/Responses/Lobby/CreateGameRoomResponse.cs | 596 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using NFluent;
using Xunit;
namespace DefaultEcs.Test
{
public sealed class EntitySetTest
{
#region Tests
[Fact]
public void World_Should_return_parent_world()
{
using World world = new(4);
using EntitySet set = world.GetEntities().AsSet();
Check.That(set.World).IsEqualTo(world);
}
[Fact]
public void GetEntities_Should_return_previously_created_Entity()
{
using World world = new(4);
List<Entity> entities = new()
{
world.CreateEntity(),
world.CreateEntity(),
world.CreateEntity(),
world.CreateEntity()
};
using EntitySet set = world.GetEntities().AsSet();
Check.That(set.GetEntities().ToArray()).ContainsExactly(entities);
}
[Fact]
public void Contains_Should_return_true_When_containing_entity()
{
using World world = new(4);
Entity entity = world.CreateEntity();
using EntitySet set = world.GetEntities().AsSet();
Check.That(set.Contains(entity)).IsTrue();
}
[Fact]
public void Contains_Should_return_false_When_not_containing_entity()
{
using World world = new(4);
world.CreateEntity();
world.CreateEntity();
world.CreateEntity();
Entity entity = world.CreateEntity();
using EntitySet set = world.GetDisabledEntities().AsSet();
Check.That(set.Contains(entity)).IsFalse();
}
[Fact]
public void GetEntities_Should_not_return_disabled_Entity()
{
using World world = new(4);
List<Entity> entities = new()
{
world.CreateEntity(),
world.CreateEntity(),
world.CreateEntity(),
world.CreateEntity()
};
using EntitySet set = world.GetEntities().AsSet();
Check.That(set.GetEntities().ToArray()).ContainsExactly(entities);
entities[3].Disable();
Check.That(set.GetEntities().ToArray()).ContainsExactly(entities.Take(3));
entities[3].Enable();
Check.That(set.GetEntities().ToArray()).ContainsExactly(entities);
}
[Fact]
public void GetEntities_Should_return_only_disabled_Entity()
{
using World world = new(4);
List<Entity> entities = new()
{
world.CreateEntity(),
world.CreateEntity(),
world.CreateEntity(),
world.CreateEntity()
};
using EntitySet set = world.GetDisabledEntities().AsSet();
Check.That(set.GetEntities().ToArray()).IsEmpty();
foreach (Entity entity in entities)
{
entity.Disable();
}
Check.That(set.GetEntities().ToArray()).ContainsExactly(entities);
entities[3].Enable();
Check.That(set.GetEntities().ToArray()).ContainsExactly(entities.Take(3));
}
[Fact]
public void GetEntities_Should_not_return_Entity_with_disabled_component()
{
using World world = new(4);
List<Entity> entities = new()
{
world.CreateEntity(),
world.CreateEntity(),
world.CreateEntity(),
world.CreateEntity()
};
foreach (Entity entity in entities)
{
entity.Set<bool>();
}
entities[0].Disable<bool>();
using EntitySet set = world.GetEntities().With<bool>().AsSet();
Check.That(set.GetEntities().ToArray()).ContainsExactly(entities.Skip(1));
}
[Fact]
public void Dispose_Should_not_throw_When_world_already_disposed()
{
World world = new(4);
EntitySet set = world.GetEntities().AsSet();
world.Dispose();
Check.ThatCode(set.Dispose).DoesNotThrow();
}
[Fact]
public void TrimExcess_Should_fit_storage_to_number_of_entities()
{
World world = new();
EntitySet set = world.GetEntities().AsSet();
world.CreateEntity();
Check.That(((Array)typeof(EntitySet).GetField("_mapping", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(set)).Length).IsNotEqualTo(set.Count + 1);
Check.That(((Array)typeof(EntitySet).GetField("_entities", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(set)).Length).IsNotEqualTo(set.Count);
set.TrimExcess();
Check.That(((Array)typeof(EntitySet).GetField("_mapping", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(set)).Length).IsEqualTo(set.Count + 1);
Check.That(((Array)typeof(EntitySet).GetField("_entities", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(set)).Length).IsEqualTo(set.Count);
}
#endregion
}
}
| 29.222222 | 169 | 0.561977 | [
"MIT-0"
] | poettlr/DefaultEcs | source/DefaultEcs.Test/EntitySetTest.cs | 5,262 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using RedemptionEngine.Items;
using RedemptionEngine.Items.Weapons;
namespace RedemptionEngine.ObjectClasses.Enemy
{
public class SnowMan : Hostile
{
public SnowMan(ContentManager content)
: base(content)
{
name = "Snowman";
speed = 100.0f;
texture = content.Load<Texture2D>("Characters//SnowMan");
//Add animations
animations.Add("Walking_Down",
new Animation(new Point(0, 0), new Point(32, 32), 2, 200));
animations.Add("Walking_Up",
new Animation(new Point(0, 64), new Point(32, 32), 2, 200));
animations.Add("Walking_Right",
new Animation(new Point(0,32), new Point(32, 32), 2, 200));
animations.Add("Walking_Left",
new Animation(new Point(0, 0), new Point(32, 32), 2, 200));
animations.Add("Idle_Down",
new Animation(new Point(0, 0), new Point(32, 32), 1, 200));
animations.Add("Idle_Up",
new Animation(new Point(0, 64), new Point(32, 32), 1, 200));
animations.Add("Idle_Right",
new Animation(new Point(0, 32), new Point(32, 32), 1, 200));
animations.Add("Idle_Left",
new Animation(new Point(0, 0), new Point(32, 32), 1, 200));
CurrentAnimationKey = "Walking_Down";
inventory = new Inventory(this);
boundsXOffset = 5;
boundsYOffset = 4;
boundsWidthOffset = -10;
boundsHeightOffset = -4;
int r = DropItems.Rand.Next(10);
if(r >= 0) inventory.EquipmentRight.InsertItem(new SnowShot(content));
if (r > 4) inventory.EquipmentRight.InsertItem(new IceSickle(content));
if (r > 7) inventory.EquipmentRight.InsertItem(new IcicleShot(content));
if (r > 8) inventory.EquipmentRight.InsertItem(new Popsickle(content));
dropPool.AddItem(DropItems.Items["Potion"], 60);
dropPool.AddItem(DropItems.Items["ManaPotion"], 20);
dropPool.AddItem(DropItems.Items["SnowShot"], 8);
dropPool.AddItem(DropItems.Items["IceSickle"], 6);
dropPool.AddItem(DropItems.Items["IcicleShot"], 4);
dropPool.AddItem(DropItems.Items["FootWarmers"], 2);
dropPool.AddItem(DropItems.Items["Popsickle"], 2);
}
public override CharacterAttribute Level
{
set
{
int x = value.Value;
level.Value = value.Value;
baseHealth = new CharacterAttribute("Health", (int)(150 + x * 6.2), (int)(150 + x * 3.2));
baseDefense = new CharacterAttribute("Defense", (int)(20 + x * 1.8), 200);
baseStrength = new CharacterAttribute("Strength", (int)(25 + x * 1.35), 160);
baseStrength = new CharacterAttribute("Magic", (int)(20 + x * 2), 220);
baseStrength = new CharacterAttribute("Mana", (int)(20 + x * 5), 520);
InitializeAttributes();
}
}
public override void Die(Character attacker)
{
int level = Level.Value;
int expAmount = (int)(2.2 * Math.Pow(1.15, level));
attacker.AddExperience(expAmount);
GameManager.RemoveEntity(this);
DropItem(.2f);
}
public override void Update(GameTime gameTime)
{
base.Update(gameTime);
AI();
if (velocity.X > 0)
{
if (CurrentAnimationKey != "Walking_Right")
{
CurrentAnimationKey = "Walking_Right";
}
}
if (velocity.X < 0)
{
if (CurrentAnimationKey != "Walking_Left")
{
CurrentAnimationKey = "Walking_Left";
}
}
if (velocity.Y < 0)
{
if (CurrentAnimationKey != "Walking_Up")
{
CurrentAnimationKey = "Walking_Up";
}
}
if (velocity.Y > 0)
{
if (CurrentAnimationKey != "Walking_Down")
{
CurrentAnimationKey = "Walking_Down";
}
}
if (velocity == Vector2.Zero)
{
if (CurrentAnimationKey == "Walking_Down") CurrentAnimationKey = "Idle_Down";
if (CurrentAnimationKey == "Walking_Right") CurrentAnimationKey = "Idle_Right";
if (CurrentAnimationKey == "Walking_Up") CurrentAnimationKey = "Idle_Up";
if (CurrentAnimationKey == "Walking_Left") CurrentAnimationKey = "Idle_Left";
}
}
int attackDelay = 0;
protected virtual void AI()
{
if (pTarget == null)
{
pTarget = gameManager.Player;
}
target = new Vector2(pTarget.Bounds.X + pTarget.Bounds.Width / 2, pTarget.Bounds.Y + pTarget.Bounds.Height / 2);
float deltaX = MathHelper.Distance(target.X, Bounds.X + Bounds.Width / 2);
float deltaY = MathHelper.Distance(target.Y, Bounds.Y + Bounds.Height / 2);
float d = (float)Math.Sqrt((deltaX * deltaX) + (deltaY * deltaY));
if (state == State.IDLE)
{
velocity = Vector2.Zero;
if (d <= 400)
{
state = State.CHASING;
return;
}
}
if (state == State.CHASING)
{
MoveTowardsTarget();
if (d <= 120 && (inventory.EquipmentRight.Item is SnowShot || inventory.EquipmentRight.Item is IcicleShot))
{
state = State.ATTACKING;
Stop();
return;
}
else if (d <= 32)
{
state = State.ATTACKING;
Stop();
return;
}
if (d > 400)
{
state = State.IDLE;
Stop();
return;
}
}
if (state == State.ATTACKING)
{
if(inventory.EquipmentRight.Item is Popsickle || inventory.EquipmentRight.Item is IceSickle)
Stop();
else
LineUpWithTarget();
//attack stuff
attackDelay += DropItems.Rand.Next(8);
if (attackDelay >= 150)
{
attackDelay = 0;
Attack();
}
if (inventory.EquipmentRight.Item is SnowShot || inventory.EquipmentRight.Item is IcicleShot)
{
if(d > 120)
{
state = State.CHASING;
return;
}
}
else if (d > 32)
{
state = State.CHASING;
return;
}
}
}
public void Attack()
{
Mana.Value = Mana.MaxValue;
(inventory.EquipmentRight.Item as Weapon).Attack(this);
}
public override void Draw(SpriteBatch spriteBatch)
{
base.Draw(spriteBatch);
//spriteBatch.Draw(colTex, Bounds, Color.White);
}
}
}
| 32.933054 | 124 | 0.481006 | [
"MIT"
] | Erbelding/Redemption | PROJECT/RedemptionEngine/ObjectClasses/Enemy/SnowMan.cs | 7,873 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.20506.1
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace HelloWorld.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "10.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default {
get {
return defaultInstance;
}
}
}
}
| 39.296296 | 151 | 0.579642 | [
"MIT"
] | Plankankul/SharpDevelop-w-Framework | src/AddIns/Analysis/Profiler/Tests/HelloWorld/Properties/Settings.Designer.cs | 1,063 | C# |
using Microsoft.Graph;
using System;
using System.Collections.Generic;
using System.Text;
namespace Graph.Community
{
public class SharePointAPIRequestBuilder : BaseRequestBuilder, ISharePointAPIRequestBuilder
{
public SharePointAPIRequestBuilder(
string siteUrl,
IBaseClient client)
: base(siteUrl, client)
{
}
public ISiteDesignRequestBuilder SiteDesigns
{
get
{
return new SiteDesignRequestBuilder(this.AppendSegmentToRequestUrl("_api"), this.Client);
}
}
public ISiteScriptRequestBuilder SiteScripts
{
get
{
return new SiteScriptRequestBuilder(this.AppendSegmentToRequestUrl("_api"), this.Client);
}
}
public Graph.Community.ISiteRequestBuilder Site
{
get
{
return new Graph.Community.SiteRequestBuilder(this.AppendSegmentToRequestUrl("_api/site"), this.Client);
}
}
public Graph.Community.IWebRequestBuilder Web
{
get
{
return new Graph.Community.WebRequestBuilder(this.AppendSegmentToRequestUrl("_api/web"), this.Client);
}
}
}
}
| 20.72 | 108 | 0.740347 | [
"MIT"
] | piotrci/msgraph-sdk-dotnet-contrib | src/Requests/SharePointAPIRequestBuilder.cs | 1,038 | C# |
namespace GameMath.Tests.Geometry
{
using NUnit.Framework;
public class RectangleTests
{
#region Public Methods and Operators
[Test]
public void TestRectangleFCenter()
{
// ARRANGE.
var rectangle = new RectangleF(new Vector2F(2, 3), new Vector2F(6, 8));
var center = new Vector2F(5, 7);
// ASSERT.
Assert.AreEqual(center, rectangle.Center);
}
[Test]
public void TestRectangleICenter()
{
// ARRANGE.
var rectangle = new RectangleI(new Vector2I(2, 3), new Vector2I(6, 8));
var center = new Vector2I(5, 7);
// ASSERT.
Assert.AreEqual(center, rectangle.Center);
}
#endregion
}
} | 24.151515 | 83 | 0.531995 | [
"MIT"
] | npruehs/game-math | Source/GameMath.Tests/Geometry/RectangleTests.cs | 799 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using TGL.WebApp.Models;
namespace TGL.WebApp.Data
{
public class StudentStore
{
//private List<Student> Students { get; set; } = new List<Student>();
public TGLContext Context { get; set; }
public StudentStore(TGLContext context)
{
Context = context;
}
internal void EditStudent(Student student)
{
Student currentStudent = GetStudentById(student.Id);
currentStudent.Name = student.Name;
currentStudent.LastName = student.LastName;
currentStudent.Nit = student.Nit;
currentStudent.Age = student.Age;
Context.Student.Update(currentStudent);
Context.SaveChanges();
}
internal Student GetStudentById(Guid id)
{
return Context.Student.FirstOrDefault(x => x.Id == id);
}
internal void AddStudent(Student student)
{
Context.Student.Add(student);
Context.SaveChanges();
}
internal void DeleteStudent(Guid id)
{
var student = Context.Student.FirstOrDefault(x => x.Id == id);
Context.Student.Remove(student);
Context.SaveChanges();
}
public List<Student> GetStudents() {
return Context.Student.ToList();
}
}
}
| 27.358491 | 77 | 0.585517 | [
"MIT"
] | Elkinssm/Tgl-3 | TGL/TGL.WebApp/Data/StudentStore.cs | 1,452 | C# |
using System;
using System.Globalization;
using System.Text;
using LiteGui;
using LiteGui.Graphics;
namespace LiteGuiDemo.Demos
{
internal class DemoMemoryEditor : DemoBase
{
private readonly byte[] MemoryBuffer = new byte[10240];
private enum DataType : byte
{
DataType_S8,
DataType_U8,
DataType_S16,
DataType_U16,
DataType_S32,
DataType_U32,
DataType_S64,
DataType_U64,
DataType_Float,
DataType_Double,
DataType_COUNT
};
private enum DataFormat : byte
{
DataFormat_Bin = 0,
DataFormat_Dec = 1,
DataFormat_Hex = 2,
DataFormat_COUNT
};
// Settings
private bool Open; // = true // set to false when DrawWindow() was closed. ignore if not using DrawWindow().
private bool ReadOnly; // = false // disable any editing.
private int Cols; // = 16 // number of columns to display.
private bool
OptShowOptions; // = true // display options button/context menu. when disabled, options will be locked unless you provide your own UI for them.
private bool
OptShowDataPreview; // = false // display a footer previewing the decimal/binary/hex/float representation of the currently selected bytes.
private bool
OptShowHexII; // = false // display values in HexII representation instead of regular hexadecimal: hide null/zero bytes, ascii values as ".X".
private bool OptShowAscii; // = true // display ASCII representation on the right side.
private bool OptGreyOutZeroes; // = true // display null/zero bytes using the TextDisabled color.
private bool OptUpperCaseHex; // = true // display hexadecimal values as "FF" instead of "ff".
private int OptMidColsCount; // = 8 // set to 0 to disable extra spacing between every mid-cols.
private int
OptAddrDigitsCount; // = 0 // number of addr digits to display (default calculated based on maximum displayed addr).
private LGuiColor HighlightColor; // // background color of highlighted bytes.
//u8(*ReadFn)(const u8* data, size_t off); // = NULL // optional handler to read bytes.
//void (* WriteFn) (u8* data, size_t off, u8 d); // = NULL // optional handler to write bytes.
//bool (* HighlightFn) (const u8* data, size_t off);//NULL // optional handler to return Highlight property (to support non-contiguous highlighting).
// [Internal State]
private bool ContentsWidthChanged;
private int DataPreviewAddr;
private int DataEditingAddr;
private bool DataEditingTakeFocus;
private string DataInputBuf = string.Empty;
private string AddrInputBuf = string.Empty;
private int GotoAddr;
private int HighlightMin, HighlightMax;
private int PreviewEndianess;
private DataType PreviewDataType;
internal DemoMemoryEditor()
{
var R = new Random((int)DateTime.Now.Ticks);
R.NextBytes(MemoryBuffer);
// Settings
Open = true;
ReadOnly = false;
Cols = 16;
OptShowOptions = true;
OptShowDataPreview = false;
OptShowHexII = false;
OptShowAscii = true;
OptGreyOutZeroes = true;
OptUpperCaseHex = true;
OptMidColsCount = 8;
OptAddrDigitsCount = 0;
HighlightColor = new LGuiColor(255, 255, 255, 50);
// State/Internals
ContentsWidthChanged = false;
DataPreviewAddr = DataEditingAddr = (int)-1;
DataEditingTakeFocus = false;
GotoAddr = 4 - 1;
HighlightMin = HighlightMax = (int)-1;
PreviewEndianess = 0;
PreviewDataType = DataType.DataType_S32;
}
void GotoAddrAndHighlight(int addr_min, int addr_max)
{
GotoAddr = addr_min;
HighlightMin = addr_min;
HighlightMax = addr_max;
}
private struct Sizes
{
internal int AddrDigitsCount;
internal float LineHeight;
internal float GlyphWidth;
internal float HexCellWidth;
internal float SpacingBetweenMidCols;
internal float PosHexStart;
internal float PosHexEnd;
internal float PosAsciiStart;
internal float PosAsciiEnd;
internal float WindowWidth;
};
internal override bool Startup()
{
return true;
}
internal override void Shutdown()
{
}
internal override void Tick(float Seconds)
{
var R = new Random((int)DateTime.Now.Ticks);
for (var Index = 0; Index < 300; ++Index)
{
if (R.NextDouble() < 0.005f)
{
MemoryBuffer[Index] = (byte)R.Next(byte.MinValue, byte.MaxValue);
}
}
}
internal override void Render()
{
DrawWindow("MemoryDemo", MemoryBuffer, MemoryBuffer.Length);
}
void CalcSizes(ref Sizes s, int mem_size, int base_display_addr)
{
//ImGuiStyle & style = ImGui::GetStyle();
s.AddrDigitsCount = OptAddrDigitsCount;
if (s.AddrDigitsCount == 0)
for (int n = base_display_addr + mem_size - 1; n > 0; n >>= 4)
s.AddrDigitsCount++;
s.LineHeight = LGuiFont.Default.FontHeight + 2;
s.GlyphWidth = LGuiFont.Default.FontWidth + 1; // We assume the font is mono-space
s.HexCellWidth =
(float) (int) (s.GlyphWidth *
2.5f); // "FF " we include trailing space in the width to easily catch clicks everywhere
s.SpacingBetweenMidCols =
(float) (int) (s.HexCellWidth * 0.25f); // Every OptMidColsCount columns we add a bit of extra spacing
s.PosHexStart = (s.AddrDigitsCount + 2) * s.GlyphWidth;
s.PosHexEnd = s.PosHexStart + (s.HexCellWidth * Cols);
s.PosAsciiStart = s.PosAsciiEnd = s.PosHexEnd;
if (OptShowAscii)
{
s.PosAsciiStart = s.PosHexEnd + s.GlyphWidth * 1;
if (OptMidColsCount > 0)
s.PosAsciiStart += ((Cols + OptMidColsCount - 1) / OptMidColsCount) * s.SpacingBetweenMidCols;
s.PosAsciiEnd = s.PosAsciiStart + Cols * s.GlyphWidth;
}
s.WindowWidth = s.PosAsciiEnd + 5 * 2 + s.GlyphWidth;
}
// Standalone Memory Editor window
internal void DrawWindow(string title, byte[] mem_data, int mem_size, int base_display_addr = 0x0000)
{
Sizes s = new Sizes();
CalcSizes(ref s, mem_size, base_display_addr);
LGui.Begin();
LGui.BeginFrame(title, new LGuiVec2(s.WindowWidth, 500));
DrawContents(mem_data, mem_size, base_display_addr);
LGui.EndFrame();
LGui.Slider("Cols", ref Cols, 4, 32, 1, true, "{0}", 200.0f);
LGui.SameLine();
OptShowAscii = LGui.CheckBox("OptShowAscii", OptShowAscii);
LGui.SameLine();
OptShowDataPreview = LGui.CheckBox("OptShowDataPreview", OptShowDataPreview);
if (OptShowDataPreview && DataPreviewAddr == -1)
{
DataPreviewAddr = 0;
}
LGui.End();
}
// Memory Editor contents only
void DrawContents(byte[] mem_data_void_ptr, int mem_size, int base_display_addr = 0x0000)
{
var CmdList = LGui.CreateCommandList();
var mem_data = mem_data_void_ptr;
Sizes s = new Sizes();
CalcSizes(ref s, mem_size, base_display_addr);
var IO = LGui.GetIO();
// We begin into our scrolling region with the 'ImGuiWindowFlags_NoMove' in order to prevent click from moving the window.
// This is used as a facility since our main click detection code doesn't assign an ActiveId so the click would normally be caught as a window-move.
float height_separator = 5;
int line_total_count = (int)((mem_size + Cols - 1) / Cols);
/*ImGuiListClipper clipper(line_total_count, s.LineHeight);
const size_t visible_start_addr = clipper.DisplayStart * Cols;
const size_t visible_end_addr = clipper.DisplayEnd * Cols;*/
var DisplayStart = (int)(LGui.GetFrameScrollY() / (s.LineHeight + 3));
var DisplayEnd = (int)((LGui.GetFrameScrollY() + 500) / (s.LineHeight + 3));
int visible_start_addr = DisplayStart * Cols;
int visible_end_addr = DisplayEnd * Cols;
bool data_next = false;
if (ReadOnly || DataEditingAddr >= mem_size)
DataEditingAddr = (int)-1;
if (DataPreviewAddr >= mem_size)
DataPreviewAddr = (int)-1;
int preview_data_type_size = OptShowDataPreview ? DataTypeGetSize(PreviewDataType) : 0;
int data_editing_addr_backup = DataEditingAddr;
int data_editing_addr_next = (int)-1;
if (DataEditingAddr != (int)-1)
{
// Move cursor but only apply on next frame so scrolling with be synchronized (because currently we can't change the scrolling while the window is being rendered)
if (IO.IsKeyPressed(LGuiKeys.Up) && DataEditingAddr >= (int)Cols) { data_editing_addr_next = DataEditingAddr - Cols; DataEditingTakeFocus = true; }
else if (IO.IsKeyPressed(LGuiKeys.Down) && DataEditingAddr < mem_size - Cols) { data_editing_addr_next = DataEditingAddr + Cols; DataEditingTakeFocus = true; }
else if (IO.IsKeyPressed(LGuiKeys.Left) && DataEditingAddr > 0) { data_editing_addr_next = DataEditingAddr - 1; DataEditingTakeFocus = true; }
else if (IO.IsKeyPressed(LGuiKeys.Right) && DataEditingAddr < mem_size - 1) { data_editing_addr_next = DataEditingAddr + 1; DataEditingTakeFocus = true; }
}
if (data_editing_addr_next != (int)-1 && (data_editing_addr_next / Cols) != (data_editing_addr_backup / Cols))
{
// Track cursor movements
int scroll_offset = ((int)(data_editing_addr_next / Cols) - (int)(data_editing_addr_backup / Cols));
bool scroll_desired = (scroll_offset < 0 && data_editing_addr_next < visible_start_addr + Cols * 2) || (scroll_offset > 0 && data_editing_addr_next > visible_end_addr - Cols * 2);
if (scroll_desired)
LGui.SetFrameScrollY(LGui.GetFrameScrollY() + scroll_offset * (s.LineHeight + 3));
}
// Draw vertical separator
LGuiVec2 window_pos = new LGuiVec2(5, 5);
if (OptShowAscii)
{
CmdList.DrawLine(
new LGuiVec2(window_pos.X + s.PosAsciiStart - s.GlyphWidth, window_pos.Y),
new LGuiVec2(window_pos.X + s.PosAsciiStart - s.GlyphWidth, window_pos.Y + 9999),
new LGuiColor(0.43f, 0.43f, 0.50f, 0.50f));
}
var color_text = new LGuiColor(1.00f, 1.00f, 1.00f, 1.00f);
var color_disabled = OptGreyOutZeroes ? new LGuiColor(0.50f, 0.50f, 0.50f, 1.00f) : color_text;
var format_address = OptUpperCaseHex ? "{0:X4}: " : "{0:X4}: ";
var format_data = OptUpperCaseHex ? "{0:X4}: " : "{0:X4}: ";
var format_range = OptUpperCaseHex ? "Range {0:X4}..{1:X4}" : "Range {0:X4}..{1:X4}";
var format_byte = OptUpperCaseHex ? "{0:X2}" : "{0:X2}";
var format_byte_space = OptUpperCaseHex ? "{0:X2}" : "{0:X2}";
for (int line_i = 0; line_i < mem_size / Cols; ++line_i)
{
int addr = (int)(line_i * Cols);
LGui.Text(format_address, base_display_addr + addr);
for (int n = 0; n < Cols && addr < mem_size; ++n, ++addr)
{
LGui.PushID(addr);
float byte_pos_x = s.PosHexStart + s.HexCellWidth * n;
if (OptMidColsCount > 0)
byte_pos_x += (n / OptMidColsCount) * s.SpacingBetweenMidCols;
LGui.SameLine(byte_pos_x);
// Draw highlight
bool is_highlight_from_user_range = (addr >= HighlightMin && addr < HighlightMax);
bool is_highlight_from_preview = (addr >= DataPreviewAddr && addr < DataPreviewAddr + preview_data_type_size);
if (is_highlight_from_user_range || is_highlight_from_preview)
{
var pos = LGui.GetCursorPos();
float highlight_width = s.GlyphWidth * 2;
bool is_next_byte_highlighted = (addr + 1 < mem_size) && ((HighlightMax != (int)-1 && addr + 1 < HighlightMax));
if (is_next_byte_highlighted || (n + 1 == Cols))
{
highlight_width = s.HexCellWidth;
if (OptMidColsCount > 0 && n > 0 && (n + 1) < Cols && ((n + 1) % OptMidColsCount) == 0)
highlight_width += s.SpacingBetweenMidCols;
}
CmdList.DrawRect(new LGuiRect(pos, new LGuiVec2(highlight_width, s.LineHeight)), HighlightColor, true, false);
}
if (DataEditingAddr == addr)
{// Display text input on current byte
bool data_write = false;
if (DataEditingTakeFocus)
{
AddrInputBuf = string.Format(format_data, s.AddrDigitsCount, base_display_addr + addr);
DataInputBuf = string.Format(format_byte, mem_data[addr]);
}
var itemwidth = s.GlyphWidth * 2;
/*struct UserData
{
// FIXME: We should have a way to retrieve the text edit cursor position more easily in the API, this is rather tedious. This is such a ugly mess we may be better off not using InputText() at all here.
static int Callback(ImGuiInputTextCallbackData* data)
{
UserData* user_data = (UserData*)data->UserData;
if (!data->HasSelection())
user_data->CursorPos = data->CursorPos;
if (data->SelectionStart == 0 && data->SelectionEnd == data->BufTextLen)
{
// When not editing a byte, always rewrite its content (this is a bit tricky, since InputText technically "owns" the master copy of the buffer we edit it in there)
data->DeleteChars(0, data->BufTextLen);
data->InsertChars(0, user_data->CurrentBufOverwrite);
data->SelectionStart = 0;
data->SelectionEnd = data->CursorPos = 2;
}
return 0;
}
char CurrentBufOverwrite[3]; // Input
int CursorPos; // Output
};
UserData user_data;
user_data.CursorPos = -1;
sprintf(user_data.CurrentBufOverwrite, format_byte, ReadFn? ReadFn(mem_data, addr) : mem_data[addr]);
ImGuiInputTextFlags flags = ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_EnterReturnsTrue | ImGuiInputTextFlags_AutoSelectAll | ImGuiInputTextFlags_NoHorizontalScroll | ImGuiInputTextFlags_AlwaysInsertMode | ImGuiInputTextFlags_CallbackAlways;
if (ImGui::InputText("##data", DataInputBuf, 32, flags, UserData::Callback, &user_data))
data_write = data_next = true;
else if (!DataEditingTakeFocus && !ImGui::IsItemActive())
DataEditingAddr = data_editing_addr_next = (size_t)-1;
DataEditingTakeFocus = false;
if (user_data.CursorPos >= 2)
data_write = data_next = true;
if (data_editing_addr_next != (size_t)-1)
data_write = data_next = false;
int data_input_value;
if (data_write && sscanf(DataInputBuf, "%X", &data_input_value) == 1)
{
if (WriteFn)
WriteFn(mem_data, addr, (u8) data_input_value);
else
mem_data[addr] = (u8) data_input_value;
}*/
var Flags = LGuiInputTextFlags.CharsHexadecimal | /*LGuiInputTextFlags.AutoSelectAll |*/
LGuiInputTextFlags.InsertMode | LGuiInputTextFlags.EnterReturnsTrue;
if (LGui.InputText("##data", ref DataInputBuf, 2,
new LGuiVec2(itemwidth + 5, LGuiFont.Default.FontHeight + 2), Flags))
{
data_write = data_next = true;
}
else if (!DataEditingTakeFocus && !LGui.PreviousControlIsActive())
{
DataEditingAddr = data_editing_addr_next = (int)-1;
}
//LGui.PreviousControlFocus();
int data_input_value;
if (data_write && int.TryParse(DataInputBuf, NumberStyles.HexNumber, null, out data_input_value))
{
mem_data[addr] = (byte)data_input_value;
}
}
else
{
byte b = mem_data[addr];
if (OptShowHexII)
{
if ((b >= 32 && b < 128))
LGui.Text(".{0}", (char)b);
else if (b == 0xFF && OptGreyOutZeroes)
LGui.Text(color_disabled, "##");
else if (b == 0x00)
LGui.Text(" ");
else
LGui.Text(format_byte_space, b);
}
else
{
if (b == 0 && OptGreyOutZeroes)
LGui.Text(color_disabled, "00");
else
LGui.Text(format_byte_space, b);
}
if (!ReadOnly && LGui.PreviousControlIsHovered() && IO.IsMouseClick(LGuiMouseButtons.Left))
{
DataEditingTakeFocus = true;
data_editing_addr_next = addr;
}
}
LGui.PopID();
}
if (OptShowAscii)
{
// Draw ASCII values
LGui.SameLine(s.PosAsciiStart);
var pos = LGui.GetCursorPos();
addr = line_i * Cols;
LGui.PushID(line_i);
if (LGui.InvisibleButton("ascii", new LGuiVec2(s.PosAsciiEnd - s.PosAsciiStart, s.LineHeight)))
{
DataEditingAddr = DataPreviewAddr = addr + (int)((LGui.GetIO().MousePos.X - pos.X) / s.GlyphWidth);
DataEditingTakeFocus = true;
}
LGui.PopID();
for (int n = 0; n < Cols && addr < mem_size; n++, addr++)
{
if (addr == DataEditingAddr)
{
CmdList.DrawRect(new LGuiRect(pos, new LGuiVec2(s.GlyphWidth, s.LineHeight)), new LGuiColor(0.16f, 0.29f, 0.48f, 0.54f), true, false);
CmdList.DrawRect(new LGuiRect(pos, new LGuiVec2(s.GlyphWidth, s.LineHeight)), new LGuiColor(0.26f, 0.59f, 0.98f, 0.35f), true, false);
}
byte c = mem_data[addr];
char display_c = (c < 32 || c >= 128) ? '.' : (char)c;
LGui.SameLine(pos.X);
LGui.Text((display_c == '.') ? color_disabled : color_text, "{0}", display_c.ToString());
//LGuiGraphics.DrawText(display_c.ToString(), pos, new LGuiTextStyle(LGuiFontStyle.Default, (display_c == '.') ? color_disabled : color_text));
pos.X += s.GlyphWidth;
}
}
}
if (data_next && DataEditingAddr < mem_size)
{
DataEditingAddr = DataPreviewAddr = DataEditingAddr + 1;
DataEditingTakeFocus = true;
}
else if (data_editing_addr_next != (int)-1)
{
DataEditingAddr = DataPreviewAddr = data_editing_addr_next;
}
LGui.AddCommandList(CmdList);
/*for (int line_i = clipper.DisplayStart; line_i < clipper.DisplayEnd; line_i++) // display only visible lines
{
int addr = (int)(line_i * Cols);
LGui.Text(format_address, base_display_addr + addr);
// Draw Hexadecimal
for (int n = 0; n < Cols && addr < mem_size; n++, addr++)
{
float byte_pos_x = s.PosHexStart + s.HexCellWidth * n;
if (OptMidColsCount > 0)
byte_pos_x += (n / OptMidColsCount) * s.SpacingBetweenMidCols;
ImGui::SameLine(byte_pos_x);
// Draw highlight
bool is_highlight_from_user_range = (addr >= HighlightMin && addr < HighlightMax);
bool is_highlight_from_user_func = (HighlightFn && HighlightFn(mem_data, addr));
bool is_highlight_from_preview = (addr >= DataPreviewAddr && addr < DataPreviewAddr + preview_data_type_size);
if (is_highlight_from_user_range || is_highlight_from_user_func || is_highlight_from_preview)
{
ImVec2 pos = ImGui::GetCursorScreenPos();
float highlight_width = s.GlyphWidth * 2;
bool is_next_byte_highlighted = (addr + 1 < mem_size) && ((HighlightMax != (size_t) - 1 && addr + 1 < HighlightMax) || (HighlightFn && HighlightFn(mem_data, addr + 1)));
if (is_next_byte_highlighted || (n + 1 == Cols))
{
highlight_width = s.HexCellWidth;
if (OptMidColsCount > 0 && n > 0 && (n + 1) < Cols && ((n + 1) % OptMidColsCount) == 0)
highlight_width += s.SpacingBetweenMidCols;
}
draw_list->AddRectFilled(pos, ImVec2(pos.x + highlight_width, pos.y + s.LineHeight), HighlightColor);
}
if (DataEditingAddr == addr)
{
// Display text input on current byte
bool data_write = false;
ImGui::PushID((void*)addr);
if (DataEditingTakeFocus)
{
ImGui::SetKeyboardFocusHere();
ImGui::CaptureKeyboardFromApp(true);
sprintf(AddrInputBuf, format_data, s.AddrDigitsCount, base_display_addr + addr);
sprintf(DataInputBuf, format_byte, ReadFn ? ReadFn(mem_data, addr) : mem_data[addr]);
}
ImGui::PushItemWidth(s.GlyphWidth * 2);
struct UserData
{
// FIXME: We should have a way to retrieve the text edit cursor position more easily in the API, this is rather tedious. This is such a ugly mess we may be better off not using InputText() at all here.
static int Callback(ImGuiInputTextCallbackData* data)
{
UserData* user_data = (UserData*)data->UserData;
if (!data->HasSelection())
user_data->CursorPos = data->CursorPos;
if (data->SelectionStart == 0 && data->SelectionEnd == data->BufTextLen)
{
// When not editing a byte, always rewrite its content (this is a bit tricky, since InputText technically "owns" the master copy of the buffer we edit it in there)
data->DeleteChars(0, data->BufTextLen);
data->InsertChars(0, user_data->CurrentBufOverwrite);
data->SelectionStart = 0;
data->SelectionEnd = data->CursorPos = 2;
}
return 0;
}
char CurrentBufOverwrite[3]; // Input
int CursorPos; // Output
};
UserData user_data;
user_data.CursorPos = -1;
sprintf(user_data.CurrentBufOverwrite, format_byte, ReadFn? ReadFn(mem_data, addr) : mem_data[addr]);
ImGuiInputTextFlags flags = ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_EnterReturnsTrue | ImGuiInputTextFlags_AutoSelectAll | ImGuiInputTextFlags_NoHorizontalScroll | ImGuiInputTextFlags_AlwaysInsertMode | ImGuiInputTextFlags_CallbackAlways;
if (ImGui::InputText("##data", DataInputBuf, 32, flags, UserData::Callback, &user_data))
data_write = data_next = true;
else if (!DataEditingTakeFocus && !ImGui::IsItemActive())
DataEditingAddr = data_editing_addr_next = (size_t)-1;
DataEditingTakeFocus = false;
ImGui::PopItemWidth();
if (user_data.CursorPos >= 2)
data_write = data_next = true;
if (data_editing_addr_next != (size_t)-1)
data_write = data_next = false;
int data_input_value;
if (data_write && sscanf(DataInputBuf, "%X", &data_input_value) == 1)
{
if (WriteFn)
WriteFn(mem_data, addr, (u8) data_input_value);
else
mem_data[addr] = (u8) data_input_value;
}
ImGui::PopID();
}
else
{
// NB: The trailing space is not visible but ensure there's no gap that the mouse cannot click on.
u8 b = ReadFn ? ReadFn(mem_data, addr) : mem_data[addr];
if (OptShowHexII)
{
if ((b >= 32 && b< 128))
ImGui::Text(".%c ", b);
else if (b == 0xFF && OptGreyOutZeroes)
ImGui::TextDisabled("## ");
else if (b == 0x00)
ImGui::Text(" ");
else
ImGui::Text(format_byte_space, b);
}
else
{
if (b == 0 && OptGreyOutZeroes)
ImGui::TextDisabled("00 ");
else
ImGui::Text(format_byte_space, b);
}
if (!ReadOnly && ImGui::IsItemHovered() && ImGui::IsMouseClicked(0))
{
DataEditingTakeFocus = true;
data_editing_addr_next = addr;
}
}
}
if (OptShowAscii)
{
// Draw ASCII values
ImGui::SameLine(s.PosAsciiStart);
ImVec2 pos = ImGui::GetCursorScreenPos();
addr = line_i* Cols;
ImGui::PushID(line_i);
if (ImGui::InvisibleButton("ascii", ImVec2(s.PosAsciiEnd - s.PosAsciiStart, s.LineHeight)))
{
DataEditingAddr = DataPreviewAddr = addr + (size_t) ((ImGui::GetIO().MousePos.x - pos.x) / s.GlyphWidth);
DataEditingTakeFocus = true;
}
ImGui::PopID();
for (int n = 0; n<Cols && addr<mem_size; n++, addr++)
{
if (addr == DataEditingAddr)
{
draw_list->AddRectFilled(pos, ImVec2(pos.x + s.GlyphWidth, pos.y + s.LineHeight), ImGui::GetColorU32(ImGuiCol_FrameBg));
draw_list->AddRectFilled(pos, ImVec2(pos.x + s.GlyphWidth, pos.y + s.LineHeight), ImGui::GetColorU32(ImGuiCol_TextSelectedBg));
}
unsigned char c = ReadFn ? ReadFn(mem_data, addr) : mem_data[addr];
char display_c = (c < 32 || c >= 128) ? '.' : c;
draw_list->AddText(pos, (display_c == '.') ? color_disabled : color_text, &display_c, &display_c + 1);
pos.x += s.GlyphWidth;
}
}
}
clipper.End();
ImGui::PopStyleVar(2);
ImGui::EndChild();
if (data_next && DataEditingAddr<mem_size)
{
DataEditingAddr = DataPreviewAddr = DataEditingAddr + 1;
DataEditingTakeFocus = true;
}
else if (data_editing_addr_next != (size_t)-1)
{
DataEditingAddr = DataPreviewAddr = data_editing_addr_next;
}
bool next_show_data_preview = OptShowDataPreview;
if (OptShowOptions)
{
ImGui::Separator();
// Options menu
if (ImGui::Button("Options"))
ImGui::OpenPopup("context");
if (ImGui::BeginPopup("context"))
{
ImGui::PushItemWidth(56);
if (ImGui::DragInt("##cols", &Cols, 0.2f, 4, 32, "%d cols")) { ContentsWidthChanged = true; }
ImGui::PopItemWidth();
ImGui::Checkbox("Show Data Preview", &next_show_data_preview);
ImGui::Checkbox("Show HexII", &OptShowHexII);
if (ImGui::Checkbox("Show Ascii", &OptShowAscii)) { ContentsWidthChanged = true; }
ImGui::Checkbox("Grey out zeroes", &OptGreyOutZeroes);
ImGui::Checkbox("Uppercase Hex", &OptUpperCaseHex);
ImGui::EndPopup();
}
ImGui::SameLine();
ImGui::Text(format_range, s.AddrDigitsCount, base_display_addr, s.AddrDigitsCount, base_display_addr + mem_size - 1);
ImGui::SameLine();
ImGui::PushItemWidth((s.AddrDigitsCount + 1) * s.GlyphWidth + style.FramePadding.x* 2.0f);
if (ImGui::InputText("##addr", AddrInputBuf, 32, ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_EnterReturnsTrue))
{
size_t goto_addr;
if (sscanf(AddrInputBuf, "%" _PRISizeT "X", &goto_addr) == 1)
{
GotoAddr = goto_addr - base_display_addr;
HighlightMin = 3 = (size_t)-1;
}
}
ImGui::PopItemWidth();
if (GotoAddr != (size_t)-1)
{
if (GotoAddr<mem_size)
{
ImGui::BeginChild("##scrolling");
ImGui::SetScrollFromPosY(ImGui::GetCursorStartPos().y + (GotoAddr / Cols) * ImGui::GetTextLineHeight());
ImGui::EndChild();
DataEditingAddr = DataPreviewAddr = GotoAddr;
DataEditingTakeFocus = true;
}
GotoAddr = (size_t)-1;
}
}
if (OptShowDataPreview)
{
ImGui::Separator();
ImGui::AlignTextToFramePadding();
ImGui::Text("Preview as:");
ImGui::SameLine();
ImGui::PushItemWidth((s.GlyphWidth* 10.0f) + style.FramePadding.x* 2.0f + style.ItemInnerSpacing.x);
if (ImGui::BeginCombo("##combo_type", DataTypeGetDesc(PreviewDataType), ImGuiComboFlags_HeightLargest))
{
for (int n = 0; n<DataType_COUNT; n++)
if (ImGui::Selectable(DataTypeGetDesc((DataType) n), PreviewDataType == n))
PreviewDataType = (DataType) n;
ImGui::EndCombo();
}
ImGui::PopItemWidth();
ImGui::SameLine();
ImGui::PushItemWidth((s.GlyphWidth* 6.0f) + style.FramePadding.x* 2.0f + style.ItemInnerSpacing.x);
ImGui::Combo("##combo_endianess", &PreviewEndianess, "LE\0BE\0\0");
ImGui::PopItemWidth();
char buf[128];
float x = s.GlyphWidth * 6.0f;
bool has_value = DataPreviewAddr != (size_t) - 1;
if (has_value)
DisplayPreviewData(DataPreviewAddr, mem_data, mem_size, PreviewDataType, DataFormat_Dec, buf, (size_t) IM_ARRAYSIZE(buf));
ImGui::Text("Dec"); ImGui::SameLine(x); ImGui::TextUnformatted(has_value? buf : "N/A");
if (has_value)
DisplayPreviewData(DataPreviewAddr, mem_data, mem_size, PreviewDataType, DataFormat_Hex, buf, (size_t) IM_ARRAYSIZE(buf));
ImGui::Text("Hex"); ImGui::SameLine(x); ImGui::TextUnformatted(has_value? buf : "N/A");
if (has_value)
DisplayPreviewData(DataPreviewAddr, mem_data, mem_size, PreviewDataType, DataFormat_Bin, buf, (size_t) IM_ARRAYSIZE(buf));
ImGui::Text("Bin"); ImGui::SameLine(x); ImGui::TextUnformatted(has_value? buf : "N/A");
}
OptShowDataPreview = next_show_data_preview;
// Notify the main window of our ideal child content size (FIXME: we are missing an API to get the contents size from the child)
ImGui::SetCursorPosX(s.WindowWidth);*/
}
// Utilities for Data Preview
private string DataTypeGetDesc(DataType data_type)
{
string[] descs =
{"Int8", "Uint8", "Int16", "Uint16", "Int32", "Uint32", "Int64", "Uint64", "Float", "Double"};
return descs[(int) data_type];
}
private int DataTypeGetSize(DataType data_type)
{
int[] sizes = {1, 1, 2, 2, 4, 4, 8, 8, 4, 8};
return sizes[(int) data_type];
}
private string DataFormatGetDesc(DataFormat data_format)
{
string[] descs = {"Bin", "Dec", "Hex"};
return descs[(int) data_format];
}
private bool IsBigEndian()
{
return !BitConverter.IsLittleEndian;
}
private T EndianessCopy<T>(ref byte[] src, int size)
{
return (T) Convert.ChangeType(src, typeof(T));
}
private string FormatBinary(byte[] buf, int width)
{
int out_n = 0;
StringBuilder out_buf = new StringBuilder(64 + 8 + 1);
for (int j = 0, n = width / 8; j < n; ++j)
{
for (int i = 0; i < 8; ++i)
{
out_buf[out_n++] = (buf[j] & (1 << (7 - i))) == 1 ? '1' : '0';
}
out_buf[out_n++] = ' ';
}
return out_buf.ToString();
}
private string DisplayPreviewData(int addr, byte[] mem_data, int mem_size, DataType data_type, DataFormat data_format)
{
byte[] buf = new byte[8];
int elem_size = DataTypeGetSize(data_type);
int size = addr + elem_size > mem_size ? mem_size - addr : elem_size;
Array.Copy(mem_data, addr, buf, 0, size);
if (data_format == DataFormat.DataFormat_Bin)
{
return FormatBinary(buf, (int) size * 8);
}
switch (data_type)
{
case DataType.DataType_S8:
{
char int8 = EndianessCopy<char>(ref buf, size);
if (data_format == DataFormat.DataFormat_Dec)
{
return $"{int8:D2}";
}
if (data_format == DataFormat.DataFormat_Hex)
{
return $"{int8 & 0xFF:X2}";
}
break;
}
case DataType.DataType_U8:
{
byte uint8 = EndianessCopy<byte>(ref buf, size);
if (data_format == DataFormat.DataFormat_Dec)
{
return $"{uint8:D2}";
}
if (data_format == DataFormat.DataFormat_Hex)
{
return $"{uint8 & 0XFF:X2}";
}
break;
}
case DataType.DataType_S16:
{
short int16 = EndianessCopy<short>(ref buf, size);
if (data_format == DataFormat.DataFormat_Dec)
{
return $"{int16:D4}";
}
if (data_format == DataFormat.DataFormat_Hex)
{
return $"{int16 & 0xFFFF:X4}";
}
break;
}
case DataType.DataType_U16:
{
ushort uint16 = EndianessCopy<ushort>(ref buf, size);
if (data_format == DataFormat.DataFormat_Dec)
{
return $"{uint16:D4}";
}
if (data_format == DataFormat.DataFormat_Hex)
{
return $"{uint16 & 0xFFFF:X4}";
}
break;
}
case DataType.DataType_S32:
{
int int32 = EndianessCopy<int>(ref buf, size);
if (data_format == DataFormat.DataFormat_Dec)
{
return $"{int32:D8}";
}
if (data_format == DataFormat.DataFormat_Hex)
{
return $"{int32 & 0xFFFF:X8}";
}
break;
}
case DataType.DataType_U32:
{
uint uint32 = EndianessCopy<uint>(ref buf, size);
if (data_format == DataFormat.DataFormat_Dec)
{
return $"{uint32:D8}";
}
if (data_format == DataFormat.DataFormat_Hex)
{
return $"{uint32 & 0xFFFF:X8}";
}
break;
}
case DataType.DataType_S64:
{
long int64 = EndianessCopy<long>(ref buf, size);
if (data_format == DataFormat.DataFormat_Dec)
{
return $"{int64:D16}";
}
if (data_format == DataFormat.DataFormat_Hex)
{
return $"{int64:X16}";
}
break;
}
case DataType.DataType_U64:
{
ulong uint64 = EndianessCopy<ulong>(ref buf, size);
if (data_format == DataFormat.DataFormat_Dec)
{
return $"{uint64:D16}";
}
if (data_format == DataFormat.DataFormat_Hex)
{
return $"{uint64:X16}";
}
break;
}
case DataType.DataType_Float:
{
float float32 = EndianessCopy<float>(ref buf, size);
if (data_format == DataFormat.DataFormat_Dec)
{
return $"{float32:F}";
}
if (data_format == DataFormat.DataFormat_Hex)
{
return $"{float32:G}";
}
break;
}
case DataType.DataType_Double:
{
double float64 = EndianessCopy<double>(ref buf, size);
if (data_format == DataFormat.DataFormat_Dec)
{
return $"{float64:F}";
}
if (data_format == DataFormat.DataFormat_Hex)
{
return $"{float64:G}";
}
}
break;
}
return string.Empty;
}
}
} | 46.274784 | 281 | 0.482779 | [
"MIT"
] | UnSkyToo/LiteGui | LiteGuiDemo/Demos/DemoMemoryEditor.cs | 42,945 | C# |
// <copyright file="Armors.cs" company="MUnique">
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
// </copyright>
namespace MUnique.OpenMU.Persistence.Initialization.Items
{
using System.Collections.Generic;
using System.Linq;
using MUnique.OpenMU.AttributeSystem;
using MUnique.OpenMU.DataModel.Attributes;
using MUnique.OpenMU.DataModel.Configuration;
using MUnique.OpenMU.DataModel.Configuration.Items;
using MUnique.OpenMU.GameLogic.Attributes;
/// <summary>
/// Initializer for armor data.
/// </summary>
public class Armors : InitializerBase
{
private static readonly int[] DefenseIncreaseByLevel = { 0, 3, 6, 9, 12, 15, 18, 21, 24, 27, 31, 36, 42, 49, 57, 66 };
private List<LevelBonus> defenseBonusPerLevel;
private List<LevelBonus> shieldDefenseBonusPerLevel;
/// <summary>
/// Initializes a new instance of the <see cref="Armors"/> class.
/// </summary>
/// <param name="context">The persistence context.</param>
/// <param name="gameConfiguration">The game configuration.</param>
public Armors(IContext context, GameConfiguration gameConfiguration)
: base(context, gameConfiguration)
{
}
/// <summary>
/// Initializes armor data.
/// </summary>
/// <remarks>
/// Regex: (?m)^\s*(\d+)\s+(-*\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+\"(.+?)\"\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+).*$
/// Replace by: this.CreateArmor($1, $2, $4, $5, "$9", $10, $11, $13, $14, $15, $16, $17, $18, $19, $21, $22, $23, $24, $25, $26, $27);
/// </remarks>
public override void Initialize()
{
this.CreateBonusDefensePerLevel();
// Shields:
this.CreateShield(0, 1, 0, 2, 2, "Small Shield", 3, 1, 3, 22, 0, 70, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0);
this.CreateShield(1, 1, 0, 2, 2, "Horn Shield", 9, 3, 9, 28, 0, 100, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0);
this.CreateShield(2, 1, 0, 2, 2, "Kite Shield", 12, 4, 12, 32, 0, 110, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0);
this.CreateShield(3, 1, 0, 2, 2, "Elven Shield", 21, 8, 21, 36, 0, 30, 100, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0);
this.CreateShield(4, 1, 18, 2, 2, "Buckler", 6, 2, 6, 24, 0, 80, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0);
this.CreateShield(5, 1, 18, 2, 2, "Dragon Slayer Shield", 35, 10, 36, 44, 0, 100, 40, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0);
this.CreateShield(6, 1, 18, 2, 2, "Skull Shield", 15, 5, 15, 34, 0, 110, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0);
this.CreateShield(7, 1, 18, 2, 2, "Spiked Shield", 30, 9, 30, 40, 0, 130, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0);
this.CreateShield(8, 1, 18, 2, 2, "Tower Shield", 40, 11, 40, 46, 0, 130, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0);
this.CreateShield(9, 1, 18, 2, 2, "Plate Shield", 25, 8, 25, 38, 0, 120, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0);
this.CreateShield(10, 1, 18, 2, 2, "Big Round Shield", 18, 6, 18, 35, 0, 120, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0);
this.CreateShield(11, 1, 18, 2, 2, "Serpent Shield", 45, 12, 45, 48, 0, 130, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0);
this.CreateShield(12, 1, 18, 2, 2, "Bronze Shield", 54, 13, 54, 52, 0, 140, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0);
this.CreateShield(13, 1, 18, 2, 2, "Dragon Shield", 60, 14, 60, 60, 0, 120, 40, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0);
this.CreateShield(14, 1, 0, 2, 3, "Legendary Shield", 48, 7, 48, 50, 0, 90, 25, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0);
this.CreateShield(15, 1, 0, 2, 3, "Grand Soul Shield", 74, 12, 55, 55, 0, 70, 23, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0);
this.CreateShield(16, 1, 0, 2, 2, "Elemental Shield", 66, 11, 28, 51, 0, 30, 60, 30, 0, 0, 0, 0, 2, 0, 0, 0, 0);
this.CreateShield(17, 1, 18, 2, 2, "CrimsonGlory", 104, 19, 90, 51, 0, 95, 48, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0);
this.CreateShield(18, 1, 18, 2, 2, "Salamander Shield", 102, 20, 96, 51, 0, 80, 61, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0);
this.CreateShield(19, 1, 0, 2, 2, "Frost Barrier", 99, 14, 58, 51, 0, 26, 53, 26, 0, 0, 0, 0, 2, 0, 0, 0, 0);
this.CreateShield(20, 1, 18, 2, 2, "Guardian Shiled", 106, 12, 30, 51, 0, 54, 18, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0);
this.CreateShield(21, 1, 18, 2, 2, "Cross Shield", 70, 16, 75, 65, 0, 140, 55, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0);
// Helmets:
this.CreateArmor(0, 2, 2, 2, "Bronze Helm", 16, 9, 34, 0, 80, 20, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0);
this.CreateArmor(1, 2, 2, 2, "Dragon Helm", 57, 24, 68, 0, 120, 30, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0);
this.CreateArmor(2, 2, 2, 2, "Pad Helm", 5, 4, 28, 0, 20, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0);
this.CreateArmor(3, 2, 2, 2, "Legendary Helm", 50, 18, 42, 0, 30, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0);
this.CreateArmor(4, 2, 2, 2, "Bone Helm", 18, 9, 30, 0, 30, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0);
this.CreateArmor(5, 2, 2, 2, "Leather Helm", 6, 5, 30, 0, 80, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1);
this.CreateArmor(6, 2, 2, 2, "Scale Helm", 26, 12, 40, 0, 110, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1);
this.CreateArmor(7, 2, 2, 2, "Sphinx Mask", 32, 13, 36, 0, 30, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0);
this.CreateArmor(8, 2, 2, 2, "Brass Helm", 36, 17, 44, 0, 100, 30, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
this.CreateArmor(9, 2, 2, 2, "Plate Helm", 46, 20, 50, 0, 130, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
this.CreateArmor(10, 2, 2, 2, "Vine Helm", 6, 4, 22, 0, 30, 60, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0);
this.CreateArmor(11, 2, 2, 2, "Silk Helm", 16, 8, 26, 0, 30, 70, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0);
this.CreateArmor(12, 2, 2, 2, "Wind Helm", 28, 12, 32, 0, 30, 80, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0);
this.CreateArmor(13, 2, 2, 2, "Spirit Helm", 40, 16, 38, 0, 40, 80, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0);
this.CreateArmor(14, 2, 2, 2, "Guardian Helm", 53, 23, 45, 0, 40, 80, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0);
this.CreateArmor(16, 2, 2, 2, "Black Dragon Helm", 82, 30, 74, 0, 170, 60, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0);
this.CreateArmor(17, 2, 2, 2, "Dark Phoenix Helm", 92, 43, 80, 0, 205, 62, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0);
this.CreateArmor(18, 2, 2, 2, "Grand Soul Helm", 81, 27, 67, 0, 59, 20, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0);
this.CreateArmor(19, 2, 2, 2, "Divine Helm", 85, 37, 74, 0, 50, 110, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0);
this.CreateArmor(21, 2, 2, 2, "Great Dragon Helm", 104, 53, 86, 0, 200, 58, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0);
this.CreateArmor(22, 2, 2, 2, "Dark Soul Helm", 110, 36, 75, 0, 55, 18, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0);
this.CreateArmor(24, 2, 2, 2, "Red Spirit Helm", 93, 46, 80, 0, 52, 115, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0);
this.CreateArmor(25, 2, 2, 2, "Light Plate Mask", 46, 20, 42, 0, 70, 20, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0);
this.CreateArmor(26, 2, 2, 2, "Adamantine Mask", 66, 24, 56, 0, 77, 21, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0);
this.CreateArmor(27, 2, 2, 2, "Dark Steel Mask", 86, 26, 70, 0, 84, 22, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0);
this.CreateArmor(28, 2, 2, 2, "Dark Master Mask", 106, 34, 78, 0, 80, 21, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0);
this.CreateArmor(29, 2, 2, 2, "Dragon Knight Helm", 130, 66, 90, 0, 170, 60, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0);
this.CreateArmor(30, 2, 2, 2, "Venom Mist Helm", 126, 48, 86, 0, 44, 15, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0);
this.CreateArmor(31, 2, 2, 2, "Sylphid Ray Helm", 126, 57, 86, 0, 38, 80, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0);
this.CreateArmor(33, 2, 2, 2, "Sunlight Mask", 130, 46, 82, 0, 62, 16, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0);
this.CreateArmor(34, 2, 2, 2, "Ashcrow Helm", 67, 27, 72, 0, 160, 50, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0);
this.CreateArmor(35, 2, 2, 2, "Eclipse Helm", 67, 22, 54, 0, 53, 12, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0);
this.CreateArmor(36, 2, 2, 2, "Iris Helm", 67, 30, 59, 0, 50, 70, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0);
this.CreateArmor(38, 2, 2, 2, "Glorious Mask", 97, 30, 74, 0, 80, 21, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0);
this.CreateArmor(39, 2, 2, 2, "Mistery Helm", 28, 13, 36, 0, 31, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0);
this.CreateArmor(40, 2, 2, 2, "Red Wing Helm", 50, 18, 42, 0, 26, 4, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0);
this.CreateArmor(41, 2, 2, 2, "Ancient Helm", 68, 24, 54, 0, 52, 16, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0);
this.CreateArmor(42, 2, 2, 2, "Black Rose Helm", 81, 32, 67, 0, 60, 20, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0);
this.CreateArmor(43, 2, 2, 2, "Aura Helm", 110, 43, 75, 0, 56, 20, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0);
this.CreateArmor(44, 2, 2, 2, "Lilium Helm", 110, 50, 80, 0, 80, 50, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0);
this.CreateArmor(45, 2, 2, 2, "Titan Helm", 111, 63, 86, 0, 222, 32, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0);
this.CreateArmor(46, 2, 2, 2, "Brave Helm", 107, 51, 86, 0, 74, 162, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0);
this.CreateArmor(49, 2, 2, 2, "Seraphim Helm", 111, 50, 86, 0, 55, 197, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0);
this.CreateArmor(50, 2, 2, 2, "Faith Helm", 104, 44, 86, 0, 32, 29, 138, 0, 0, 0, 0, 1, 0, 0, 0, 0);
this.CreateArmor(51, 2, 2, 2, "Paewang Mask", 111, 44, 86, 0, 105, 38, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0);
this.CreateArmor(52, 2, 2, 2, "Hades Helm", 109, 41, 86, 0, 60, 15, 181, 0, 0, 1, 0, 0, 0, 0, 0, 0);
this.CreateArmor(59, 2, 2, 2, "Sacred Helm", 54, 24, 52, 1, 85, 0, 0, 75, 0, 0, 0, 0, 0, 0, 0, 1);
this.CreateArmor(60, 2, 2, 2, "Storm Hard Helm", 70, 32, 68, 1, 100, 0, 0, 90, 0, 0, 0, 0, 0, 0, 0, 1);
this.CreateArmor(61, 2, 2, 2, "Piercing Helm", 90, 45, 82, 1, 115, 0, 0, 100, 0, 0, 0, 0, 0, 0, 0, 1);
this.CreateArmor(73, 2, 2, 2, "Phoenix Soul Helmet", 128, 60, 88, 0, 97, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1);
// Armors:
this.CreateArmor(0, 3, 2, 2, "Bronze Armor", 18, 14, 34, 0, 80, 20, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0);
this.CreateArmor(1, 3, 2, 3, "Dragon Armor", 59, 37, 68, 0, 120, 30, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0);
this.CreateArmor(2, 3, 2, 2, "Pad Armor", 10, 7, 28, 0, 30, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0);
this.CreateArmor(3, 3, 2, 2, "Legendary Armor", 56, 22, 42, 0, 40, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0);
this.CreateArmor(4, 3, 2, 2, "Bone Armor", 22, 13, 30, 0, 40, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0);
this.CreateArmor(5, 3, 2, 3, "Leather Armor", 10, 10, 30, 0, 80, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 1);
this.CreateArmor(6, 3, 2, 2, "Scale Armor", 28, 18, 40, 0, 110, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 1);
this.CreateArmor(7, 3, 2, 3, "Sphinx Armor", 38, 17, 36, 0, 40, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0);
this.CreateArmor(8, 3, 2, 2, "Brass Armor", 38, 22, 44, 0, 100, 30, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1);
this.CreateArmor(9, 3, 2, 2, "Plate Armor", 48, 30, 50, 0, 130, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1);
this.CreateArmor(10, 3, 2, 2, "Vine Armor", 10, 8, 22, 0, 30, 60, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0);
this.CreateArmor(11, 3, 2, 2, "Silk Armor", 20, 12, 26, 0, 30, 70, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0);
this.CreateArmor(12, 3, 2, 2, "Wind Armor", 32, 16, 32, 0, 30, 80, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0);
this.CreateArmor(13, 3, 2, 2, "Spirit Armor", 44, 21, 38, 0, 40, 80, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0);
this.CreateArmor(14, 3, 2, 2, "Guardian Armor", 57, 29, 45, 0, 40, 80, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0);
this.CreateArmor(15, 3, 2, 3, "Storm Crow Armor", 80, 44, 80, 0, 150, 70, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0);
this.CreateArmor(16, 3, 2, 3, "Black Dragon Armor", 90, 48, 74, 0, 170, 60, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0);
this.CreateArmor(17, 3, 2, 3, "Dark Phoenix Armor", 100, 63, 80, 0, 214, 65, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0);
this.CreateArmor(18, 3, 2, 3, "Grand Soul Armor", 91, 33, 67, 0, 59, 20, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0);
this.CreateArmor(19, 3, 2, 2, "Divine Armor", 92, 44, 74, 0, 50, 110, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0);
this.CreateArmor(20, 3, 2, 3, "Thunder Hawk Armor", 107, 60, 82, 0, 170, 70, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0);
this.CreateArmor(21, 3, 2, 3, "Great Dragon Armor", 126, 75, 86, 0, 200, 58, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0);
this.CreateArmor(22, 3, 2, 3, "Dark Soul Armor", 122, 43, 75, 0, 55, 18, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0);
this.CreateArmor(23, 3, 2, 3, "Hurricane Armor", 128, 73, 90, 0, 162, 66, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0);
this.CreateArmor(24, 3, 2, 2, "Red Sprit Armor", 109, 55, 80, 0, 52, 115, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0);
this.CreateArmor(25, 3, 2, 3, "Light Plate Armor", 62, 25, 42, 0, 70, 20, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0);
this.CreateArmor(26, 3, 2, 3, "Adamantine Armor", 78, 36, 56, 0, 77, 21, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0);
this.CreateArmor(27, 3, 2, 3, "Dark Steel Armor", 96, 43, 70, 0, 84, 22, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0);
this.CreateArmor(28, 3, 2, 3, "Dark Master Armor", 117, 51, 78, 0, 80, 21, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0);
this.CreateArmor(29, 3, 2, 3, "Dragon Knight Armor", 140, 88, 90, 0, 170, 60, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0);
this.CreateArmor(30, 3, 2, 3, "Venom Mist Armor", 146, 57, 86, 0, 44, 15, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0);
this.CreateArmor(31, 3, 2, 3, "Sylphid Ray Armor", 146, 68, 86, 0, 38, 80, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0);
this.CreateArmor(32, 3, 2, 3, "Volcano Armor", 147, 86, 95, 0, 145, 60, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0);
this.CreateArmor(33, 3, 2, 3, "Sunlight Armor", 147, 64, 82, 0, 62, 16, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0);
this.CreateArmor(34, 3, 2, 3, "Ashcrow Armor", 75, 42, 72, 0, 160, 50, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0);
this.CreateArmor(35, 3, 2, 3, "Eclipse Armor", 75, 27, 54, 0, 53, 12, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0);
this.CreateArmor(36, 3, 2, 3, "Iris Armor", 75, 36, 59, 0, 50, 70, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0);
this.CreateArmor(37, 3, 2, 3, "Valiant Armor", 105, 52, 81, 0, 155, 50, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0);
this.CreateArmor(38, 3, 2, 3, "Glorious Armor", 105, 47, 74, 0, 80, 21, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0);
this.CreateArmor(39, 3, 2, 2, "Mistery Armor", 34, 22, 36, 0, 39, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0);
this.CreateArmor(40, 3, 2, 2, "Red Wing Armor", 56, 28, 42, 0, 35, 8, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0);
this.CreateArmor(41, 3, 2, 2, "Ancient Armor", 75, 35, 54, 0, 52, 16, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0);
this.CreateArmor(42, 3, 2, 2, "Black Rose Armor", 91, 45, 67, 0, 60, 20, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0);
this.CreateArmor(43, 3, 2, 2, "Aura Armor", 122, 56, 75, 0, 57, 19, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0);
this.CreateArmor(44, 3, 2, 2, "Lilium Armor", 113, 71, 84, 0, 110, 50, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0);
this.CreateArmor(45, 3, 2, 3, "Titan Armor", 132, 81, 86, 0, 222, 32, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0);
this.CreateArmor(46, 3, 2, 3, "Brave Armor", 128, 62, 86, 0, 74, 162, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0);
this.CreateArmor(47, 3, 2, 3, "Destory Armor", 131, 80, 86, 0, 212, 57, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0);
this.CreateArmor(48, 3, 2, 3, "Phantom Armor", 125, 66, 86, 0, 62, 19, 165, 0, 0, 0, 0, 0, 1, 0, 0, 0);
this.CreateArmor(49, 3, 2, 2, "Seraphim Armor", 129, 60, 86, 0, 55, 197, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0);
this.CreateArmor(50, 3, 2, 2, "Faith Armor", 122, 52, 86, 0, 32, 29, 138, 0, 0, 0, 0, 1, 0, 0, 0, 0);
this.CreateArmor(51, 3, 2, 3, "Paewang Armor", 132, 58, 86, 0, 105, 38, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0);
this.CreateArmor(52, 3, 2, 3, "Hades Armor", 129, 50, 86, 0, 60, 15, 181, 0, 0, 1, 0, 0, 0, 0, 0, 0);
this.CreateArmor(59, 3, 2, 3, "Sacred Armor", 66, 43, 52, 1, 85, 0, 0, 75, 0, 0, 0, 0, 0, 0, 0, 1);
this.CreateArmor(60, 3, 2, 3, "Storm Hard Armor", 82, 51, 68, 1, 100, 0, 0, 90, 0, 0, 0, 0, 0, 0, 0, 1);
this.CreateArmor(61, 3, 2, 3, "Piercing Armor", 101, 59, 82, 1, 115, 0, 0, 100, 0, 0, 0, 0, 0, 0, 0, 1);
this.CreateArmor(73, 3, 2, 3, "Phoenix Soul Armor", 143, 78, 88, 0, 97, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1);
// Pants:
this.CreateArmor(0, 4, 2, 2, "Bronze Pants", 15, 10, 34, 0, 80, 20, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0);
this.CreateArmor(1, 4, 2, 2, "Dragon Pants", 55, 26, 68, 0, 120, 30, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0);
this.CreateArmor(2, 4, 2, 2, "Pad Pants", 8, 5, 28, 0, 30, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0);
this.CreateArmor(3, 4, 2, 2, "Legendary Pants", 53, 20, 42, 0, 40, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0);
this.CreateArmor(4, 4, 2, 2, "Bone Pants", 20, 10, 30, 0, 40, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0);
this.CreateArmor(5, 4, 2, 2, "Leather Pants", 8, 7, 30, 0, 80, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 1);
this.CreateArmor(6, 4, 2, 2, "Scale Pants", 25, 14, 40, 0, 110, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 1);
this.CreateArmor(7, 4, 2, 2, "Sphinx Pants", 34, 15, 36, 0, 40, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0);
this.CreateArmor(8, 4, 2, 2, "Brass Pants", 35, 18, 44, 0, 100, 30, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1);
this.CreateArmor(9, 4, 2, 2, "Plate Pants", 45, 22, 50, 0, 130, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1);
this.CreateArmor(10, 4, 2, 2, "Vine Pants", 8, 6, 22, 0, 30, 60, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0);
this.CreateArmor(11, 4, 2, 2, "Silk Pants", 18, 10, 26, 0, 30, 70, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0);
this.CreateArmor(12, 4, 2, 2, "Wind Pants", 30, 14, 32, 0, 30, 80, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0);
this.CreateArmor(13, 4, 2, 2, "Spirit Pants", 42, 18, 38, 0, 40, 80, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0);
this.CreateArmor(14, 4, 2, 2, "Guardian Pants", 54, 25, 45, 0, 40, 80, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0);
this.CreateArmor(15, 4, 2, 2, "Storm Crow Pants", 74, 34, 80, 0, 150, 70, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0);
this.CreateArmor(16, 4, 2, 2, "Black Dragon Pants", 84, 40, 74, 0, 170, 60, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0);
this.CreateArmor(17, 4, 2, 2, "Dark Phoenix Pants", 96, 54, 80, 0, 207, 63, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0);
this.CreateArmor(18, 4, 2, 2, "Grand Soul Pants", 86, 30, 67, 0, 59, 20, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0);
this.CreateArmor(19, 4, 2, 2, "Divine Pants", 88, 39, 74, 0, 50, 110, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0);
this.CreateArmor(20, 4, 2, 2, "Thunder Hawk Pants", 99, 49, 82, 0, 150, 70, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0);
this.CreateArmor(21, 4, 2, 2, "Great Dragon Pants", 113, 65, 86, 0, 200, 58, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0);
this.CreateArmor(22, 4, 2, 2, "Dark Soul Pants", 117, 39, 75, 0, 55, 18, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0);
this.CreateArmor(23, 4, 2, 2, "Hurricane Pants", 122, 61, 90, 0, 162, 66, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0);
this.CreateArmor(24, 4, 2, 2, "Red Spirit Pants", 100, 48, 80, 0, 52, 115, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0);
this.CreateArmor(25, 4, 2, 2, "Light Plate Pants", 50, 21, 42, 0, 70, 20, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0);
this.CreateArmor(26, 4, 2, 2, "Adamantine Pants", 70, 26, 56, 0, 77, 21, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0);
this.CreateArmor(27, 4, 2, 2, "Dark Steel Pants", 92, 31, 70, 0, 84, 22, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0);
this.CreateArmor(28, 4, 2, 2, "Dark Master Pants", 110, 39, 78, 0, 80, 21, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0);
this.CreateArmor(29, 4, 2, 2, "Dragon Knight Pants", 134, 78, 90, 0, 170, 60, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0);
this.CreateArmor(30, 4, 2, 2, "Venom Mist Pants", 135, 55, 86, 0, 44, 15, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0);
this.CreateArmor(31, 4, 2, 2, "Sylphid Ray Pants", 135, 61, 86, 0, 38, 80, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0);
this.CreateArmor(32, 4, 2, 2, "Volcano Pants", 135, 74, 95, 0, 145, 60, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0);
this.CreateArmor(33, 4, 2, 2, "Sunlight Pants", 140, 52, 82, 0, 62, 16, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0);
this.CreateArmor(34, 4, 2, 2, "Ashcrow Pants", 69, 33, 72, 0, 160, 50, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0);
this.CreateArmor(35, 4, 2, 2, "Eclipse Pants", 69, 25, 54, 0, 53, 12, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0);
this.CreateArmor(36, 4, 2, 2, "Iris Pants", 69, 32, 59, 0, 50, 70, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0);
this.CreateArmor(37, 4, 2, 2, "Valiant Pants", 101, 41, 81, 0, 155, 50, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0);
this.CreateArmor(38, 4, 2, 2, "Glorious Pants", 101, 35, 74, 0, 80, 21, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0);
this.CreateArmor(39, 4, 2, 2, "Mistery Pants", 30, 16, 36, 0, 36, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0);
this.CreateArmor(40, 4, 2, 2, "Red Wing Pants", 53, 22, 42, 0, 35, 7, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0);
this.CreateArmor(41, 4, 2, 2, "Ancient Pants", 72, 28, 54, 0, 49, 16, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0);
this.CreateArmor(42, 4, 2, 2, "Black Rose Pants", 86, 37, 67, 0, 60, 20, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0);
this.CreateArmor(43, 4, 2, 2, "Aura Pants", 117, 49, 75, 0, 57, 19, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0);
this.CreateArmor(44, 4, 2, 2, "Lilium Pants", 102, 52, 82, 0, 75, 30, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0);
this.CreateArmor(45, 4, 2, 2, "Titan Pants", 116, 74, 86, 0, 222, 32, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0);
this.CreateArmor(46, 4, 2, 2, "Brave Pants", 112, 58, 86, 0, 74, 162, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0);
this.CreateArmor(47, 4, 2, 2, "Destory Pants", 115, 66, 86, 0, 212, 57, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0);
this.CreateArmor(48, 4, 2, 2, "Phantom Pants", 113, 51, 86, 0, 62, 19, 165, 0, 0, 0, 0, 0, 1, 0, 0, 0);
this.CreateArmor(49, 4, 2, 2, "Seraphim Pants", 116, 53, 86, 0, 55, 197, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0);
this.CreateArmor(50, 4, 2, 2, "Faith Pants", 109, 46, 86, 0, 32, 29, 138, 0, 0, 0, 0, 1, 0, 0, 0, 0);
this.CreateArmor(51, 4, 2, 2, "Paewang Pants", 116, 46, 86, 0, 105, 38, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0);
this.CreateArmor(52, 4, 2, 2, "Hades Pants", 114, 44, 86, 0, 60, 15, 181, 0, 0, 1, 0, 0, 0, 0, 0, 0);
this.CreateArmor(59, 4, 2, 2, "Sacred Pants", 62, 33, 52, 1, 85, 0, 0, 75, 0, 0, 0, 0, 0, 0, 0, 1);
this.CreateArmor(60, 4, 2, 2, "Storm Hard Pants", 78, 41, 68, 1, 100, 0, 0, 90, 0, 0, 0, 0, 0, 0, 0, 1);
this.CreateArmor(61, 4, 2, 2, "Piercing Pants", 95, 49, 82, 1, 115, 0, 0, 100, 0, 0, 0, 0, 0, 0, 0, 1);
this.CreateArmor(73, 4, 2, 2, "Phoenix Soul Pants", 134, 68, 88, 0, 97, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1);
// Gloves:
this.CreateArmor(0, 5, 2, 2, "Bronze Gloves", 13, 4, 34, 0, 80, 20, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0);
this.CreateArmor(1, 5, 2, 2, "Dragon Gloves", 52, 14, 68, 0, 120, 30, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0);
this.CreateArmor(2, 5, 2, 2, "Pad Gloves", 3, 2, 28, 0, 20, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0);
this.CreateArmor(3, 5, 2, 2, "Legendary Gloves", 44, 11, 42, 0, 20, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0);
this.CreateArmor(4, 5, 2, 2, "Bone Gloves", 14, 5, 30, 0, 20, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0);
this.CreateArmor(5, 5, 2, 2, "Leather Gloves", 4, 2, 30, 0, 80, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0);
this.CreateArmor(6, 5, 2, 2, "Scale Gloves", 22, 7, 40, 0, 110, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0);
this.CreateArmor(7, 5, 2, 2, "Sphinx Gloves", 28, 8, 36, 0, 20, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0);
this.CreateArmor(8, 5, 2, 2, "Brass Gloves", 32, 9, 44, 0, 100, 30, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0);
this.CreateArmor(9, 5, 2, 2, "Plate Gloves", 42, 12, 50, 0, 130, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0);
this.CreateArmor(10, 5, 2, 2, "Vine Gloves", 4, 2, 22, 0, 30, 60, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0);
this.CreateArmor(11, 5, 2, 2, "Silk Gloves", 14, 4, 26, 0, 30, 70, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0);
this.CreateArmor(12, 5, 2, 2, "Wind Gloves", 26, 6, 32, 0, 30, 80, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0);
this.CreateArmor(13, 5, 2, 2, "Spirit Gloves", 38, 9, 38, 0, 40, 80, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0);
this.CreateArmor(14, 5, 2, 2, "Guardian Gloves", 50, 15, 45, 0, 40, 80, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0);
this.CreateArmor(15, 5, 2, 2, "Storm Crow Gloves", 70, 20, 80, 0, 150, 70, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0);
this.CreateArmor(16, 5, 2, 2, "Black Dragon Gloves", 76, 22, 74, 0, 170, 60, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0);
this.CreateArmor(17, 5, 2, 2, "Dark Phoenix Gloves", 86, 37, 80, 0, 205, 63, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0);
this.CreateArmor(18, 5, 2, 2, "Grand Soul Gloves", 70, 20, 67, 0, 49, 10, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0);
this.CreateArmor(19, 5, 2, 2, "Divine Gloves", 72, 29, 74, 0, 50, 110, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0);
this.CreateArmor(20, 5, 2, 2, "Thunder Hawk Gloves", 88, 34, 82, 0, 150, 70, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0);
this.CreateArmor(21, 5, 2, 2, "Great Dragon Gloves", 94, 48, 86, 0, 200, 58, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0);
this.CreateArmor(22, 5, 2, 2, "Dark Soul Gloves", 87, 30, 75, 0, 55, 18, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0);
this.CreateArmor(23, 5, 2, 2, "Hurricane Gloves", 102, 45, 90, 0, 162, 66, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0);
this.CreateArmor(24, 5, 2, 2, "Red Spirit Gloves", 84, 38, 80, 0, 52, 115, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0);
this.CreateArmor(25, 5, 2, 2, "Light Plate Gloves", 42, 12, 42, 0, 70, 20, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0);
this.CreateArmor(26, 5, 2, 2, "Adamantine Gloves", 57, 18, 56, 0, 77, 21, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0);
this.CreateArmor(27, 5, 2, 2, "Dark Steel Gloves", 75, 21, 70, 0, 84, 22, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0);
this.CreateArmor(28, 5, 2, 2, "Dark Master Gloves", 89, 29, 78, 0, 80, 21, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0);
this.CreateArmor(29, 5, 2, 2, "Dragon Knight Gloves", 114, 60, 90, 0, 170, 60, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0);
this.CreateArmor(30, 5, 2, 2, "Venom Mist Gloves", 111, 44, 86, 0, 44, 15, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0);
this.CreateArmor(31, 5, 2, 2, "Sylphid Ray Gloves", 111, 50, 86, 0, 38, 80, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0);
this.CreateArmor(32, 5, 2, 2, "Volcano Gloves", 127, 55, 95, 0, 145, 60, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0);
this.CreateArmor(33, 5, 2, 2, "Sunlight Gloves", 110, 40, 82, 0, 62, 16, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0);
this.CreateArmor(34, 5, 2, 2, "Ashcrow Gloves", 61, 18, 72, 0, 160, 50, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0);
this.CreateArmor(35, 5, 2, 2, "Eclipse Gloves", 61, 15, 54, 0, 53, 12, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0);
this.CreateArmor(36, 5, 2, 2, "Iris Gloves", 61, 22, 59, 0, 50, 70, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0);
this.CreateArmor(37, 5, 2, 2, "Valiant Gloves", 91, 27, 81, 0, 155, 50, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0);
this.CreateArmor(38, 5, 2, 2, "Glorious Gloves", 91, 25, 74, 0, 80, 21, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0);
this.CreateArmor(39, 5, 2, 2, "Mistery Gloves", 24, 9, 36, 0, 22, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0);
this.CreateArmor(40, 5, 2, 2, "Red Wing Gloves", 44, 13, 42, 0, 18, 4, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0);
this.CreateArmor(41, 5, 2, 2, "Ancient Gloves", 61, 19, 54, 0, 52, 16, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0);
this.CreateArmor(42, 5, 2, 2, "Black Rose Gloves", 70, 26, 67, 0, 50, 10, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0);
this.CreateArmor(43, 5, 2, 2, "Aura Gloves", 87, 34, 75, 0, 56, 20, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0);
this.CreateArmor(44, 5, 2, 2, "Lilium Gloves", 82, 45, 80, 0, 75, 20, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0);
this.CreateArmor(45, 5, 2, 2, "Titan Gloves", 100, 56, 86, 0, 222, 32, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0);
this.CreateArmor(46, 5, 2, 2, "Brave Gloves", 97, 42, 86, 0, 74, 162, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0);
this.CreateArmor(47, 5, 2, 2, "Destory Gloves", 101, 49, 86, 0, 212, 57, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0);
this.CreateArmor(48, 5, 2, 2, "Phantom Gloves", 99, 40, 86, 0, 62, 19, 165, 0, 0, 0, 0, 0, 1, 0, 0, 0);
this.CreateArmor(49, 5, 2, 2, "Seraphim Gloves", 100, 43, 86, 0, 55, 197, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0);
this.CreateArmor(50, 5, 2, 2, "Faith Gloves", 95, 36, 86, 0, 32, 29, 138, 0, 0, 0, 0, 1, 0, 0, 0, 0);
this.CreateArmor(51, 5, 2, 2, "Paewang Gloves", 101, 34, 86, 0, 105, 38, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0);
this.CreateArmor(52, 5, 2, 2, "Hades Gloves", 100, 31, 86, 0, 60, 15, 181, 0, 0, 1, 0, 0, 0, 0, 0, 0);
// Boots:
this.CreateArmor(0, 6, 2, 2, "Bronze Boots", 12, 4, 34, 0, 80, 20, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0);
this.CreateArmor(1, 6, 2, 2, "Dragon Boots", 54, 15, 68, 0, 120, 30, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0);
this.CreateArmor(2, 6, 2, 2, "Pad Boots", 4, 3, 28, 0, 20, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0);
this.CreateArmor(3, 6, 2, 2, "Legendary Boots", 46, 12, 42, 0, 30, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0);
this.CreateArmor(4, 6, 2, 2, "Bone Boots", 16, 6, 30, 0, 30, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0);
this.CreateArmor(5, 6, 2, 2, "Leather Boots", 5, 2, 30, 0, 80, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 1);
this.CreateArmor(6, 6, 2, 2, "Scale Boots", 22, 8, 40, 0, 110, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 1);
this.CreateArmor(7, 6, 2, 2, "Sphinx Boots", 30, 9, 36, 0, 30, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0);
this.CreateArmor(8, 6, 2, 2, "Brass Boots", 32, 10, 44, 0, 100, 30, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1);
this.CreateArmor(9, 6, 2, 2, "Plate Boots", 42, 12, 50, 0, 130, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1);
this.CreateArmor(10, 6, 2, 2, "Vine Boots", 5, 2, 22, 0, 30, 60, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0);
this.CreateArmor(11, 6, 2, 2, "Silk Boots", 15, 4, 26, 0, 30, 70, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0);
this.CreateArmor(12, 6, 2, 2, "Wind Boots", 27, 7, 32, 0, 30, 80, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0);
this.CreateArmor(13, 6, 2, 2, "Spirit Boots", 40, 10, 38, 0, 40, 80, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0);
this.CreateArmor(14, 6, 2, 2, "Guardian Boots", 52, 16, 45, 0, 40, 80, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0);
this.CreateArmor(15, 6, 2, 2, "Storm Crow Boots", 72, 22, 80, 0, 150, 70, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0);
this.CreateArmor(16, 6, 2, 2, "Black Dragon Boots", 78, 24, 74, 0, 170, 60, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0);
this.CreateArmor(17, 6, 2, 2, "Dark Phoenix Boots", 93, 40, 80, 0, 198, 60, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0);
this.CreateArmor(18, 6, 2, 2, "Grand Soul Boots", 76, 22, 67, 0, 59, 10, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0);
this.CreateArmor(19, 6, 2, 2, "Divine Boots", 81, 30, 74, 0, 50, 110, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0);
this.CreateArmor(20, 6, 2, 2, "Thunder Hawk Boots", 92, 37, 82, 0, 150, 70, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0);
this.CreateArmor(21, 6, 2, 2, "Great Dragon Boots", 98, 50, 86, 0, 200, 58, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0);
this.CreateArmor(22, 6, 2, 2, "Dark Soul Boots", 95, 31, 75, 0, 55, 18, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0);
this.CreateArmor(23, 6, 2, 2, "Hurricane Boots", 110, 50, 90, 0, 162, 66, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0);
this.CreateArmor(24, 6, 2, 2, "Red Spirit Boots", 87, 40, 80, 0, 52, 115, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0);
this.CreateArmor(25, 6, 2, 2, "Light Plate Boots", 45, 13, 42, 0, 70, 20, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0);
this.CreateArmor(26, 6, 2, 2, "Adamantine Boots", 60, 20, 56, 0, 77, 21, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0);
this.CreateArmor(27, 6, 2, 2, "Dark Steel Boots", 83, 25, 70, 0, 84, 22, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0);
this.CreateArmor(28, 6, 2, 2, "Dark Master Boots", 95, 33, 78, 0, 80, 21, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0);
this.CreateArmor(29, 6, 2, 2, "Dragon Knight Boots", 119, 63, 90, 0, 170, 60, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0);
this.CreateArmor(30, 6, 2, 2, "Venom Mist Boots", 119, 47, 86, 0, 44, 15, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0);
this.CreateArmor(31, 6, 2, 2, "Sylphid Ray Boots", 119, 53, 86, 0, 38, 80, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0);
this.CreateArmor(32, 6, 2, 2, "Volcano Boots", 131, 61, 95, 0, 145, 60, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0);
this.CreateArmor(33, 6, 2, 2, "Sunlight Boots", 121, 44, 82, 0, 62, 16, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0);
this.CreateArmor(34, 6, 2, 2, "Ashcrow Boots", 68, 19, 72, 0, 160, 50, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0);
this.CreateArmor(35, 6, 2, 2, "Eclipse Boots", 68, 17, 54, 0, 53, 12, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0);
this.CreateArmor(36, 6, 2, 2, "Iris Boots", 68, 23, 59, 0, 50, 70, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0);
this.CreateArmor(37, 6, 2, 2, "Valiant Boots", 98, 29, 81, 0, 155, 50, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0);
this.CreateArmor(38, 6, 2, 2, "Glorious Boots", 98, 29, 74, 0, 80, 21, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0);
this.CreateArmor(39, 6, 2, 2, "Mistery Boots", 26, 11, 36, 0, 27, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0);
this.CreateArmor(40, 6, 2, 2, "Red Wing Boots", 46, 15, 42, 0, 25, 4, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0);
this.CreateArmor(41, 6, 2, 2, "Ancient Boots", 65, 21, 54, 0, 53, 16, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0);
this.CreateArmor(42, 6, 2, 2, "Black Rose Boots", 76, 28, 67, 0, 60, 10, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0);
this.CreateArmor(43, 6, 2, 2, "Aura Boots", 95, 38, 75, 0, 57, 20, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0);
this.CreateArmor(44, 6, 2, 2, "Lilium Boots", 90, 50, 85, 0, 150, 30, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0);
this.CreateArmor(45, 6, 2, 2, "Titan Boots", 96, 57, 86, 0, 222, 32, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0);
this.CreateArmor(46, 6, 2, 2, "Brave Boots", 93, 45, 86, 0, 74, 162, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0);
this.CreateArmor(47, 6, 2, 2, "Destory Boots", 97, 54, 86, 0, 212, 57, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0);
this.CreateArmor(48, 6, 2, 2, "Phantom Boots", 94, 44, 86, 0, 62, 19, 165, 0, 0, 0, 0, 0, 1, 0, 0, 0);
this.CreateArmor(49, 6, 2, 2, "Seraphim Boots", 97, 42, 86, 0, 55, 197, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0);
this.CreateArmor(50, 6, 2, 2, "Faith Boots", 92, 35, 86, 0, 32, 29, 138, 0, 0, 0, 0, 1, 0, 0, 0, 0);
this.CreateArmor(51, 6, 2, 2, "Phaewang Boots", 98, 38, 86, 0, 105, 38, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0);
this.CreateArmor(52, 6, 2, 2, "Hades Boots", 94, 34, 86, 0, 60, 15, 181, 0, 0, 1, 0, 0, 0, 0, 0, 0);
this.CreateArmor(59, 6, 2, 2, "Sacred Boots", 50, 20, 52, 1, 85, 0, 0, 75, 0, 0, 0, 0, 0, 0, 0, 1);
this.CreateArmor(60, 6, 2, 2, "Storm Hard Boots", 62, 28, 68, 1, 100, 0, 0, 90, 0, 0, 0, 0, 0, 0, 0, 1);
this.CreateArmor(61, 6, 2, 2, "Piercing Boots", 82, 36, 82, 1, 115, 0, 0, 100, 0, 0, 0, 0, 0, 0, 0, 1);
this.CreateArmor(73, 6, 2, 2, "Phoenix Soul Boots", 119, 57, 88, 0, 97, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1);
this.BuildSets();
}
private ItemOption BuildDefenseBonusOption(float bonus)
{
var defenseBonus = this.Context.CreateNew<ItemOption>();
defenseBonus.PowerUpDefinition = this.Context.CreateNew<PowerUpDefinition>();
defenseBonus.PowerUpDefinition.Boost = this.Context.CreateNew<PowerUpDefinitionValue>();
defenseBonus.PowerUpDefinition.Boost.ConstantValue.AggregateType = AggregateType.Multiplicate;
defenseBonus.PowerUpDefinition.Boost.ConstantValue.Value = bonus;
defenseBonus.PowerUpDefinition.TargetAttribute = Stats.DefenseBase;
return defenseBonus;
}
private void CreateSetGroup(int setLevel, ItemOption option, ICollection<ItemDefinition> group)
{
var setForDefense = this.Context.CreateNew<ItemSetGroup>();
setForDefense.Name = $"{group.First().Name.Split(' ')[0]} Defense Bonus (Level {setLevel})";
setForDefense.MinimumItemCount = group.Count;
setForDefense.Options.Add(option);
setForDefense.SetLevel = (byte)setLevel;
foreach (var item in group)
{
var itemOfSet = this.Context.CreateNew<ItemOfItemSet>();
itemOfSet.ItemDefinition = item;
setForDefense.Items.Add(itemOfSet);
}
}
private void BuildSets()
{
var sets = this.GameConfiguration.Items.Where(item => item.Group >= 7 && item.Group <= 11).GroupBy(item => item.Number);
var defenseRateBonus = this.Context.CreateNew<ItemOption>();
defenseRateBonus.PowerUpDefinition = this.Context.CreateNew<PowerUpDefinition>();
defenseRateBonus.PowerUpDefinition.Boost = this.Context.CreateNew<PowerUpDefinitionValue>();
defenseRateBonus.PowerUpDefinition.Boost.ConstantValue.AggregateType = AggregateType.Multiplicate;
defenseRateBonus.PowerUpDefinition.Boost.ConstantValue.Value = 1.1f;
defenseRateBonus.PowerUpDefinition.TargetAttribute = Stats.DefenseRatePvm;
var defenseBonus = new Dictionary<int, ItemOption>
{
{ 10, this.BuildDefenseBonusOption(1.05f) },
{ 11, this.BuildDefenseBonusOption(1.10f) },
{ 12, this.BuildDefenseBonusOption(1.15f) },
{ 13, this.BuildDefenseBonusOption(1.20f) },
{ 14, this.BuildDefenseBonusOption(1.25f) },
{ 15, this.BuildDefenseBonusOption(1.30f) },
};
foreach (var group in sets)
{
var setForDefenseRate = this.Context.CreateNew<ItemSetGroup>();
setForDefenseRate.Name = group.First().Name.Split(' ')[0] + " Defense Rate Bonus";
setForDefenseRate.MinimumItemCount = group.Count();
setForDefenseRate.Options.Add(defenseRateBonus);
foreach (var item in group)
{
var itemOfSet = this.Context.CreateNew<ItemOfItemSet>();
itemOfSet.ItemDefinition = item;
setForDefenseRate.Items.Add(itemOfSet);
}
for (int setLevel = 10; setLevel <= 15; setLevel++)
{
this.CreateSetGroup(setLevel, defenseBonus[setLevel], group.ToList());
}
}
}
private void CreateShield(byte number, byte slot, byte skill, byte width, byte height, string name, byte dropLevel, int defense, int defenseRate, byte durability, int levelRequirement, int strengthRequirement, int agilityRequirement, int energyRequirement, int vitalityRequirement, int leadershipRequirement, int darkWizardClassLevel, int darkKnightClassLevel, int elfClassLevel, int magicGladiatorClassLevel, int darkLordClassLevel, int summonerClassLevel, int ragefighterClassLevel)
{
var shield = this.CreateArmor(number, slot, width, height, name, dropLevel, 0, durability, levelRequirement, strengthRequirement, agilityRequirement, energyRequirement, vitalityRequirement, leadershipRequirement,darkWizardClassLevel, darkKnightClassLevel, elfClassLevel, magicGladiatorClassLevel, darkLordClassLevel, summonerClassLevel, ragefighterClassLevel);
if (skill != 0)
{
shield.Skill = this.GameConfiguration.Skills.First(s => s.SkillID == skill);
}
if (defense > 0)
{
var powerUp = this.Context.CreateNew<ItemBasePowerUpDefinition>();
powerUp.TargetAttribute = Stats.DefenseBase;
powerUp.BaseValue = defense;
this.shieldDefenseBonusPerLevel.ForEach(powerUp.BonusPerLevel.Add);
shield.BasePowerUpAttributes.Add(powerUp);
}
if (defenseRate > 0)
{
var powerUp = this.Context.CreateNew<ItemBasePowerUpDefinition>();
powerUp.TargetAttribute = Stats.DefenseRatePvm;
powerUp.BaseValue = defenseRate;
this.defenseBonusPerLevel.ForEach(powerUp.BonusPerLevel.Add);
shield.BasePowerUpAttributes.Add(powerUp);
}
}
private ItemDefinition CreateArmor(byte number, byte slot, byte width, byte height, string name, byte dropLevel, int defense, byte durability, int levelRequirement, int strengthRequirement, int agilityRequirement, int energyRequirement, int vitalityRequirement, int leadershipRequirement, int darkWizardClassLevel, int darkKnightClassLevel, int elfClassLevel, int magicGladiatorClassLevel, int darkLordClassLevel, int summonerClassLevel, int ragefighterClassLevel)
{
var armor = this.Context.CreateNew<ItemDefinition>();
this.GameConfiguration.Items.Add(armor);
armor.Group = (byte)(slot + 5);
armor.Number = number;
armor.Width = width;
armor.Height = height;
armor.Name = name;
armor.DropLevel = dropLevel;
armor.DropsFromMonsters = true;
armor.Durability = durability;
armor.ItemSlot = this.GameConfiguration.ItemSlotTypes.First(st => st.ItemSlots.Contains(slot));
this.CreateRequirementIfNeeded(armor, Stats.Level, levelRequirement);
this.CreateRequirementIfNeeded(armor, Stats.TotalStrength, strengthRequirement);
this.CreateRequirementIfNeeded(armor, Stats.TotalAgility, agilityRequirement);
this.CreateRequirementIfNeeded(armor, Stats.TotalEnergy, energyRequirement);
this.CreateRequirementIfNeeded(armor, Stats.TotalVitality, vitalityRequirement);
this.CreateRequirementIfNeeded(armor, Stats.TotalLeadership, leadershipRequirement);
if (defense > 0)
{
var powerUp = this.Context.CreateNew<ItemBasePowerUpDefinition>();
powerUp.TargetAttribute = Stats.DefenseBase;
powerUp.BaseValue = defense;
this.defenseBonusPerLevel.ForEach(powerUp.BonusPerLevel.Add);
armor.BasePowerUpAttributes.Add(powerUp);
}
var classes = this.GameConfiguration.DetermineCharacterClasses(darkWizardClassLevel, darkKnightClassLevel, elfClassLevel, magicGladiatorClassLevel, darkLordClassLevel, summonerClassLevel, ragefighterClassLevel);
foreach (var characterClass in classes)
{
armor.QualifiedCharacters.Add(characterClass);
}
armor.PossibleItemOptions.Add(this.GameConfiguration.GetLuck());
armor.PossibleItemOptions.Add(this.GameConfiguration.GetDefenseOption());
armor.PossibleItemOptions.Add(this.GameConfiguration.ItemOptions.First(o => o.Name == ExcellentOptions.DefenseOptionsName));
//// TODO: HarmonyOptions for level 380 items
//// TODO: JoH Options
return armor;
}
private void CreateBonusDefensePerLevel()
{
this.defenseBonusPerLevel = new List<LevelBonus>();
this.shieldDefenseBonusPerLevel = new List<LevelBonus>();
for (int level = 1; level <= 15; level++)
{
var levelBonus = this.Context.CreateNew<LevelBonus>();
levelBonus.Level = level;
levelBonus.AdditionalValue = DefenseIncreaseByLevel[level];
this.defenseBonusPerLevel.Add(levelBonus);
var shieldLevelBonus = this.Context.CreateNew<LevelBonus>();
levelBonus.Level = level;
levelBonus.AdditionalValue = level;
this.shieldDefenseBonusPerLevel.Add(shieldLevelBonus);
}
}
private void CreateRequirementIfNeeded(ItemDefinition armor, AttributeDefinition attribute, int requiredValue)
{
if (requiredValue == 0)
{
return;
}
//// TODO: each level increases some requirements
var persistentAttribute = attribute.GetPersistent(this.GameConfiguration);
var requirement = this.CreateAttributeRequirement(persistentAttribute, requiredValue);
armor.Requirements.Add(requirement);
}
/// <summary>
/// Creates the attribute requirement.
/// TODO: Remove duplicated method.
/// </summary>
/// <param name="attributeDefinition">The attribute definition.</param>
/// <param name="minimumValue">The minimum value.</param>
/// <returns>The attribute requirement.</returns>
private AttributeRequirement CreateAttributeRequirement(AttributeDefinition attributeDefinition, int minimumValue)
{
var requirement = this.Context.CreateNew<AttributeRequirement>();
requirement.Attribute = attributeDefinition;
requirement.MinimumValue = minimumValue;
return requirement;
}
}
} | 84.795203 | 492 | 0.511869 | [
"MIT"
] | ThisMushroom/OpenMu | src/Persistence/Initialization/Items/Armors.cs | 45,961 | 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.Text;
using System.Runtime.InteropServices;
namespace System.Diagnostics.TraceSourceTests
{
static class TraceTestHelper
{
internal static bool IsFullFramework => RuntimeInformation.FrameworkDescription.StartsWith(".NET Framework", StringComparison.OrdinalIgnoreCase);
/// <summary>
/// Resets the static state of the trace objects before a unit test.
/// </summary>
public static void ResetState()
{
Trace.Listeners.Clear();
Trace.Listeners.Add(new DefaultTraceListener());
Trace.AutoFlush = false;
Trace.IndentLevel = 0;
Trace.IndentSize = 4;
Trace.UseGlobalLock = true;
// Trace holds on to instances through weak refs
// this is intended to clean those up.
GC.Collect();
Trace.Refresh();
}
}
}
| 34.53125 | 153 | 0.642534 | [
"MIT"
] | rionmonster/corefx | src/System.Diagnostics.TraceSource/tests/TraceTestHelper.cs | 1,105 | C# |
using Newtonsoft.Json;
namespace TrueLayer.Pokedex.Service.Responses.Pokemon
{
internal class Language
{
public Language(string name)
{
Name = name;
}
[JsonProperty("name")]
public string Name { get; }
}
} | 16 | 53 | 0.645833 | [
"MIT"
] | BBehboodi/Pokedex | Service/Responses/Pokemon/Language.cs | 242 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Navigation;
using System.Data.SqlLocalDb;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace com.blueboxmoon.RockLauncher
{
/// <summary>
/// Interaction logic for InstancesView.xaml
/// </summary>
public partial class InstancesView : UserControl
{
#region Private Fields
/// <summary>
/// Identifies the currently executing IIS Express process.
/// </summary>
private ConsoleApp iisExpressProcess = null;
/// <summary>
/// Identifies the SQL Server Local DB instance that we are running.
/// </summary>
private SqlLocalDbInstance localDb = null;
/// <summary>
/// Identifies the main instances view so we can refresh the state externally.
/// </summary>
static private InstancesView DefaultInstancesView = null;
/// <summary>
/// Template to be used when building the webConnectionString.config file.
/// </summary>
string connectionStringTemplate = @"<?xml version=""1.0""?>
<connectionStrings>
<add name=""RockContext"" connectionString=""Data Source=(LocalDB)\{0};AttachDbFileName=|DataDirectory|\Database.mdf; Initial Catalog={1}; Integrated Security=true; MultipleActiveResultSets=true"" providerName=""System.Data.SqlClient""/>
</connectionStrings>
";
#endregion
#region Constructors
/// <summary>
/// Initialize a new instance of the control.
/// </summary>
public InstancesView()
{
InitializeComponent();
DefaultInstancesView = this;
UpdateInstances();
Dispatcher.ShutdownStarted += Dispatcher_ShutdownStarted;
}
#endregion
#region Public Static Methods
/// <summary>
/// Update the list of instances in the window.
/// </summary>
static public void UpdateInstances()
{
DefaultInstancesView.txtStatus.Text = "Loading...";
DefaultInstancesView.btnDelete.IsEnabled = false;
DefaultInstancesView.btnStart.IsEnabled = false;
DefaultInstancesView.btnStop.IsEnabled = false;
new Task( DefaultInstancesView.LoadData ).Start();
}
#endregion
#region Tasks
/// <summary>
/// Load all github tags in the background.
/// </summary>
private void LoadData()
{
//
// Initialize the LocalDb service only once.
//
if ( localDb == null )
{
var provider = new SqlLocalDbProvider();
SqlLocalDbInstance instance;
try
{
//
// If we find an existing instance then shut it down and delete it.
//
instance = provider.GetInstance( "RockLauncher" );
if ( instance.IsRunning )
{
instance.Stop();
}
SqlLocalDbInstance.Delete( instance );
}
finally
{
//
// Create a new instance and keep a reference to it.
//
localDb = provider.CreateInstance( "RockLauncher" );
localDb.Start();
}
}
//
// Load all the instances from the file system.
//
var instances = Directory.GetDirectories( Support.GetInstancesPath() )
.Select( d => Path.GetFileName( d ) ).ToList();
//
// Convert pre-1.0 instance folders to 1.0 instance folders, which contain a
// RockWeb for the current instance data.
//
foreach ( string instance in instances )
{
string instancePath = Path.Combine( Support.GetInstancesPath(), instance );
string rockwebPath = Path.Combine( instancePath, "RockWeb" );
if ( !Directory.Exists( rockwebPath ) )
{
Directory.CreateDirectory( rockwebPath );
foreach ( var d in Directory.GetDirectories( instancePath ) )
{
if ( !Path.GetFileName( d ).Equals( "RockWeb", StringComparison.CurrentCultureIgnoreCase ) )
{
Directory.Move( d, Path.Combine( rockwebPath, Path.GetFileName( d ) ) );
}
}
foreach ( var f in Directory.GetFiles( instancePath ) )
{
Directory.Move( f, Path.Combine( rockwebPath, Path.GetFileName( f ) ) );
}
}
}
//
// Update the UI with the new list of instances.
//
Dispatcher.Invoke( () =>
{
cbInstances.ItemsSource = instances;
if ( instances.Count > 0 )
{
cbInstances.SelectedIndex = 0;
}
txtStatus.Text = "Idle";
UpdateState();
} );
}
#endregion
#region Internal Methods
/// <summary>
/// Update the UI to match our internal state.
/// </summary>
private void UpdateState()
{
bool enableButtons = cbInstances.SelectedIndex != -1;
btnStart.IsEnabled = enableButtons && iisExpressProcess == null;
btnStop.IsEnabled = enableButtons && iisExpressProcess != null;
btnDelete.IsEnabled = enableButtons && iisExpressProcess == null;
}
/// <summary>
/// Write the web.ConnectionStrings.config file for the given RockWeb folder.
/// </summary>
/// <param name="rockWeb">The folder that contains the Rock instance.</param>
private void ConfigureConnectionString( string rockWeb )
{
string dbName = Path.GetFileName( rockWeb );
string configFile = Path.Combine( rockWeb, "web.ConnectionStrings.config" );
string contents = string.Format( connectionStringTemplate, "RockLauncher", dbName );
if ( File.Exists( configFile ) )
{
File.Delete( configFile );
}
File.WriteAllText( configFile, contents );
}
/// <summary>
/// The the path to the IIS Express executable.
/// </summary>
/// <returns>The path to the executable.</returns>
private string GetIisExecutable()
{
var key = Environment.Is64BitOperatingSystem ? "programfiles(x86)" : "programfiles";
var programfiles = Environment.GetEnvironmentVariable( key );
//check file exists
var iisPath = string.Format( "{0}\\IIS Express\\iisexpress.exe", programfiles );
if ( !File.Exists( iisPath ) )
{
throw new ArgumentException( "IIS Express executable not found", iisPath );
}
return iisPath;
}
#endregion
#region Event Handlers
/// <summary>
/// Notification that the application is about to shutdown. Terminate all our child
/// processes.
/// </summary>
/// <param name="sender">The object that is sending this event.</param>
/// <param name="e">The arguments that describe the event.</param>
private void Dispatcher_ShutdownStarted( object sender, EventArgs e )
{
//
// If we have an IIS Express process, then kill it.
//
if ( iisExpressProcess != null )
{
iisExpressProcess.Kill();
iisExpressProcess = null;
}
//
// If we have a LocalDb instance, then kill it off.
//
if ( localDb != null )
{
if ( localDb.IsRunning )
{
localDb.Stop();
}
localDb = null;
}
UpdateState();
}
/// <summary>
/// The user has changed the selection of the instances list. Update the UI button states.
/// </summary>
/// <param name="sender">The object that is sending this event.</param>
/// <param name="e">The arguments that describe the event.</param>
private void cbInstances_SelectionChanged( object sender, SelectionChangedEventArgs e )
{
UpdateState();
}
/// <summary>
/// Start up a new IIS Express instance for the Rock instance that is selected.
/// </summary>
/// <param name="sender">The object that is sending this event.</param>
/// <param name="e">The arguments that describe the event.</param>
private void btnStart_Click( object sender, RoutedEventArgs e )
{
txtStatus.Text = "Starting...";
txtConsole.Text = string.Empty;
//
// Just in case something goes wrong and they managed to type in a non-numeric.
//
if ( !int.TryParse( txtPort.Text, out int port ) )
{
port = 6229;
}
//
// Find the path to the RockWeb instance.
//
var items = ( List<string> ) cbInstances.ItemsSource;
var path = Path.Combine( Support.GetInstancesPath(), items[cbInstances.SelectedIndex], "RockWeb" );
//
// Check if the Database file already exists and if not create the
// Run.Migration file so Rock initializes itself.
//
var dbPath = Path.Combine( path, "App_Data", "Database.mdf" );
if ( !File.Exists( dbPath ) )
{
var runMigrationPath = Path.Combine( path, "App_Data", "Run.Migration" );
File.WriteAllText( runMigrationPath, string.Empty );
}
ConfigureConnectionString( path );
//
// Launch the IIS Express process for this RockWeb.
//
iisExpressProcess = new ConsoleApp( GetIisExecutable() );
iisExpressProcess.ProcessExited += IisExpressProcess_Exited;
iisExpressProcess.StandardTextReceived += IisExpressProcess_StandardTextReceived;
iisExpressProcess.ExecuteAsync( String.Format( "/path:\"{0}\"", path ), String.Format( "/port:{0}", port ) );
//
// Update the status text to contain a clickable link to the instance.
//
var linkText = string.Format( "http://localhost:{0}/", port );
var link = new Hyperlink( new Run( linkText ) )
{
NavigateUri = new Uri( linkText )
};
link.RequestNavigate += StatusLink_RequestNavigate;
txtStatus.Inlines.Clear();
txtStatus.Inlines.Add( new Run( "Running at " ) );
txtStatus.Inlines.Add( link );
UpdateState();
}
/// <summary>
/// Stop the current IIS Express instance.
/// </summary>
/// <param name="sender">The object that is sending this event.</param>
/// <param name="e">The arguments that describe the event.</param>
private void btnStop_Click( object sender, RoutedEventArgs e )
{
if ( iisExpressProcess != null )
{
iisExpressProcess.Kill();
iisExpressProcess = null;
}
txtStatus.Text = "Idle";
UpdateState();
}
/// <summary>
/// Delete the selected instance from disk.
/// </summary>
/// <param name="sender">The object that is sending this event.</param>
/// <param name="e">The arguments that describe the event.</param>
private void btnDelete_Click( object sender, RoutedEventArgs e )
{
var result = MessageBox.Show( "Delete this instance?", "Confirmation", MessageBoxButton.YesNo, MessageBoxImage.Question );
if ( result == MessageBoxResult.Yes )
{
var items = cbInstances.ItemsSource as List<string>;
string file = items[cbInstances.SelectedIndex];
string path = Path.Combine( Support.GetInstancesPath(), file );
Directory.Delete( path, true );
new Thread( LoadData ).Start();
}
}
/// <summary>
/// User has clicked on a hyperlink in the status text.
/// </summary>
/// <param name="sender">The object that is sending this event.</param>
/// <param name="e">The arguments that describe the event.</param>
private void StatusLink_RequestNavigate( object sender, RequestNavigateEventArgs e )
{
Process.Start( e.Uri.AbsoluteUri );
}
/// <summary>
/// The IIS Express process has spit out some text on the stdout stream.
/// </summary>
/// <param name="sender">The object that is sending this event.</param>
/// <param name="text">The text received by the console application.</param>
private void IisExpressProcess_StandardTextReceived( object sender, string text )
{
Dispatcher.Invoke( () =>
{
txtConsole.AppendText( text );
txtConsole.ScrollToEnd();
} );
}
/// <summary>
/// The IIS Express process has ended, perhaps unexpectedly.
/// </summary>
/// <param name="sender">The object that is sending this event.</param>
/// <param name="e">The arguments that describe the event.</param>
private void IisExpressProcess_Exited( object sender, EventArgs e )
{
iisExpressProcess = null;
Dispatcher.Invoke( () => { UpdateState(); } );
}
/// <summary>
/// User is typing text into the txtPort control. Validate it as numeric.
/// </summary>
/// <param name="sender">The object that is sending this event.</param>
/// <param name="e">The arguments that describe the event.</param>
private void txtPort_PreviewTextInput( object sender, TextCompositionEventArgs e )
{
e.Handled = new Regex( "[^0-9]+" ).IsMatch( e.Text );
}
#endregion
}
}
| 35.146226 | 241 | 0.540599 | [
"MIT"
] | cabal95/RockLauncher | RockLauncher/InstancesView.xaml.cs | 14,904 | C# |
using System;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
// 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("AWSSDK.DataPipeline")]
#if BCL35
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - AWS Data Pipeline. AWS Data Pipeline is a managed extract-transform-load (ETL) service that helps you reliably and cost-effectively move and process data across your on-premise data stores and AWS services.")]
#elif BCL45
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (4.5) - AWS Data Pipeline. AWS Data Pipeline is a managed extract-transform-load (ETL) service that helps you reliably and cost-effectively move and process data across your on-premise data stores and AWS services.")]
#elif NETSTANDARD20
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (NetStandard 2.0) - AWS Data Pipeline. AWS Data Pipeline is a managed extract-transform-load (ETL) service that helps you reliably and cost-effectively move and process data across your on-premise data stores and AWS services.")]
#elif NETCOREAPP3_1
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (.NET Core 3.1) - AWS Data Pipeline. AWS Data Pipeline is a managed extract-transform-load (ETL) service that helps you reliably and cost-effectively move and process data across your on-premise data stores and AWS services.")]
#else
#error Unknown platform constant - unable to set correct AssemblyDescription
#endif
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyProduct("Amazon Web Services SDK for .NET")]
[assembly: AssemblyCompany("Amazon.com, Inc")]
[assembly: AssemblyCopyright("Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.")]
[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)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("3.3")]
[assembly: AssemblyFileVersion("3.7.1.45")]
[assembly: System.CLSCompliant(true)]
#if BCL
[assembly: System.Security.AllowPartiallyTrustedCallers]
#endif | 53.980392 | 298 | 0.772612 | [
"Apache-2.0"
] | mikemissakian/aws-sdk-net | sdk/src/Services/DataPipeline/Properties/AssemblyInfo.cs | 2,753 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
namespace WinRTXamlToolkit.Controls
{
public sealed partial class AutoCompleteTextBox
{
/// <summary>
/// Algorithm implementation for AutoCompleteTextBox that scores suggestions from the dictionary
/// based on the Damerau-Levenshtein distance.
/// </summary>
public class PrefixSuggestion : AutoCompletable
{
private ScoredString GetSuggestionPrefixScore(string wordToSuggest, string suggestion)
{
int smallestLength = Math.Min(wordToSuggest.Length, suggestion.Length);
ScoredString suggestionScore = new ScoredString() {Text = suggestion};
int score = 0;
for (int i = 0; i < smallestLength; ++i)
{
if (wordToSuggest[i] != suggestion[i])
break;
score++;
}
suggestionScore.Score = score;
return suggestionScore;
}
/// <summary>
/// Gets a list of suggested word completions for the specified word, given a dictionary of words.
/// </summary>
/// <param name="wordToSuggest">Word/string to get suggestions for.</param>
/// <param name="suggestionDictionary">Dictionary of words to select suggestions from.</param>
/// <returns>A list of suggestions.</returns>
public override IList<string> GetSuggestedWords(string wordToSuggest, ICollection<string> suggestionDictionary)
{
var scoredStrings =
suggestionDictionary.Select(suggestion => GetSuggestionPrefixScore(wordToSuggest, suggestion));
int maximalScore = scoredStrings.Max(scoredString => scoredString.Score);
IComparer<int> scoreComparer =
Comparer<int>.Create((firstScore, secondScore) => secondScore.CompareTo(firstScore));
return
scoredStrings.Where(
scoredString => scoredString.Score != 0 && maximalScore - scoredString.Score <= 1)
.OrderBy(scoredString => scoredString.Score, scoreComparer)
.Take(this.MaximumSuggestionCount)
.Select(scoredString => scoredString.Text)
.ToList();
}
}
}
} | 43.586207 | 124 | 0.562104 | [
"MIT"
] | SivilTaram/WinRTXamlToolk | WinRTXamlToolkit/Controls/AutoCompleteTextBox/Algorithm/PrefixSuggestion.cs | 2,530 | C# |
using System.Collections.Generic;
using Lucene.Net.Documents;
using Lucene.Net.Index;
using NUnit.Framework;
using JCG = J2N.Collections.Generic;
using Assert = Lucene.Net.TestFramework.Assert;
namespace Lucene.Net.Search.Similarities
{
/*
* 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 Directory = Lucene.Net.Store.Directory;
using Document = Documents.Document;
using Field = Field;
using FieldType = FieldType;
using IndexReader = Lucene.Net.Index.IndexReader;
using LuceneTestCase = Lucene.Net.Util.LuceneTestCase;
using RandomIndexWriter = Lucene.Net.Index.RandomIndexWriter;
using SpanOrQuery = Lucene.Net.Search.Spans.SpanOrQuery;
using SpanTermQuery = Lucene.Net.Search.Spans.SpanTermQuery;
using Term = Lucene.Net.Index.Term;
using TextField = TextField;
/// <summary>
/// Tests against all the similarities we have
/// </summary>
[TestFixture]
public class TestSimilarity2 : LuceneTestCase
{
internal IList<Similarity> sims;
[SetUp]
public override void SetUp()
{
base.SetUp();
sims = new JCG.List<Similarity>();
sims.Add(new DefaultSimilarity());
sims.Add(new BM25Similarity());
// TODO: not great that we dup this all with TestSimilarityBase
foreach (BasicModel basicModel in TestSimilarityBase.BASIC_MODELS)
{
foreach (AfterEffect afterEffect in TestSimilarityBase.AFTER_EFFECTS)
{
foreach (Normalization normalization in TestSimilarityBase.NORMALIZATIONS)
{
sims.Add(new DFRSimilarity(basicModel, afterEffect, normalization));
}
}
}
foreach (Distribution distribution in TestSimilarityBase.DISTRIBUTIONS)
{
foreach (Lambda lambda in TestSimilarityBase.LAMBDAS)
{
foreach (Normalization normalization in TestSimilarityBase.NORMALIZATIONS)
{
sims.Add(new IBSimilarity(distribution, lambda, normalization));
}
}
}
sims.Add(new LMDirichletSimilarity());
sims.Add(new LMJelinekMercerSimilarity(0.1f));
sims.Add(new LMJelinekMercerSimilarity(0.7f));
}
/// <summary>
/// because of stupid things like querynorm, its possible we computeStats on a field that doesnt exist at all
/// test this against a totally empty index, to make sure sims handle it
/// </summary>
[Test]
public virtual void TestEmptyIndex()
{
Directory dir = NewDirectory();
RandomIndexWriter iw = new RandomIndexWriter(
#if FEATURE_INSTANCE_TESTDATA_INITIALIZATION
this,
#endif
Random, dir);
IndexReader ir = iw.GetReader();
iw.Dispose();
IndexSearcher @is = NewSearcher(ir);
foreach (Similarity sim in sims)
{
@is.Similarity = sim;
Assert.AreEqual(0, @is.Search(new TermQuery(new Term("foo", "bar")), 10).TotalHits);
}
ir.Dispose();
dir.Dispose();
}
/// <summary>
/// similar to the above, but ORs the query with a real field </summary>
[Test]
public virtual void TestEmptyField()
{
Directory dir = NewDirectory();
RandomIndexWriter iw = new RandomIndexWriter(
#if FEATURE_INSTANCE_TESTDATA_INITIALIZATION
this,
#endif
Random, dir);
Document doc = new Document();
doc.Add(NewTextField("foo", "bar", Field.Store.NO));
iw.AddDocument(doc);
IndexReader ir = iw.GetReader();
iw.Dispose();
IndexSearcher @is = NewSearcher(ir);
foreach (Similarity sim in sims)
{
@is.Similarity = sim;
BooleanQuery query = new BooleanQuery(true);
query.Add(new TermQuery(new Term("foo", "bar")), Occur.SHOULD);
query.Add(new TermQuery(new Term("bar", "baz")), Occur.SHOULD);
Assert.AreEqual(1, @is.Search(query, 10).TotalHits);
}
ir.Dispose();
dir.Dispose();
}
/// <summary>
/// similar to the above, however the field exists, but we query with a term that doesnt exist too </summary>
[Test]
public virtual void TestEmptyTerm()
{
Directory dir = NewDirectory();
RandomIndexWriter iw = new RandomIndexWriter(
#if FEATURE_INSTANCE_TESTDATA_INITIALIZATION
this,
#endif
Random, dir);
Document doc = new Document();
doc.Add(NewTextField("foo", "bar", Field.Store.NO));
iw.AddDocument(doc);
IndexReader ir = iw.GetReader();
iw.Dispose();
IndexSearcher @is = NewSearcher(ir);
foreach (Similarity sim in sims)
{
@is.Similarity = sim;
BooleanQuery query = new BooleanQuery(true);
query.Add(new TermQuery(new Term("foo", "bar")), Occur.SHOULD);
query.Add(new TermQuery(new Term("foo", "baz")), Occur.SHOULD);
Assert.AreEqual(1, @is.Search(query, 10).TotalHits);
}
ir.Dispose();
dir.Dispose();
}
/// <summary>
/// make sure we can retrieve when norms are disabled </summary>
[Test]
public virtual void TestNoNorms()
{
Directory dir = NewDirectory();
RandomIndexWriter iw = new RandomIndexWriter(
#if FEATURE_INSTANCE_TESTDATA_INITIALIZATION
this,
#endif
Random, dir);
Document doc = new Document();
FieldType ft = new FieldType(TextField.TYPE_NOT_STORED);
ft.OmitNorms = true;
ft.Freeze();
doc.Add(NewField("foo", "bar", ft));
iw.AddDocument(doc);
IndexReader ir = iw.GetReader();
iw.Dispose();
IndexSearcher @is = NewSearcher(ir);
foreach (Similarity sim in sims)
{
@is.Similarity = sim;
BooleanQuery query = new BooleanQuery(true);
query.Add(new TermQuery(new Term("foo", "bar")), Occur.SHOULD);
Assert.AreEqual(1, @is.Search(query, 10).TotalHits);
}
ir.Dispose();
dir.Dispose();
}
/// <summary>
/// make sure all sims work if TF is omitted </summary>
[Test]
public virtual void TestOmitTF()
{
Directory dir = NewDirectory();
RandomIndexWriter iw = new RandomIndexWriter(
#if FEATURE_INSTANCE_TESTDATA_INITIALIZATION
this,
#endif
Random, dir);
Document doc = new Document();
FieldType ft = new FieldType(TextField.TYPE_NOT_STORED);
ft.IndexOptions = IndexOptions.DOCS_ONLY;
ft.Freeze();
Field f = NewField("foo", "bar", ft);
doc.Add(f);
iw.AddDocument(doc);
IndexReader ir = iw.GetReader();
iw.Dispose();
IndexSearcher @is = NewSearcher(ir);
foreach (Similarity sim in sims)
{
@is.Similarity = sim;
BooleanQuery query = new BooleanQuery(true);
query.Add(new TermQuery(new Term("foo", "bar")), Occur.SHOULD);
Assert.AreEqual(1, @is.Search(query, 10).TotalHits);
}
ir.Dispose();
dir.Dispose();
}
/// <summary>
/// make sure all sims work if TF and norms is omitted </summary>
[Test]
public virtual void TestOmitTFAndNorms()
{
Directory dir = NewDirectory();
RandomIndexWriter iw = new RandomIndexWriter(
#if FEATURE_INSTANCE_TESTDATA_INITIALIZATION
this,
#endif
Random, dir);
Document doc = new Document();
FieldType ft = new FieldType(TextField.TYPE_NOT_STORED);
ft.IndexOptions = IndexOptions.DOCS_ONLY;
ft.OmitNorms = true;
ft.Freeze();
Field f = NewField("foo", "bar", ft);
doc.Add(f);
iw.AddDocument(doc);
IndexReader ir = iw.GetReader();
iw.Dispose();
IndexSearcher @is = NewSearcher(ir);
foreach (Similarity sim in sims)
{
@is.Similarity = sim;
BooleanQuery query = new BooleanQuery(true);
query.Add(new TermQuery(new Term("foo", "bar")), Occur.SHOULD);
Assert.AreEqual(1, @is.Search(query, 10).TotalHits);
}
ir.Dispose();
dir.Dispose();
}
/// <summary>
/// make sure all sims work with spanOR(termX, termY) where termY does not exist </summary>
[Test]
public virtual void TestCrazySpans()
{
// The problem: "normal" lucene queries create scorers, returning null if terms dont exist
// this means they never score a term that does not exist.
// however with spans, there is only one scorer for the whole hierarchy:
// inner queries are not real queries, their boosts are ignored, etc.
Directory dir = NewDirectory();
RandomIndexWriter iw = new RandomIndexWriter(
#if FEATURE_INSTANCE_TESTDATA_INITIALIZATION
this,
#endif
Random, dir);
Document doc = new Document();
FieldType ft = new FieldType(TextField.TYPE_NOT_STORED);
doc.Add(NewField("foo", "bar", ft));
iw.AddDocument(doc);
IndexReader ir = iw.GetReader();
iw.Dispose();
IndexSearcher @is = NewSearcher(ir);
foreach (Similarity sim in sims)
{
@is.Similarity = sim;
SpanTermQuery s1 = new SpanTermQuery(new Term("foo", "bar"));
SpanTermQuery s2 = new SpanTermQuery(new Term("foo", "baz"));
Query query = new SpanOrQuery(s1, s2);
TopDocs td = @is.Search(query, 10);
Assert.AreEqual(1, td.TotalHits);
float score = td.ScoreDocs[0].Score;
Assert.IsTrue(score >= 0.0f);
Assert.IsFalse(float.IsInfinity(score), "inf score for " + sim);
}
ir.Dispose();
dir.Dispose();
}
}
} | 38.233553 | 117 | 0.55829 | [
"Apache-2.0"
] | Maxwellwr/lucenenet | src/Lucene.Net.Tests/Search/Similarities/TestSimilarity2.cs | 11,625 | C# |
using System.Collections.Generic;
namespace LaserCutterTools.BoxBuilder
{
public sealed class StartPositionConfiguration
{
private Dictionary<CubeSide, SideStartPositionConfiguration> startConfigs = new Dictionary<CubeSide, SideStartPositionConfiguration>();
public StartPositionConfiguration(
SideStartPositionConfiguration Top,
SideStartPositionConfiguration Bottom,
SideStartPositionConfiguration Left,
SideStartPositionConfiguration Right,
SideStartPositionConfiguration Front,
SideStartPositionConfiguration Back)
{
startConfigs.Add(CubeSide.Top, Top);
startConfigs.Add(CubeSide.Bottom, Bottom);
startConfigs.Add(CubeSide.Left, Left);
startConfigs.Add(CubeSide.Right, Right);
startConfigs.Add(CubeSide.Front, Front);
startConfigs.Add(CubeSide.Back, Back);
}
public SideStartPositionConfiguration Top
{
get { return startConfigs[CubeSide.Top]; }
}
public SideStartPositionConfiguration Bottom
{
get { return startConfigs[CubeSide.Bottom]; }
}
public SideStartPositionConfiguration Left
{
get { return startConfigs[CubeSide.Left]; }
}
public SideStartPositionConfiguration Right
{
get { return startConfigs[CubeSide.Right]; }
}
public SideStartPositionConfiguration Front
{
get { return startConfigs[CubeSide.Front]; }
}
public SideStartPositionConfiguration Back
{
get { return startConfigs[CubeSide.Back]; }
}
}
public sealed class SideStartPositionConfiguration
{
public TabPosition StartPositionX { get; set; }
public TabPosition StartPositionY { get; set; }
public TabPosition StartPositionXMinus { get; set; }
public TabPosition StartPositionYMinus { get; set; }
public TabPosition GetStartPosition(PieceSide Side)
{
switch (Side)
{
case PieceSide.X:
return StartPositionX;
case PieceSide.Y:
return StartPositionY;
case PieceSide.XMinus:
return StartPositionXMinus;
default:
return StartPositionYMinus;
}
}
}
} | 31.846154 | 143 | 0.605878 | [
"MIT"
] | MrSim17/LaserCutterTools | BoxBuilder/StartPositionConfiguration.cs | 2,486 | C# |
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Shouldly;
using Spect.Net.SpectrumEmu.Devices.Tape;
using Spect.Net.SpectrumEmu.Devices.Tape.Tap;
// ReSharper disable PossibleNullReferenceException
namespace Spect.Net.SpectrumEmu.Test.Devices.Tape
{
[TestClass]
public class TapPlayerTests
{
private const string TAPESET = "Pinball.tap";
[TestMethod]
public void TapFileCanBeReadSuccessfully()
{
// --- Act
var player = TapPlayerHelper.CreatePlayer(TAPESET);
// --- Assert
player.DataBlocks.Count.ShouldBe(4);
player.Eof.ShouldBeFalse();
}
[TestMethod]
public void InitPlayWorksAsExpected()
{
// --- Arrange
var player = TapPlayerHelper.CreatePlayer(TAPESET);
// --- Act
player.InitPlay(100);
// --- Assert
player.PlayPhase.ShouldBe(PlayPhase.None);
player.StartTact.ShouldBe(100);
player.CurrentBlockIndex.ShouldBe(0);
}
[TestMethod]
public void InitPlayInitializesTheFirstDataBlock()
{
// --- Arrange
var player = TapPlayerHelper.CreatePlayer(TAPESET);
// --- Act
player.InitPlay(100);
// --- Assert
var currentBlock = player.CurrentBlock as TapDataBlock;
currentBlock.ShouldNotBeNull();
currentBlock.PlayPhase.ShouldBe(PlayPhase.Pilot);
currentBlock.StartTact.ShouldBe(player.StartTact);
currentBlock.ByteIndex.ShouldBe(0);
currentBlock.BitMask.ShouldBe((byte)0x80);
}
[TestMethod]
public void PlayMovesToNextBlock()
{
// --- Arrange
var player = TapPlayerHelper.CreatePlayer(TAPESET);
player.InitPlay(100);
var currentBlock = player.CurrentBlock as TapDataBlock;
// --- Act
var indexBefore = player.CurrentBlockIndex;
currentBlock.CompleteBlock();
var lastTact = currentBlock.LastTact;
player.GetEarBit(lastTact);
var indexAfter = player.CurrentBlockIndex;
// --- Assert
indexBefore.ShouldBe(0);
indexAfter.ShouldBe(1);
currentBlock = player.CurrentBlock as TapDataBlock;
currentBlock.ShouldNotBeNull();
currentBlock.PlayPhase.ShouldBe(PlayPhase.Pilot);
currentBlock.StartTact.ShouldBe(lastTact);
currentBlock.ByteIndex.ShouldBe(0);
currentBlock.BitMask.ShouldBe((byte)0x80);
}
[TestMethod]
public void PlaySetsEofAtTheLastPlayableBlock()
{
// --- Arrange
var player = TapPlayerHelper.CreatePlayer(TAPESET);
player.InitPlay(100);
for (var i = 0; i < 4; i++) // Block 4 is the last
{
var currentBlock = player.CurrentBlock as TapDataBlock;
currentBlock.CompleteBlock();
var lastTact = currentBlock.LastTact;
player.GetEarBit(lastTact);
}
// --- Act
var lastBlock = player.CurrentBlock as TapDataBlock;
var lastPos = lastBlock.ReadUntilPause();
player.GetEarBit(lastPos);
// --- Assert
player.Eof.ShouldBeTrue();
}
[TestMethod]
public void PlayDoesNotSetEofUntilEnd()
{
// --- Arrange
var player = TapPlayerHelper.CreatePlayer(TAPESET);
player.InitPlay(100);
for (var i = 0; i < 3; i++) // Block 3 is a middle block
{
var currentBlock = player.CurrentBlock as TapDataBlock;
currentBlock.CompleteBlock();
var lastTact = currentBlock.LastTact;
player.GetEarBit(lastTact);
}
// --- Act
var lastBlock = player.CurrentBlock as TapDataBlock;
lastBlock.ReadUntilPause();
// --- Assert
player.Eof.ShouldBeFalse();
}
}
} | 32.238462 | 71 | 0.560964 | [
"MIT"
] | Dotneteer/spectnetide | Tests/Spect.Net.SpectrumEmu.Test/Devices/Tape/TapPlayerTests.cs | 4,193 | C# |
using UdonSharp;
using UnityEngine;
using UnityEngine.UI;
using VRC.SDKBase;
using VRC.Udon;
public class PlayerTelepoter : UdonSharpBehaviour
{
int playerID;
[SerializeField]
Text playerName;
bool isEnabledNode = false;
void Start()
{
}
public void SetPlayerID(int id)
{
playerID = id;
if (Networking.LocalPlayer == null)
{
playerName.text = "None Player" + playerID.ToString();
}
else
{
var targetPlayer = VRCPlayerApi.GetPlayerById(playerID);
if (targetPlayer != null)
{
playerName.text = string.Format("{0} : {1}", targetPlayer.playerId, targetPlayer.displayName);
}
else
{
Debug.LogError("TargetPlayer not found");
}
}
}
public void Teleport()
{
var targetPlayer = VRCPlayerApi.GetPlayerById(playerID);
if(targetPlayer != null)
{
Networking.LocalPlayer.TeleportTo(targetPlayer.GetPosition(), targetPlayer.GetRotation());
}
else
{
Destroy(gameObject);
}
}
public bool isManagedPlayer(VRCPlayerApi player)
{
if (player == null) return false;
return player.playerId == playerID;
}
public bool IsEnabled()
{
return isEnabledNode;
}
public void SetEnabled(bool flag)
{
isEnabledNode = flag;
gameObject.SetActive(flag);
if(flag)
{
transform.SetAsLastSibling();
}
else
{
SetPlayerID(0);
}
}
}
| 20.616279 | 111 | 0.50705 | [
"MIT"
] | kurotori4423/KurotoriUdonMenu | Assets/KurotoriUdonUtilites/KurotoriUdonMenu/UdonScripts/Teleporter/PlayerTelepoter.cs | 1,775 | 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.AzureNextGen.DataFactory.V20180601.Inputs
{
/// <summary>
/// A copy activity source for SAP Table source.
/// </summary>
public sealed class SapTableSourceArgs : Pulumi.ResourceArgs
{
[Input("additionalColumns")]
private InputList<Inputs.AdditionalColumnsArgs>? _additionalColumns;
/// <summary>
/// Specifies the additional columns to be added to source data. Type: array of objects (or Expression with resultType array of objects).
/// </summary>
public InputList<Inputs.AdditionalColumnsArgs> AdditionalColumns
{
get => _additionalColumns ?? (_additionalColumns = new InputList<Inputs.AdditionalColumnsArgs>());
set => _additionalColumns = value;
}
/// <summary>
/// Specifies the maximum number of rows that will be retrieved at a time when retrieving data from SAP Table. Type: integer (or Expression with resultType integer).
/// </summary>
[Input("batchSize")]
public Input<object>? BatchSize { get; set; }
/// <summary>
/// Specifies the custom RFC function module that will be used to read data from SAP Table. Type: string (or Expression with resultType string).
/// </summary>
[Input("customRfcReadTableFunctionModule")]
public Input<object>? CustomRfcReadTableFunctionModule { get; set; }
/// <summary>
/// The maximum concurrent connection count for the source data store. Type: integer (or Expression with resultType integer).
/// </summary>
[Input("maxConcurrentConnections")]
public Input<object>? MaxConcurrentConnections { get; set; }
/// <summary>
/// The partition mechanism that will be used for SAP table read in parallel. Possible values include: "None", "PartitionOnInt", "PartitionOnCalendarYear", "PartitionOnCalendarMonth", "PartitionOnCalendarDate", "PartitionOnTime".
/// </summary>
[Input("partitionOption")]
public Input<object>? PartitionOption { get; set; }
/// <summary>
/// The settings that will be leveraged for SAP table source partitioning.
/// </summary>
[Input("partitionSettings")]
public Input<Inputs.SapTablePartitionSettingsArgs>? PartitionSettings { get; set; }
/// <summary>
/// Query timeout. Type: string (or Expression with resultType string), pattern: ((\d+)\.)?(\d\d):(60|([0-5][0-9])):(60|([0-5][0-9])).
/// </summary>
[Input("queryTimeout")]
public Input<object>? QueryTimeout { get; set; }
/// <summary>
/// The fields of the SAP table that will be retrieved. For example, column0, column1. Type: string (or Expression with resultType string).
/// </summary>
[Input("rfcTableFields")]
public Input<object>? RfcTableFields { get; set; }
/// <summary>
/// The options for the filtering of the SAP Table. For example, COLUMN0 EQ SOME VALUE. Type: string (or Expression with resultType string).
/// </summary>
[Input("rfcTableOptions")]
public Input<object>? RfcTableOptions { get; set; }
/// <summary>
/// The number of rows to be retrieved. Type: integer(or Expression with resultType integer).
/// </summary>
[Input("rowCount")]
public Input<object>? RowCount { get; set; }
/// <summary>
/// The number of rows that will be skipped. Type: integer (or Expression with resultType integer).
/// </summary>
[Input("rowSkips")]
public Input<object>? RowSkips { get; set; }
/// <summary>
/// The single character that will be used as delimiter passed to SAP RFC as well as splitting the output data retrieved. Type: string (or Expression with resultType string).
/// </summary>
[Input("sapDataColumnDelimiter")]
public Input<object>? SapDataColumnDelimiter { get; set; }
/// <summary>
/// Source retry count. Type: integer (or Expression with resultType integer).
/// </summary>
[Input("sourceRetryCount")]
public Input<object>? SourceRetryCount { get; set; }
/// <summary>
/// Source retry wait. Type: string (or Expression with resultType string), pattern: ((\d+)\.)?(\d\d):(60|([0-5][0-9])):(60|([0-5][0-9])).
/// </summary>
[Input("sourceRetryWait")]
public Input<object>? SourceRetryWait { get; set; }
/// <summary>
/// Copy source type.
/// Expected value is 'TabularSource'.
/// </summary>
[Input("type", required: true)]
public Input<string> Type { get; set; } = null!;
public SapTableSourceArgs()
{
}
}
}
| 42.5 | 237 | 0.622157 | [
"Apache-2.0"
] | pulumi/pulumi-azure-nextgen | sdk/dotnet/DataFactory/V20180601/Inputs/SapTableSourceArgs.cs | 5,100 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.CSharp.UnitTests;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Roslyn.Test.Utilities.TestGenerators;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.Semantic.UnitTests.SourceGeneration
{
public class GeneratorDriverTests
: CSharpTestBase
{
[Fact]
public void Running_With_No_Changes_Is_NoOp()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
GeneratorDriver driver = CSharpGeneratorDriver.Create(ImmutableArray<ISourceGenerator>.Empty, parseOptions: parseOptions);
driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var diagnostics);
Assert.Empty(diagnostics);
Assert.Single(outputCompilation.SyntaxTrees);
Assert.Equal(compilation, outputCompilation);
}
[Fact]
public void Generator_Is_Initialized_Before_Running()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
int initCount = 0, executeCount = 0;
var generator = new CallbackGenerator((ic) => initCount++, (sgc) => executeCount++);
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions);
driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var diagnostics);
Assert.Equal(1, initCount);
Assert.Equal(1, executeCount);
}
[Fact]
public void Generator_Is_Not_Initialized_If_Not_Run()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
int initCount = 0, executeCount = 0;
var generator = new CallbackGenerator((ic) => initCount++, (sgc) => executeCount++);
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions);
Assert.Equal(0, initCount);
Assert.Equal(0, executeCount);
}
[Fact]
public void Generator_Is_Only_Initialized_Once()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
int initCount = 0, executeCount = 0;
var generator = new CallbackGenerator((ic) => initCount++, (sgc) => executeCount++, source: "public class C { }");
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions);
driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _);
driver = driver.RunGeneratorsAndUpdateCompilation(outputCompilation, out outputCompilation, out _);
driver.RunGeneratorsAndUpdateCompilation(outputCompilation, out outputCompilation, out _);
Assert.Equal(1, initCount);
Assert.Equal(3, executeCount);
}
[Fact]
public void Single_File_Is_Added()
{
var source = @"
class C { }
";
var generatorSource = @"
class GeneratedClass { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
SingleFileTestGenerator testGenerator = new SingleFileTestGenerator(generatorSource);
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator }, parseOptions: parseOptions);
driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _);
Assert.Equal(2, outputCompilation.SyntaxTrees.Count());
Assert.NotEqual(compilation, outputCompilation);
var generatedClass = outputCompilation.GlobalNamespace.GetTypeMembers("GeneratedClass").Single();
Assert.True(generatedClass.Locations.Single().IsInSource);
}
[Fact]
public void Analyzer_Is_Run()
{
var source = @"
class C { }
";
var generatorSource = @"
class GeneratedClass { }
";
var parseOptions = TestOptions.Regular;
var analyzer = new Analyzer_Is_Run_Analyzer();
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
compilation.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify();
Assert.Equal(0, analyzer.GeneratedClassCount);
SingleFileTestGenerator testGenerator = new SingleFileTestGenerator(generatorSource);
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator }, parseOptions: parseOptions);
driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _);
outputCompilation.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify();
Assert.Equal(1, analyzer.GeneratedClassCount);
}
private class Analyzer_Is_Run_Analyzer : DiagnosticAnalyzer
{
public int GeneratedClassCount;
private static readonly DiagnosticDescriptor Descriptor =
new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test");
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
=> ImmutableArray.Create(Descriptor);
public override void Initialize(AnalysisContext context)
{
context.RegisterSymbolAction(Handle, SymbolKind.NamedType);
}
private void Handle(SymbolAnalysisContext context)
{
switch (context.Symbol.ToTestDisplayString())
{
case "GeneratedClass":
Interlocked.Increment(ref GeneratedClassCount);
break;
case "C":
case "System.Runtime.CompilerServices.IsExternalInit":
break;
default:
Assert.True(false);
break;
}
}
}
[Fact]
public void Single_File_Is_Added_OnlyOnce_For_Multiple_Calls()
{
var source = @"
class C { }
";
var generatorSource = @"
class GeneratedClass { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
SingleFileTestGenerator testGenerator = new SingleFileTestGenerator(generatorSource);
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator }, parseOptions: parseOptions);
driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation1, out _);
driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation2, out _);
driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation3, out _);
Assert.Equal(2, outputCompilation1.SyntaxTrees.Count());
Assert.Equal(2, outputCompilation2.SyntaxTrees.Count());
Assert.Equal(2, outputCompilation3.SyntaxTrees.Count());
Assert.NotEqual(compilation, outputCompilation1);
Assert.NotEqual(compilation, outputCompilation2);
Assert.NotEqual(compilation, outputCompilation3);
}
[Fact]
public void User_Source_Can_Depend_On_Generated_Source()
{
var source = @"
#pragma warning disable CS0649
class C
{
public D d;
}
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics(
// (5,12): error CS0246: The type or namespace name 'D' could not be found (are you missing a using directive or an assembly reference?)
// public D d;
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "D").WithArguments("D").WithLocation(5, 12)
);
Assert.Single(compilation.SyntaxTrees);
var generator = new SingleFileTestGenerator("public class D { }");
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions);
driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics);
outputCompilation.VerifyDiagnostics();
generatorDiagnostics.Verify();
}
[Fact]
public void Error_During_Initialization_Is_Reported()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var exception = new InvalidOperationException("init error");
var generator = new CallbackGenerator((ic) => throw exception, (sgc) => { });
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions);
driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics);
outputCompilation.VerifyDiagnostics();
generatorDiagnostics.Verify(
// warning CS8784: Generator 'CallbackGenerator' failed to initialize. It will not contribute to the output and compilation errors may occur as a result. Exception was 'InvalidOperationException' with message 'init error'
Diagnostic("CS" + (int)ErrorCode.WRN_GeneratorFailedDuringInitialization).WithArguments("CallbackGenerator", "InvalidOperationException", "init error").WithLocation(1, 1)
);
}
[Fact]
public void Error_During_Initialization_Generator_Does_Not_Run()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var exception = new InvalidOperationException("init error");
var generator = new CallbackGenerator((ic) => throw exception, (sgc) => { }, source: "class D { }");
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions);
driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _);
Assert.Single(outputCompilation.SyntaxTrees);
}
[Fact]
public void Error_During_Generation_Is_Reported()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var exception = new InvalidOperationException("generate error");
var generator = new CallbackGenerator((ic) => { }, (sgc) => throw exception);
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions);
driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics);
outputCompilation.VerifyDiagnostics();
generatorDiagnostics.Verify(
// warning CS8785: Generator 'CallbackGenerator' failed to generate source. It will not contribute to the output and compilation errors may occur as a result. Exception was 'InvalidOperationException' with message 'generate error'
Diagnostic("CS" + (int)ErrorCode.WRN_GeneratorFailedDuringGeneration).WithArguments("CallbackGenerator", "InvalidOperationException", "generate error").WithLocation(1, 1)
);
}
[Fact]
public void Error_During_Generation_Does_Not_Affect_Other_Generators()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var exception = new InvalidOperationException("generate error");
var generator = new CallbackGenerator((ic) => { }, (sgc) => throw exception);
var generator2 = new CallbackGenerator2((ic) => { }, (sgc) => { }, source: "public class D { }");
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator, generator2 }, parseOptions: parseOptions);
driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics);
outputCompilation.VerifyDiagnostics();
Assert.Equal(2, outputCompilation.SyntaxTrees.Count());
generatorDiagnostics.Verify(
// warning CS8785: Generator 'CallbackGenerator' failed to generate source. It will not contribute to the output and compilation errors may occur as a result. Exception was 'InvalidOperationException' with message 'generate error'
Diagnostic("CS" + (int)ErrorCode.WRN_GeneratorFailedDuringGeneration).WithArguments("CallbackGenerator", "InvalidOperationException", "generate error").WithLocation(1, 1)
);
}
[Fact]
public void Error_During_Generation_With_Dependent_Source()
{
var source = @"
#pragma warning disable CS0649
class C
{
public D d;
}
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics(
// (5,12): error CS0246: The type or namespace name 'D' could not be found (are you missing a using directive or an assembly reference?)
// public D d;
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "D").WithArguments("D").WithLocation(5, 12)
);
Assert.Single(compilation.SyntaxTrees);
var exception = new InvalidOperationException("generate error");
var generator = new CallbackGenerator((ic) => { }, (sgc) => throw exception, source: "public class D { }");
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions);
driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics);
outputCompilation.VerifyDiagnostics(
// (5,12): error CS0246: The type or namespace name 'D' could not be found (are you missing a using directive or an assembly reference?)
// public D d;
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "D").WithArguments("D").WithLocation(5, 12)
);
generatorDiagnostics.Verify(
// warning CS8785: Generator 'CallbackGenerator' failed to generate source. It will not contribute to the output and compilation errors may occur as a result. Exception was 'InvalidOperationException' with message 'generate error'
Diagnostic("CS" + (int)ErrorCode.WRN_GeneratorFailedDuringGeneration).WithArguments("CallbackGenerator", "InvalidOperationException", "generate error").WithLocation(1, 1)
);
}
[Fact]
public void Error_During_Generation_Has_Exception_In_Description()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var exception = new InvalidOperationException("generate error");
var generator = new CallbackGenerator((ic) => { }, (sgc) => throw exception);
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions);
driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics);
outputCompilation.VerifyDiagnostics();
// Since translated description strings can have punctuation that differs based on locale, simply ensure the
// exception message is contains in the diagnostic description.
Assert.Contains(exception.ToString(), generatorDiagnostics.Single().Descriptor.Description.ToString());
}
[Fact]
public void Generator_Can_Report_Diagnostics()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
string description = "This is a test diagnostic";
DiagnosticDescriptor generatorDiagnostic = new DiagnosticDescriptor("TG001", "Test Diagnostic", description, "Generators", DiagnosticSeverity.Warning, isEnabledByDefault: true, description: description);
var diagnostic = Microsoft.CodeAnalysis.Diagnostic.Create(generatorDiagnostic, Location.None);
var generator = new CallbackGenerator((ic) => { }, (sgc) => sgc.ReportDiagnostic(diagnostic));
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions);
driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics);
outputCompilation.VerifyDiagnostics();
generatorDiagnostics.Verify(
Diagnostic("TG001").WithLocation(1, 1)
);
}
[Fact]
public void Generator_HintName_MustBe_Unique()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var generator = new CallbackGenerator((ic) => { }, (sgc) =>
{
sgc.AddSource("test", SourceText.From("public class D{}", Encoding.UTF8));
// the assert should swallow the exception, so we'll actually successfully generate
Assert.Throws<ArgumentException>("hintName", () => sgc.AddSource("test", SourceText.From("public class D{}", Encoding.UTF8)));
// also throws for <name> vs <name>.cs
Assert.Throws<ArgumentException>("hintName", () => sgc.AddSource("test.cs", SourceText.From("public class D{}", Encoding.UTF8)));
});
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions);
driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics);
outputCompilation.VerifyDiagnostics();
generatorDiagnostics.Verify();
Assert.Equal(2, outputCompilation.SyntaxTrees.Count());
}
[ConditionalFact(typeof(MonoOrCoreClrOnly), Reason = "Desktop CLR displays argument exceptions differently")]
public void Generator_HintName_MustBe_Unique_Across_Outputs()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular.WithLanguageVersion(LanguageVersion.Preview);
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var generator = new PipelineCallbackGenerator((ctx) =>
{
ctx.RegisterSourceOutput(ctx.CompilationProvider, (spc, c) =>
{
spc.AddSource("test", SourceText.From("public class D{}", Encoding.UTF8));
// throws immediately, because we're within the same output node
Assert.Throws<ArgumentException>("hintName", () => spc.AddSource("test", SourceText.From("public class D{}", Encoding.UTF8)));
// throws for .cs too
Assert.Throws<ArgumentException>("hintName", () => spc.AddSource("test.cs", SourceText.From("public class D{}", Encoding.UTF8)));
});
ctx.RegisterSourceOutput(ctx.CompilationProvider, (spc, c) =>
{
// will not throw at this point, because we have no way of knowing what the other outputs added
// we *will* throw later in the driver when we combine them however (this is a change for V2, but not visible from V1)
spc.AddSource("test", SourceText.From("public class D{}", Encoding.UTF8));
});
});
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator.AsSourceGenerator() }, parseOptions: parseOptions);
driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics);
outputCompilation.VerifyDiagnostics();
generatorDiagnostics.Verify(
Diagnostic("CS8785").WithArguments("PipelineCallbackGenerator", "ArgumentException", "The hintName 'test.cs' of the added source file must be unique within a generator. (Parameter 'hintName')").WithLocation(1, 1)
);
Assert.Equal(1, outputCompilation.SyntaxTrees.Count());
}
[Fact]
public void Generator_HintName_Is_Appended_With_GeneratorName()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var generator = new SingleFileTestGenerator("public class D {}", "source.cs");
var generator2 = new SingleFileTestGenerator2("public class E {}", "source.cs");
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator, generator2 }, parseOptions: parseOptions);
driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics);
outputCompilation.VerifyDiagnostics();
generatorDiagnostics.Verify();
Assert.Equal(3, outputCompilation.SyntaxTrees.Count());
var filePaths = outputCompilation.SyntaxTrees.Skip(1).Select(t => t.FilePath).ToArray();
Assert.Equal(new[] {
Path.Combine(generator.GetType().Assembly.GetName().Name!, generator.GetType().FullName!, "source.cs"),
Path.Combine(generator2.GetType().Assembly.GetName().Name!, generator2.GetType().FullName!, "source.cs")
}, filePaths);
}
[Fact]
public void RunResults_Are_Empty_Before_Generation()
{
GeneratorDriver driver = CSharpGeneratorDriver.Create(ImmutableArray<ISourceGenerator>.Empty, parseOptions: TestOptions.Regular);
var results = driver.GetRunResult();
Assert.Empty(results.GeneratedTrees);
Assert.Empty(results.Diagnostics);
Assert.Empty(results.Results);
}
[Fact]
public void RunResults_Are_Available_After_Generation()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var generator = new CallbackGenerator((ic) => { }, (sgc) => { sgc.AddSource("test", SourceText.From("public class D {}", Encoding.UTF8)); });
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions);
driver = driver.RunGenerators(compilation);
var results = driver.GetRunResult();
Assert.Single(results.GeneratedTrees);
Assert.Single(results.Results);
Assert.Empty(results.Diagnostics);
var result = results.Results.Single();
Assert.Null(result.Exception);
Assert.Empty(result.Diagnostics);
Assert.Single(result.GeneratedSources);
Assert.Equal(results.GeneratedTrees.Single(), result.GeneratedSources.Single().SyntaxTree);
}
[Fact]
public void RunResults_Combine_SyntaxTrees()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var generator = new CallbackGenerator((ic) => { }, (sgc) => { sgc.AddSource("test", SourceText.From("public class D {}", Encoding.UTF8)); sgc.AddSource("test2", SourceText.From("public class E {}", Encoding.UTF8)); });
var generator2 = new SingleFileTestGenerator("public class F{}");
var generator3 = new SingleFileTestGenerator2("public class G{}");
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator, generator2, generator3 }, parseOptions: parseOptions);
driver = driver.RunGenerators(compilation);
var results = driver.GetRunResult();
Assert.Equal(4, results.GeneratedTrees.Length);
Assert.Equal(3, results.Results.Length);
Assert.Empty(results.Diagnostics);
var result1 = results.Results[0];
var result2 = results.Results[1];
var result3 = results.Results[2];
Assert.Null(result1.Exception);
Assert.Empty(result1.Diagnostics);
Assert.Equal(2, result1.GeneratedSources.Length);
Assert.Equal(results.GeneratedTrees[0], result1.GeneratedSources[0].SyntaxTree);
Assert.Equal(results.GeneratedTrees[1], result1.GeneratedSources[1].SyntaxTree);
Assert.Null(result2.Exception);
Assert.Empty(result2.Diagnostics);
Assert.Single(result2.GeneratedSources);
Assert.Equal(results.GeneratedTrees[2], result2.GeneratedSources[0].SyntaxTree);
Assert.Null(result3.Exception);
Assert.Empty(result3.Diagnostics);
Assert.Single(result3.GeneratedSources);
Assert.Equal(results.GeneratedTrees[3], result3.GeneratedSources[0].SyntaxTree);
}
[Fact]
public void RunResults_Combine_Diagnostics()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
string description = "This is a test diagnostic";
DiagnosticDescriptor generatorDiagnostic1 = new DiagnosticDescriptor("TG001", "Test Diagnostic", description, "Generators", DiagnosticSeverity.Warning, isEnabledByDefault: true, description: description);
DiagnosticDescriptor generatorDiagnostic2 = new DiagnosticDescriptor("TG002", "Test Diagnostic", description, "Generators", DiagnosticSeverity.Warning, isEnabledByDefault: true, description: description);
DiagnosticDescriptor generatorDiagnostic3 = new DiagnosticDescriptor("TG003", "Test Diagnostic", description, "Generators", DiagnosticSeverity.Warning, isEnabledByDefault: true, description: description);
var diagnostic1 = Microsoft.CodeAnalysis.Diagnostic.Create(generatorDiagnostic1, Location.None);
var diagnostic2 = Microsoft.CodeAnalysis.Diagnostic.Create(generatorDiagnostic2, Location.None);
var diagnostic3 = Microsoft.CodeAnalysis.Diagnostic.Create(generatorDiagnostic3, Location.None);
var generator = new CallbackGenerator((ic) => { }, (sgc) => { sgc.ReportDiagnostic(diagnostic1); sgc.ReportDiagnostic(diagnostic2); });
var generator2 = new CallbackGenerator2((ic) => { }, (sgc) => { sgc.ReportDiagnostic(diagnostic3); });
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator, generator2 }, parseOptions: parseOptions);
driver = driver.RunGenerators(compilation);
var results = driver.GetRunResult();
Assert.Equal(2, results.Results.Length);
Assert.Equal(3, results.Diagnostics.Length);
Assert.Empty(results.GeneratedTrees);
var result1 = results.Results[0];
var result2 = results.Results[1];
Assert.Null(result1.Exception);
Assert.Equal(2, result1.Diagnostics.Length);
Assert.Empty(result1.GeneratedSources);
Assert.Equal(results.Diagnostics[0], result1.Diagnostics[0]);
Assert.Equal(results.Diagnostics[1], result1.Diagnostics[1]);
Assert.Null(result2.Exception);
Assert.Single(result2.Diagnostics);
Assert.Empty(result2.GeneratedSources);
Assert.Equal(results.Diagnostics[2], result2.Diagnostics[0]);
}
[Fact]
public void FullGeneration_Diagnostics_AreSame_As_RunResults()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
string description = "This is a test diagnostic";
DiagnosticDescriptor generatorDiagnostic1 = new DiagnosticDescriptor("TG001", "Test Diagnostic", description, "Generators", DiagnosticSeverity.Warning, isEnabledByDefault: true, description: description);
DiagnosticDescriptor generatorDiagnostic2 = new DiagnosticDescriptor("TG002", "Test Diagnostic", description, "Generators", DiagnosticSeverity.Warning, isEnabledByDefault: true, description: description);
DiagnosticDescriptor generatorDiagnostic3 = new DiagnosticDescriptor("TG003", "Test Diagnostic", description, "Generators", DiagnosticSeverity.Warning, isEnabledByDefault: true, description: description);
var diagnostic1 = Microsoft.CodeAnalysis.Diagnostic.Create(generatorDiagnostic1, Location.None);
var diagnostic2 = Microsoft.CodeAnalysis.Diagnostic.Create(generatorDiagnostic2, Location.None);
var diagnostic3 = Microsoft.CodeAnalysis.Diagnostic.Create(generatorDiagnostic3, Location.None);
var generator = new CallbackGenerator((ic) => { }, (sgc) => { sgc.ReportDiagnostic(diagnostic1); sgc.ReportDiagnostic(diagnostic2); });
var generator2 = new CallbackGenerator2((ic) => { }, (sgc) => { sgc.ReportDiagnostic(diagnostic3); });
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator, generator2 }, parseOptions: parseOptions);
driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out _, out var fullDiagnostics);
var results = driver.GetRunResult();
Assert.Equal(3, results.Diagnostics.Length);
Assert.Equal(3, fullDiagnostics.Length);
AssertEx.Equal(results.Diagnostics, fullDiagnostics);
}
[Fact]
public void Cancellation_During_Execution_Doesnt_Report_As_Generator_Error()
{
var source = @"
class C
{
}
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
CancellationTokenSource cts = new CancellationTokenSource();
var testGenerator = new CallbackGenerator(
onInit: (i) => { },
onExecute: (e) => { cts.Cancel(); }
);
// test generator cancels the token. Check that the call to this generator doesn't make it look like it errored.
var testGenerator2 = new CallbackGenerator2(
onInit: (i) => { },
onExecute: (e) =>
{
e.AddSource("a", SourceText.From("public class E {}", Encoding.UTF8));
e.CancellationToken.ThrowIfCancellationRequested();
});
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator, testGenerator2 }, parseOptions: parseOptions);
var oldDriver = driver;
Assert.Throws<OperationCanceledException>(() =>
driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var outputDiagnostics, cts.Token)
);
Assert.Same(oldDriver, driver);
}
[ConditionalFact(typeof(MonoOrCoreClrOnly), Reason = "Desktop CLR displays argument exceptions differently")]
public void Adding_A_Source_Text_Without_Encoding_Fails_Generation()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var generator = new CallbackGenerator((ic) => { }, (sgc) => { sgc.AddSource("a", SourceText.From("")); });
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions);
driver.RunGeneratorsAndUpdateCompilation(compilation, out _, out var outputDiagnostics);
Assert.Single(outputDiagnostics);
outputDiagnostics.Verify(
Diagnostic("CS" + (int)ErrorCode.WRN_GeneratorFailedDuringGeneration).WithArguments("CallbackGenerator", "ArgumentException", "The SourceText with hintName 'a.cs' must have an explicit encoding set. (Parameter 'source')").WithLocation(1, 1)
);
}
[Fact]
public void ParseOptions_Are_Passed_To_Generator()
{
var source = @"
class C
{
}
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
ParseOptions? passedOptions = null;
var testGenerator = new CallbackGenerator(
onInit: (i) => { },
onExecute: (e) => { passedOptions = e.ParseOptions; }
);
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator }, parseOptions: parseOptions);
driver.RunGeneratorsAndUpdateCompilation(compilation, out _, out _);
Assert.Same(parseOptions, passedOptions);
}
[Fact]
public void AdditionalFiles_Are_Passed_To_Generator()
{
var source = @"
class C
{
}
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var texts = ImmutableArray.Create<AdditionalText>(new InMemoryAdditionalText("a", "abc"), new InMemoryAdditionalText("b", "def"));
ImmutableArray<AdditionalText> passedIn = default;
var testGenerator = new CallbackGenerator(
onInit: (i) => { },
onExecute: (e) => passedIn = e.AdditionalFiles
);
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator }, parseOptions: parseOptions, additionalTexts: texts);
driver.RunGeneratorsAndUpdateCompilation(compilation, out _, out _);
Assert.Equal(2, passedIn.Length);
Assert.Equal<AdditionalText>(texts, passedIn);
}
[Fact]
public void AnalyzerConfigOptions_Are_Passed_To_Generator()
{
var source = @"
class C
{
}
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var options = new CompilerAnalyzerConfigOptionsProvider(ImmutableDictionary<object, AnalyzerConfigOptions>.Empty, new CompilerAnalyzerConfigOptions(ImmutableDictionary<string, string>.Empty.Add("a", "abc").Add("b", "def")));
AnalyzerConfigOptionsProvider? passedIn = null;
var testGenerator = new CallbackGenerator(
onInit: (i) => { },
onExecute: (e) => passedIn = e.AnalyzerConfigOptions
);
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator }, parseOptions: parseOptions, optionsProvider: options);
driver.RunGeneratorsAndUpdateCompilation(compilation, out _, out _);
Assert.NotNull(passedIn);
Assert.True(passedIn!.GlobalOptions.TryGetValue("a", out var item1));
Assert.Equal("abc", item1);
Assert.True(passedIn!.GlobalOptions.TryGetValue("b", out var item2));
Assert.Equal("def", item2);
}
[Fact]
public void Generator_Can_Provide_Source_In_PostInit()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
static void postInit(GeneratorPostInitializationContext context)
{
context.AddSource("postInit", "public class D {} ");
}
var generator = new CallbackGenerator((ic) => ic.RegisterForPostInitialization(postInit), (sgc) => { });
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions);
driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _);
outputCompilation.VerifyDiagnostics();
Assert.Equal(2, outputCompilation.SyntaxTrees.Count());
}
[Fact]
public void PostInit_Source_Is_Available_During_Execute()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
static void postInit(GeneratorPostInitializationContext context)
{
context.AddSource("postInit", "public class D {} ");
}
INamedTypeSymbol? dSymbol = null;
var generator = new CallbackGenerator((ic) => ic.RegisterForPostInitialization(postInit), (sgc) => { dSymbol = sgc.Compilation.GetTypeByMetadataName("D"); }, source = "public class E : D {}");
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions);
driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _);
outputCompilation.VerifyDiagnostics();
Assert.NotNull(dSymbol);
}
[Fact]
public void PostInit_Source_Is_Available_To_Other_Generators_During_Execute()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
static void postInit(GeneratorPostInitializationContext context)
{
context.AddSource("postInit", "public class D {} ");
}
INamedTypeSymbol? dSymbol = null;
var generator = new CallbackGenerator((ic) => ic.RegisterForPostInitialization(postInit), (sgc) => { });
var generator2 = new CallbackGenerator2((ic) => { }, (sgc) => { dSymbol = sgc.Compilation.GetTypeByMetadataName("D"); }, source = "public class E : D {}");
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator, generator2 }, parseOptions: parseOptions);
driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _);
outputCompilation.VerifyDiagnostics();
Assert.NotNull(dSymbol);
}
[Fact]
public void PostInit_Is_Only_Called_Once()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
int postInitCount = 0;
int executeCount = 0;
void postInit(GeneratorPostInitializationContext context)
{
context.AddSource("postInit", "public class D {} ");
postInitCount++;
}
var generator = new CallbackGenerator((ic) => ic.RegisterForPostInitialization(postInit), (sgc) => executeCount++, source = "public class E : D {}");
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions);
driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out _, out _);
driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out _, out _);
driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _);
outputCompilation.VerifyDiagnostics();
Assert.Equal(1, postInitCount);
Assert.Equal(3, executeCount);
}
[Fact]
public void Error_During_PostInit_Is_Reported()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
static void postInit(GeneratorPostInitializationContext context)
{
context.AddSource("postInit", "public class D {} ");
throw new InvalidOperationException("post init error");
}
var generator = new CallbackGenerator((ic) => ic.RegisterForPostInitialization(postInit), (sgc) => Assert.True(false, "Should not execute"), source = "public class E : D {}");
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions);
driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics);
outputCompilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
generatorDiagnostics.Verify(
// warning CS8784: Generator 'CallbackGenerator' failed to initialize. It will not contribute to the output and compilation errors may occur as a result. Exception was 'InvalidOperationException' with message 'post init error'
Diagnostic("CS" + (int)ErrorCode.WRN_GeneratorFailedDuringInitialization).WithArguments("CallbackGenerator", "InvalidOperationException", "post init error").WithLocation(1, 1)
);
}
[Fact]
public void Error_During_Initialization_PostInit_Does_Not_Run()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
static void init(GeneratorInitializationContext context)
{
context.RegisterForPostInitialization(postInit);
throw new InvalidOperationException("init error");
}
static void postInit(GeneratorPostInitializationContext context)
{
context.AddSource("postInit", "public class D {} ");
Assert.True(false, "Should not execute");
}
var generator = new CallbackGenerator(init, (sgc) => Assert.True(false, "Should not execute"), source = "public class E : D {}");
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions);
driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics);
outputCompilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
generatorDiagnostics.Verify(
// warning CS8784: Generator 'CallbackGenerator' failed to initialize. It will not contribute to the output and compilation errors may occur as a result. Exception was 'InvalidOperationException' with message 'init error'
Diagnostic("CS" + (int)ErrorCode.WRN_GeneratorFailedDuringInitialization).WithArguments("CallbackGenerator", "InvalidOperationException", "init error").WithLocation(1, 1)
);
}
[Fact]
public void PostInit_SyntaxTrees_Are_Available_In_RunResults()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var generator = new CallbackGenerator((ic) => ic.RegisterForPostInitialization(pic => pic.AddSource("postInit", "public class D{}")), (sgc) => { }, "public class E{}");
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions);
driver = driver.RunGenerators(compilation);
var results = driver.GetRunResult();
Assert.Single(results.Results);
Assert.Empty(results.Diagnostics);
var result = results.Results[0];
Assert.Null(result.Exception);
Assert.Empty(result.Diagnostics);
Assert.Equal(2, result.GeneratedSources.Length);
}
[Fact]
public void PostInit_SyntaxTrees_Are_Combined_In_RunResults()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var generator = new CallbackGenerator((ic) => ic.RegisterForPostInitialization(pic => pic.AddSource("postInit", "public class D{}")), (sgc) => { }, "public class E{}");
var generator2 = new SingleFileTestGenerator("public class F{}");
var generator3 = new SingleFileTestGenerator2("public class G{}");
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator, generator2, generator3 }, parseOptions: parseOptions);
driver = driver.RunGenerators(compilation);
var results = driver.GetRunResult();
Assert.Equal(4, results.GeneratedTrees.Length);
Assert.Equal(3, results.Results.Length);
Assert.Empty(results.Diagnostics);
var result1 = results.Results[0];
var result2 = results.Results[1];
var result3 = results.Results[2];
Assert.Null(result1.Exception);
Assert.Empty(result1.Diagnostics);
Assert.Equal(2, result1.GeneratedSources.Length);
Assert.Equal(results.GeneratedTrees[0], result1.GeneratedSources[0].SyntaxTree);
Assert.Equal(results.GeneratedTrees[1], result1.GeneratedSources[1].SyntaxTree);
Assert.Null(result2.Exception);
Assert.Empty(result2.Diagnostics);
Assert.Single(result2.GeneratedSources);
Assert.Equal(results.GeneratedTrees[2], result2.GeneratedSources[0].SyntaxTree);
Assert.Null(result3.Exception);
Assert.Empty(result3.Diagnostics);
Assert.Single(result3.GeneratedSources);
Assert.Equal(results.GeneratedTrees[3], result3.GeneratedSources[0].SyntaxTree);
}
[Fact]
public void SyntaxTrees_Are_Lazy()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var generator = new SingleFileTestGenerator("public class D {}", "source.cs");
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions);
driver = driver.RunGenerators(compilation);
var results = driver.GetRunResult();
var tree = Assert.Single(results.GeneratedTrees);
Assert.False(tree.TryGetRoot(out _));
var rootFromGetRoot = tree.GetRoot();
Assert.NotNull(rootFromGetRoot);
Assert.True(tree.TryGetRoot(out var rootFromTryGetRoot));
Assert.Same(rootFromGetRoot, rootFromTryGetRoot);
}
[Fact]
public void Diagnostics_Respect_Suppression()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
CallbackGenerator gen = new CallbackGenerator((c) => { }, (c) =>
{
c.ReportDiagnostic(CSDiagnostic.Create("GEN001", "generators", "message", DiagnosticSeverity.Warning, DiagnosticSeverity.Warning, true, 2));
c.ReportDiagnostic(CSDiagnostic.Create("GEN002", "generators", "message", DiagnosticSeverity.Warning, DiagnosticSeverity.Warning, true, 3));
});
var options = ((CSharpCompilationOptions)compilation.Options);
// generator driver diagnostics are reported separately from the compilation
verifyDiagnosticsWithOptions(options,
Diagnostic("GEN001").WithLocation(1, 1),
Diagnostic("GEN002").WithLocation(1, 1));
// warnings can be individually suppressed
verifyDiagnosticsWithOptions(options.WithSpecificDiagnosticOptions("GEN001", ReportDiagnostic.Suppress),
Diagnostic("GEN002").WithLocation(1, 1));
verifyDiagnosticsWithOptions(options.WithSpecificDiagnosticOptions("GEN002", ReportDiagnostic.Suppress),
Diagnostic("GEN001").WithLocation(1, 1));
// warning level is respected
verifyDiagnosticsWithOptions(options.WithWarningLevel(0));
verifyDiagnosticsWithOptions(options.WithWarningLevel(2),
Diagnostic("GEN001").WithLocation(1, 1));
verifyDiagnosticsWithOptions(options.WithWarningLevel(3),
Diagnostic("GEN001").WithLocation(1, 1),
Diagnostic("GEN002").WithLocation(1, 1));
// warnings can be upgraded to errors
verifyDiagnosticsWithOptions(options.WithSpecificDiagnosticOptions("GEN001", ReportDiagnostic.Error),
Diagnostic("GEN001").WithLocation(1, 1).WithWarningAsError(true),
Diagnostic("GEN002").WithLocation(1, 1));
verifyDiagnosticsWithOptions(options.WithSpecificDiagnosticOptions("GEN002", ReportDiagnostic.Error),
Diagnostic("GEN001").WithLocation(1, 1),
Diagnostic("GEN002").WithLocation(1, 1).WithWarningAsError(true));
void verifyDiagnosticsWithOptions(CompilationOptions options, params DiagnosticDescription[] expected)
{
GeneratorDriver driver = CSharpGeneratorDriver.Create(ImmutableArray.Create(gen), parseOptions: parseOptions);
var updatedCompilation = compilation.WithOptions(options);
driver.RunGeneratorsAndUpdateCompilation(updatedCompilation, out var outputCompilation, out var diagnostics);
outputCompilation.VerifyDiagnostics();
diagnostics.Verify(expected);
}
}
[Fact]
public void Diagnostics_Respect_Pragma_Suppression()
{
var gen001 = CSDiagnostic.Create("GEN001", "generators", "message", DiagnosticSeverity.Warning, DiagnosticSeverity.Warning, true, 2);
// reported diagnostics can have a location in source
verifyDiagnosticsWithSource("//comment",
new[] { (gen001, TextSpan.FromBounds(2, 5)) },
Diagnostic("GEN001", "com").WithLocation(1, 3));
// diagnostics are suppressed via #pragma
verifyDiagnosticsWithSource(
@"#pragma warning disable
//comment",
new[] { (gen001, TextSpan.FromBounds(27, 30)) },
Diagnostic("GEN001", "com", isSuppressed: true).WithLocation(2, 3));
// but not when they don't have a source location
verifyDiagnosticsWithSource(
@"#pragma warning disable
//comment",
new[] { (gen001, new TextSpan(0, 0)) },
Diagnostic("GEN001").WithLocation(1, 1));
// can be suppressed explicitly
verifyDiagnosticsWithSource(
@"#pragma warning disable GEN001
//comment",
new[] { (gen001, TextSpan.FromBounds(34, 37)) },
Diagnostic("GEN001", "com", isSuppressed: true).WithLocation(2, 3));
// suppress + restore
verifyDiagnosticsWithSource(
@"#pragma warning disable GEN001
//comment
#pragma warning restore GEN001
//another",
new[] { (gen001, TextSpan.FromBounds(34, 37)), (gen001, TextSpan.FromBounds(77, 80)) },
Diagnostic("GEN001", "com", isSuppressed: true).WithLocation(2, 3),
Diagnostic("GEN001", "ano").WithLocation(4, 3));
void verifyDiagnosticsWithSource(string source, (Diagnostic, TextSpan)[] reportDiagnostics, params DiagnosticDescription[] expected)
{
var parseOptions = TestOptions.Regular;
source = source.Replace(Environment.NewLine, "\r\n");
Compilation compilation = CreateCompilation(source, sourceFileName: "sourcefile.cs", options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
CallbackGenerator gen = new CallbackGenerator((c) => { }, (c) =>
{
foreach ((var d, var l) in reportDiagnostics)
{
if (l.IsEmpty)
{
c.ReportDiagnostic(d);
}
else
{
c.ReportDiagnostic(d.WithLocation(Location.Create(c.Compilation.SyntaxTrees.First(), l)));
}
}
});
GeneratorDriver driver = CSharpGeneratorDriver.Create(ImmutableArray.Create(gen), parseOptions: parseOptions);
driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var diagnostics);
outputCompilation.VerifyDiagnostics();
diagnostics.Verify(expected);
}
}
[Fact]
public void GeneratorDriver_Prefers_Incremental_Generators()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
int initCount = 0, executeCount = 0;
var generator = new CallbackGenerator((ic) => initCount++, (sgc) => executeCount++);
int incrementalInitCount = 0;
var generator2 = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ic) => incrementalInitCount++));
int dualInitCount = 0, dualExecuteCount = 0, dualIncrementalInitCount = 0;
var generator3 = new IncrementalAndSourceCallbackGenerator((ic) => dualInitCount++, (sgc) => dualExecuteCount++, (ic) => dualIncrementalInitCount++);
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator, generator2, generator3 }, parseOptions: parseOptions);
driver.RunGenerators(compilation);
// ran individual incremental and source generators
Assert.Equal(1, initCount);
Assert.Equal(1, executeCount);
Assert.Equal(1, incrementalInitCount);
// ran the combined generator only as an IIncrementalGenerator
Assert.Equal(0, dualInitCount);
Assert.Equal(0, dualExecuteCount);
Assert.Equal(1, dualIncrementalInitCount);
}
[Fact]
public void GeneratorDriver_Initializes_Incremental_Generators()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
int incrementalInitCount = 0;
var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ic) => incrementalInitCount++));
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions);
driver.RunGenerators(compilation);
// ran the incremental generator
Assert.Equal(1, incrementalInitCount);
}
[Fact]
public void Incremental_Generators_Exception_During_Initialization()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.RegularPreview;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var e = new InvalidOperationException("abc");
var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ic) => throw e));
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions);
driver = driver.RunGenerators(compilation);
var runResults = driver.GetRunResult();
Assert.Single(runResults.Diagnostics);
Assert.Single(runResults.Results);
Assert.Empty(runResults.GeneratedTrees);
Assert.Equal(e, runResults.Results[0].Exception);
}
[Fact]
public void Incremental_Generators_Exception_During_Execution()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.RegularPreview;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var e = new InvalidOperationException("abc");
var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ctx) => ctx.RegisterSourceOutput(ctx.CompilationProvider, (spc, c) => throw e)));
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions);
driver = driver.RunGenerators(compilation);
var runResults = driver.GetRunResult();
Assert.Single(runResults.Diagnostics);
Assert.Single(runResults.Results);
Assert.Empty(runResults.GeneratedTrees);
Assert.Equal(e, runResults.Results[0].Exception);
}
[Fact]
public void Incremental_Generators_Exception_During_Execution_Doesnt_Produce_AnySource()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.RegularPreview;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var e = new InvalidOperationException("abc");
var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ctx) =>
{
ctx.RegisterSourceOutput(ctx.CompilationProvider, (spc, c) => spc.AddSource("test", ""));
ctx.RegisterSourceOutput(ctx.CompilationProvider, (spc, c) => throw e);
}));
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions);
driver = driver.RunGenerators(compilation);
var runResults = driver.GetRunResult();
Assert.Single(runResults.Diagnostics);
Assert.Single(runResults.Results);
Assert.Empty(runResults.GeneratedTrees);
Assert.Equal(e, runResults.Results[0].Exception);
}
[Fact]
public void Incremental_Generators_Exception_During_Execution_Doesnt_Stop_Other_Generators()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.RegularPreview;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var e = new InvalidOperationException("abc");
var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ctx) =>
{
ctx.RegisterSourceOutput(ctx.CompilationProvider, (spc, c) => throw e);
}));
var generator2 = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator2((ctx) =>
{
ctx.RegisterSourceOutput(ctx.CompilationProvider, (spc, c) => spc.AddSource("test", ""));
}));
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator, generator2 }, parseOptions: parseOptions);
driver = driver.RunGenerators(compilation);
var runResults = driver.GetRunResult();
Assert.Single(runResults.Diagnostics);
Assert.Equal(2, runResults.Results.Length);
Assert.Single(runResults.GeneratedTrees);
Assert.Equal(e, runResults.Results[0].Exception);
}
[Fact]
public void IncrementalGenerator_With_No_Pipeline_Callback_Is_Valid()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.RegularPreview;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ic) => { }));
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions);
driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var diagnostics);
outputCompilation.VerifyDiagnostics();
Assert.Empty(diagnostics);
}
[Fact]
public void IncrementalGenerator_Can_Add_PostInit_Source()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.RegularPreview;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ic) => ic.RegisterPostInitializationOutput(c => c.AddSource("a", "class D {}"))));
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions);
driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var diagnostics);
Assert.Equal(2, outputCompilation.SyntaxTrees.Count());
Assert.Empty(diagnostics);
}
[Fact]
public void User_WrappedFunc_Throw_Exceptions()
{
Func<int, CancellationToken, int> func = (input, _) => input;
Func<int, CancellationToken, int> throwsFunc = (input, _) => throw new InvalidOperationException("user code exception");
Func<int, CancellationToken, int> timeoutFunc = (input, ct) => { ct.ThrowIfCancellationRequested(); return input; };
Func<int, CancellationToken, int> otherTimeoutFunc = (input, _) => throw new OperationCanceledException();
var userFunc = func.WrapUserFunction();
var userThrowsFunc = throwsFunc.WrapUserFunction();
var userTimeoutFunc = timeoutFunc.WrapUserFunction();
var userOtherTimeoutFunc = otherTimeoutFunc.WrapUserFunction();
// user functions return same values when wrapped
var result = userFunc(10, CancellationToken.None);
var userResult = userFunc(10, CancellationToken.None);
Assert.Equal(10, result);
Assert.Equal(result, userResult);
// exceptions thrown in user code are wrapped
Assert.Throws<InvalidOperationException>(() => throwsFunc(20, CancellationToken.None));
Assert.Throws<UserFunctionException>(() => userThrowsFunc(20, CancellationToken.None));
try
{
userThrowsFunc(20, CancellationToken.None);
}
catch (UserFunctionException e)
{
Assert.IsType<InvalidOperationException>(e.InnerException);
}
// cancellation is not wrapped, and is bubbled up
Assert.Throws<OperationCanceledException>(() => timeoutFunc(30, new CancellationToken(true)));
Assert.Throws<OperationCanceledException>(() => userTimeoutFunc(30, new CancellationToken(true)));
// unless it wasn't *our* cancellation token, in which case it still gets wrapped
Assert.Throws<OperationCanceledException>(() => otherTimeoutFunc(30, CancellationToken.None));
Assert.Throws<UserFunctionException>(() => userOtherTimeoutFunc(30, CancellationToken.None));
}
[Fact]
public void IncrementalGenerator_Doesnt_Run_For_Same_Input()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.RegularPreview;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
List<Compilation> compilationsCalledFor = new List<Compilation>();
var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator(ctx =>
{
var filePaths = ctx.CompilationProvider.SelectMany((c, _) => c.SyntaxTrees).Select((tree, _) => tree.FilePath);
ctx.RegisterSourceOutput(ctx.CompilationProvider, (spc, c) => { compilationsCalledFor.Add(c); });
}));
// run the generator once, and check it was passed the compilation
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions);
driver = driver.RunGenerators(compilation);
Assert.Equal(1, compilationsCalledFor.Count);
Assert.Equal(compilation, compilationsCalledFor[0]);
// run the same compilation through again, and confirm the output wasn't called
driver = driver.RunGenerators(compilation);
Assert.Equal(1, compilationsCalledFor.Count);
Assert.Equal(compilation, compilationsCalledFor[0]);
}
[Fact]
public void IncrementalGenerator_Runs_Only_For_Changed_Inputs()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.RegularPreview;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var text1 = new InMemoryAdditionalText("Text1", "content1");
var text2 = new InMemoryAdditionalText("Text2", "content2");
List<Compilation> compilationsCalledFor = new List<Compilation>();
List<AdditionalText> textsCalledFor = new List<AdditionalText>();
var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator(ctx =>
{
ctx.RegisterSourceOutput(ctx.CompilationProvider, (spc, c) => { compilationsCalledFor.Add(c); });
ctx.RegisterSourceOutput(ctx.AdditionalTextsProvider, (spc, c) => { textsCalledFor.Add(c); });
}));
// run the generator once, and check it was passed the compilation
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, additionalTexts: new[] { text1 }, parseOptions: parseOptions);
driver = driver.RunGenerators(compilation);
Assert.Equal(1, compilationsCalledFor.Count);
Assert.Equal(compilation, compilationsCalledFor[0]);
Assert.Equal(1, textsCalledFor.Count);
Assert.Equal(text1, textsCalledFor[0]);
// clear the results, add an additional text, but keep the compilation the same
compilationsCalledFor.Clear();
textsCalledFor.Clear();
driver = driver.AddAdditionalTexts(ImmutableArray.Create<AdditionalText>(text2));
driver = driver.RunGenerators(compilation);
Assert.Equal(0, compilationsCalledFor.Count);
Assert.Equal(1, textsCalledFor.Count);
Assert.Equal(text2, textsCalledFor[0]);
// now edit the compilation
compilationsCalledFor.Clear();
textsCalledFor.Clear();
var newCompilation = compilation.WithOptions(compilation.Options.WithModuleName("newComp"));
driver = driver.RunGenerators(newCompilation);
Assert.Equal(1, compilationsCalledFor.Count);
Assert.Equal(newCompilation, compilationsCalledFor[0]);
Assert.Equal(0, textsCalledFor.Count);
// re run without changing anything
compilationsCalledFor.Clear();
textsCalledFor.Clear();
driver = driver.RunGenerators(newCompilation);
Assert.Equal(0, compilationsCalledFor.Count);
Assert.Equal(0, textsCalledFor.Count);
}
[Fact]
public void IncrementalGenerator_Can_Add_Comparer_To_Input_Node()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.RegularPreview;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
List<Compilation> compilationsCalledFor = new List<Compilation>();
var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator(ctx =>
{
var compilationSource = ctx.CompilationProvider.WithComparer(new LambdaComparer<Compilation>((c1, c2) => true, 0));
ctx.RegisterSourceOutput(compilationSource, (spc, c) =>
{
compilationsCalledFor.Add(c);
});
}));
// run the generator once, and check it was passed the compilation
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions);
driver = driver.RunGenerators(compilation);
Assert.Equal(1, compilationsCalledFor.Count);
Assert.Equal(compilation, compilationsCalledFor[0]);
// now edit the compilation, run the generator, and confirm that the output was not called again this time
Compilation newCompilation = compilation.WithOptions(compilation.Options.WithModuleName("newCompilation"));
driver = driver.RunGenerators(newCompilation);
Assert.Equal(1, compilationsCalledFor.Count);
Assert.Equal(compilation, compilationsCalledFor[0]);
}
[Fact]
public void IncrementalGenerator_Can_Add_Comparer_To_Combine_Node()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.RegularPreview;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
List<AdditionalText> texts = new List<AdditionalText>() { new InMemoryAdditionalText("abc", "") };
List<(Compilation, ImmutableArray<AdditionalText>)> calledFor = new List<(Compilation, ImmutableArray<AdditionalText>)>();
var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator(ctx =>
{
var compilationSource = ctx.CompilationProvider.Combine(ctx.AdditionalTextsProvider.Collect())
// comparer that ignores the LHS (additional texts)
.WithComparer(new LambdaComparer<(Compilation, ImmutableArray<AdditionalText>)>((c1, c2) => c1.Item1 == c2.Item1, 0));
ctx.RegisterSourceOutput(compilationSource, (spc, c) =>
{
calledFor.Add(c);
});
}));
// run the generator once, and check it was passed the compilation + additional texts
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions, additionalTexts: texts);
driver = driver.RunGenerators(compilation);
Assert.Equal(1, calledFor.Count);
Assert.Equal(compilation, calledFor[0].Item1);
Assert.Equal(texts[0], calledFor[0].Item2.Single());
// edit the additional texts, and verify that the output was *not* called again on the next run
driver = driver.RemoveAdditionalTexts(texts.ToImmutableArray());
driver = driver.RunGenerators(compilation);
Assert.Equal(1, calledFor.Count);
// now edit the compilation, run the generator, and confirm that the output *was* called again this time with the new compilation and no additional texts
Compilation newCompilation = compilation.WithOptions(compilation.Options.WithModuleName("newCompilation"));
driver = driver.RunGenerators(newCompilation);
Assert.Equal(2, calledFor.Count);
Assert.Equal(newCompilation, calledFor[1].Item1);
Assert.Empty(calledFor[1].Item2);
}
[Fact]
public void IncrementalGenerator_Register_End_Node_Only_Once_Through_Combines()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.RegularPreview;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
List<Compilation> compilationsCalledFor = new List<Compilation>();
var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator(ctx =>
{
var source = ctx.CompilationProvider;
var source2 = ctx.CompilationProvider.Combine(source);
var source3 = ctx.CompilationProvider.Combine(source2);
var source4 = ctx.CompilationProvider.Combine(source3);
var source5 = ctx.CompilationProvider.Combine(source4);
ctx.RegisterSourceOutput(source5, (spc, c) =>
{
compilationsCalledFor.Add(c.Item1);
});
}));
// run the generator and check that we didn't multiple register the generate source node through the combine
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions);
driver = driver.RunGenerators(compilation);
Assert.Equal(1, compilationsCalledFor.Count);
Assert.Equal(compilation, compilationsCalledFor[0]);
}
[Fact]
public void IncrementalGenerator_PostInit_Source_Is_Cached()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.RegularPreview;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
List<ClassDeclarationSyntax> classes = new List<ClassDeclarationSyntax>();
var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ctx) =>
{
ctx.RegisterPostInitializationOutput(c => c.AddSource("a", "class D {}"));
ctx.RegisterSourceOutput(ctx.SyntaxProvider.CreateSyntaxProvider(static (n, _) => n is ClassDeclarationSyntax, (gsc, _) => (ClassDeclarationSyntax)gsc.Node), (spc, node) => classes.Add(node));
}));
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions);
driver = driver.RunGenerators(compilation);
Assert.Equal(2, classes.Count);
Assert.Equal("C", classes[0].Identifier.ValueText);
Assert.Equal("D", classes[1].Identifier.ValueText);
// clear classes, re-run
classes.Clear();
driver = driver.RunGenerators(compilation);
Assert.Empty(classes);
// modify the original tree, see that the post init is still cached
var c2 = compilation.ReplaceSyntaxTree(compilation.SyntaxTrees.First(), CSharpSyntaxTree.ParseText("class E{}", parseOptions));
classes.Clear();
driver = driver.RunGenerators(c2);
Assert.Single(classes);
Assert.Equal("E", classes[0].Identifier.ValueText);
}
[Fact]
public void Incremental_Generators_Can_Be_Cancelled()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.RegularPreview;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
CancellationTokenSource cts = new CancellationTokenSource();
bool generatorCancelled = false;
var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ctx) =>
{
var step1 = ctx.CompilationProvider.Select((c, ct) => { generatorCancelled = true; cts.Cancel(); return c; });
var step2 = step1.Select((c, ct) => { ct.ThrowIfCancellationRequested(); return c; });
ctx.RegisterSourceOutput(step2, (spc, c) => spc.AddSource("a", ""));
}));
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions);
Assert.Throws<OperationCanceledException>(() => driver = driver.RunGenerators(compilation, cancellationToken: cts.Token));
Assert.True(generatorCancelled);
}
[Fact]
public void ParseOptions_Can_Be_Updated()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.RegularPreview;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
List<ParseOptions> parseOptionsCalledFor = new List<ParseOptions>();
var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator(ctx =>
{
ctx.RegisterSourceOutput(ctx.ParseOptionsProvider, (spc, p) => { parseOptionsCalledFor.Add(p); });
}));
// run the generator once, and check it was passed the parse options
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions);
driver = driver.RunGenerators(compilation);
Assert.Equal(1, parseOptionsCalledFor.Count);
Assert.Equal(parseOptions, parseOptionsCalledFor[0]);
// clear the results, and re-run
parseOptionsCalledFor.Clear();
driver = driver.RunGenerators(compilation);
Assert.Empty(parseOptionsCalledFor);
// now update the parse options
parseOptionsCalledFor.Clear();
var newParseOptions = parseOptions.WithDocumentationMode(DocumentationMode.Diagnose);
driver = driver.WithUpdatedParseOptions(newParseOptions);
// check we ran
driver = driver.RunGenerators(compilation);
Assert.Equal(1, parseOptionsCalledFor.Count);
Assert.Equal(newParseOptions, parseOptionsCalledFor[0]);
// clear the results, and re-run
parseOptionsCalledFor.Clear();
driver = driver.RunGenerators(compilation);
Assert.Empty(parseOptionsCalledFor);
// replace it with null, and check that it throws
Assert.Throws<ArgumentNullException>(() => driver.WithUpdatedParseOptions(null!));
}
[Fact]
public void AnalyzerConfig_Can_Be_Updated()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.RegularPreview;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
string? analyzerOptionsValue = string.Empty;
var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator(ctx =>
{
ctx.RegisterSourceOutput(ctx.AnalyzerConfigOptionsProvider, (spc, p) => p.GlobalOptions.TryGetValue("test", out analyzerOptionsValue));
}));
var builder = ImmutableDictionary<string, string>.Empty.ToBuilder();
builder.Add("test", "value1");
var optionsProvider = new CompilerAnalyzerConfigOptionsProvider(ImmutableDictionary<object, AnalyzerConfigOptions>.Empty, new CompilerAnalyzerConfigOptions(builder.ToImmutable()));
// run the generator once, and check it was passed the configs
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions, optionsProvider: optionsProvider);
driver = driver.RunGenerators(compilation);
Assert.Equal("value1", analyzerOptionsValue);
// clear the results, and re-run
analyzerOptionsValue = null;
driver = driver.RunGenerators(compilation);
Assert.Null(analyzerOptionsValue);
// now update the config
analyzerOptionsValue = null;
builder.Clear();
builder.Add("test", "value2");
var newOptionsProvider = optionsProvider.WithGlobalOptions(new CompilerAnalyzerConfigOptions(builder.ToImmutable()));
driver = driver.WithUpdatedAnalyzerConfigOptions(newOptionsProvider);
// check we ran
driver = driver.RunGenerators(compilation);
Assert.Equal("value2", analyzerOptionsValue);
// replace it with null, and check that it throws
Assert.Throws<ArgumentNullException>(() => driver.WithUpdatedAnalyzerConfigOptions(null!));
}
[Fact]
public void AdditionalText_Can_Be_Replaced()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.RegularPreview;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
InMemoryAdditionalText additionalText1 = new InMemoryAdditionalText("path1.txt", "");
InMemoryAdditionalText additionalText2 = new InMemoryAdditionalText("path2.txt", "");
InMemoryAdditionalText additionalText3 = new InMemoryAdditionalText("path3.txt", "");
List<string?> additionalTextPaths = new List<string?>();
var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator(ctx =>
{
ctx.RegisterSourceOutput(ctx.AdditionalTextsProvider.Select((t, _) => t.Path), (spc, p) => { additionalTextPaths.Add(p); });
}));
// run the generator once and check we saw the additional file
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions, additionalTexts: new[] { additionalText1, additionalText2, additionalText3 });
driver = driver.RunGenerators(compilation);
Assert.Equal(3, additionalTextPaths.Count);
Assert.Equal("path1.txt", additionalTextPaths[0]);
Assert.Equal("path2.txt", additionalTextPaths[1]);
Assert.Equal("path3.txt", additionalTextPaths[2]);
// re-run and check nothing else got added
additionalTextPaths.Clear();
driver = driver.RunGenerators(compilation);
Assert.Empty(additionalTextPaths);
// now, update the additional text, but keep the path the same
additionalTextPaths.Clear();
driver = driver.ReplaceAdditionalText(additionalText2, new InMemoryAdditionalText("path4.txt", ""));
// run, and check that only the replaced file was invoked
driver = driver.RunGenerators(compilation);
Assert.Single(additionalTextPaths);
Assert.Equal("path4.txt", additionalTextPaths[0]);
// replace it with null, and check that it throws
Assert.Throws<ArgumentNullException>(() => driver.ReplaceAdditionalText(additionalText1, null!));
}
[Fact]
public void Replaced_Input_Is_Treated_As_Modified()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.RegularPreview;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
InMemoryAdditionalText additionalText = new InMemoryAdditionalText("path.txt", "abc");
List<string?> additionalTextPaths = new List<string?>();
List<string?> additionalTextsContents = new List<string?>();
var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator(ctx =>
{
var texts = ctx.AdditionalTextsProvider;
var paths = texts.Select((t, _) => t?.Path);
var contents = texts.Select((t, _) => t?.GetText()?.ToString());
ctx.RegisterSourceOutput(paths, (spc, p) => { additionalTextPaths.Add(p); });
ctx.RegisterSourceOutput(contents, (spc, p) => { additionalTextsContents.Add(p); });
}));
// run the generator once and check we saw the additional file
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions, additionalTexts: new[] { additionalText });
driver = driver.RunGenerators(compilation);
Assert.Equal(1, additionalTextPaths.Count);
Assert.Equal("path.txt", additionalTextPaths[0]);
Assert.Equal(1, additionalTextsContents.Count);
Assert.Equal("abc", additionalTextsContents[0]);
// re-run and check nothing else got added
driver = driver.RunGenerators(compilation);
Assert.Equal(1, additionalTextPaths.Count);
Assert.Equal(1, additionalTextsContents.Count);
// now, update the additional text, but keep the path the same
additionalTextPaths.Clear();
additionalTextsContents.Clear();
var secondText = new InMemoryAdditionalText("path.txt", "def");
driver = driver.ReplaceAdditionalText(additionalText, secondText);
// run, and check that only the contents got re-run
driver = driver.RunGenerators(compilation);
Assert.Empty(additionalTextPaths);
Assert.Equal(1, additionalTextsContents.Count);
Assert.Equal("def", additionalTextsContents[0]);
// now replace the text with a different path, but the same text
additionalTextPaths.Clear();
additionalTextsContents.Clear();
var thirdText = new InMemoryAdditionalText("path2.txt", "def");
driver = driver.ReplaceAdditionalText(secondText, thirdText);
// run, and check that only the paths got re-run
driver = driver.RunGenerators(compilation);
Assert.Equal(1, additionalTextPaths.Count);
Assert.Equal("path2.txt", additionalTextPaths[0]);
Assert.Empty(additionalTextsContents);
}
[Theory]
[CombinatorialData]
[InlineData(IncrementalGeneratorOutputKind.Source | IncrementalGeneratorOutputKind.Implementation)]
[InlineData(IncrementalGeneratorOutputKind.Source | IncrementalGeneratorOutputKind.PostInit)]
[InlineData(IncrementalGeneratorOutputKind.Implementation | IncrementalGeneratorOutputKind.PostInit)]
[InlineData(IncrementalGeneratorOutputKind.Source | IncrementalGeneratorOutputKind.Implementation | IncrementalGeneratorOutputKind.PostInit)]
public void Generator_Output_Kinds_Can_Be_Disabled(IncrementalGeneratorOutputKind disabledOutput)
{
var source = @"
class C { }
";
var parseOptions = TestOptions.RegularPreview;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var generator = new PipelineCallbackGenerator(ctx =>
{
ctx.RegisterPostInitializationOutput((context) => context.AddSource("PostInit", ""));
ctx.RegisterSourceOutput(ctx.CompilationProvider, (context, ct) => context.AddSource("Source", ""));
ctx.RegisterImplementationSourceOutput(ctx.CompilationProvider, (context, ct) => context.AddSource("Implementation", ""));
});
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator.AsSourceGenerator() }, driverOptions: new GeneratorDriverOptions(disabledOutput), parseOptions: parseOptions);
driver = driver.RunGenerators(compilation);
var result = driver.GetRunResult();
Assert.Single(result.Results);
Assert.Empty(result.Results[0].Diagnostics);
// verify the expected outputs were generated
// NOTE: adding new output types will cause this test to fail. Update above as needed.
foreach (IncrementalGeneratorOutputKind kind in Enum.GetValues(typeof(IncrementalGeneratorOutputKind)))
{
if (kind == IncrementalGeneratorOutputKind.None)
continue;
if (disabledOutput.HasFlag((IncrementalGeneratorOutputKind)kind))
{
Assert.DoesNotContain(result.Results[0].GeneratedSources, isTextForKind);
}
else
{
Assert.Contains(result.Results[0].GeneratedSources, isTextForKind);
}
bool isTextForKind(GeneratedSourceResult s) => s.HintName == Enum.GetName(typeof(IncrementalGeneratorOutputKind), kind) + ".cs";
}
}
[Fact]
public void Metadata_References_Provider()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.RegularPreview;
var metadataRefs = new[] {
MetadataReference.CreateFromAssemblyInternal(this.GetType().Assembly),
MetadataReference.CreateFromAssemblyInternal(typeof(object).Assembly)
};
Compilation compilation = CreateEmptyCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions, references: metadataRefs);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
List<string?> referenceList = new List<string?>();
var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator(ctx =>
{
ctx.RegisterSourceOutput(ctx.MetadataReferencesProvider, (spc, r) => { referenceList.Add(r.Display); });
}));
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions);
driver = driver.RunGenerators(compilation);
Assert.Equal(referenceList[0], metadataRefs[0].Display);
Assert.Equal(referenceList[1], metadataRefs[1].Display);
// re-run and check we didn't see anything new
referenceList.Clear();
driver = driver.RunGenerators(compilation);
Assert.Empty(referenceList);
// Modify the reference
var modifiedRef = metadataRefs[0].WithAliases(new[] { "Alias " });
metadataRefs[0] = modifiedRef;
compilation = compilation.WithReferences(metadataRefs);
driver = driver.RunGenerators(compilation);
Assert.Single(referenceList, modifiedRef.Display);
}
}
}
| 46.762465 | 256 | 0.64666 | [
"MIT"
] | AlFasGD/roslyn | src/Compilers/CSharp/Test/Semantic/SourceGeneration/GeneratorDriverTests.cs | 99,419 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using WalkingTec.Mvvm.Admin.ViewModels;
using WalkingTec.Mvvm.Core;
using WalkingTec.Mvvm.Core.Auth;
using WalkingTec.Mvvm.Core.Auth.Attribute;
using WalkingTec.Mvvm.Core.Extensions;
using WalkingTec.Mvvm.Mvc;
namespace WalkingTec.Mvvm.Admin.Api
{
[AuthorizeJwtWithCookie]
[ApiController]
[Route("api/_[controller]")]
[Route("api/_login")]
[ActionDescription("Login")]
public class AccountController : BaseApiController
{
private readonly ILogger _logger;
private readonly ITokenService _authService;
public AccountController(
ILogger<AccountController> logger,
ITokenService authService)
{
_logger = logger;
_authService = authService;
}
[AllowAnonymous]
[HttpPost("[action]")]
public async Task<IActionResult> Login([FromForm]string userid, [FromForm]string password, [FromForm]bool rememberLogin = false, [FromForm]bool cookie = true)
{
var user = DC.Set<FrameworkUserBase>()
.Include(x => x.UserRoles)
.Include(x => x.UserGroups)
.Where(x => x.ITCode.ToLower() == userid.ToLower() && x.Password == Utils.GetMD5String(password) && x.IsValid)
.SingleOrDefault();
//如果没有找到则输出错误
if (user == null)
{
return BadRequest(Mvc.Admin.Program._localizer["LoginFailed"].Value);
}
var roleIDs = user.UserRoles.Select(x => x.RoleId).ToList();
var groupIDs = user.UserGroups.Select(x => x.GroupId).ToList();
//查找登录用户的数据权限
var dpris = DC.Set<DataPrivilege>()
.Where(x => x.UserId == user.ID || (x.GroupId != null && groupIDs.Contains(x.GroupId.Value)))
.ToList();
ProcessTreeDp(dpris);
//生成并返回登录用户信息
var rv = new LoginUserInfo();
rv.Id = user.ID;
rv.ITCode = user.ITCode;
rv.Name = user.Name;
rv.Roles = DC.Set<FrameworkRole>().Where(x => user.UserRoles.Select(y => y.RoleId).Contains(x.ID)).ToList();
rv.Groups = DC.Set<FrameworkGroup>().Where(x => user.UserGroups.Select(y => y.GroupId).Contains(x.ID)).ToList();
rv.DataPrivileges = dpris;
//查找登录用户的页面权限
var pris = DC.Set<FunctionPrivilege>()
.Where(x => x.UserId == user.ID || (x.RoleId != null && roleIDs.Contains(x.RoleId.Value)))
.ToList();
rv.FunctionPrivileges = pris;
rv.PhotoId = user.PhotoId;
LoginUserInfo = rv;
if (cookie) // cookie auth
{
AuthenticationProperties properties = null;
if (rememberLogin)
{
properties = new AuthenticationProperties
{
IsPersistent = true,
ExpiresUtc = DateTimeOffset.UtcNow.Add(TimeSpan.FromDays(30))
};
}
var principal = LoginUserInfo.CreatePrincipal();
// 在上面注册AddAuthentication时,指定了默认的Scheme,在这里便可以不再指定Scheme。
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal, properties);
List<SimpleMenu> ms = new List<SimpleMenu>();
LoginUserInfo forapi = new LoginUserInfo();
forapi.Id = LoginUserInfo.Id;
forapi.ITCode = LoginUserInfo.ITCode;
forapi.Name = LoginUserInfo.Name;
forapi.Roles = LoginUserInfo.Roles;
forapi.Groups = LoginUserInfo.Groups;
forapi.PhotoId = LoginUserInfo.PhotoId;
var menus = DC.Set<FunctionPrivilege>()
.Where(x => x.UserId == user.ID || (x.RoleId != null && roleIDs.Contains(x.RoleId.Value)))
.Select(x => x.MenuItem)
.Where(x => x.MethodName == null)
.OrderBy(x=>x.DisplayOrder)
.Select(x => new SimpleMenu
{
Id = x.ID.ToString().ToLower(),
ParentId = x.ParentId.ToString().ToLower(),
Text = x.PageName,
Url = x.Url,
Icon = x.ICon
}).ToList();
LocalizeMenu(menus);
ms.AddRange(menus);
List<string> urls = new List<string>();
urls.AddRange(DC.Set<FunctionPrivilege>()
.Where(x => x.UserId == user.ID || (x.RoleId != null && roleIDs.Contains(x.RoleId.Value)))
.Select(x => x.MenuItem)
.Where(x => x.MethodName != null)
.Select(x => x.Url)
);
urls.AddRange(GlobaInfo.AllModule.Where(x => x.IsApi == true).SelectMany(x => x.Actions).Where(x => (x.IgnorePrivillege == true || x.Module.IgnorePrivillege == true) && x.Url != null).Select(x => x.Url));
forapi.Attributes = new Dictionary<string, object>();
forapi.Attributes.Add("Menus", menus);
forapi.Attributes.Add("Actions", urls);
return Ok(forapi);
}
else // jwt auth
{
var authService = HttpContext.RequestServices.GetService(typeof(ITokenService)) as ITokenService;
var token = await authService.IssueTokenAsync(LoginUserInfo);
return Content(JsonConvert.SerializeObject(token), "application/json");
}
}
private void LocalizeMenu(List<SimpleMenu> menus)
{
if (menus == null)
{
return;
}
//循环所有菜单项
foreach (var menu in menus)
{
if (menu.Text?.StartsWith("MenuKey.") == true)
{
if (Core.Program._Callerlocalizer[menu.Text].ResourceNotFound == true)
{
menu.Text = Core.Program._localizer[menu.Text];
}
else
{
menu.Text = Core.Program._Callerlocalizer[menu.Text];
}
}
}
}
[HttpPost("[action]")]
[AllRights]
[ProducesResponseType(typeof(Token), StatusCodes.Status200OK)]
public async Task<Token> RefreshToken(string refreshToken)
{
return await _authService.RefreshTokenAsync(refreshToken);
}
[AllRights]
[HttpGet("[action]/{id}")]
public IActionResult CheckLogin(Guid? id)
{
if (LoginUserInfo == null || LoginUserInfo?.Id == Guid.Empty)
{
return BadRequest();
}
else
{
var forapi = new LoginUserInfo();
forapi.Id = LoginUserInfo.Id;
forapi.ITCode = LoginUserInfo.ITCode;
forapi.Name = LoginUserInfo.Name;
forapi.Roles = LoginUserInfo.Roles;
forapi.Groups = LoginUserInfo.Groups;
forapi.PhotoId = LoginUserInfo.PhotoId;
var ms = new List<SimpleMenu>();
var roleIDs = LoginUserInfo.Roles.Select(x => x.ID).ToList();
var data = DC.Set<FrameworkMenu>().Where(x => x.MethodName == null).ToList();
var topdata = data.Where(x => x.ParentId == null && x.ShowOnMenu).ToList().FlatTree(x => x.DisplayOrder).Where(x => (x.IsInside == false || x.FolderOnly == true || string.IsNullOrEmpty(x.MethodName)) && x.ShowOnMenu).ToList(); var allowed = DC.Set<FunctionPrivilege>()
.AsNoTracking()
.Where(x => x.UserId == LoginUserInfo.Id || (x.RoleId != null && roleIDs.Contains(x.RoleId.Value)))
.Select(x => new { x.MenuItem.ID, x.MenuItem.Url })
.ToList();
var allowedids = allowed.Select(x => x.ID).ToList();
foreach (var item in topdata)
{
if (allowedids.Contains(item.ID))
{
ms.Add(new SimpleMenu {
Id = item.ID.ToString().ToLower(),
ParentId = item.ParentId?.ToString()?.ToLower(),
Text = item.PageName,
Url = item.Url,
Icon = item.ICon
});
}
}
LocalizeMenu(ms);
List<string> urls = new List<string>();
urls.AddRange(allowed.Select(x=>x.Url).Distinct());
urls.AddRange(GlobaInfo.AllModule.Where(x => x.IsApi == true).SelectMany(x => x.Actions).Where(x => (x.IgnorePrivillege == true || x.Module.IgnorePrivillege == true) && x.Url != null).Select(x => x.Url));
forapi.Attributes = new Dictionary<string, object>();
forapi.Attributes.Add("Menus", ms);
forapi.Attributes.Add("Actions", urls);
return Ok(forapi);
}
}
[AllRights]
[HttpGet("[action]")]
public IActionResult CheckUserInfo()
{
if (LoginUserInfo == null)
{
return BadRequest();
}
else
{
var forapi = new LoginUserInfo();
forapi.Id = LoginUserInfo.Id;
forapi.ITCode = LoginUserInfo.ITCode;
forapi.Name = LoginUserInfo.Name;
forapi.Roles = LoginUserInfo.Roles;
forapi.Groups = LoginUserInfo.Groups;
forapi.PhotoId = LoginUserInfo.PhotoId;
var ms = new List<SimpleMenu>();
var roleIDs = LoginUserInfo.Roles.Select(x => x.ID).ToList();
var data = DC.Set<FrameworkMenu>().Where(x => x.MethodName == null).ToList();
var topdata = data.Where(x => x.ParentId == null && x.ShowOnMenu).ToList().FlatTree(x => x.DisplayOrder).Where(x => (x.IsInside == false || x.FolderOnly == true || string.IsNullOrEmpty(x.MethodName)) && x.ShowOnMenu).ToList();
var allowed = DC.Set<FunctionPrivilege>()
.AsNoTracking()
.Where(x => x.UserId == LoginUserInfo.Id || (x.RoleId != null && roleIDs.Contains(x.RoleId.Value)))
.Select(x => new { x.MenuItem.ID, x.MenuItem.Url })
.ToList();
var allowedids = allowed.Select(x => x.ID).ToList();
foreach (var item in topdata)
{
if (allowedids.Contains(item.ID))
{
ms.Add(new SimpleMenu
{
Id = item.ID.ToString().ToLower(),
ParentId = item.ParentId?.ToString()?.ToLower(),
Text = item.PageName,
Url = item.Url,
Icon = item.ICon
});
}
}
LocalizeMenu(ms);
List<string> urls = new List<string>();
urls.AddRange(allowed.Select(x => x.Url).Distinct());
urls.AddRange(GlobaInfo.AllModule.Where(x => x.IsApi == true).SelectMany(x => x.Actions).Where(x => (x.IgnorePrivillege == true || x.Module.IgnorePrivillege == true) && x.Url != null).Select(x => x.Url));
forapi.Attributes = new Dictionary<string, object>();
forapi.Attributes.Add("Menus", ms);
forapi.Attributes.Add("Actions", urls);
return Ok(forapi);
}
}
[AllRights]
[HttpPost("[action]")]
public IActionResult ChangePassword(ChangePasswordVM vm)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState.GetErrorJson());
}
else
{
vm.DoChange();
if (!ModelState.IsValid)
{
return BadRequest(ModelState.GetErrorJson());
}
else
{
return Ok();
}
}
}
[AllRights]
[HttpGet("[action]/{id}")]
public async Task Logout(Guid? id)
{
HttpContext.Session.Clear();
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
HttpContext.Response.Redirect("/");
}
private void ProcessTreeDp(List<DataPrivilege> dps)
{
var dpsSetting = GlobalServices.GetService<Configs>().DataPrivilegeSettings;
foreach (var ds in dpsSetting)
{
if (typeof(ITreeData).IsAssignableFrom(ds.ModelType))
{
var ids = dps.Where(x => x.TableName == ds.ModelName).Select(x => x.RelateId).ToList();
if (ids.Count > 0 && ids.Contains(null) == false)
{
List<Guid> tempids = new List<Guid>();
foreach (var item in ids)
{
if (Guid.TryParse(item, out Guid g))
{
tempids.Add(g);
}
}
List<Guid> subids = new List<Guid>();
subids.AddRange(GetSubIds(tempids.ToList(), ds.ModelType));
subids = subids.Distinct().ToList();
subids.ForEach(x => dps.Add(new DataPrivilege
{
TableName = ds.ModelName,
RelateId = x.ToString()
}));
}
}
}
}
private IEnumerable<Guid> GetSubIds(List<Guid> p_id, Type modelType)
{
var basequery = DC.GetType().GetTypeInfo().GetMethod("Set").MakeGenericMethod(modelType).Invoke(DC, null) as IQueryable;
var subids = basequery.Cast<ITreeData>().Where(x => p_id.Contains(x.ParentId.Value)).Select(x => x.ID).ToList();
if (subids.Count > 0)
{
return subids.Concat(GetSubIds(subids, modelType));
}
else
{
return new List<Guid>();
}
}
}
public class SimpleMenu
{
public string Id { get; set; }
public string ParentId { get; set; }
public string Text { get; set; }
public string Url { get; set; }
public string Icon { get; set; }
}
}
| 40.777487 | 284 | 0.494062 | [
"MIT"
] | SiberianHuskyL/WTM | src/WalkingTec.Mvvm.Mvc.Admin/ApiControllers/AccountController.cs | 15,729 | C# |
using System;
namespace PipelineExtensions
{
public class GameEditorEvent
{
public int Y { get; set; }
public static GameEditorEvent GetEvent(string typeName)
{
var fullyQualifiedName = $"PipelineExtensions.{typeName}";
var eventType = Type.GetType(fullyQualifiedName);
if (eventType != null)
{
return (GameEditorEvent) Activator.CreateInstance(eventType);
}
return null;
}
}
public class GameEditorGenerate2Choppers : GameEditorEvent
{
public GameEditorGenerate2Choppers() { }
}
public class GameEditorGenerate4Choppers : GameEditorEvent
{
public GameEditorGenerate4Choppers() { }
}
public class GameEditorGenerate6Choppers : GameEditorEvent
{
public GameEditorGenerate6Choppers() { }
}
public class GameEditorStartLevel : GameEditorEvent
{
public GameEditorStartLevel() { }
}
public class GameEditorEndLevel : GameEditorEvent
{
public GameEditorEndLevel() { }
}
}
| 22.632653 | 77 | 0.624887 | [
"MIT"
] | louissalin/gamedev-with-monogame | PipelineExtensions/GameEditorEvent.cs | 1,111 | C# |
using System;
using _10_interface.Models;
namespace _10_interface
{
class Program
{
static void Main(string[] args)
{
Weapon[] weapons = { new Knife(), new Gun(), new LaserGun(), new Bow() };
Player player = new();
foreach (var item in weapons)
{
player.CheckInfo(item);
player.Fire(item);
player.MeleeAttack(item);
Console.WriteLine();
}
player.CheckInfo(new Box());
}
}
}
| 22 | 85 | 0.483636 | [
"MIT"
] | GreedNeSS/Inheritance | 10-interface/Program.cs | 552 | C# |
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Identity;
using ToDoList.Models;
using System.Threading.Tasks;
using ToDoList.ViewModels;
namespace ToDoList.Controllers
{
public class AccountController : Controller
{
private readonly ToDoListContext _db;
private readonly UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signInManager;
public AccountController (UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager, ToDoListContext db)
{
_userManager = userManager;
_signInManager = signInManager;
_db = db;
}
public ActionResult Index()
{
return View();
}
public IActionResult Register()
{
return View();
}
[HttpPost]
public async Task<ActionResult> Register (RegisterViewModel model)
{
var user = new ApplicationUser { UserName = model.Email };
IdentityResult result = await _userManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
return RedirectToAction("Index");
}
else
{
return View();
}
}
public ActionResult Login()
{
return View();
}
[HttpPost]
public async Task<ActionResult> Login(LoginViewModel model)
{
Microsoft.AspNetCore.Identity.SignInResult result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, isPersistent: true, lockoutOnFailure: false);
if (result.Succeeded)
{
return RedirectToAction("Index");
}
else
{
return View();
}
}
[HttpPost]
public async Task<ActionResult> LogOff()
{
await _signInManager.SignOutAsync();
return RedirectToAction("Index");
}
}
} | 24.643836 | 173 | 0.667593 | [
"MIT"
] | chynnalew/ToDoList.Solution | ToDoList/Controllers/AccountController.cs | 1,799 | C# |
using System;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using Diploms.Dto;
using Diploms.Services.Departments;
using Diploms.Requests;
using System.Threading.Tasks;
using Microsoft.Net.Http.Headers;
using System.IO;
namespace Diploms.Controllers
{
[Route("api/documents")]
[Authorize]
public class DocumentsController : Controller
{
private readonly RequestService _service;
public DocumentsController(RequestService service)
{
if (service == null) throw new ArgumentNullException(nameof(service));
_service = service;
}
[HttpPost("latex/preview")]
public async Task<IActionResult> GeneratePreviewLatex([FromBody] string latex)
{
var objectToSend = new {
data = latex
};
byte[] file = System.IO.File.ReadAllBytes( "../../templates/master-thesis.pdf");
//var stream = await _service.SendRequest(objectToSend , false);
return new FileContentResult(file,"application/pdf");
}
[HttpPost("norm-control-doc")]
public async Task<IActionResult> CreateNormControlList([FromBody] NormControlTryResultDto data)
{
var stream = await _service.SendRequest(data);
return new FileStreamResult(stream,"application/pdf");
}
}
} | 32.627907 | 103 | 0.655738 | [
"MIT"
] | denismaster/dcs | src/Diploms.WebUI/Controllers/DocumentController.cs | 1,403 | C# |
using System;
namespace TomatoLog.Server.Models
{
public class ErrorViewModel
{
public string RequestId { get; set; }
public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
}
} | 19.454545 | 70 | 0.672897 | [
"MIT"
] | lamondlu/TomatoLog | TomatoLog.Server/Models/ErrorViewModel.cs | 214 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
namespace Microsoft.AdvocacyPlatform.Contracts
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Twilio = Twilio.Http;
/// <summary>
/// Interface for interacting with an HttpClient wrapper.
/// </summary>
public interface IHttpClientWrapper
{
/// <summary>
/// Initializes the Twilio Client.
/// </summary>
/// <param name="accountSid">The account SID to connect with.</param>
/// <param name="authToken">The auth token to connect with.</param>
void InitTwilioClient(Secret accountSid, Secret authToken);
/// <summary>
/// Returns the wrapped HttpClient.
/// </summary>
/// <returns>The HttpClient instance used to make requests.</returns>
HttpClient GetHttpClient();
/// <summary>
/// Performs a GET request.
/// </summary>
/// <param name="requestUri">The URI to GET.</param>
/// <param name="log">Trace logger instance.</param>
/// <returns>A Task returning the response message.</returns>
Task<HttpResponseMessage> GetAsync(string requestUri, ILogger log);
/// <summary>
/// Performs a GET request.
/// </summary>
/// <param name="requestUri">The URI to GET.</param>
/// <param name="log">Trace logger instance.</param>
/// <returns>A Task returning the response as a stream.</returns>
Task<Stream> GetStreamAsync(string requestUri, ILogger log);
/// <summary>
/// Performs a POST request.
/// </summary>
/// <param name="requestUri">The URI to POST to.</param>
/// <param name="content">The content of the request.</param>
/// <param name="log">Trace logging instance.</param>
/// <returns>A Task returning the response message.</returns>
Task<HttpResponseMessage> PostAsync(string requestUri, HttpContent content, ILogger log);
}
}
| 37.793103 | 97 | 0.620894 | [
"MIT"
] | Bhaskers-Blu-Org2/AdvocacyPlatform | API/Microsoft.AdvocacyPlatform.Contracts/Interface/IHttpClientWrapper.cs | 2,194 | C# |
#region S# License
/******************************************************************************************
NOTICE!!! This program and source code is owned and licensed by
StockSharp, LLC, www.stocksharp.com
Viewing or use of this code requires your acceptance of the license
agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE
Removal of this comment is a violation of the license agreement.
Project: SampleHistoryTesting.SampleHistoryTestingPublic
File: SmaStrategy.cs
Created: 2015, 11, 11, 2:32 PM
Copyright 2010 by StockSharp, LLC
*******************************************************************************************/
#endregion S# License
namespace SampleHistoryTesting
{
using System.Linq;
using System.Collections.Generic;
using System.Drawing;
using Ecng.Common;
using StockSharp.Algo;
using StockSharp.Algo.Candles;
using StockSharp.Algo.Indicators;
using StockSharp.Algo.Strategies;
using StockSharp.Logging;
using StockSharp.BusinessEntities;
using StockSharp.Messages;
using StockSharp.Localization;
using StockSharp.Charting;
class SmaStrategy : Strategy
{
private IChart _chart;
private IChartCandleElement _candlesElem;
private IChartTradeElement _tradesElem;
private IChartIndicatorElement _shortElem;
private IChartIndicatorElement _longElem;
private readonly List<MyTrade> _myTrades = new();
private readonly Subscription _series;
private bool? _isShortLessThenLong;
public SmaStrategy(CandleSeries series)
{
_series = new Subscription(series);
}
public SimpleMovingAverage LongSma { get; } = new();
public SimpleMovingAverage ShortSma { get; } = new();
protected override void OnStarted()
{
_chart = this.GetChart();
if (_chart is not null)
{
// creates chart's components in his own thread
_chart.ThreadDispatcher.Invoke(() =>
{
var area = _chart.CreateArea();
_chart.AddArea(area);
_candlesElem = _chart.CreateCandleElement();
_candlesElem.ShowAxisMarker = false;
_chart.AddElement(area, _candlesElem);
_tradesElem = _chart.CreateTradeElement();
_tradesElem.FullTitle = LocalizedStrings.Str985;
_chart.AddElement(area, _tradesElem);
_shortElem = _chart.CreateIndicatorElement();
_shortElem.Color = Color.Coral;
_shortElem.ShowAxisMarker = false;
_shortElem.FullTitle = ShortSma.ToString();
_chart.AddElement(area, _shortElem);
_longElem = _chart.CreateIndicatorElement();
_longElem.ShowAxisMarker = false;
_longElem.FullTitle = LongSma.ToString();
_chart.AddElement(area, _longElem);
});
}
this
.WhenCandlesFinished(_series.CandleSeries)
.Do(ProcessCandle)
.Apply(this);
this
.WhenNewMyTrade()
.Do(trade => _myTrades.Add(trade))
.Apply(this);
_isShortLessThenLong = null;
Subscribe(_series);
base.OnStarted();
}
private void ProcessCandle(Candle candle)
{
// strategy are stopping
if (ProcessState == ProcessStates.Stopping)
{
CancelActiveOrders();
return;
}
this.AddInfoLog(LocalizedStrings.Str3634Params.Put(candle.OpenTime, candle.OpenPrice, candle.HighPrice, candle.LowPrice, candle.ClosePrice, candle.TotalVolume, candle.Security));
// process new candle
var longValue = LongSma.Process(candle);
var shortValue = ShortSma.Process(candle);
if (LongSma.IsFormed && ShortSma.IsFormed)
{
// calc new values for short and long
var isShortLessThenLong = ShortSma.GetCurrentValue() < LongSma.GetCurrentValue();
if (_isShortLessThenLong == null)
{
_isShortLessThenLong = isShortLessThenLong;
}
else if (_isShortLessThenLong != isShortLessThenLong) // crossing happened
{
// if short less than long, the sale, otherwise buy
var direction = isShortLessThenLong ? Sides.Sell : Sides.Buy;
// calc size for open position or revert
var volume = Position == 0 ? Volume : Position.Abs().Min(Volume) * 2;
// calc order price as a close price + offset
var price = candle.ClosePrice + ((direction == Sides.Buy ? Security.PriceStep : -Security.PriceStep) ?? 1);
RegisterOrder(this.CreateOrder(direction, price, volume));
// or revert position via market quoting
//var strategy = new MarketQuotingStrategy(direction, volume);
//ChildStrategies.Add(strategy);
// store current values for short and long
_isShortLessThenLong = isShortLessThenLong;
}
}
var trade = _myTrades.FirstOrDefault();
_myTrades.Clear();
if (_chart == null)
return;
var data = _chart.CreateData();
data
.Group(candle.OpenTime)
.Add(_candlesElem, candle)
.Add(_shortElem, shortValue)
.Add(_longElem, longValue)
.Add(_tradesElem, trade);
_chart.Draw(data);
}
}
} | 28.420118 | 181 | 0.690194 | [
"Apache-2.0"
] | chenghuasheng/StockSharp | Samples/Testing/SampleHistoryTesting/SmaStrategy.cs | 4,803 | C# |
using Xunit;
namespace Exercism.TestRunner.CSharp.IntegrationTests
{
public class TestRunnerTests
{
[Theory]
[TestSolutionsData]
public void SolutionIsTestedCorrectly(TestSolution solution)
{
var testRun = TestSolutionRunner.Run(solution);
Assert.Equal(testRun.Expected.NormalizeJson(), testRun.Actual.NormalizeJson());
}
}
} | 26.8 | 91 | 0.664179 | [
"MIT"
] | jrr/csharp-test-runner | test/Exercism.TestRunner.CSharp.IntegrationTests/TestRunnerTests.cs | 402 | C# |
using ClientCore;
using ClientCore.CnCNet5;
using DTAClient.Domain;
using DTAClient.DXGUI.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Rampastring.Tools;
using Rampastring.XNAUI;
using System;
using System.Diagnostics;
using System.IO;
using System.Security.Principal;
using System.Windows.Forms;
namespace DTAClient.DXGUI
{
/// <summary>
/// The main class for the game. Sets up asset search paths
/// and initializes components.
/// </summary>
public class GameClass : Game
{
public GameClass()
{
graphics = new GraphicsDeviceManager(this);
graphics.SynchronizeWithVerticalRetrace = false;
#if !XNA
graphics.HardwareModeSwitch = false;
#endif
content = new ContentManager(Services);
}
private static GraphicsDeviceManager graphics;
ContentManager content;
protected override void Initialize()
{
Logger.Log("Initializing GameClass.");
string windowTitle = ClientConfiguration.Instance.WindowTitle;
Window.Title = string.IsNullOrEmpty(windowTitle) ?
string.Format("{0} Client", MainClientConstants.GAME_NAME_SHORT) : windowTitle;
base.Initialize();
string primaryNativeCursorPath = ProgramConstants.GetResourcePath() + "cursor.cur";
string alternativeNativeCursorPath = ProgramConstants.GetBaseResourcePath() + "cursor.cur";
AssetLoader.Initialize(GraphicsDevice, content);
AssetLoader.AssetSearchPaths.Add(ProgramConstants.GetResourcePath());
AssetLoader.AssetSearchPaths.Add(ProgramConstants.GetBaseResourcePath());
AssetLoader.AssetSearchPaths.Add(ProgramConstants.GamePath);
#if !XNA && !WINDOWSGL
// Try to create and load a texture to check for MonoGame 3.7.1 compatibility
try
{
Texture2D texture = new Texture2D(GraphicsDevice, 100, 100, false, SurfaceFormat.Color);
Color[] colorArray = new Color[100 * 100];
texture.SetData(colorArray);
UISettings.ActiveSettings.CheckBoxClearTexture = AssetLoader.LoadTextureUncached("checkBoxClear.png");
}
catch (Exception ex)
{
if (ex.Message.Contains("DeviceRemoved"))
{
Logger.Log("Creating texture on startup failed! Creating .dxfail file and re-launching client launcher.");
if (!Directory.Exists(ProgramConstants.GamePath + "Client"))
Directory.CreateDirectory(ProgramConstants.GamePath + "Client");
// Create .dxfail file that the launcher can check for this error
// and handle it by redirecting the user to the XNA version instead
File.WriteAllBytes(ProgramConstants.GamePath + "Client" + Path.DirectorySeparatorChar + ".dxfail",
new byte[] { 1 });
string launcherExe = ClientConfiguration.Instance.LauncherExe;
if (string.IsNullOrEmpty(launcherExe))
{
// LauncherExe is unspecified, just throw the exception forward
// because we can't handle it
Logger.Log("No LauncherExe= specified in ClientDefinitions.ini! " +
"Forwarding exception to regular exception handler.");
throw ex;
}
else
{
Logger.Log("Starting " + launcherExe + " and exiting.");
Process.Start(ProgramConstants.GamePath + launcherExe);
Environment.Exit(0);
}
}
}
#endif
InitializeUISettings();
WindowManager wm = new WindowManager(this, graphics);
wm.Initialize(content, ProgramConstants.GetBaseResourcePath());
SetGraphicsMode(wm);
wm.SetIcon(ProgramConstants.GetBaseResourcePath() + "clienticon.ico");
wm.SetControlBox(true);
wm.Cursor.Textures = new Texture2D[]
{
AssetLoader.LoadTexture("cursor.png"),
AssetLoader.LoadTexture("waitCursor.png")
};
if (File.Exists(primaryNativeCursorPath))
wm.Cursor.LoadNativeCursor(primaryNativeCursorPath);
else if (File.Exists(alternativeNativeCursorPath))
wm.Cursor.LoadNativeCursor(alternativeNativeCursorPath);
Components.Add(wm);
string playerName = UserINISettings.Instance.PlayerName.Value.Trim();
if (UserINISettings.Instance.AutoRemoveUnderscoresFromName)
{
while (playerName.EndsWith("_"))
playerName = playerName.Substring(0, playerName.Length - 1);
}
if (string.IsNullOrEmpty(playerName))
{
playerName = WindowsIdentity.GetCurrent().Name;
playerName = playerName.Substring(playerName.IndexOf("\\") + 1);
}
playerName = Renderer.GetSafeString(NameValidator.GetValidOfflineName(playerName), 0);
ProgramConstants.PLAYERNAME = playerName;
UserINISettings.Instance.PlayerName.Value = playerName;
LoadingScreen ls = new LoadingScreen(wm);
wm.AddAndInitializeControl(ls);
ls.ClientRectangle = new Rectangle((wm.RenderResolutionX - ls.Width) / 2,
(wm.RenderResolutionY - ls.Height) / 2, ls.Width, ls.Height);
}
private void InitializeUISettings()
{
UISettings settings = new UISettings();
settings.AltColor = AssetLoader.GetColorFromString(ClientConfiguration.Instance.AltUIColor);
settings.SubtleTextColor = AssetLoader.GetColorFromString(ClientConfiguration.Instance.UIHintTextColor);
settings.ButtonTextColor = settings.AltColor;
settings.ButtonHoverColor = AssetLoader.GetColorFromString(ClientConfiguration.Instance.ButtonHoverColor);
settings.TextColor = AssetLoader.GetColorFromString(ClientConfiguration.Instance.UILabelColor);
//settings.WindowBorderColor = AssetLoader.GetColorFromString(ClientConfiguration.Instance.WindowBorderColor);
settings.PanelBorderColor = AssetLoader.GetColorFromString(ClientConfiguration.Instance.PanelBorderColor);
settings.BackgroundColor = AssetLoader.GetColorFromString(ClientConfiguration.Instance.AltUIBackgroundColor);
settings.FocusColor = AssetLoader.GetColorFromString(ClientConfiguration.Instance.ListBoxFocusColor);
settings.DisabledItemColor = AssetLoader.GetColorFromString(ClientConfiguration.Instance.DisabledButtonColor);
settings.DefaultAlphaRate = ClientConfiguration.Instance.DefaultAlphaRate;
settings.CheckBoxAlphaRate = ClientConfiguration.Instance.CheckBoxAlphaRate;
settings.CheckBoxClearTexture = AssetLoader.LoadTexture("checkBoxClear.png");
settings.CheckBoxCheckedTexture = AssetLoader.LoadTexture("checkBoxChecked.png");
settings.CheckBoxDisabledClearTexture = AssetLoader.LoadTexture("checkBoxClearD.png");
settings.CheckBoxDisabledCheckedTexture = AssetLoader.LoadTexture("checkBoxCheckedD.png");
UISettings.ActiveSettings = settings;
}
/// <summary>
/// Sets the client's graphics mode.
/// TODO move to some helper class?
/// </summary>
/// <param name="wm">The window manager</param>
public static void SetGraphicsMode(WindowManager wm)
{
int windowWidth = UserINISettings.Instance.ClientResolutionX;
int windowHeight = UserINISettings.Instance.ClientResolutionY;
bool borderlessWindowedClient = UserINISettings.Instance.BorderlessWindowedClient;
if (Screen.PrimaryScreen.Bounds.Width >= windowWidth && Screen.PrimaryScreen.Bounds.Height >= windowHeight)
{
if (!wm.InitGraphicsMode(windowWidth, windowHeight, false))
throw new GraphicsModeInitializationException("Setting graphics mode failed! " + windowWidth + "x" + windowHeight);
}
else
{
if (!wm.InitGraphicsMode(1024, 600, false))
throw new GraphicsModeInitializationException("Setting default graphics mode failed!");
}
int renderResolutionX = Math.Max(windowWidth, ClientConfiguration.Instance.MinimumRenderWidth);
int renderResolutionY = Math.Max(windowHeight, ClientConfiguration.Instance.MinimumRenderHeight);
renderResolutionX = Math.Min(renderResolutionX, ClientConfiguration.Instance.MaximumRenderWidth);
renderResolutionY = Math.Min(renderResolutionY, ClientConfiguration.Instance.MaximumRenderHeight);
wm.SetBorderlessMode(borderlessWindowedClient);
#if !XNA
if (borderlessWindowedClient)
{
graphics.IsFullScreen = true;
graphics.ApplyChanges();
}
#endif
wm.CenterOnScreen();
wm.SetRenderResolution(renderResolutionX, renderResolutionY);
}
}
/// <summary>
/// An exception that is thrown when initializing display / graphics mode fails.
/// </summary>
class GraphicsModeInitializationException : Exception
{
public GraphicsModeInitializationException(string message) : base(message)
{
}
}
}
| 43.782609 | 136 | 0.622542 | [
"MIT"
] | 0999312/xna-cncnet-client | DXMainClient/DXGUI/GameClass.cs | 9,843 | C# |
using DSharpPlus.Entities;
using System;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
namespace DSharpPlus.SlashCommands
{
/// <summary>
/// Represents a context for an interaction
/// </summary>
public sealed class InteractionContext
{
/// <summary>
/// Gets the interaction that was created
/// </summary>
public DiscordInteraction Interaction { get; internal set; }
/// <summary>
/// Gets the client for this interaction
/// </summary>
public DiscordClient Client { get; internal set; }
/// <summary>
/// Gets the guild this interaction was executed in
/// </summary>
public DiscordGuild Guild { get; internal set; }
/// <summary>
/// Gets the channel this interaction was executed in
/// </summary>
public DiscordChannel Channel { get; internal set; }
/// <summary>
/// Gets the user which executed this interaction
/// </summary>
public DiscordUser User { get; internal set; }
/// <summary>
/// Gets the member which executed this interaction, or null if the command is in a DM
/// </summary>
public DiscordMember Member
=> this.User is DiscordMember member ? member : null;
/// <summary>
/// Gets the slash command module this interaction was created in
/// </summary>
public SlashCommandsExtension SlashCommandsExtension { get; internal set; }
/// <summary>
/// Gets the token for this interaction
/// </summary>
public string Token { get; internal set; }
/// <summary>
/// Gets the id for this interaction
/// </summary>
public ulong InteractionId { get; internal set; }
/// <summary>
/// Gets the name of the command
/// </summary>
public string CommandName { get; internal set; }
/// <summary>
/// <para>Gets the service provider.</para>
/// <para>This allows passing data around without resorting to static members.</para>
/// <para>Defaults to null.</para>
/// </summary>
public IServiceProvider Services { get; internal set; } = new ServiceCollection().BuildServiceProvider(true);
/// <summary>
/// Creates a response to this interaction
/// <para>You must create a response within 3 seconds of this interaction being executed; if the command has the potential to take more than 3 seconds, create a <see cref="InteractionResponseType.DeferredChannelMessageWithSource"/> at the start, and edit the response later</para>
/// </summary>
/// <param name="type">The type of the response</param>
/// <param name="builder">The data to be sent, if any</param>
/// <returns></returns>
public async Task CreateResponseAsync(InteractionResponseType type, DiscordInteractionResponseBuilder builder = null)
{
await Interaction.CreateResponseAsync(type, builder);
}
/// <summary>
/// Edits the interaction response
/// </summary>
/// <param name="builder">The data to edit the response with</param>
/// <returns></returns>
public async Task<DiscordMessage> EditResponseAsync(DiscordWebhookBuilder builder)
{
return await Interaction.EditOriginalResponseAsync(builder);
}
/// <summary>
/// Deletes the interaction response
/// </summary>
/// <returns></returns>
public async Task DeleteResponseAsync()
{
await Interaction.DeleteOriginalResponseAsync();
}
/// <summary>
/// Creates a follow up message to the interaction
/// </summary>
/// <param name="builder">The message to be sent, in the form of a webhook</param>
/// <returns>The created message</returns>
public async Task<DiscordMessage> FollowUpAsync(DiscordFollowupMessageBuilder builder)
{
return await Interaction.CreateFollowupMessageAsync(builder);
}
/// <summary>
/// Edits a followup message
/// </summary>
/// <param name="followupMessageId">The id of the followup message to edit</param>
/// <param name="builder">The webhook builder</param>
/// <returns></returns>
public async Task<DiscordMessage> EditFollowupAsync(ulong followupMessageId, DiscordWebhookBuilder builder)
{
return await Interaction.EditFollowupMessageAsync(followupMessageId, builder);
}
/// <summary>
/// Deletes a followup message
/// </summary>
/// <param name="followupMessageId">The id of the followup message to delete</param>
/// <returns></returns>
public async Task DeleteFollowupAsync(ulong followupMessageId)
{
await Interaction.DeleteFollowupMessageAsync(followupMessageId);
}
}
} | 38.052632 | 288 | 0.611737 | [
"MIT"
] | VelvetThePanda/DSharpPlus.SlashCommands | InteractionContext.cs | 5,063 | C# |
/*
* NeutrinoAPI.PCL
*
* This file was automatically generated for NeutrinoAPI by APIMATIC v2.0 ( https://apimatic.io ).
*/
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json.Converters;
using NeutrinoAPI;
using NeutrinoAPI.Utilities;
using NeutrinoAPI.Http.Request;
using NeutrinoAPI.Http.Response;
using NeutrinoAPI.Http.Client;
using NeutrinoAPI.Exceptions;
namespace NeutrinoAPI.Controllers
{
public partial class WWW: BaseController, IWWW
{
#region Singleton Pattern
//private static variables for the singleton pattern
private static object syncObject = new object();
private static WWW instance = null;
/// <summary>
/// Singleton pattern implementation
/// </summary>
internal static WWW Instance
{
get
{
lock (syncObject)
{
if (null == instance)
{
instance = new WWW();
}
}
return instance;
}
}
#endregion Singleton Pattern
/// <summary>
/// Parse, analyze and retrieve content from the supplied URL. See: https://www.neutrinoapi.com/api/url-info/
/// </summary>
/// <param name="url">Required parameter: The URL to probe</param>
/// <param name="fetchContent">Optional parameter: If this URL responds with html, text, json or xml then return the response. This option is useful if you want to perform further processing on the URL content (e.g. with the HTML Extract or HTML Clean APIs)</param>
/// <param name="ignoreCertificateErrors">Optional parameter: Ignore any TLS/SSL certificate errors and load the URL anyway</param>
/// <param name="timeout">Optional parameter: Timeout in seconds. Give up if still trying to load the URL after this number of seconds</param>
/// <return>Returns the Models.URLInfoResponse response from the API call</return>
public Models.URLInfoResponse URLInfo(
string url,
bool? fetchContent = false,
bool? ignoreCertificateErrors = false,
int? timeout = 20)
{
Task<Models.URLInfoResponse> t = URLInfoAsync(url, fetchContent, ignoreCertificateErrors, timeout);
APIHelper.RunTaskSynchronously(t);
return t.Result;
}
/// <summary>
/// Parse, analyze and retrieve content from the supplied URL. See: https://www.neutrinoapi.com/api/url-info/
/// </summary>
/// <param name="url">Required parameter: The URL to probe</param>
/// <param name="fetchContent">Optional parameter: If this URL responds with html, text, json or xml then return the response. This option is useful if you want to perform further processing on the URL content (e.g. with the HTML Extract or HTML Clean APIs)</param>
/// <param name="ignoreCertificateErrors">Optional parameter: Ignore any TLS/SSL certificate errors and load the URL anyway</param>
/// <param name="timeout">Optional parameter: Timeout in seconds. Give up if still trying to load the URL after this number of seconds</param>
/// <return>Returns the Models.URLInfoResponse response from the API call</return>
public async Task<Models.URLInfoResponse> URLInfoAsync(
string url,
bool? fetchContent = false,
bool? ignoreCertificateErrors = false,
int? timeout = 20)
{
//the base uri for api requests
string _baseUri = Configuration.GetBaseURI();
//prepare query string for API call
StringBuilder _queryBuilder = new StringBuilder(_baseUri);
_queryBuilder.Append("/url-info");
//process optional query parameters
APIHelper.AppendUrlWithQueryParameters(_queryBuilder, new Dictionary<string, object>()
{
{ "user-id", Configuration.UserId },
{ "api-key", Configuration.ApiKey }
},ArrayDeserializationFormat,ParameterSeparator);
//validate and preprocess url
string _queryUrl = APIHelper.CleanUrl(_queryBuilder);
//append request with appropriate headers and parameters
var _headers = new Dictionary<string,string>()
{
{ "user-agent", "APIMATIC 2.0" },
{ "accept", "application/json" }
};
//append form/field parameters
var _fields = new List<KeyValuePair<string, Object>>()
{
new KeyValuePair<string, object>( "output-case", "camel" ),
new KeyValuePair<string, object>( "url", url ),
new KeyValuePair<string, object>( "fetch-content", (null != fetchContent) ? fetchContent : false ),
new KeyValuePair<string, object>( "ignore-certificate-errors", (null != ignoreCertificateErrors) ? ignoreCertificateErrors : false ),
new KeyValuePair<string, object>( "timeout", (null != timeout) ? timeout : 20 )
};
//remove null parameters
_fields = _fields.Where(kvp => kvp.Value != null).ToList();
//prepare the API call request to fetch the response
HttpRequest _request = ClientInstance.Post(_queryUrl, _headers, _fields);
//invoke request and get response
HttpStringResponse _response = (HttpStringResponse) await ClientInstance.ExecuteAsStringAsync(_request).ConfigureAwait(false);
HttpContext _context = new HttpContext(_request,_response);
//handle errors defined at the API level
base.ValidateResponse(_response, _context);
try
{
return APIHelper.JsonDeserialize<Models.URLInfoResponse>(_response.Body);
}
catch (Exception _ex)
{
throw new APIException("Failed to parse the response: " + _ex.Message, _context);
}
}
/// <summary>
/// Clean and sanitize untrusted HTML. See: https://www.neutrinoapi.com/api/html-clean/
/// </summary>
/// <param name="content">Required parameter: The HTML content. This can be either a URL to load HTML from or an actual HTML content string</param>
/// <param name="outputType">Required parameter: The level of sanitization, possible values are: <b>plain-text</b>: reduce the content to plain text only (no HTML tags at all) <b>simple-text</b>: allow only very basic text formatting tags like b, em, i, strong, u <b>basic-html</b>: allow advanced text formatting and hyper links <b>basic-html-with-images</b>: same as basic html but also allows image tags <b>advanced-html</b>: same as basic html with images but also allows many more common HTML tags like table, ul, dl, pre</param>
/// <return>Returns the Stream response from the API call</return>
public Stream HTMLClean(string content, string outputType)
{
Task<Stream> t = HTMLCleanAsync(content, outputType);
APIHelper.RunTaskSynchronously(t);
return t.Result;
}
/// <summary>
/// Clean and sanitize untrusted HTML. See: https://www.neutrinoapi.com/api/html-clean/
/// </summary>
/// <param name="content">Required parameter: The HTML content. This can be either a URL to load HTML from or an actual HTML content string</param>
/// <param name="outputType">Required parameter: The level of sanitization, possible values are: <b>plain-text</b>: reduce the content to plain text only (no HTML tags at all) <b>simple-text</b>: allow only very basic text formatting tags like b, em, i, strong, u <b>basic-html</b>: allow advanced text formatting and hyper links <b>basic-html-with-images</b>: same as basic html but also allows image tags <b>advanced-html</b>: same as basic html with images but also allows many more common HTML tags like table, ul, dl, pre</param>
/// <return>Returns the Stream response from the API call</return>
public async Task<Stream> HTMLCleanAsync(string content, string outputType)
{
//the base uri for api requests
string _baseUri = Configuration.GetBaseURI();
//prepare query string for API call
StringBuilder _queryBuilder = new StringBuilder(_baseUri);
_queryBuilder.Append("/html-clean");
//process optional query parameters
APIHelper.AppendUrlWithQueryParameters(_queryBuilder, new Dictionary<string, object>()
{
{ "user-id", Configuration.UserId },
{ "api-key", Configuration.ApiKey }
},ArrayDeserializationFormat,ParameterSeparator);
//validate and preprocess url
string _queryUrl = APIHelper.CleanUrl(_queryBuilder);
//append request with appropriate headers and parameters
var _headers = new Dictionary<string,string>()
{
{ "user-agent", "APIMATIC 2.0" }
};
//append form/field parameters
var _fields = new List<KeyValuePair<string, Object>>()
{
new KeyValuePair<string, object>( "content", content ),
new KeyValuePair<string, object>( "output-type", outputType )
};
//remove null parameters
_fields = _fields.Where(kvp => kvp.Value != null).ToList();
//prepare the API call request to fetch the response
HttpRequest _request = ClientInstance.Post(_queryUrl, _headers, _fields);
//invoke request and get response
HttpResponse _response = await ClientInstance.ExecuteAsBinaryAsync(_request).ConfigureAwait(false);
HttpContext _context = new HttpContext(_request,_response);
//handle errors defined at the API level
base.ValidateResponse(_response, _context);
try
{
return _response.RawBody;
}
catch (Exception _ex)
{
throw new APIException("Failed to parse the response: " + _ex.Message, _context);
}
}
/// <summary>
/// Browser bot can extract content, interact with keyboard and mouse events, and execute JavaScript on a website. See: https://www.neutrinoapi.com/api/browser-bot/
/// </summary>
/// <param name="url">Required parameter: The URL to load</param>
/// <param name="timeout">Optional parameter: Timeout in seconds. Give up if still trying to load the page after this number of seconds</param>
/// <param name="delay">Optional parameter: Delay in seconds to wait before capturing any page data, executing selectors or JavaScript</param>
/// <param name="selector">Optional parameter: Extract content from the page DOM using this selector. Commonly known as a CSS selector, you can find a good reference <a href="https://www.w3schools.com/cssref/css_selectors.asp">here</a></param>
/// <param name="exec">Optional parameter: Execute JavaScript on the page. Each array element should contain a valid JavaScript statement in string form. If a statement returns any kind of value it will be returned in the 'exec-results' response. For your convenience you can also use the following special shortcut functions: <div> sleep(seconds); Just wait/sleep for the specified number of seconds. click('selector'); Click on the first element matching the given selector. focus('selector'); Focus on the first element matching the given selector. keys('characters'); Send the specified keyboard characters. Use click() or focus() first to send keys to a specific element. enter(); Send the Enter key. tab(); Send the Tab key. </div> Example: <div> [ "click('#button-id')", "sleep(1)", "click('.field-class')", "keys('1234')", "enter()" ] </div></param>
/// <param name="userAgent">Optional parameter: Override the browsers default user-agent string with this one</param>
/// <param name="ignoreCertificateErrors">Optional parameter: Ignore any TLS/SSL certificate errors and load the page anyway</param>
/// <return>Returns the Models.BrowserBotResponse response from the API call</return>
public Models.BrowserBotResponse BrowserBot(
string url,
int? timeout = 30,
int? delay = 3,
string selector = null,
List<string> exec = null,
string userAgent = null,
bool? ignoreCertificateErrors = false)
{
Task<Models.BrowserBotResponse> t = BrowserBotAsync(url, timeout, delay, selector, exec, userAgent, ignoreCertificateErrors);
APIHelper.RunTaskSynchronously(t);
return t.Result;
}
/// <summary>
/// Browser bot can extract content, interact with keyboard and mouse events, and execute JavaScript on a website. See: https://www.neutrinoapi.com/api/browser-bot/
/// </summary>
/// <param name="url">Required parameter: The URL to load</param>
/// <param name="timeout">Optional parameter: Timeout in seconds. Give up if still trying to load the page after this number of seconds</param>
/// <param name="delay">Optional parameter: Delay in seconds to wait before capturing any page data, executing selectors or JavaScript</param>
/// <param name="selector">Optional parameter: Extract content from the page DOM using this selector. Commonly known as a CSS selector, you can find a good reference <a href="https://www.w3schools.com/cssref/css_selectors.asp">here</a></param>
/// <param name="exec">Optional parameter: Execute JavaScript on the page. Each array element should contain a valid JavaScript statement in string form. If a statement returns any kind of value it will be returned in the 'exec-results' response. For your convenience you can also use the following special shortcut functions: <div> sleep(seconds); Just wait/sleep for the specified number of seconds. click('selector'); Click on the first element matching the given selector. focus('selector'); Focus on the first element matching the given selector. keys('characters'); Send the specified keyboard characters. Use click() or focus() first to send keys to a specific element. enter(); Send the Enter key. tab(); Send the Tab key. </div> Example: <div> [ "click('#button-id')", "sleep(1)", "click('.field-class')", "keys('1234')", "enter()" ] </div></param>
/// <param name="userAgent">Optional parameter: Override the browsers default user-agent string with this one</param>
/// <param name="ignoreCertificateErrors">Optional parameter: Ignore any TLS/SSL certificate errors and load the page anyway</param>
/// <return>Returns the Models.BrowserBotResponse response from the API call</return>
public async Task<Models.BrowserBotResponse> BrowserBotAsync(
string url,
int? timeout = 30,
int? delay = 3,
string selector = null,
List<string> exec = null,
string userAgent = null,
bool? ignoreCertificateErrors = false)
{
//the base uri for api requests
string _baseUri = Configuration.GetBaseURI();
//prepare query string for API call
StringBuilder _queryBuilder = new StringBuilder(_baseUri);
_queryBuilder.Append("/browser-bot");
//process optional query parameters
APIHelper.AppendUrlWithQueryParameters(_queryBuilder, new Dictionary<string, object>()
{
{ "user-id", Configuration.UserId },
{ "api-key", Configuration.ApiKey }
},ArrayDeserializationFormat,ParameterSeparator);
//validate and preprocess url
string _queryUrl = APIHelper.CleanUrl(_queryBuilder);
//append request with appropriate headers and parameters
var _headers = new Dictionary<string,string>()
{
{ "user-agent", "APIMATIC 2.0" },
{ "accept", "application/json" }
};
//append form/field parameters
var _fields = new List<KeyValuePair<string, Object>>()
{
new KeyValuePair<string, object>( "output-case", "camel" ),
new KeyValuePair<string, object>( "url", url ),
new KeyValuePair<string, object>( "timeout", (null != timeout) ? timeout : 30 ),
new KeyValuePair<string, object>( "delay", (null != delay) ? delay : 3 ),
new KeyValuePair<string, object>( "selector", selector ),
new KeyValuePair<string, object>( "user-agent", userAgent ),
new KeyValuePair<string, object>( "ignore-certificate-errors", (null != ignoreCertificateErrors) ? ignoreCertificateErrors : false )
};
_fields.AddRange(APIHelper.PrepareFormFieldsFromObject("exec", exec, arrayDeserializationFormat: ArrayDeserializationFormat));
//remove null parameters
_fields = _fields.Where(kvp => kvp.Value != null).ToList();
//prepare the API call request to fetch the response
HttpRequest _request = ClientInstance.Post(_queryUrl, _headers, _fields);
//invoke request and get response
HttpStringResponse _response = (HttpStringResponse) await ClientInstance.ExecuteAsStringAsync(_request).ConfigureAwait(false);
HttpContext _context = new HttpContext(_request,_response);
//handle errors defined at the API level
base.ValidateResponse(_response, _context);
try
{
return APIHelper.JsonDeserialize<Models.BrowserBotResponse>(_response.Body);
}
catch (Exception _ex)
{
throw new APIException("Failed to parse the response: " + _ex.Message, _context);
}
}
}
} | 58.551724 | 866 | 0.62662 | [
"MIT"
] | NeutrinoAPI/NeutrinoAPI-CSharp | NeutrinoAPI.PCL/Controllers/WWW.cs | 18,678 | C# |
/* --------------------------------------------------------------------------------------------------------------------
* AUDIO-GALLERY-SUITE
* --------------------------------------------------------------------------------------------------------------------
* Author: Robin Rizvi
* Email: mail@robinrizvi.info
* Website: http://robinrizvi.info/
* Blog: http://blog.robinrizvi.info/
* Copyright: Copyright © 2012, Robin Rizvi
* License: MIT (http://www.opensource.org/licenses/MIT)
* This attribution (header-comment) should remain intact while using, distributing or modifying the source in any way
* -------------------------------------------------------------------------------------------------------------------
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using audiogallery.Properties;
using System.Data;
using MySql.Data;
using MySql.Data.MySqlClient;
using System.Net;
using System.IO;
using System.Collections;
using System.Text.RegularExpressions;
namespace audiogallery
{
public class FtpListing
{
#region Constructor
public FtpListing()
{
}
#endregion
# region Private Members
private string _fileName = string.Empty; // Represents the filename without extension
private string _fileExtension = string.Empty; // Represents the file extension
private string _path = string.Empty; // Represents the complete path
private DirectoryEntryType _fileType; // Represents if the current listing represents a file/directory.
private long _size; // Represents the size.
private DateTime _fileDateTime; // DateTime of file/Directory
private string _permissions; // Permissions on the directory
private string _fullName; // Represents FileName with extension
IFormatProvider culture = System.Globalization.CultureInfo.InvariantCulture; //Eliminate DateTime parsing issues.
# endregion
# region Public Properties
public string FileName
{
get { return _fileName; }
set
{
_fileName = value;
// Set the FileExtension.
if (_fileName.LastIndexOf(".") > -1)
{
FileExtension = _fileName.Substring(_fileName.LastIndexOf(".") + 1);
}
}
}
public string FileExtension
{
get { return _fileExtension; }
set { _fileExtension = value; }
}
public string FullName
{
get { return _fullName; }
set { _fullName = value; }
}
public string Path
{
get { return _path; }
set { _path = value; }
}
internal DirectoryEntryType FileType;
public long Size
{
get { return _size; }
set { _size = value; }
}
public DateTime FileDateTime
{
get { return _fileDateTime; }
set { _fileDateTime = value; }
}
public string Permissions
{
get { return _permissions; }
set { _permissions = value; }
}
public string NameOnly
{
get
{
int i = this.FileName.LastIndexOf(".");
if (i > 0)
return this.FileName.Substring(0, i);
else
return this.FileName;
}
}
public enum DirectoryEntryType
{
File,
Directory
}
# endregion
# region Regular expressions for parsing List results
/// <summary>
/// List of REGEX formats for different FTP server listing formats
/// The first three are various UNIX/LINUX formats,
/// fourth is for MS FTP in detailed mode and the last for MS FTP in 'DOS' mode.
/// </summary>
// These regular expressions will be used to match a directory/file
// listing as explained at the top of this class.
internal string[] _ParseFormats =
{
@"(?<dir>[\-d])(?<permission>([\-r][\-w][\-xs]){3})\s+\d+\s+\w+\s+\w+\s+(?<size>\d+)\s+(?<timestamp>\w+\s+\d+\s+\d{4})\s+(?<name>.+)",
@"(?<dir>[\-d])(?<permission>([\-r][\-w][\-xs]){3})\s+\d+\s+\d+\s+(?<size>\d+)\s+(?<timestamp>\w+\s+\d+\s+\d{4})\s+(?<name>.+)",
@"(?<dir>[\-d])(?<permission>([\-r][\-w][\-xs]){3})\s+\d+\s+\d+\s+(?<size>\d+)\s+(?<timestamp>\w+\s+\d+\s+\d{1,2}:\d{2})\s+(?<name>.+)",
@"(?<dir>[\-d])(?<permission>([\-r][\-w][\-xs]){3})\s+\d+\s+\w+\s+\w+\s+(?<size>\d+)\s+(?<timestamp>\w+\s+\d+\s+\d{1,2}:\d{2})\s+(?<name>.+)",
@"(?<dir>[\-d])(?<permission>([\-r][\-w][\-xs]){3})(\s+)(?<size>(\d+))(\s+)(?<ctbit>(\w+\s\w+))(\s+)(?<size2>(\d+))\s+(?<timestamp>\w+\s+\d+\s+\d{2}:\d{2})\s+(?<name>.+)",
@"(?<timestamp>\d{2}\-\d{2}\-\d{2}\s+\d{2}:\d{2}[Aa|Pp][mM])\s+(?<dir>\<\w+\>){0,1}(?<size>\d+){0,1}\s+(?<name>.+)",
@"([<timestamp>]*\d{2}\-\d{2}\-\d{2}\s+\d{2}:\d{2}[Aa|Pp][mM])\s+([<dir>]*\<\w+\>){0,1}([<size>]*\d+){0,1}\s+([<name>]*.+)"
};
# endregion
# region Private Functions
/// <summary>
/// Depending on the various directory listing formats,
/// the current listing will be matched against the set of available matches.
/// </summary>
/// <param name="line"></param>
/// <returns></returns>
// This method evaluates the directory/file listing by applying
// each of the regular expression defined by the string array, _ParseFormats and returns success on a successful match.
private Match GetMatchingRegex(string line)
{
Regex regExpression;
Match match;
int counter;
for (counter = 0; counter < _ParseFormats.Length - 1; counter++)
{
regExpression = new Regex(_ParseFormats[counter], RegexOptions.IgnoreCase);
match = regExpression.Match(line);
if (match.Success)
return match;
}
return null;
}
# endregion
# region Public Functions
/// <summary>
/// The method accepts a directory listing and initialises all the attributes of a file.
/// </summary>
/// <param name="line">Directory Listing line returned by the DetailedDirectoryList method</param>
/// <param name="path">The path of the Directory</param>
// This method populates the needful properties such as filename,path etc.
public void GetFtpFileInfo(string line, string path)
{
string directory;
Match match = GetMatchingRegex(line); //Get the match of the current listing.
if (match == null)
throw new Exception("Unable to parse the line " + line);
else
{
_fileName = match.Groups["name"].Value; //Set the name of the file/directory.
_path = path; // Set the path from which the listing needs to be obtained.
_permissions = match.Groups["permission"].Value; // Set the permissions available for the listing
directory = match.Groups["dir"].Value;
//Set the filetype to either Directory or File basing on the listing.
if (!string.IsNullOrEmpty(directory) && directory != "-")
_fileType = DirectoryEntryType.Directory;
else
{
_fileType = DirectoryEntryType.File;
_size = long.Parse(match.Groups["size"].Value, culture);
}
try
{
_fileDateTime = DateTime.Parse(match.Groups["timestamp"].Value, culture); // Set the datetime of the listing.
}
catch
{
_fileDateTime = DateTime.Now;
}
}
// Initialize the readonly properties.
FileName = _fileName;
Path = _path;
FileType = _fileType;
FullName = Path + FileName;
Size = _size;
FileDateTime = _fileDateTime;
Permissions = _permissions;
}
# endregion
}
public class DeleteFTPDirectory
{
public DeleteFTPDirectory()
{
}
// Set the credentials here to access the target FTP Site.
// For ananymous access, leave it blank.
public ICredentials GetCredentials()
{
return new NetworkCredential(audiogallery.user.ftpusername, audiogallery.user.ftppassword); //Fill this to logon to your FTP Server.
}
//Send the command/request to the target FTP location identified by the parameter, URI
public FtpWebRequest GetRequest(string URI)
{
FtpWebRequest result = ((FtpWebRequest)(FtpWebRequest.Create(URI)));
result.Credentials = GetCredentials();
result.KeepAlive = true;//this was set to false earlier which degraded performance
result.EnableSsl = false;
result.UsePassive = false;
result.ReadWriteTimeout = 100;
return result;
}
//Deletes the target FTP file identified by the parameter, filePath
public bool DeleteFile(string filePath)
{
string URI = (filePath.TrimEnd());
FtpWebRequest ftp = GetRequest(URI);
ftp.Credentials = GetCredentials();
ftp.Method = WebRequestMethods.Ftp.DeleteFile;
string str = GetStringResponse(ftp);
return true;
}
//The master method that deletes the entire directory hierarchy. Root directory is identified by the parameter, dirPath
// Remember: if the path was ftp://testserver/testfolder/testorder then all the folders inside the testorder folder will be deleted including testorder folder.
public bool DeleteDirectoryHierarcy(string dirPath)
{
FtpListing fileObj = new FtpListing(); //Create the FTPListing object
ArrayList DirectoriesList = new ArrayList(); //Create a collection to hold list of directories within the root and including the root directory.
DirectoriesList.Add(dirPath); //Add the root folder to the collection
string currentDirectory = string.Empty;
//For each of the directories in the DirectoriesListCollection, obtain the
// sub directories. Add them to the collection.Repeat the process until every path
// was traversed. For example consider the following hierarchy.
// Ex: ftp://testftpserver/testfolders/testfolder
// Sample Hierarchy of testfolder
// testfolder
// - testfolder1
// - testfolder2
// - testfolder3
// - testfile.txt
// - testfolder4
// DirectorieList is a self modifying collection. Meaning it loops through itself and adds directories to itself.
// DirectoriesList will have the following entries basing on the above hierarchy by the time the first for loop gets complete executed.
//ftp://testftpserver/testfolders/testfolder
//ftp://testftpserver/testfolders/testfolder/testfolder1
//ftp://testftpserver/testfolders/testfolder/testfolder2
//ftp://testftpserver/testfolders/testfolder/testfolder4
//ftp://testftpserver/testfolders/testfolder/testfolder1/testfolder3
//At the end of the for loop the DirectorLists is traversed bottom up
//Meaning deletion of folders will be from the last entry towards to first,
//which would ensure that all the subdirectories are deleted before the root folder is going to be deleted.
for (int directoryCount = 0; directoryCount < DirectoriesList.Count; directoryCount++)
{
currentDirectory = DirectoriesList[directoryCount].ToString() + "/";
if (currentDirectory.StartsWith("ftp://", StringComparison.OrdinalIgnoreCase) == false)
{
currentDirectory = string.Concat("ftp://", currentDirectory);
}
string[] directoryInfo = GetDirectoryList(currentDirectory);
for (int counter = 0; counter < directoryInfo.Length; counter++)
{
string currentFileOrDir = directoryInfo[counter];
if (currentFileOrDir.Length < 1) // If all entries were scanned then break
{
break;
}
currentFileOrDir = currentFileOrDir.Replace("\r", "");
fileObj.GetFtpFileInfo(currentFileOrDir, currentDirectory);
if (fileObj.FileType == FtpListing.DirectoryEntryType.Directory)
{
if (fileObj.FileName != "." && fileObj.FileName != "..") DirectoriesList.Add(fileObj.FullName); //If Directory add to the collection.
}
else if (fileObj.FileType == FtpListing.DirectoryEntryType.File)
{
DeleteFile(fileObj.FullName); //If file,then delete.
}
}
}
//Remove the directories in the collection from bottom toward top.
//This would ensure that all the sub directories were deleted first before deleting the root folder.
for (int count = DirectoriesList.Count; count > 0; count--)
{
RemoveDirectory(DirectoriesList[count - 1].ToString());
}
return true;
}
//Deletes one target directory at a time, identified by the parameter, dirPath
public bool RemoveDirectory(string dirPath)
{
dirPath = dirPath.Trim(new char[] { '/' }); //Trim the path.
FtpWebRequest ftp = GetRequest(dirPath); //Prepare the request.
ftp.Credentials = GetCredentials(); //Set the Credentials to access the ftp target.
ftp.Method = WebRequestMethods.Ftp.RemoveDirectory; //set request method, RemoveDirectory
string str = GetStringResponse(ftp); // Fire the command to remove directory.
return true;
}
//Gets the directory listing given the path
public string[] GetDirectoryList(string path)
{
string[] result = null;
FtpWebRequest ftpReq = GetRequest(path.TrimEnd()); //Create the request
ftpReq.Method = WebRequestMethods.Ftp.ListDirectoryDetails; //Set the request method
ftpReq.Credentials = GetCredentials(); //Set the credentials
FtpWebResponse ftpResp = (FtpWebResponse)ftpReq.GetResponse();//Fire the command
Stream ftpResponseStream = ftpResp.GetResponseStream(); //Get the output
StreamReader reader = new StreamReader(ftpResponseStream, System.Text.Encoding.UTF8);//Encode the output to UTF8 format
result = (reader.ReadToEnd().Split('\n')); //Split the output for newline characters.
ftpResp.Close(); //Close the response object.
return result; // return the output
}
//Gets the response for a given request. Meaning executes the command identified
// by FtpWebRequest and outputs the response/output.
public string GetStringResponse(FtpWebRequest ftpRequest)
{
//Get the result, streaming to a string
string result = "";
using (FtpWebResponse response = ((FtpWebResponse)(ftpRequest.GetResponse()))) //Get the response for the request identified by the parameter ftpRequest
{
using (Stream datastream = response.GetResponseStream())
{
using (StreamReader sr = new StreamReader(datastream))
{
result = sr.ReadToEnd();
sr.Close();
}
datastream.Close();
}
response.Close();
}
return result;
}
}
static class user
{
#region properties
static MySqlConnection conn = new MySqlConnection(Resources.mysqlconnectionstring);
public static string ftpurl;
public static string ftpusername;
public static string ftppassword;
public struct playlist
{
public UInt64 id;
public string name;
public string description;
public string thumb;
}
public struct audio
{
public UInt64 id;
public string name;
public string title;
public string description;
}
#endregion
#region currentstate
public static bool isvalid;
public static UInt32 userid;
public static bool superuser;
public static bool uploading = false;
public static Int32 currentplaylistid = -1;
public static List<playlist> playlists = new List<playlist>();
public static List<audio> audios = new List<audio>();
#endregion
#region methods
public static bool initialize()
{
bool initialized = false;
try
{
if (conn.State == ConnectionState.Closed) conn.Open();
string query = "SELECT * FROM settings";
MySqlCommand cmd = new MySqlCommand(query, conn);
MySqlDataReader rdr = cmd.ExecuteReader();
if (rdr.Read())
{
ftpurl = rdr["ftpurl"].ToString();
ftpusername = rdr["ftpusername"].ToString();
ftppassword = rdr["ftppassword"].ToString();
initialized = true;
}
conn.Close();
}
catch (Exception)
{
System.Windows.Forms.MessageBox.Show("The connection to the database could not be made. Please check your internet connection.");
initialized = false;
//System.Windows.Forms.Application.Exit();
}
return initialized;
}
public static void login(object data)
{
string[] unamepwd= (string[]) data;
bool validuser = false;
if (initialize())
{
try
{
if (conn.State == ConnectionState.Closed) conn.Open();
string query = "SELECT * FROM user WHERE username=@uname and password=@pwd";
MySqlCommand cmd = new MySqlCommand(query, conn);
cmd.Parameters.AddWithValue("@uname", unamepwd[0]);
cmd.Parameters.AddWithValue("@pwd", unamepwd[1]);
MySqlDataReader rdr = cmd.ExecuteReader();
if (rdr.Read())
{
validuser = true;
userid = UInt32.Parse(rdr["id"].ToString());
superuser=(userid==0);//if userid=0 then the user is the superuser
}
conn.Close();
}
catch (Exception)
{
System.Windows.Forms.MessageBox.Show("The connection to the database could not be made. Please check your internet connection.");
validuser = false;
//System.Windows.Forms.Application.Exit();
}
}
isvalid=validuser;
}
public static void getplaylists()//reads the records from playlist table and for each entry calls downloadplaylist() to download the thumb and save it into local temp foler
{
playlists.Clear();
try
{
if (conn.State == ConnectionState.Closed) conn.Open();
string query = "SELECT * FROM playlist WHERE user_id=@userid";
MySqlCommand cmd = new MySqlCommand(query, conn);
cmd.Parameters.AddWithValue("@userid", userid);
MySqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
playlist a1;
a1.id = UInt64.Parse(rdr["id"].ToString());
a1.name = rdr["name"].ToString();
a1.description = rdr["description"].ToString();
a1.thumb = rdr["thumb"].ToString();
if (downloadplaylistthumb(a1)) playlists.Add(a1);//add the playlist to the list of playlist and do not make it dependent on whether the thumb is downloaded or not
}
conn.Close();
}
catch (Exception)
{
System.Windows.Forms.MessageBox.Show("The connection to the database could not be made. Please check your internet connection." + Environment.NewLine+"The application will now exit.");
System.Windows.Forms.Application.Exit();
}
}
private static bool downloadplaylistthumb(playlist playlisttodownload)//downloads the playlist thumbs and saves it into local temp and adds the entries in the albums list
{
try
{
string pathtotemp = System.Windows.Forms.Application.StartupPath + "\\temp";
if (!Directory.Exists(pathtotemp)) Directory.CreateDirectory(pathtotemp);
string pathtoplaylist = pathtotemp + "\\playlist_" + playlisttodownload.id;
if (!Directory.Exists(pathtoplaylist)) Directory.CreateDirectory(pathtoplaylist);
if (!Directory.Exists(pathtoplaylist + "\\audios")) Directory.CreateDirectory(pathtoplaylist + "\\audios");
//if (!Directory.Exists(pathtoplaylist + "\\thumbs")) Directory.CreateDirectory(pathtoplaylist + "\\thumbs");Audios have no thumbs
string filename = pathtoplaylist + "\\" + playlisttodownload.thumb;
if (!File.Exists(filename))
{
FileStream fs = new FileStream(filename, FileMode.Create);
string remotealbumthumb = "user_" + userid + "/playlist_" + playlisttodownload.id + "/" + playlisttodownload.thumb;
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpurl + remotealbumthumb);
request.Method = WebRequestMethods.Ftp.DownloadFile;
request.Credentials = new NetworkCredential(ftpusername, ftppassword);
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
byte[] buffer = new byte[1024];
int bytesread = 0;
while ((bytesread = responseStream.Read(buffer, 0, buffer.Length)) > 0)
fs.Write(buffer, 0, bytesread);
fs.Close();
responseStream.Close();
response.Close();
}
}
catch
{
return false;
}
return true;
}
public static void getaudios(object data)//reads records from the audio table for a particular albumid and then saves the entries in the pictures list
{
Int32 currentplaylistid = (Int32)data;
audios.Clear();
try
{
if (conn.State == ConnectionState.Closed) conn.Open();
string query = "SELECT * FROM audio WHERE playlist_id=@playlistid";
MySqlCommand cmd = new MySqlCommand(query, conn);
cmd.Parameters.AddWithValue("@playlistid", currentplaylistid);
MySqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
audio p1;
p1.id = UInt64.Parse(rdr["id"].ToString());
p1.name = rdr["name"].ToString();
p1.title = rdr["title"].ToString();
p1.description = rdr["description"].ToString();
if (downloadaudio(p1, currentplaylistid)) audios.Add(p1);//add the audios to the list
}
conn.Close();
}
catch (Exception)
{
System.Windows.Forms.MessageBox.Show("The connection to the database could not be made. Please check your internet connection." + Environment.NewLine+"The application will now exit.");
System.Windows.Forms.Application.Exit();
}
}
private static bool downloadaudio(audio audiotodownload, Int32 playlistid)//downloads audio and audio thumbs and saves it to local temp in particular album's directory. This feature will be used in the future to allow the users to listen to audios as well inside the software
{
try
{
string pathtotemp = System.Windows.Forms.Application.StartupPath + "\\temp";
if (!Directory.Exists(pathtotemp)) Directory.CreateDirectory(pathtotemp);
string pathtoplaylist = pathtotemp + "\\playlist_" + playlistid;
if (!Directory.Exists(pathtoplaylist)) Directory.CreateDirectory(pathtoplaylist);
if (!Directory.Exists(pathtoplaylist + "\\audios")) Directory.CreateDirectory(pathtoplaylist + "\\audios");
//if (!Directory.Exists(pathtoplaylist + "\\thumbs")) Directory.CreateDirectory(pathtoplaylist + "\\thumbs");
string audiofilename = pathtoplaylist + "\\audios\\" + audiotodownload.name;
//string audiothumbfilename = pathtoplaylist + "\\thumbs\\" + audiotodownload.thumb;
//skipped downloading of the audio that would take a whole lot of time
//if (!File.Exists(audiofilename))
//{
// FileStream fs = new FileStream(audiofilename, FileMode.Create);
// string remotepicturefilename = "user_" + userid + "/playlist_" + playlistid + "/audios/" + audiotodownload.name;
// FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpurl + remotepicturefilename);
// request.Method = WebRequestMethods.Ftp.DownloadFile;
// request.Credentials = new NetworkCredential(ftpusername, ftppassword);
// FtpWebResponse response = (FtpWebResponse)request.GetResponse();
// Stream responseStream = response.GetResponseStream();
// byte[] buffer = new byte[1024];
// int bytesread = 0;
// while ((bytesread = responseStream.Read(buffer, 0, buffer.Length)) > 0)
// fs.Write(buffer, 0, bytesread);
// fs.Close();
// responseStream.Close();
// response.Close();
//}
//if (!File.Exists(audiothumbfilename))
//{
// FileStream fs = new FileStream(audiothumbfilename, FileMode.Create);
// string remotealbumthumb = "user_" + userid + "/playlist_" + playlistid + "/thumbs/" + audiotodownload.thumb;
// FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpurl + remotealbumthumb);
// request.Method = WebRequestMethods.Ftp.DownloadFile;
// request.Credentials = new NetworkCredential(ftpusername, ftppassword);
// FtpWebResponse response = (FtpWebResponse)request.GetResponse();
// Stream responseStream = response.GetResponseStream();
// byte[] buffer = new byte[1024];
// int bytesread = 0;
// while ((bytesread = responseStream.Read(buffer, 0, buffer.Length)) > 0)
// fs.Write(buffer, 0, bytesread);
// fs.Close();
// responseStream.Close();
// response.Close();
//}
}
catch
{
return false;
}
return true;
}
public static bool insertaudio(string name,string title,string description,long playlist_id)
{
bool inserted=true;
try
{
if (conn.State == ConnectionState.Closed) conn.Open();
string query = "INSERT INTO audio (name,title,description,playlist_id) VALUES(@name,@title,@description,@playlist_id)";
MySqlCommand cmd = new MySqlCommand(query, conn);
cmd.Parameters.AddWithValue("@name", name);
cmd.Parameters.AddWithValue("@title", title);
cmd.Parameters.AddWithValue("@description", description);
cmd.Parameters.AddWithValue("@playlist_id", playlist_id);
if (cmd.ExecuteNonQuery() < 0) inserted = false;
conn.Close();
}
catch
{
inserted = false;
}
return inserted;
}
public static bool deleteaudio(ulong id)
{
bool deleted = true;
try
{
if (conn.State == ConnectionState.Closed) conn.Open();
string query = "DELETE FROM audio WHERE id=@id";
MySqlCommand cmd = new MySqlCommand(query, conn);
cmd.Parameters.AddWithValue("@id", id);
if (cmd.ExecuteNonQuery() < 0) deleted = false;
conn.Close();
}
catch
{
deleted = false;
}
return deleted;
}
public static bool deleteaudio(string name,int playlist_id)//this is an unnecessary method. But let it be
{
bool deleted = true;
try
{
if (conn.State == ConnectionState.Closed) conn.Open();
string query = "DELETE FROM audio WHERE name=@name and playlist_id=@playlist_id";
MySqlCommand cmd = new MySqlCommand(query, conn);
cmd.Parameters.AddWithValue("@name", name);
cmd.Parameters.AddWithValue("@playlist_id", playlist_id);
if (cmd.ExecuteNonQuery() < 0) deleted = false;
conn.Close();
}
catch
{
deleted = false;
}
return deleted;
}
public static UInt32 addplaylist(string name,string thumb,string description)
{
UInt32 playlistid = 0;
try
{
if (conn.State == ConnectionState.Closed) conn.Open();
string query = "INSERT INTO playlist (name,thumb,description,user_id) VALUES(@name,@thumb,@description,@user_id)";
MySqlCommand cmd = new MySqlCommand(query, conn);
cmd.Parameters.AddWithValue("@name", name);
cmd.Parameters.AddWithValue("@thumb", thumb);
cmd.Parameters.AddWithValue("@description", description);
cmd.Parameters.AddWithValue("@user_id", userid);
if (cmd.ExecuteNonQuery() < 0) throw new Exception();
query = "SELECT id FROM playlist WHERE name=@name AND user_id=@user_id";
cmd = new MySqlCommand(query, conn);
cmd.Parameters.AddWithValue("@name", name);
cmd.Parameters.AddWithValue("@user_id", userid);
MySqlDataReader rdr = cmd.ExecuteReader();
if (rdr.Read()) playlistid = UInt32.Parse(rdr["id"].ToString());
conn.Close();
}
catch
{
playlistid = 0;
}
return playlistid;
}
public static bool deleteplaylist(UInt32 id)
{
bool deleted = true;
try
{
if (conn.State == ConnectionState.Closed) conn.Open();
string query = "DELETE FROM playlist WHERE id=@id";
MySqlCommand cmd = new MySqlCommand(query, conn);
cmd.Parameters.AddWithValue("@id", id);
if (cmd.ExecuteNonQuery() < 0) deleted = false;
conn.Close();
}
catch
{
deleted = false;
}
return deleted;
}
public static bool updateplaylist(UInt32 id,string name,string thumb,string description)
{
bool updated = true;
try
{
if (conn.State == ConnectionState.Closed) conn.Open();
string query = "UPDATE playlist SET name=@name,thumb=@thumb,description=@description WHERE id=@id";
MySqlCommand cmd = new MySqlCommand(query, conn);
cmd.Parameters.AddWithValue("@id", id);
cmd.Parameters.AddWithValue("@name", name);
cmd.Parameters.AddWithValue("@thumb", thumb);
cmd.Parameters.AddWithValue("@description", description);
if (cmd.ExecuteNonQuery() < 0) updated = false;
conn.Close();
}
catch
{
updated = false;
}
return updated;
}
public static bool checkuserpassword(string pwd)
{
bool validpwd = false;
if (conn.State == ConnectionState.Closed) conn.Open();
string query = "SELECT password FROM user where id=@userid";
MySqlCommand cmd = new MySqlCommand(query, conn);
cmd.Parameters.AddWithValue("@userid", user.userid);
MySqlDataReader rdr = cmd.ExecuteReader();
if (rdr.Read())
{
string dbpwd = rdr["password"].ToString();
if (dbpwd == pwd) validpwd = true;
}
conn.Close();
return validpwd;
}
public static bool changepassword(string pwd)
{
bool changed = true;
if (conn.State == ConnectionState.Closed) conn.Open();
string query = "UPDATE user SET password=@pwd where id=@userid";
MySqlCommand cmd = new MySqlCommand(query, conn);
cmd.Parameters.AddWithValue("@userid", user.userid);
cmd.Parameters.AddWithValue("@pwd", pwd);
if (cmd.ExecuteNonQuery() < 0) changed = false;
conn.Close();
return changed;
}
public static bool createuser(string name,string username,string password,string description)
{
bool created = true;
UInt32 userid=0;//Used 0 here creating a new user will never result in a 0 because I create the superuser with the id=0 myself and don't let it deleted. So...
try
{
#region Inserting record in the database
if (conn.State == ConnectionState.Closed) conn.Open();
string query = "INSERT INTO user (name,username,password,description) VALUES(@name,@username,@password,@description)";
MySqlCommand cmd = new MySqlCommand(query, conn);
cmd.Parameters.AddWithValue("@name", name);
cmd.Parameters.AddWithValue("@username", username);
cmd.Parameters.AddWithValue("@password", password);
cmd.Parameters.AddWithValue("@description", description);
if (cmd.ExecuteNonQuery() < 0) throw new Exception();
conn.Close();
#endregion
#region Getting the id of newly inserted user
if (conn.State == ConnectionState.Closed) conn.Open();
query = "SELECT id FROM user WHERE username=@username";
cmd = new MySqlCommand(query, conn);
cmd.Parameters.AddWithValue("@username", username);
MySqlDataReader rdr = cmd.ExecuteReader();
if (rdr.Read()) userid = UInt32.Parse(rdr["id"].ToString());
else throw new Exception();
conn.Close();
#endregion
#region Creating folder for user on the remote site
string createpath = user.ftpurl + "user_" + userid;
FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(createpath);
request.Credentials = new NetworkCredential(user.ftpusername, user.ftppassword);
request.KeepAlive = true;
request.Method = WebRequestMethods.Ftp.MakeDirectory;
request.GetResponse();
#endregion
}
catch
{
created = false;
#region Deleting record from the database
if (userid != 0)
{
if (conn.State == ConnectionState.Closed) conn.Open();
string query = "DELETE FROM user WHERE id=@id";
MySqlCommand cmd = new MySqlCommand(query, conn);
cmd.Parameters.AddWithValue("@id", userid);
cmd.ExecuteNonQuery();
conn.Close();
}
#endregion
}
return created;
}
public static Dictionary<string,UInt32> listallusers()
{
Dictionary<string,UInt32> users = new Dictionary<string,UInt32>();
try
{
if (conn.State == ConnectionState.Closed) conn.Open();
string query = "SELECT username,id FROM user";
MySqlCommand cmd = new MySqlCommand(query, conn);
MySqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
string uname=rdr["username"].ToString();
UInt32 id=UInt32.Parse(rdr["id"].ToString());
users.Add(uname, id);
}
conn.Close();
}
catch
{
//do nothing
}
return users;
}
public static Dictionary<string, UInt32> listnormalusers()
{
Dictionary<string, UInt32> users = new Dictionary<string, UInt32>();
try
{
if (conn.State == ConnectionState.Closed) conn.Open();
string query = "SELECT username,id FROM user WHERE id<>0";
MySqlCommand cmd = new MySqlCommand(query, conn);
MySqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
string uname = rdr["username"].ToString();
UInt32 id = UInt32.Parse(rdr["id"].ToString());
users.Add(uname, id);
}
conn.Close();
}
catch
{
//do nothing
}
return users;
}
public static string[] getuserdetails(UInt32 id)
{
string[] details = new string[4];
try
{
if (conn.State == ConnectionState.Closed) conn.Open();
string query = "SELECT * FROM user WHERE id=@id";
MySqlCommand cmd = new MySqlCommand(query, conn);
cmd.Parameters.AddWithValue("@id", id);
MySqlDataReader rdr = cmd.ExecuteReader();
if (rdr.Read())
{
details[0] = rdr["name"].ToString();
details[1] = rdr["username"].ToString();
details[2] = rdr["password"].ToString();
details[3] = rdr["description"].ToString();
}
conn.Close();
}
catch
{
//do nothing
}
return details;
}
public static bool edituser(UInt32 id,string name, string username, string password, string description)
{
bool edited = true;
try
{
if (conn.State == ConnectionState.Closed) conn.Open();
string query = "UPDATE user SET name=@name,username=@username,password=@password,description=@description WHERE id=@id";
MySqlCommand cmd = new MySqlCommand(query, conn);
cmd.Parameters.AddWithValue("@id", id);
cmd.Parameters.AddWithValue("@name", name);
cmd.Parameters.AddWithValue("@username", username);
cmd.Parameters.AddWithValue("@password", password);
cmd.Parameters.AddWithValue("@description", description);
if (cmd.ExecuteNonQuery() < 0) throw new Exception();
conn.Close();
}
catch
{
edited = false;
}
return edited;
}
public static bool deleteuser(UInt32 id)
{
bool deleted = true;
try
{
#region Deleting record from the database
if (conn.State == ConnectionState.Closed) conn.Open();
string query = "DELETE FROM user WHERE id=@id";
MySqlCommand cmd = new MySqlCommand(query, conn);
cmd.Parameters.AddWithValue("@id", id);
if (cmd.ExecuteNonQuery() < 0) throw new Exception();
conn.Close();
#endregion
#region Delete folder of the user on the remote site
string deletepath = user.ftpurl + "user_" + id;
new DeleteFTPDirectory().DeleteDirectoryHierarcy(deletepath);
#endregion
}
catch
{
deleted = false;
}
return deleted;
}
public static bool updateaudio(ulong id, string title,string description)
{
bool updated = true;
try
{
if (conn.State==ConnectionState.Closed) conn.Open();
string query = "UPDATE audio SET title=@title,description=@description WHERE id=@id";
MySqlCommand cmd = new MySqlCommand(query, conn);
cmd.Parameters.AddWithValue("@id", id);
cmd.Parameters.AddWithValue("@title", title);
cmd.Parameters.AddWithValue("@description", description);
if (cmd.ExecuteNonQuery() < 0) updated = false;
conn.Close();
}
catch
{
updated = false;
}
return updated;
}
public static string getaudiofilename(ulong audioid)
{
string audiofilename = string.Empty;
try
{
if (conn.State == ConnectionState.Closed) conn.Open();
string query = "SELECT name FROM audio WHERE id=@id";
MySqlCommand cmd = new MySqlCommand(query, conn);
cmd.Parameters.AddWithValue("@id", audioid);
MySqlDataReader rdr = cmd.ExecuteReader();
if (rdr.Read())
{
audiofilename = rdr["name"].ToString();
}
conn.Close();
}
catch (Exception)
{
System.Windows.Forms.MessageBox.Show("The connection to the database could not be made. Please check your internet connection." + Environment.NewLine + "The application will now exit.");
System.Windows.Forms.Application.Exit();
}
return audiofilename;
}
#endregion
}
}
| 29.333333 | 277 | 0.646961 | [
"MIT"
] | dineshkummarc/Audio-Gallery-Suite | Software/audiogallery/user.cs | 36,523 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Text.RegularExpressions;
namespace SIPSorcery.Entities
{
public partial class SIPAccount
{
private const string BANNED_SIPACCOUNT_NAME = "dispatcher";
public static int TimeZoneOffsetMinutes;
public DateTime InsertedLocal
{
get
{
return (Inserted != null) ? TimeZoneHelper.ApplyOffset(Inserted, TimeZoneOffsetMinutes) : DateTime.MinValue;
}
}
public bool IsDisabled
{
get { return IsUserDisabled || IsAdminDisabled; }
}
public static SIPAccount Create(
string owner,
string domain,
string username,
string password,
string outDialPlanName)
{
return new SIPAccount()
{
ID = Guid.NewGuid().ToString(),
Inserted = DateTimeOffset.UtcNow.ToString("o"),
SIPUsername = username,
SIPDomain = domain,
Owner = owner,
SIPPassword = password,
OutDialPlanName = outDialPlanName,
IsSwitchboardEnabled = true
};
}
#if !SILVERLIGHT
public static string Validate(SIPAccount sipAccount)
{
TypeDescriptor.AddProviderTransparent(new AssociatedMetadataTypeTypeDescriptionProvider(typeof(SIPAccount), typeof(SIPAccountMetadata)), typeof(SIPAccount));
var validationContext = new ValidationContext(sipAccount, null, null);
var validationResults = new List<ValidationResult>();
Validator.TryValidateObject(sipAccount, validationContext, validationResults);
if (validationResults.Count > 0)
{
return validationResults.First().ErrorMessage;
}
else
{
Guid testGuid = Guid.Empty;
if(!Guid.TryParse(sipAccount.ID, out testGuid))
{
return "The ID was not a valid GUID.";
}
else if (String.Compare(sipAccount.SIPUsername, BANNED_SIPACCOUNT_NAME, true) == 0)
{
return "The username you have requested is not permitted.";
}
else if (sipAccount.SIPUsername.Contains(".") &&
(sipAccount.SIPUsername.Substring(sipAccount.SIPUsername.LastIndexOf(".") + 1).Trim().Length >= SIPAccount.USERNAME_MIN_LENGTH &&
sipAccount.SIPUsername.Substring(sipAccount.SIPUsername.LastIndexOf(".") + 1).Trim() != sipAccount.Owner))
{
return "You are not permitted to create this username. Only user " + sipAccount.SIPUsername.Substring(sipAccount.SIPUsername.LastIndexOf(".") + 1).Trim() + " can create SIP accounts ending in " + sipAccount.SIPUsername.Substring(sipAccount.SIPUsername.LastIndexOf(".")).Trim() + ".";
}
}
return null;
}
#endif
public static void Clean(SIPAccount sipAccount)
{
sipAccount.Owner = sipAccount.Owner.Trim();
sipAccount.SIPUsername = sipAccount.SIPUsername.Trim();
sipAccount.SIPPassword = (sipAccount.SIPPassword == null) ? null : sipAccount.SIPPassword.Trim();
sipAccount.SIPDomain = sipAccount.SIPDomain.Trim();
}
}
}
| 37.454545 | 304 | 0.575243 | [
"BSD-3-Clause"
] | Rehan-Mirza/sipsorcery | sipsorcery-core/SIPSorcery.Entities.Client/Generated_Code/Entities/SIPAccount.shared.cs | 3,710 | C# |
using System;
using System.Text;
using System.Collections.Generic;
using ExcelKit.Core.Constraint.Enums;
namespace ExcelKit.Core.Constraint.Mappings
{
/// <summary>
/// Excel中列的类型转换
/// </summary>
internal class ColumnTypeMapping
{
public static object Convert(string convertValue, ColumnType columnType, bool allowNull)
{
object result = null;
switch (columnType)
{
case ColumnType.Int:
result = allowNull && string.IsNullOrWhiteSpace(convertValue) ? 0 : int.Parse(convertValue);
break;
case ColumnType.NullInt:
break;
case ColumnType.Long:
result = allowNull && string.IsNullOrWhiteSpace(convertValue) ? 0 : long.Parse(convertValue);
break;
case ColumnType.NullLong:
break;
case ColumnType.Decimal:
//这样写主要是为了解决读取出1.0133E-2这种数据,这样才能转换
result = allowNull && string.IsNullOrWhiteSpace(convertValue) ? 0 : System.Convert.ToDecimal(System.Convert.ToDouble(convertValue));
break;
case ColumnType.NullDecimal:
break;
case ColumnType.Time:
var status = DateTime.TryParse(convertValue, out DateTime dateTime);
if (allowNull && string.IsNullOrWhiteSpace(convertValue))
result = DateTime.MinValue;
else
result = status ? dateTime : DateTime.FromOADate(System.Convert.ToDouble(convertValue));
break;
case ColumnType.NullTime:
break;
default:
result = convertValue;
break;
}
return result;
}
}
}
| 28.392157 | 137 | 0.703039 | [
"MIT"
] | AdvanceOpen/ExcelK | src/ExcelKit.Core/Constraint/Mappings/ColumnTypeMapping.cs | 1,512 | C# |
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using ProductShop.Data;
namespace ProductShop.Migrations
{
[DbContext(typeof(ProductShopContext))]
partial class ProductShopContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "2.2.0-rtm-35687")
.HasAnnotation("Relational:MaxIdentifierLength", 128)
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("ProductShop.Models.Category", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("Name");
b.HasKey("Id");
b.ToTable("Categories");
});
modelBuilder.Entity("ProductShop.Models.CategoryProduct", b =>
{
b.Property<int>("CategoryId");
b.Property<int>("ProductId");
b.HasKey("CategoryId", "ProductId");
b.HasIndex("ProductId");
b.ToTable("CategoryProducts");
});
modelBuilder.Entity("ProductShop.Models.Product", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<int?>("BuyerId");
b.Property<string>("Name");
b.Property<decimal>("Price");
b.Property<int>("SellerId");
b.HasKey("Id");
b.HasIndex("BuyerId");
b.HasIndex("SellerId");
b.ToTable("Products");
});
modelBuilder.Entity("ProductShop.Models.User", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<int?>("Age");
b.Property<string>("FirstName");
b.Property<string>("LastName");
b.HasKey("Id");
b.ToTable("Users");
});
modelBuilder.Entity("ProductShop.Models.CategoryProduct", b =>
{
b.HasOne("ProductShop.Models.Category", "Category")
.WithMany("CategoryProducts")
.HasForeignKey("CategoryId")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("ProductShop.Models.Product", "Product")
.WithMany("CategoryProducts")
.HasForeignKey("ProductId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("ProductShop.Models.Product", b =>
{
b.HasOne("ProductShop.Models.User", "Buyer")
.WithMany("ProductsBought")
.HasForeignKey("BuyerId");
b.HasOne("ProductShop.Models.User", "Seller")
.WithMany("ProductsSold")
.HasForeignKey("SellerId")
.OnDelete(DeleteBehavior.Cascade);
});
#pragma warning restore 612, 618
}
}
}
| 34.560345 | 125 | 0.514343 | [
"MIT"
] | stanislavstoyanov99/SoftUni-Software-Engineering | DB-with-C#/Labs-And-Homeworks/Entity Framework Core/10. JSON Processing - Exercise/ProductShop/Migrations/ProductShopContextModelSnapshot.cs | 4,011 | C# |
using ElectronNET.API;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
namespace Test.ElectronAngular
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseElectron(args);
webBuilder.UseStartup<Startup>();
});
}
}
| 26.086957 | 70 | 0.585 | [
"MIT"
] | Arthur-Neto/test-electron-angular | Program.cs | 600 | C# |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// File System.Web.UI.WebControls.CheckBoxField.cs
// Automatically generated contract file.
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;
// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108
namespace System.Web.UI.WebControls
{
public partial class CheckBoxField : BoundField
{
#region Methods and constructors
public CheckBoxField()
{
}
protected override void CopyProperties(DataControlField newField)
{
}
protected override DataControlField CreateField()
{
return default(DataControlField);
}
public override void ExtractValuesFromCell(System.Collections.Specialized.IOrderedDictionary dictionary, DataControlFieldCell cell, DataControlRowState rowState, bool includeReadOnly)
{
}
protected override Object GetDesignTimeValue()
{
return default(Object);
}
protected override void InitializeDataCell(DataControlFieldCell cell, DataControlRowState rowState)
{
}
protected override void OnDataBindField(Object sender, EventArgs e)
{
}
public override void ValidateSupportsCallback()
{
}
#endregion
#region Properties and indexers
public override bool ApplyFormatInEditMode
{
get
{
return default(bool);
}
set
{
}
}
public override bool ConvertEmptyStringToNull
{
get
{
return default(bool);
}
set
{
}
}
public override string DataField
{
get
{
return default(string);
}
set
{
}
}
public override string DataFormatString
{
get
{
return default(string);
}
set
{
}
}
public override bool HtmlEncode
{
get
{
return default(bool);
}
set
{
}
}
public override bool HtmlEncodeFormatString
{
get
{
return default(bool);
}
set
{
}
}
public override string NullDisplayText
{
get
{
return default(string);
}
set
{
}
}
protected override bool SupportsHtmlEncode
{
get
{
return default(bool);
}
}
public virtual new string Text
{
get
{
return default(string);
}
set
{
}
}
#endregion
}
}
| 23.61236 | 463 | 0.663098 | [
"MIT"
] | Acidburn0zzz/CodeContracts | Microsoft.Research/Contracts/System.Web/Sources/System.Web.UI.WebControls.CheckBoxField.cs | 4,203 | C# |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.Dialogflow.Cx.V3Beta1.Snippets
{
using Google.Cloud.Dialogflow.Cx.V3Beta1;
using System.Threading.Tasks;
public sealed partial class GeneratedSessionEntityTypesClientStandaloneSnippets
{
/// <summary>Snippet for DeleteSessionEntityTypeAsync</summary>
/// <remarks>
/// This snippet has been automatically generated for illustrative purposes only.
/// It may require modifications to work in your environment.
/// </remarks>
public async Task DeleteSessionEntityTypeAsync()
{
// Create client
SessionEntityTypesClient sessionEntityTypesClient = await SessionEntityTypesClient.CreateAsync();
// Initialize request argument(s)
string name = "projects/[PROJECT]/locations/[LOCATION]/agents/[AGENT]/sessions/[SESSION]/entityTypes/[ENTITY_TYPE]";
// Make the request
await sessionEntityTypesClient.DeleteSessionEntityTypeAsync(name);
}
}
}
| 40.9 | 128 | 0.707824 | [
"Apache-2.0"
] | googleapis/googleapis-gen | google/cloud/dialogflow/cx/v3beta1/google-cloud-dialogflow-cx-v3beta1-csharp/Google.Cloud.Dialogflow.Cx.V3Beta1.StandaloneSnippets/SessionEntityTypesClient.DeleteSessionEntityTypeAsyncSnippet.g.cs | 1,636 | C# |
// ------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version: 17.0.0.0
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
// ------------------------------------------------------------------------------
namespace Amazon.Lambda.Annotations.SourceGenerator.Templates
{
using System.Linq;
using System.Text;
using System.Collections.Generic;
using Amazon.Lambda.Annotations.SourceGenerator.Models;
using Amazon.Lambda.Annotations.SourceGenerator.Extensions;
using Amazon.Lambda.Annotations.SourceGenerator.Models.Attributes;
using Microsoft.CodeAnalysis;
using Amazon.Lambda.Annotations.SourceGenerator.Validation;
using System;
/// <summary>
/// Class to produce the template output
/// </summary>
#line 1 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TextTemplating", "17.0.0.0")]
public partial class LambdaFunctionTemplate : LambdaFunctionTemplateBase
{
#line hidden
/// <summary>
/// Create the template output
/// </summary>
public virtual string TransformText()
{
#line 11 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
foreach (var ns in _model.GeneratedMethod.Usings)
{
#line default
#line hidden
this.Write("using ");
#line 15 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(ns));
#line default
#line hidden
this.Write(";\r\n");
#line 16 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
}
#line default
#line hidden
this.Write("\r\nnamespace ");
#line 20 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(_model.LambdaMethod.ContainingNamespace));
#line default
#line hidden
this.Write("\r\n{\r\n public class ");
#line 22 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(_model.GeneratedMethod.ContainingType.Name));
#line default
#line hidden
this.Write("\r\n {\r\n");
#line 24 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
if (_model.LambdaMethod.UsingDependencyInjection)
{
#line default
#line hidden
this.Write(" private readonly ServiceProvider serviceProvider;\r\n");
#line 29 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
}
else
{
#line default
#line hidden
this.Write(" private readonly ");
#line 34 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(_model.LambdaMethod.ContainingType.Name));
#line default
#line hidden
this.Write(" ");
#line 34 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(_model.LambdaMethod.ContainingType.Name.ToCamelCase()));
#line default
#line hidden
this.Write(";\r\n");
#line 35 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
}
#line default
#line hidden
this.Write("\r\n public ");
#line 39 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(_model.GeneratedMethod.ContainingType.Name));
#line default
#line hidden
this.Write("()\r\n {\r\n SetExecutionEnvironment();\r\n");
#line 42 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
if (_model.LambdaMethod.UsingDependencyInjection)
{
#line default
#line hidden
this.Write(@" var services = new ServiceCollection();
// By default, Lambda function class is added to the service container using the singleton lifetime
// To use a different lifetime, specify the lifetime in Startup.ConfigureServices(IServiceCollection) method.
services.AddSingleton<");
#line 50 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(_model.LambdaMethod.ContainingType.Name));
#line default
#line hidden
this.Write(">();\r\n\r\n var startup = new ");
#line 52 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(_model.StartupType.FullName));
#line default
#line hidden
this.Write("();\r\n startup.ConfigureServices(services);\r\n serviceProvide" +
"r = services.BuildServiceProvider();\r\n");
#line 55 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
}
else
{
#line default
#line hidden
this.Write(" ");
#line 60 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(_model.LambdaMethod.ContainingType.Name.ToCamelCase()));
#line default
#line hidden
this.Write(" = new ");
#line 60 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(_model.LambdaMethod.ContainingType.Name));
#line default
#line hidden
this.Write("();\r\n");
#line 61 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
}
#line default
#line hidden
this.Write(" }\r\n\r\n public ");
#line 66 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(_model.LambdaMethod.IsAsync ? "async Task<" : ""));
#line default
#line hidden
#line 66 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(_model.GeneratedMethod.ReturnType.FullName));
#line default
#line hidden
#line 66 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(_model.LambdaMethod.IsAsync ? ">" : ""));
#line default
#line hidden
this.Write(" ");
#line 66 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(_model.LambdaMethod.Name));
#line default
#line hidden
this.Write("(");
#line 66 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(string.Join(", ", _model.GeneratedMethod.Parameters.Select(p => $"{p.Type.FullName} {p.Name}"))));
#line default
#line hidden
this.Write(")\r\n {\r\n");
#line 68 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
if (_model.LambdaMethod.UsingDependencyInjection)
{
#line default
#line hidden
this.Write(" // Create a scope for every request,\r\n // this allows crea" +
"ting scoped dependencies without creating a scope manually.\r\n using v" +
"ar scope = serviceProvider.CreateScope();\r\n var ");
#line 75 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(_model.LambdaMethod.ContainingType.Name.ToCamelCase()));
#line default
#line hidden
this.Write(" = scope.ServiceProvider.GetRequiredService<");
#line 76 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(_model.LambdaMethod.ContainingType.Name));
#line default
#line hidden
this.Write(">();\r\n\r\n");
#line 78 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
}
if (_model.LambdaMethod.Events.Contains(EventType.API))
{
var parameters = string.Join(", ", _model.LambdaMethod.Parameters
.Select(p =>
{
// Pass the same context parameter for ILambdaContext that comes from the generated method.
if (p.Type.FullName == TypeFullNames.ILambdaContext)
{
return "context";
}
// Pass the same request parameter for Request Type that comes from the generated method.
if (TypeFullNames.Requests.Contains(p.Type.FullName))
{
return "request";
}
return p.Name;
}));
var restApiAttribute = _model.LambdaMethod.Attributes.FirstOrDefault(att => att.Type.FullName == TypeFullNames.RestApiAttribute) as AttributeModel<RestApiAttribute>;
var httpApiAttribute = _model.LambdaMethod.Attributes.FirstOrDefault(att => att.Type.FullName == TypeFullNames.HttpApiAttribute) as AttributeModel<HttpApiAttribute>;
if (restApiAttribute != null && httpApiAttribute != null)
{
throw new NotSupportedException($"A method cannot have both {TypeFullNames.RestApiAttribute} and {TypeFullNames.HttpApiAttribute} attribute at the same time.");
}
var routeParameters = restApiAttribute?.Data?.GetTemplateParameters() ?? httpApiAttribute?.Data?.GetTemplateParameters() ?? new HashSet<string>();
var (routeTemplateValid, missingRouteParams) = RouteParametersValidator.Validate(routeParameters, _model.LambdaMethod.Parameters);
if (!routeTemplateValid)
{
var template = restApiAttribute?.Data?.Template ?? httpApiAttribute?.Data?.Template ?? string.Empty;
throw new InvalidOperationException($"Route template {template} is invalid. Missing {string.Join(",", missingRouteParams)} parameters in method definition.");
}
if (_model.LambdaMethod.Parameters.HasConvertibleParameter())
{
#line default
#line hidden
this.Write(" var validationErrors = new List<string>();\r\n\r\n");
#line 122 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
}
foreach (var parameter in _model.LambdaMethod.Parameters)
{
if (parameter.Type.FullName == TypeFullNames.ILambdaContext || TypeFullNames.Requests.Contains(parameter.Type.FullName))
{
// No action required for ILambdaContext and RequestType, they are passed from the generated method parameter directly to the original method.
}
else if (parameter.Attributes.Any(att => att.Type.FullName == TypeFullNames.FromServiceAttribute))
{
#line default
#line hidden
this.Write(" var ");
#line 134 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(parameter.Name));
#line default
#line hidden
this.Write(" = scope.ServiceProvider.GetRequiredService<");
#line 134 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(parameter.Type.FullName));
#line default
#line hidden
this.Write(">();\r\n");
#line 135 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
}
else if (parameter.Attributes.Any(att => att.Type.FullName == TypeFullNames.FromQueryAttribute))
{
var fromQueryAttribute = parameter.Attributes.First(att => att.Type.FullName == TypeFullNames.FromQueryAttribute) as AttributeModel<FromQueryAttribute>;
// Use parameter name as key, if Name has not specified explicitly in the attribute definition.
var parameterKey = fromQueryAttribute?.Data?.Name ?? parameter.Name;
var queryStringParameters = "QueryStringParameters";
#line default
#line hidden
this.Write(" var ");
#line 147 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(parameter.Name));
#line default
#line hidden
this.Write(" = default(");
#line 147 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(parameter.Type.FullName));
#line default
#line hidden
this.Write(");\r\n");
#line 148 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
if (parameter.Type.IsEnumerable && parameter.Type.IsGenericType)
{
// In HTTP API V2 multiple values for the same parameter are represented via comma separated string
// Therefore, it is required to split the string to convert to an enumerable
// and convert individual item to target data type.
var commaSplit = "";
if (httpApiAttribute?.Data.Version == HttpApiVersion.V2)
{
commaSplit = @".Split("","")";
}
// HTTP API V1 and Rest API, multiple values for the same parameter are provided
// dedicated dictionary of string key and list value.
if (restApiAttribute != null || httpApiAttribute?.Data.Version == HttpApiVersion.V1)
{
queryStringParameters = "MultiValueQueryStringParameters";
}
if (parameter.Type.TypeArguments.Count != 1)
{
throw new NotSupportedException("Only one type argument is supported for generic types.");
}
// Generic types are mapped using Select statement to the target parameter type argument.
var typeArgument = parameter.Type.TypeArguments.First();
#line default
#line hidden
this.Write(" if (request.");
#line 176 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(queryStringParameters));
#line default
#line hidden
this.Write("?.ContainsKey(\"");
#line 176 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(parameterKey));
#line default
#line hidden
this.Write("\") == true)\r\n {\r\n ");
#line 178 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(parameter.Name));
#line default
#line hidden
this.Write(" = request.");
#line 178 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(queryStringParameters));
#line default
#line hidden
this.Write("[\"");
#line 178 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(parameterKey));
#line default
#line hidden
this.Write("\"]");
#line 178 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(commaSplit));
#line default
#line hidden
this.Write("\r\n .Select(q =>\r\n {\r\n " +
" try\r\n {\r\n return (");
#line 183 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(typeArgument.FullName));
#line default
#line hidden
this.Write(")Convert.ChangeType(q, typeof(");
#line 183 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(typeArgument.FullName));
#line default
#line hidden
this.Write(@"));
}
catch (Exception e) when (e is InvalidCastException || e is FormatException || e is OverflowException || e is ArgumentException)
{
validationErrors.Add($""Value {q} at '");
#line 187 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(parameterKey));
#line default
#line hidden
this.Write("\' failed to satisfy constraint: {e.Message}\");\r\n retur" +
"n default;\r\n }\r\n })\r\n " +
" .ToList();\r\n }\r\n\r\n");
#line 194 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
}
else
{
// Non-generic types are mapped directly to the target parameter.
#line default
#line hidden
this.Write(" if (request.");
#line 200 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(queryStringParameters));
#line default
#line hidden
this.Write("?.ContainsKey(\"");
#line 200 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(parameterKey));
#line default
#line hidden
this.Write("\") == true)\r\n {\r\n try\r\n {\r\n " +
" ");
#line 204 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(parameter.Name));
#line default
#line hidden
this.Write(" = (");
#line 204 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(parameter.Type.FullName));
#line default
#line hidden
this.Write(")Convert.ChangeType(request.");
#line 204 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(queryStringParameters));
#line default
#line hidden
this.Write("[\"");
#line 204 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(parameterKey));
#line default
#line hidden
this.Write("\"], typeof(");
#line 204 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(parameter.Type.FullName));
#line default
#line hidden
this.Write("));\r\n }\r\n catch (Exception e) when (e is InvalidCas" +
"tException || e is FormatException || e is OverflowException || e is ArgumentExc" +
"eption)\r\n {\r\n validationErrors.Add($\"Value {re" +
"quest.");
#line 208 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(queryStringParameters));
#line default
#line hidden
this.Write("[\"");
#line 208 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(parameterKey));
#line default
#line hidden
this.Write("\"]} at \'");
#line 208 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(parameterKey));
#line default
#line hidden
this.Write("\' failed to satisfy constraint: {e.Message}\");\r\n }\r\n }\r" +
"\n\r\n");
#line 212 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
}
}
else if (parameter.Attributes.Any(att => att.Type.FullName == TypeFullNames.FromHeaderAttribute))
{
var fromHeaderAttribute =
parameter.Attributes.First(att => att.Type.FullName == TypeFullNames.FromHeaderAttribute) as
AttributeModel<FromHeaderAttribute>;
// Use parameter name as key, if Name has not specified explicitly in the attribute definition.
var headerKey = fromHeaderAttribute?.Data?.Name ?? parameter.Name;
var headers = "Headers";
#line default
#line hidden
this.Write(" var ");
#line 228 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(parameter.Name));
#line default
#line hidden
this.Write(" = default(");
#line 228 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(parameter.Type.FullName));
#line default
#line hidden
this.Write(");\r\n");
#line 229 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
if (parameter.Type.IsEnumerable && parameter.Type.IsGenericType)
{
// In HTTP API V2 multiple values for the same header are represented via comma separated string
// Therefore, it is required to split the string to convert to an enumerable
// and convert individual item to target data type.
var commaSplit = "";
if (httpApiAttribute?.Data.Version == HttpApiVersion.V2)
{
commaSplit = @".Split("","")";
}
// HTTP API V1 and Rest API, multiple values for the same header are provided
// dedicated dictionary of string key and list value.
if (restApiAttribute != null || httpApiAttribute?.Data.Version == HttpApiVersion.V1)
{
headers = "MultiValueHeaders";
}
if (parameter.Type.TypeArguments.Count != 1)
{
throw new NotSupportedException("Only one type argument is supported for generic types.");
}
// Generic types are mapped using Select statement to the target parameter type argument.
var typeArgument = parameter.Type.TypeArguments.First();
#line default
#line hidden
this.Write(" if (request.");
#line 257 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(headers));
#line default
#line hidden
this.Write("?.ContainsKey(\"");
#line 257 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(headerKey));
#line default
#line hidden
this.Write("\") == true)\r\n {\r\n ");
#line 259 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(parameter.Name));
#line default
#line hidden
this.Write(" = request.");
#line 259 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(headers));
#line default
#line hidden
this.Write("[\"");
#line 259 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(headerKey));
#line default
#line hidden
this.Write("\"]");
#line 259 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(commaSplit));
#line default
#line hidden
this.Write("\r\n .Select(q =>\r\n {\r\n " +
" try\r\n {\r\n return (");
#line 264 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(typeArgument.FullName));
#line default
#line hidden
this.Write(")Convert.ChangeType(q, typeof(");
#line 264 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(typeArgument.FullName));
#line default
#line hidden
this.Write(@"));
}
catch (Exception e) when (e is InvalidCastException || e is FormatException || e is OverflowException || e is ArgumentException)
{
validationErrors.Add($""Value {q} at '");
#line 268 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(headerKey));
#line default
#line hidden
this.Write("\' failed to satisfy constraint: {e.Message}\");\r\n retur" +
"n default;\r\n }\r\n })\r\n " +
" .ToList();\r\n }\r\n\r\n");
#line 275 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
}
else
{
// Non-generic types are mapped directly to the target parameter.
#line default
#line hidden
this.Write(" if (request.");
#line 281 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(headers));
#line default
#line hidden
this.Write("?.ContainsKey(\"");
#line 281 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(headerKey));
#line default
#line hidden
this.Write("\") == true)\r\n {\r\n try\r\n {\r\n " +
" ");
#line 285 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(parameter.Name));
#line default
#line hidden
this.Write(" = (");
#line 285 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(parameter.Type.FullName));
#line default
#line hidden
this.Write(")Convert.ChangeType(request.");
#line 285 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(headers));
#line default
#line hidden
this.Write("[\"");
#line 285 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(headerKey));
#line default
#line hidden
this.Write("\"], typeof(");
#line 285 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(parameter.Type.FullName));
#line default
#line hidden
this.Write("));\r\n }\r\n catch (Exception e) when (e is InvalidCas" +
"tException || e is FormatException || e is OverflowException || e is ArgumentExc" +
"eption)\r\n {\r\n validationErrors.Add($\"Value {re" +
"quest.");
#line 289 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(headers));
#line default
#line hidden
this.Write("[\"");
#line 289 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(headerKey));
#line default
#line hidden
this.Write("\"]} at \'");
#line 289 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(headerKey));
#line default
#line hidden
this.Write("\' failed to satisfy constraint: {e.Message}\");\r\n }\r\n }\r" +
"\n\r\n");
#line 293 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
}
}
else if (parameter.Attributes.Any(att => att.Type.FullName == TypeFullNames.FromBodyAttribute))
{
// string parameter does not need to be de-serialized
if (parameter.Type.IsString())
{
#line default
#line hidden
this.Write(" var ");
#line 302 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(parameter.Name));
#line default
#line hidden
this.Write(" = request.Body;\r\n\r\n");
#line 304 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
}
else
{
#line default
#line hidden
this.Write(" var ");
#line 309 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(parameter.Name));
#line default
#line hidden
this.Write(" = default(");
#line 309 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(parameter.Type.FullName));
#line default
#line hidden
this.Write(");\r\n try\r\n {\r\n ");
#line 312 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(parameter.Name));
#line default
#line hidden
this.Write(" = ");
#line 312 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(_model.Serializer));
#line default
#line hidden
this.Write(".Deserialize<");
#line 312 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(parameter.Type.FullName));
#line default
#line hidden
this.Write(">(request.Body);\r\n }\r\n catch (Exception e)\r\n {\r\n" +
" validationErrors.Add($\"Value {request.Body} at \'body\' failed to " +
"satisfy constraint: {e.Message}\");\r\n }\r\n\r\n");
#line 319 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
}
}
else if (parameter.Attributes.Any(att => att.Type.FullName == TypeFullNames.FromRouteAttribute) || routeParameters.Contains(parameter.Name))
{
var fromRouteAttribute = parameter.Attributes?.FirstOrDefault(att => att.Type.FullName == TypeFullNames.FromRouteAttribute) as AttributeModel<FromRouteAttribute>;
// Use parameter name as key, if Name has not specified explicitly in the attribute definition.
var routeKey = fromRouteAttribute?.Data?.Name ?? parameter.Name;
#line default
#line hidden
this.Write(" var ");
#line 329 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(parameter.Name));
#line default
#line hidden
this.Write(" = default(");
#line 329 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(parameter.Type.FullName));
#line default
#line hidden
this.Write(");\r\n if (request.PathParameters?.ContainsKey(\"");
#line 330 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(routeKey));
#line default
#line hidden
this.Write("\") == true)\r\n {\r\n try\r\n {\r\n " +
" ");
#line 334 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(parameter.Name));
#line default
#line hidden
this.Write(" = (");
#line 334 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(parameter.Type.FullName));
#line default
#line hidden
this.Write(")Convert.ChangeType(request.PathParameters[\"");
#line 334 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(routeKey));
#line default
#line hidden
this.Write("\"], typeof(");
#line 334 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(parameter.Type.FullName));
#line default
#line hidden
this.Write(@"));
}
catch (Exception e) when (e is InvalidCastException || e is FormatException || e is OverflowException || e is ArgumentException)
{
validationErrors.Add($""Value {request.PathParameters[""");
#line 338 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(routeKey));
#line default
#line hidden
this.Write("\"]} at \'");
#line 338 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(routeKey));
#line default
#line hidden
this.Write("\' failed to satisfy constraint: {e.Message}\");\r\n }\r\n }\r" +
"\n\r\n");
#line 342 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
}
else
{
throw new NotSupportedException($"{parameter.Name} parameter of type {parameter.Type.FullName} passing is not supported.");
}
}
if (_model.LambdaMethod.Parameters.HasConvertibleParameter())
{
#line default
#line hidden
this.Write(" // return 400 Bad Request if there exists a validation error\r\n " +
" if (validationErrors.Any())\r\n {\r\n return new ");
#line 356 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(_model.GeneratedMethod.ReturnType.Name));
#line default
#line hidden
this.Write(@"
{
Body = @$""{{""""message"""": """"{validationErrors.Count} validation error(s) detected: {string.Join("","", validationErrors)}""""}}"",
Headers = new Dictionary<string, string>
{
{""Content-Type"", ""application/json""},
{""x-amzn-ErrorType"", ""ValidationException""}
},
StatusCode = 200
};
}
");
#line 368 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
}
if (_model.LambdaMethod.ReturnsVoidOrTask)
{
#line default
#line hidden
this.Write(" ");
#line 374 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(_model.LambdaMethod.IsAsync ? "await " : ""));
#line default
#line hidden
#line 374 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(_model.LambdaMethod.ContainingType.Name.ToCamelCase()));
#line default
#line hidden
this.Write(".");
#line 374 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(_model.LambdaMethod.Name));
#line default
#line hidden
this.Write("(");
#line 374 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(parameters));
#line default
#line hidden
this.Write(");\r\n");
#line 375 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
}
else
{
#line default
#line hidden
this.Write(" var response = ");
#line 380 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(_model.LambdaMethod.IsAsync ? "await " : ""));
#line default
#line hidden
#line 380 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(_model.LambdaMethod.ContainingType.Name.ToCamelCase()));
#line default
#line hidden
this.Write(".");
#line 380 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(_model.LambdaMethod.Name));
#line default
#line hidden
this.Write("(");
#line 380 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(parameters));
#line default
#line hidden
this.Write(");\r\n");
#line 381 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
}
if (_model.GeneratedMethod.ReturnType.FullName == _model.LambdaMethod.ReturnType.FullName)
{
#line default
#line hidden
this.Write(" return response;\r\n");
#line 388 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
}
else
{
if (!_model.LambdaMethod.ReturnsVoidOrTask)
{
if (_model.LambdaMethod.ReturnType.IsValueType)
{
#line default
#line hidden
this.Write("\r\n var body = response.ToString();\r\n");
#line 399 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
}
else if (_model.LambdaMethod.ReturnType.IsString())
{
// no action
}
else
{
#line default
#line hidden
this.Write("\r\n var body = ");
#line 409 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(_model.Serializer));
#line default
#line hidden
this.Write(".Serialize(response);\r\n");
#line 410 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
}
}
#line default
#line hidden
this.Write("\r\n return new ");
#line 415 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(_model.GeneratedMethod.ReturnType.Name));
#line default
#line hidden
this.Write("\r\n {\r\n");
#line 417 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
if (!_model.LambdaMethod.ReturnsVoidOrTask)
{
#line default
#line hidden
this.Write(" Body = ");
#line 421 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(_model.LambdaMethod.ReturnType.IsString() ? "response" : "body"));
#line default
#line hidden
this.Write(",\r\n Headers = new Dictionary<string, string>\r\n {\r\n " +
" {\"Content-Type\", ");
#line 424 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(_model.LambdaMethod.ReturnType.IsString() ? "\"text/plain\"" : "\"application/json\""));
#line default
#line hidden
this.Write("}\r\n },\r\n");
#line 426 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
}
#line default
#line hidden
this.Write(" StatusCode = 200\r\n };\r\n");
#line 431 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
}
}
else if (_model.LambdaMethod.Events.Count == 0)
{
var parameters = string.Join(", ", _model.LambdaMethod.Parameters
.Select(p =>
{
// Pass the same context parameter for ILambdaContext that comes from the generated method.
if (p.Type.FullName == TypeFullNames.ILambdaContext)
{
return "context";
}
return p.Name;
}));
foreach (var parameter in _model.LambdaMethod.Parameters)
{
if (parameter.Attributes.Any(att => att.Type.FullName == TypeFullNames.FromServiceAttribute))
{
#line default
#line hidden
this.Write(" var ");
#line 453 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(parameter.Name));
#line default
#line hidden
this.Write(" = scope.ServiceProvider.GetRequiredService<");
#line 453 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(parameter.Type.FullName));
#line default
#line hidden
this.Write(">();\r\n");
#line 454 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
}
}
if (_model.LambdaMethod.ReturnsVoidOrTask)
{
#line default
#line hidden
this.Write(" return ");
#line 461 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(_model.LambdaMethod.IsAsync ? "await " : ""));
#line default
#line hidden
#line 461 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(_model.LambdaMethod.ContainingType.Name.ToCamelCase()));
#line default
#line hidden
this.Write(".");
#line 461 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(_model.LambdaMethod.Name));
#line default
#line hidden
this.Write("(");
#line 461 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(parameters));
#line default
#line hidden
this.Write(");\r\n");
#line 462 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
}
else
{
#line default
#line hidden
this.Write(" return ");
#line 467 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(_model.LambdaMethod.IsAsync ? "await " : ""));
#line default
#line hidden
#line 467 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(_model.LambdaMethod.ContainingType.Name.ToCamelCase()));
#line default
#line hidden
this.Write(".");
#line 467 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(_model.LambdaMethod.Name));
#line default
#line hidden
this.Write("(");
#line 467 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(parameters));
#line default
#line hidden
this.Write(");\r\n");
#line 468 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
}
}
#line default
#line hidden
this.Write(@" }
private static void SetExecutionEnvironment()
{
const string envName = ""AWS_EXECUTION_ENV"";
var envValue = new StringBuilder();
// If there is an existing execution environment variable add the annotations package as a suffix.
if(!string.IsNullOrEmpty(Environment.GetEnvironmentVariable(envName)))
{
envValue.Append($""{Environment.GetEnvironmentVariable(envName)}_"");
}
envValue.Append(""amazon-lambda-annotations_");
#line 486 "C:\Users\jangirg\source\repos\aws-lambda-dotnet\Libraries\src\Amazon.Lambda.Annotations.SourceGenerator\Templates\LambdaFunctionTemplate.tt"
this.Write(this.ToStringHelper.ToStringWithCulture(_model.SourceGeneratorVersion));
#line default
#line hidden
this.Write("\");\r\n\r\n Environment.SetEnvironmentVariable(envName, envValue.ToString(" +
"));\r\n }\r\n }\r\n}");
return this.GenerationEnvironment.ToString();
}
}
#line default
#line hidden
#region Base class
/// <summary>
/// Base class for this transformation
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TextTemplating", "17.0.0.0")]
public class LambdaFunctionTemplateBase
{
#region Fields
private global::System.Text.StringBuilder generationEnvironmentField;
private global::System.CodeDom.Compiler.CompilerErrorCollection errorsField;
private global::System.Collections.Generic.List<int> indentLengthsField;
private string currentIndentField = "";
private bool endsWithNewline;
private global::System.Collections.Generic.IDictionary<string, object> sessionField;
#endregion
#region Properties
/// <summary>
/// The string builder that generation-time code is using to assemble generated output
/// </summary>
protected System.Text.StringBuilder GenerationEnvironment
{
get
{
if ((this.generationEnvironmentField == null))
{
this.generationEnvironmentField = new global::System.Text.StringBuilder();
}
return this.generationEnvironmentField;
}
set
{
this.generationEnvironmentField = value;
}
}
/// <summary>
/// The error collection for the generation process
/// </summary>
public System.CodeDom.Compiler.CompilerErrorCollection Errors
{
get
{
if ((this.errorsField == null))
{
this.errorsField = new global::System.CodeDom.Compiler.CompilerErrorCollection();
}
return this.errorsField;
}
}
/// <summary>
/// A list of the lengths of each indent that was added with PushIndent
/// </summary>
private System.Collections.Generic.List<int> indentLengths
{
get
{
if ((this.indentLengthsField == null))
{
this.indentLengthsField = new global::System.Collections.Generic.List<int>();
}
return this.indentLengthsField;
}
}
/// <summary>
/// Gets the current indent we use when adding lines to the output
/// </summary>
public string CurrentIndent
{
get
{
return this.currentIndentField;
}
}
/// <summary>
/// Current transformation session
/// </summary>
public virtual global::System.Collections.Generic.IDictionary<string, object> Session
{
get
{
return this.sessionField;
}
set
{
this.sessionField = value;
}
}
#endregion
#region Transform-time helpers
/// <summary>
/// Write text directly into the generated output
/// </summary>
public void Write(string textToAppend)
{
if (string.IsNullOrEmpty(textToAppend))
{
return;
}
// If we're starting off, or if the previous text ended with a newline,
// we have to append the current indent first.
if (((this.GenerationEnvironment.Length == 0)
|| this.endsWithNewline))
{
this.GenerationEnvironment.Append(this.currentIndentField);
this.endsWithNewline = false;
}
// Check if the current text ends with a newline
if (textToAppend.EndsWith(global::System.Environment.NewLine, global::System.StringComparison.CurrentCulture))
{
this.endsWithNewline = true;
}
// This is an optimization. If the current indent is "", then we don't have to do any
// of the more complex stuff further down.
if ((this.currentIndentField.Length == 0))
{
this.GenerationEnvironment.Append(textToAppend);
return;
}
// Everywhere there is a newline in the text, add an indent after it
textToAppend = textToAppend.Replace(global::System.Environment.NewLine, (global::System.Environment.NewLine + this.currentIndentField));
// If the text ends with a newline, then we should strip off the indent added at the very end
// because the appropriate indent will be added when the next time Write() is called
if (this.endsWithNewline)
{
this.GenerationEnvironment.Append(textToAppend, 0, (textToAppend.Length - this.currentIndentField.Length));
}
else
{
this.GenerationEnvironment.Append(textToAppend);
}
}
/// <summary>
/// Write text directly into the generated output
/// </summary>
public void WriteLine(string textToAppend)
{
this.Write(textToAppend);
this.GenerationEnvironment.AppendLine();
this.endsWithNewline = true;
}
/// <summary>
/// Write formatted text directly into the generated output
/// </summary>
public void Write(string format, params object[] args)
{
this.Write(string.Format(global::System.Globalization.CultureInfo.CurrentCulture, format, args));
}
/// <summary>
/// Write formatted text directly into the generated output
/// </summary>
public void WriteLine(string format, params object[] args)
{
this.WriteLine(string.Format(global::System.Globalization.CultureInfo.CurrentCulture, format, args));
}
/// <summary>
/// Raise an error
/// </summary>
public void Error(string message)
{
System.CodeDom.Compiler.CompilerError error = new global::System.CodeDom.Compiler.CompilerError();
error.ErrorText = message;
this.Errors.Add(error);
}
/// <summary>
/// Raise a warning
/// </summary>
public void Warning(string message)
{
System.CodeDom.Compiler.CompilerError error = new global::System.CodeDom.Compiler.CompilerError();
error.ErrorText = message;
error.IsWarning = true;
this.Errors.Add(error);
}
/// <summary>
/// Increase the indent
/// </summary>
public void PushIndent(string indent)
{
if ((indent == null))
{
throw new global::System.ArgumentNullException("indent");
}
this.currentIndentField = (this.currentIndentField + indent);
this.indentLengths.Add(indent.Length);
}
/// <summary>
/// Remove the last indent that was added with PushIndent
/// </summary>
public string PopIndent()
{
string returnValue = "";
if ((this.indentLengths.Count > 0))
{
int indentLength = this.indentLengths[(this.indentLengths.Count - 1)];
this.indentLengths.RemoveAt((this.indentLengths.Count - 1));
if ((indentLength > 0))
{
returnValue = this.currentIndentField.Substring((this.currentIndentField.Length - indentLength));
this.currentIndentField = this.currentIndentField.Remove((this.currentIndentField.Length - indentLength));
}
}
return returnValue;
}
/// <summary>
/// Remove any indentation
/// </summary>
public void ClearIndent()
{
this.indentLengths.Clear();
this.currentIndentField = "";
}
#endregion
#region ToString Helpers
/// <summary>
/// Utility class to produce culture-oriented representation of an object as a string.
/// </summary>
public class ToStringInstanceHelper
{
private System.IFormatProvider formatProviderField = global::System.Globalization.CultureInfo.InvariantCulture;
/// <summary>
/// Gets or sets format provider to be used by ToStringWithCulture method.
/// </summary>
public System.IFormatProvider FormatProvider
{
get
{
return this.formatProviderField ;
}
set
{
if ((value != null))
{
this.formatProviderField = value;
}
}
}
/// <summary>
/// This is called from the compile/run appdomain to convert objects within an expression block to a string
/// </summary>
public string ToStringWithCulture(object objectToConvert)
{
if ((objectToConvert == null))
{
throw new global::System.ArgumentNullException("objectToConvert");
}
System.Type t = objectToConvert.GetType();
System.Reflection.MethodInfo method = t.GetMethod("ToString", new System.Type[] {
typeof(System.IFormatProvider)});
if ((method == null))
{
return objectToConvert.ToString();
}
else
{
return ((string)(method.Invoke(objectToConvert, new object[] {
this.formatProviderField })));
}
}
}
private ToStringInstanceHelper toStringHelperField = new ToStringInstanceHelper();
/// <summary>
/// Helper to produce culture-oriented representation of an object as a string
/// </summary>
public ToStringInstanceHelper ToStringHelper
{
get
{
return this.toStringHelperField;
}
}
#endregion
}
#endregion
}
| 46.952502 | 178 | 0.5812 | [
"Apache-2.0"
] | TobbenTM/aws-lambda-dotnet | Libraries/src/Amazon.Lambda.Annotations.SourceGenerator/Templates/LambdaFunctionTemplate.cs | 74,140 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using STG.SRP.Core.Utilities;
namespace STG.SRP.ControlRoom
{
public partial class CRRibbon : UserControl
{
public List<RibbonPanel> Panels { get; set; }
public void Add(RibbonPanel panel)
{
if (Panels == null) Panels = new List<RibbonPanel>();
Panels.Add(panel);
}
public new bool Visible
{
get
{
return pnlRibbon.Visible;
}
set
{
pnlRibbon.Visible = value;
}
}
protected void PageLoad(object sender, EventArgs e)
{
if (Panels == null) Panels = new List<RibbonPanel>();
if (!IsPostBack)
{
DataBind();
}
}
public new void DataBind()
{
if (Panels == null || Panels.Count == 0) { Visible = false; return; }
rptPnl.DataSource = Panels;
rptPnl.DataBind();
}
public bool IsList(int count)
{
return count <= 4;
}
public string GetLinks(List<RibbonLink> links)
{
if (links.Count <= 3)
{
string slinks = "<ul class=\"cntUL0\" style=\"margin-bottom: 0px\">";
foreach (RibbonLink l in links)
{
slinks = slinks + "<li class=\"cntSqbulletedlist\"><a href=\"" +
l.Url + "\">" + l.Name + "</a></li> ";
}
slinks = slinks + "</ul>";
return slinks;
}
else
{
string slinks = " <select name='aList' onchange='if (this.options[this.selectedIndex].value != \"\") document.location.href=this.options[this.selectedIndex].value;'><option value=''>[Make a Selection]</option>";
foreach (RibbonLink l in links)
{
slinks = slinks + "<option value='" +
l.Url + "'>" + l.Name + "</option> ";
}
slinks = slinks + "</select>";
return slinks;
}
}
}
} | 27.541176 | 232 | 0.45707 | [
"BSD-3-Clause"
] | CityOfBurlington/btvsrp | SRP/ControlRoom/Controls/CRRibbon.ascx.cs | 2,343 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace egg.db.SqlStatements {
/// <summary>
/// 数据更新语句
/// </summary>
public class Update : egg.Object, ISqlStringable {
// 数据库连接
private Connection _dbc;
// 表对象
private SqlUnits.Table _table;
// 更新键字段对象
private SqlUnits.TableField _keyField;
// 行数据对象
private Row _row;
// 筛选条件
private SqlUnits.Formula _where;
/// <summary>
/// 获取是否为复杂对象
/// </summary>
public bool IsComplicated { get { return true; } set { } }
/// <summary>
/// 对象实例化
/// </summary>
/// <param name="dbc">数据库连接</param>
/// <param name="table">表对象</param>
/// <param name="row">数据行对象</param>
/// <param name="keyField">更新键字段</param>
public Update(Connection dbc, SqlUnits.Table table, Row row, SqlUnits.TableField keyField = null) {
_dbc = dbc;
_table = table;
_row = row;
_keyField = keyField;
}
/// <summary>
/// 设置筛选条件
/// </summary>
/// <param name="formula"></param>
/// <returns></returns>
public Update Where(SqlUnits.Formula formula) {
_where = formula;
return this;
}
/// <summary>
/// 获取标准SQL字符串
/// </summary>
/// <param name="tp"></param>
/// <param name="multiTable"></param>
/// <returns></returns>
public string ToSqlString(DatabaseTypes tp, bool multiTable = false) {
string res = "UPDATE ";
res += _table.ToSqlString(tp);
res += " SET ";
string cols = "";
string keyCol = "";
if (!Equals(_keyField, null)) keyCol = _keyField.ToString();
foreach (var key in _row.Keys) {
if (key != keyCol) {
if (cols != "") cols += ",";
using (SqlUnits.TableField field = new SqlUnits.TableField(_table, key)) {
cols += field.ToSqlString(tp);
}
//cols += $" = '{_row[key]}'";
switch (tp) {
case DatabaseTypes.MySQL:
cols += $" = '{_row[key].Replace("'", "\'")}'";
break;
//return $"'{_value.Replace("'", "\'")}'";
case DatabaseTypes.Microsoft_Office_Access:
case DatabaseTypes.Microsoft_Office_Access_v12:
case DatabaseTypes.Microsoft_SQL_Server:
case DatabaseTypes.SQLite:
case DatabaseTypes.SQLite_3:
case DatabaseTypes.PostgreSQL:
cols += $" = '{_row[key].Replace("'", "''")}'";
break;
//return $"'{_value.Replace("'", "''")}'";
default:
throw new Exception($"尚未支持数据库 {tp.ToString()} 中的字符串转义。");
}
}
}
res += cols;
if (!keyCol.IsNone()) {
res += " WHERE ";
using (SqlUnits.TableField field = new SqlUnits.TableField(_table, keyCol)) {
res += field.ToSqlString(tp);
switch (tp) {
case DatabaseTypes.MySQL:
res += $" = '{_row[keyCol].Replace("'", "\'")}'";
break;
//return $"'{_value.Replace("'", "\'")}'";
case DatabaseTypes.Microsoft_Office_Access:
case DatabaseTypes.Microsoft_Office_Access_v12:
case DatabaseTypes.Microsoft_SQL_Server:
case DatabaseTypes.SQLite:
case DatabaseTypes.SQLite_3:
case DatabaseTypes.PostgreSQL:
res += $" = '{_row[keyCol].Replace("'", "''")}'";
break;
//return $"'{_value.Replace("'", "''")}'";
default:
throw new Exception($"尚未支持数据库 {tp.ToString()} 中的字符串转义。");
}
//res += $" = '{_row[keyCol]}'";
}
} else {
if (!Equals(_where, null)) {
res += " WHERE " + _where.ToSqlString(tp);
}
}
return res;
}
/// <summary>
/// 获取标准SQL字符串
/// </summary>
/// <returns></returns>
public string ToSqlString() { return ToSqlString(_dbc.DatabaseType); }
/// <summary>
/// 执行更新
/// </summary>
/// <returns></returns>
public int Exec() {
return _dbc.Exec(this.ToSqlString());
}
}
}
| 33.932432 | 107 | 0.428116 | [
"MIT"
] | inmount/e | egg.db/SqlStatements/Update.cs | 5,256 | C# |
namespace Multiformats.Base
{
internal class Base64Padded : Base64
{
private static readonly char[] _alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".ToCharArray();
protected override string Name => "base64pad";
protected override char Prefix => 'M';
protected override char[] Alphabet => _alphabet;
public override byte[] Decode(string input) => Decode(input, false, true);
public override string Encode(byte[] bytes) => Encode(bytes, false, true);
}
} | 36.466667 | 133 | 0.685558 | [
"MIT"
] | 0xced/cs-multibase | src/Multiformats.Base/Base64.Padded.cs | 549 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace IAMWebServer._login2 {
public partial class recover_st1 {
/// <summary>
/// holderContent control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.PlaceHolder holderContent;
}
}
| 31.28 | 84 | 0.478261 | [
"Apache-2.0"
] | helviojunior/safeid | IAMWebServer/IAMWebServer/_login2/recover_st1.aspx.designer.cs | 784 | C# |
using System;
using Android.App;
using TestClientXamarin.Droid.Implementation;
using TestClientXamarin.Interface;
using Xamarin.Forms;
[assembly: Xamarin.Forms.Dependency(typeof(AndroidCloseAppImplementation))]
namespace TestClientXamarin.Droid.Implementation
{
public class AndroidCloseAppImplementation : IAndroidCloseApp
{
public void CloseApp()
{
var activity = (Activity)Forms.Context;
activity.FinishAffinity();
}
}
}
| 25.095238 | 75 | 0.667932 | [
"Apache-2.0"
] | JoacimWall/CoreCom | src/CoreCom/Samples/Client/TestClientXamarin/TestClientXamarin.Android/Implementation/AndroidCloseAppImplementation.cs | 529 | C# |
using System.IdentityModel.Tokens.Jwt;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace IdentityServer.ClientSample
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc(config =>
{
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
config.Filters.Add(new AuthorizeFilter(policy));
config.Filters.Add(new AutoValidateAntiforgeryTokenAttribute());
});
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
services.AddAuthentication(options =>
{
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options => { options.Cookie.Name = "aspnetmvcclient"; })
.AddOpenIdConnect(OpenIdConnectDefaults.AuthenticationScheme, options =>
{
options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.Authority = Configuration["ActiveLogin:IdentityProvider:Authority"];
options.ClientId = "mvc";
options.ClientSecret = "secret";
options.ResponseType = "code id_token";
options.SaveTokens = true;
options.Scope.Clear();
options.Scope.Add("openid");
options.Scope.Add("profile");
options.Scope.Add("personalidentitynumber");
options.UseTokenLifetime = true;
});
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseHttpsRedirection();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseAuthentication();
app.UseStaticFiles();
app.UseMvcWithDefaultRoute();
}
}
}
| 34.925 | 134 | 0.606299 | [
"MIT"
] | FredrikK/ActiveLogin.Authentication | samples/IdentityServer.ClientSample/Startup.cs | 2,796 | C# |
// -----------------------------------------------------------------
// <copyright file="IEventRuleCreationArguments.cs" company="2Dudes">
// Copyright (c) 2018 2Dudes. All rights reserved.
// Author: Jose L. Nunez de Caceres
// jlnunez89@gmail.com
// http://linkedin.com/in/jlnunez89
//
// Licensed under the MIT license.
// See LICENSE.txt file in the project root for full license information.
// </copyright>
// -----------------------------------------------------------------
namespace OpenTibia.Server.Contracts.Abstractions
{
/// <summary>
/// Interface for arguments when creating event rules.
/// </summary>
public interface IEventRuleCreationArguments
{
}
}
| 31.590909 | 73 | 0.571223 | [
"MIT"
] | Codinablack/fibula-server | src/Fibula.Server.Contracts/Abstractions/IEventRuleCreationArguments.cs | 697 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Runtime.CompilerServices;
using System.Collections.ObjectModel;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
#if FEATURE_EVENTSOURCE_XPLAT
namespace System.Diagnostics.Tracing
{
internal class XplatEventLogger : EventListener
{
private static readonly Lazy<string?> eventSourceNameFilter = new Lazy<string?>(() => CompatibilitySwitch.GetValueInternal("EventSourceFilter"));
private static readonly Lazy<string?> eventSourceEventFilter = new Lazy<string?>(() => CompatibilitySwitch.GetValueInternal("EventNameFilter"));
public XplatEventLogger() {}
private static bool initializedPersistentListener;
public static EventListener? InitializePersistentListener()
{
try
{
if (!initializedPersistentListener && XplatEventLogger.IsEventSourceLoggingEnabled())
{
initializedPersistentListener = true;
return new XplatEventLogger();
}
}
catch (Exception) { }
return null;
}
[DllImport(RuntimeHelpers.QCall, CharSet = CharSet.Unicode)]
private static extern bool IsEventSourceLoggingEnabled();
[DllImport(RuntimeHelpers.QCall, CharSet = CharSet.Unicode)]
private static extern void LogEventSource(int eventID, string? eventName, string eventSourceName, string payload);
private static readonly List<char> escape_seq = new List<char> { '\b', '\f', '\n', '\r', '\t', '\"', '\\' };
private static readonly Dictionary<char, string> seq_mapping = new Dictionary<char, string>()
{
{'\b', "b"},
{'\f', "f"},
{'\n', "n"},
{'\r', "r"},
{'\t', "t"},
{'\"', "\\\""},
{'\\', "\\\\"}
};
private static void minimalJsonserializer(string payload, StringBuilder sb)
{
foreach (var elem in payload)
{
if (escape_seq.Contains(elem))
{
sb.Append("\\\\");
sb.Append(seq_mapping[elem]);
}
else
{
sb.Append(elem);
}
}
}
private static string Serialize(ReadOnlyCollection<string>? payloadName, ReadOnlyCollection<object?>? payload, string? eventMessage)
{
if (payloadName == null || payload == null)
return string.Empty;
if (payloadName.Count == 0 || payload.Count == 0)
return string.Empty;
int eventDataCount = payloadName.Count;
if (payloadName.Count != payload.Count)
{
eventDataCount = Math.Min(payloadName.Count, payload.Count);
}
var sb = StringBuilderCache.Acquire();
sb.Append('{');
// If the event has a message, send that as well as a pseudo-field
if (!string.IsNullOrEmpty(eventMessage))
{
sb.Append("\\\"EventSource_Message\\\":\\\"");
minimalJsonserializer(eventMessage, sb);
sb.Append("\\\"");
if (eventDataCount != 0)
sb.Append(", ");
}
for (int i = 0; i < eventDataCount; i++)
{
if (i != 0)
sb.Append(", ");
var fieldstr = payloadName[i].ToString();
sb.Append("\\\"");
sb.Append(fieldstr);
sb.Append("\\\"");
sb.Append(':');
switch (payload[i])
{
case string str:
{
sb.Append("\\\"");
minimalJsonserializer(str, sb);
sb.Append("\\\"");
break;
}
case byte[] byteArr:
{
sb.Append("\\\"");
AppendByteArrayAsHexString(sb, byteArr);
sb.Append("\\\"");
break;
}
default:
{
if (payload[i] != null)
{
sb.Append(payload[i]!.ToString()); // TODO-NULLABLE: Indexer nullability tracked (https://github.com/dotnet/roslyn/issues/34644)
}
break;
}
}
}
sb.Append('}');
return StringBuilderCache.GetStringAndRelease(sb);
}
private static void AppendByteArrayAsHexString(StringBuilder builder, byte[] byteArray)
{
Debug.Assert(builder != null);
Debug.Assert(byteArray != null);
ReadOnlySpan<char> hexFormat = "X2";
Span<char> hex = stackalloc char[2];
for (int i=0; i<byteArray.Length; i++)
{
byteArray[i].TryFormat(hex, out int charsWritten, hexFormat);
Debug.Assert(charsWritten == 2);
builder.Append(hex);
}
}
protected internal override void OnEventSourceCreated(EventSource eventSource)
{
// Don't enable forwarding of NativeRuntimeEventSource events.`
if (eventSource.GetType() == typeof(NativeRuntimeEventSource))
{
return;
}
string? eventSourceFilter = eventSourceNameFilter.Value;
if (string.IsNullOrEmpty(eventSourceFilter) || (eventSource.Name.IndexOf(eventSourceFilter, StringComparison.OrdinalIgnoreCase) >= 0))
{
EnableEvents(eventSource, EventLevel.LogAlways, EventKeywords.All, null);
}
}
protected internal override void OnEventWritten(EventWrittenEventArgs eventData)
{
string? eventFilter = eventSourceEventFilter.Value;
if (string.IsNullOrEmpty(eventFilter) || (eventData.EventName!.IndexOf(eventFilter, StringComparison.OrdinalIgnoreCase) >= 0))
{
LogOnEventWritten(eventData);
}
}
private void LogOnEventWritten(EventWrittenEventArgs eventData)
{
string payload = "";
if (eventData.Payload != null)
{
try{
payload = Serialize(eventData.PayloadNames, eventData.Payload, eventData.Message);
}
catch (Exception ex)
{
payload = "XplatEventLogger failed with Exception " + ex.ToString();
}
}
LogEventSource(eventData.EventId, eventData.EventName, eventData.EventSource.Name, payload);
}
}
}
#endif //FEATURE_EVENTSOURCE_XPLAT
| 35.323529 | 156 | 0.514571 | [
"MIT"
] | 2m0nd/runtime | src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/XplatEventLogger.cs | 7,206 | C# |
using PVScan.Desktop.WPF.ViewModels;
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace PVScan.Desktop.WPF.Views
{
/// <summary>
/// Interaction logic for SortingPage.xaml
/// </summary>
public partial class SortingPage : ContentControl
{
public event EventHandler Closed;
SortingPageViewModel VM;
public SortingPage()
{
InitializeComponent();
VM = DataContext as SortingPageViewModel;
}
private void AvailiableSortingFieldsListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (VM == null)
{
return;
}
VM.SortingFieldSelectedCommand.Execute(AvailiableSortingFieldsListView.SelectedItem);
}
private void CloseButton_Click(object sender, RoutedEventArgs e)
{
Closed?.Invoke(this, new EventArgs());
}
}
}
| 25.22449 | 113 | 0.666667 | [
"MIT"
] | meJevin/PVScan | Source/Desktop/Windows/PVScan.Desktop.WPF/Views/SortingPage.xaml.cs | 1,238 | C# |
using System.IO;
using Bari.Core.Generic;
namespace Bari.Plugins.PythonScripts.Scripting
{
/// <summary>
/// Build script defined by individual files in the suite's <c>scripts</c> directory.
///
/// <para>
/// The script file's name defines the source set for which it is automatically executed.
///
/// <example>
/// A build script with the suite relative path <c>scripts\icons.py</c> will be executed on
/// every project's <c>icons</c> source set, if it has one.
/// </example>
/// </para>
/// </summary>
public class SimplePythonBuildScript : IBuildScript
{
private readonly string name;
private readonly string script;
/// <summary>
/// Gets the source set's name to be included in the script's scope
/// </summary>
public string SourceSetName
{
get { return name; }
}
/// <summary>
/// Gets the script's name
/// </summary>
public string Name
{
get { return name; }
}
/// <summary>
/// Gets the script source
/// </summary>
public string Source
{
get { return script; }
}
public SimplePythonBuildScript(SuiteRelativePath scriptPath, [SuiteRoot] IFileSystemDirectory suiteRoot)
{
name = Path.GetFileNameWithoutExtension(scriptPath);
using (var reader = suiteRoot.ReadTextFile(scriptPath))
{
script = reader.ReadToEnd();
}
}
}
} | 28.285714 | 112 | 0.558081 | [
"Apache-2.0"
] | Psychobilly87/bari | src/scripting/Bari.Plugins.PythonScripts/cs/Scripting/SimplePythonBuildScript.cs | 1,586 | C# |
using System;
using System.Collections.Generic;
using Gallio.Collections;
using Gallio.Framework.Pattern;
using Gallio.Reflection;
using NBehave.Core;
namespace NBehave.Spec.Framework
{
/// <summary>
/// When applied to a method of a context class, declares a setup action to be performed before
/// evaluating all of its specifications.
/// </summary>
[AttributeUsage(PatternAttributeTargets.ContributionMethod, AllowMultiple = false, Inherited = true)]
public class ContextSetUpAttribute : ContributionMethodPatternAttribute
{
/// <inheritdoc />
protected override void DecorateContainingScope(PatternEvaluationScope containingScope, IMethodInfo method)
{
containingScope.Test.TestInstanceActions.SetUpTestInstanceChain.Before(
delegate(PatternTestInstanceState testInstanceState)
{
testInstanceState.InvokeFixtureMethod(method, EmptyArray<KeyValuePair<ISlotInfo, object>>.Instance);
});
}
/// <inheritdoc />
protected override void Validate(PatternEvaluationScope containingScope, IMethodInfo method)
{
base.Validate(containingScope, method);
if (! containingScope.IsTestDeclaration
|| containingScope.Test.Kind != NBehaveTestKinds.Context)
throw new PatternUsageErrorException("The [ContextSetUp] attribute can only appear on a method within a context class.");
}
}
} | 39.657895 | 137 | 0.69144 | [
"ECL-2.0",
"Apache-2.0"
] | citizenmatt/gallio | contrib/NBehave/NBehave/Spec/Framework/ContextSetUpAttribute.cs | 1,507 | C# |
using System.ComponentModel.Composition;
using SamplePrism.Domain.Models.Accounts;
namespace SamplePrism.Services.Implementations.PrinterModule.ValueChangers
{
[Export]
public class AccountTransactionValueChanger : AbstractValueChanger<AccountTransaction>
{
public override string GetTargetTag()
{
return "TRANSACTIONS";
}
protected override string GetModelName(AccountTransaction model)
{
return model.Name;
}
}
} | 26.526316 | 90 | 0.69246 | [
"Apache-2.0"
] | XYRYTeam/SimplePrism | SamplePrism.Presentation.Services/CommonServices/Implementations/PrinterModule/ValueChangers/AccountTransactionValueChanger.cs | 504 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.