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 |
|---|---|---|---|---|---|---|---|---|
namespace CarDealer.Web.Controllers
{
using CarDealer.Services;
using CarDealer.Web.Models.Cars;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using System.Collections.Generic;
using System.Linq;
[Route("car")]
public class CarController : Controller
{
private readonly ICarService carService;
private readonly IPartService partService;
public CarController(ICarService carService, IPartService partService)
{
this.carService = carService;
this.partService = partService;
}
[Authorize]
[Route(nameof(Add))]
public IActionResult Add()
{
var model = new CarFormModel
{
OptionalParts = this.PartsIdNames()
};
return View(model);
}
[Authorize]
[HttpPost]
[Route(nameof(Add))]
public IActionResult Add(CarFormModel carFormModel)
{
if (!ModelState.IsValid)
{
carFormModel.OptionalParts = this.PartsIdNames();
return View(carFormModel);
}
this.carService.Add(
carFormModel.Make,
carFormModel.Model,
carFormModel.TravelledDistance,
carFormModel.SelectedPartsIds);
return RedirectToAction(nameof(CarsWithParts));
}
private IEnumerable<SelectListItem> PartsIdNames()
{
return this
.partService
.GetAllIdNames()
.Select(p => new SelectListItem
{
Text = p.Name,
Value = p.Id.ToString()
});
}
[Route(nameof(PagedCars) + "/{currentPage}")]
public IActionResult PagedCars(int currentPage = 1)
{
return View(this.carService.PagedCars(currentPage));
}
[Route(nameof(CarsByMake) + "/{make}")]
public IActionResult CarsByMake(string make)
{
var cars = this.carService.GetCarsByMake(make);
return View(cars);
}
[Route(nameof(CarDetails) +"/{id}")]
public IActionResult CarDetails(int id)
{
return View(this.carService.CarDetails(id));
}
[Route(nameof(CarsWithParts))]
public IActionResult CarsWithParts()
{
return View(this.carService.CarsDetails());
}
}
}
| 27.755319 | 78 | 0.543503 | [
"MIT"
] | NikolaVodenicharov/ASP.NET-Core | CarDealer/CarDealer.Web/Controllers/CarController.cs | 2,611 | C# |
using System;
using System.Threading.Tasks;
namespace Havit.Blazor.Components.Web
{
public interface IHxMessageBoxService
{
Task<MessageBoxButtons> ShowAsync(MessageBoxRequest request);
Func<MessageBoxRequest, Task<MessageBoxButtons>> OnShowAsync { get; set; }
}
}
| 21.153846 | 76 | 0.789091 | [
"MIT"
] | havit/Havit.Blazor | Havit.Blazor.Components.Web/Dialogs/IHxMessageBoxService.cs | 277 | C# |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="[PROJECT_NAME_CLASSNAME_PREFIX]DummyFactory.designer.cs" company="Naos Project">
// Copyright (c) Naos Project 2019. All rights reserved.
// </copyright>
// <auto-generated>
// Sourced from NuGet package [VISUAL_STUDIO_TEMPLATE_PACKAGE_ID] ([VISUAL_STUDIO_TEMPLATE_PACKAGE_VERSION])
// </auto-generated>
// --------------------------------------------------------------------------------------------------------------------
namespace [PROJECT_NAME]
{
using System;
using FakeItEasy;
/// <summary>
/// DO NOT EDIT.
/// THIS CLASS EXISTS SO THAT THE DUMMY FACTORY CAN INHERIT FROM IT AND THE PROJECT CAN COMPILE.
/// THIS WILL BE REPLACED BY A CODE GENERATED DEFAULT DUMMY FACTORY.
/// </summary>
[System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
[System.CodeDom.Compiler.GeneratedCode("[VISUAL_STUDIO_TEMPLATE_PACKAGE_ID]", "[VISUAL_STUDIO_TEMPLATE_PACKAGE_VERSION]")]
#if ![SOLUTION_NAME_CONDITIONAL_COMPILATION_SYMBOL]
internal
#else
public
#endif
abstract class Default[PROJECT_NAME_CLASSNAME_PREFIX]DummyFactory : IDummyFactory
{
/// <inheritdoc />
public Priority Priority => new FakeItEasy.Priority(1);
/// <inheritdoc />
public bool CanCreate(Type type)
{
return false;
}
/// <inheritdoc />
public object Create(Type type)
{
return null;
}
}
} | 34.888889 | 126 | 0.572611 | [
"MIT"
] | NaosProject/Naos.Build | Conventions/VisualStudioProjectTemplates/Domain.Test/[PROJECT_NAME_CLASSNAME_PREFIX]dummyfactory.designer.cs | 1,572 | C# |
using Servant.Service.Implemention.Injector;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
await builder.Services.AddIdentityServicesAsync(builder.Configuration);
var app = builder.Build();
app.UseSwagger();
app.UseSwaggerUI();
app.UseCors(c =>
{
c.AllowAnyHeader()
.AllowAnyMethod()
.AllowAnyOrigin();
});
//app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
await app.RunAsync(); | 21.451613 | 88 | 0.766917 | [
"Apache-2.0"
] | Ftmco/Identity | Identity/Server/Identity.Server.Api/Program.cs | 665 | C# |
using System;
using System.Collections.Generic;
using System.Xml;
namespace IDevTrack.Coder.Document
{
/// <summary>
/// This class is used for storing the state of a bookmark manager
/// </summary>
public class BookmarkManagerMemento
{
List<int> bookmarks = new List<int>();
/// <value>
/// Contains all bookmarks as int values
/// </value>
public List<int> Bookmarks {
get {
return bookmarks;
}
set {
bookmarks = value;
}
}
/// <summary>
/// Validates all bookmarks if they're in range of the document.
/// (removing all bookmarks < 0 and bookmarks > max. line number
/// </summary>
public void CheckMemento(IDocument document)
{
for (int i = 0; i < bookmarks.Count; ++i) {
int mark = (int)bookmarks[i];
if (mark < 0 || mark >= document.TotalNumberOfLines) {
bookmarks.RemoveAt(i);
--i;
}
}
}
/// <summary>
/// Creates a new instance of <see cref="BookmarkManagerMemento"/>
/// </summary>
public BookmarkManagerMemento()
{
}
/// <summary>
/// Creates a new instance of <see cref="BookmarkManagerMemento"/>
/// </summary>
public BookmarkManagerMemento(XmlElement element)
{
foreach (XmlElement el in element.ChildNodes) {
bookmarks.Add(Int32.Parse(el.Attributes["line"].InnerText));
}
}
/// <summary>
/// Creates a new instance of <see cref="BookmarkManagerMemento"/>
/// </summary>
public BookmarkManagerMemento(List<int> bookmarks)
{
this.bookmarks = bookmarks;
}
/// <summary>
/// Converts a xml element to a <see cref="BookmarkManagerMemento"/> object
/// </summary>
public object FromXmlElement(XmlElement element)
{
return new BookmarkManagerMemento(element);
}
/// <summary>
/// Converts this <see cref="BookmarkManagerMemento"/> to a xml element
/// </summary>
public XmlElement ToXmlElement(XmlDocument doc)
{
XmlElement bookmarknode = doc.CreateElement("Bookmarks");
foreach (int line in bookmarks) {
XmlElement markNode = doc.CreateElement("Mark");
XmlAttribute lineAttr = doc.CreateAttribute("line");
lineAttr.InnerText = line.ToString();
markNode.Attributes.Append(lineAttr);
bookmarknode.AppendChild(markNode);
}
return bookmarknode;
}
}
}
| 24.147368 | 77 | 0.653444 | [
"MIT"
] | rayscc/dev-track | 000/Coder/Document/BookmarkManager/BookmarkManagerMemento.cs | 2,296 | C# |
using System.Threading;
using System.Threading.Tasks;
using BoltOn.Logging;
using BoltOn.Requestor.Pipeline;
namespace BoltOn.Tests.Bus.Fakes
{
public class CreateTestStudent : IRequest
{
public string FirstName { get; set; }
}
public class CreateTestStudentHandler : IHandler<CreateTestStudent>
{
private readonly IAppLogger<CreateTestStudentHandler> _logger;
public CreateTestStudentHandler(IAppLogger<CreateTestStudentHandler> logger)
{
_logger = logger;
}
public async Task HandleAsync(CreateTestStudent request, CancellationToken cancellationToken)
{
_logger.Debug($"{nameof(CreateTestStudentHandler)} invoked");
await Task.FromResult("testing");
}
}
}
| 26.517241 | 101 | 0.702211 | [
"MIT"
] | BoltOnSuite/BoltOn | tests/BoltOn.Tests/Bus/Fakes/CreateTestStudentHandler.cs | 771 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using Discord;
using Discord.WebSocket;
using Discord.Commands;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
namespace ArbitesLog
{
public class GenUtilModule : ModuleBase<SocketCommandContext>
{
[Command("BotInfo")]
[Summary("Displays info on bot")]
public async Task BotInfoAsync()
{
var vernum = Assembly.GetEntryAssembly().GetCustomAttribute<AssemblyInformationalVersionAttribute>().InformationalVersion;
var app = await Context.Client.GetApplicationInfoAsync();
await ReplyAsync($"```\nArbitesLog\n\n/========General Info========\\ \nVersion {vernum}\nOwned by {app.Owner}\nBuilt With Discord.NET version {DiscordConfig.Version}\nRunning on {RuntimeInformation.FrameworkDescription} {RuntimeInformation.ProcessArchitecture} On {RuntimeInformation.OSDescription} {RuntimeInformation.OSArchitecture}\n\n/========Stats========\\ \nHeap Size: {GetHeapSize()}MiB\nGuilds Connected: {Context.Client.Guilds.Count}\nChannels: {Context.Client.Guilds.Sum(g => g.Channels.Count)}\nUsers: {Context.Client.Guilds.Sum(g => g.Users.Count)}\nUptime: {GetUptime()}\n```");
}
private static string GetHeapSize() => Math.Round(GC.GetTotalMemory(true) / (1024.0 * 1024.0), 2).ToString();
private static string GetUptime() => (DateTime.Now - Process.GetCurrentProcess().StartTime).ToString(@"dd\.hh\:mm\:ss");
}
}
| 49.566667 | 596 | 0.754539 | [
"MIT"
] | primebie1/ArbitesLog | ArbitesLog/GenUtilModule.cs | 1,489 | C# |
using System.ComponentModel;
using System.Runtime.CompilerServices;
using Uno;
using Uno.Diagnostics.Eventing;
using Uno.UI.DataBinding;
using Windows.ApplicationModel.Core;
using Windows.Foundation;
using Windows.Foundation.Metadata;
using Windows.UI.Core;
using Windows.UI.Xaml.Data;
namespace Windows.UI.Xaml.Controls;
[NotImplemented]
[Windows.UI.Xaml.Data.Bindable]
public class RatingItemInfo : DependencyObject, IDependencyObjectStoreProvider, IWeakReferenceProvider
{
private DependencyObjectStore __storeBackingField;
private static readonly IEventProvider _binderTrace = Tracing.Get(DependencyObjectStore.TraceProvider.Id);
private BinderReferenceHolder _refHolder;
private ManagedWeakReference _selfWeakReference;
public CoreDispatcher Dispatcher => CoreApplication.MainView.Dispatcher;
private DependencyObjectStore __Store
{
get
{
if (__storeBackingField == null)
{
__storeBackingField = new DependencyObjectStore(this, DataContextProperty, TemplatedParentProperty);
__InitializeBinder();
}
return __storeBackingField;
}
}
public bool IsStoreInitialized => __storeBackingField != null;
DependencyObjectStore IDependencyObjectStoreProvider.Store => __Store;
ManagedWeakReference IWeakReferenceProvider.WeakReference
{
get
{
if (_selfWeakReference == null)
{
_selfWeakReference = WeakReferencePool.RentSelfWeakReference(this);
}
return _selfWeakReference;
}
}
public object DataContext
{
get
{
return GetValue(DataContextProperty);
}
set
{
SetValue(DataContextProperty, value);
}
}
public static DependencyProperty DataContextProperty { get; } = DependencyProperty.Register("DataContext", typeof(object), typeof(RatingItemInfo), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.Inherits, delegate(DependencyObject s, DependencyPropertyChangedEventArgs e)
{
((RatingItemInfo)s).OnDataContextChanged(e);
}));
public DependencyObject TemplatedParent
{
get
{
return (DependencyObject)GetValue(TemplatedParentProperty);
}
set
{
SetValue(TemplatedParentProperty, value);
}
}
public static DependencyProperty TemplatedParentProperty { get; } = DependencyProperty.Register("TemplatedParent", typeof(DependencyObject), typeof(RatingItemInfo), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.Inherits | FrameworkPropertyMetadataOptions.ValueDoesNotInheritDataContext | FrameworkPropertyMetadataOptions.WeakStorage, delegate(DependencyObject s, DependencyPropertyChangedEventArgs e)
{
((RatingItemInfo)s).OnTemplatedParentChanged(e);
}));
[EditorBrowsable(EditorBrowsableState.Never)]
internal bool IsAutoPropertyInheritanceEnabled
{
get
{
return __Store.IsAutoPropertyInheritanceEnabled;
}
set
{
__Store.IsAutoPropertyInheritanceEnabled = value;
}
}
public event TypedEventHandler<FrameworkElement, DataContextChangedEventArgs> DataContextChanged;
[NotImplemented(new string[] { "__ANDROID__", "__IOS__", "NET461", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__", "__MACOS__" })]
public RatingItemInfo()
{
ApiInformation.TryRaiseNotImplemented("Windows.UI.Xaml.Controls.RatingItemInfo", "RatingItemInfo.RatingItemInfo()");
}
public object GetValue(DependencyProperty dp)
{
return __Store.GetValue(dp);
}
public void SetValue(DependencyProperty dp, object value)
{
__Store.SetValue(dp, value);
}
public void ClearValue(DependencyProperty dp)
{
__Store.ClearValue(dp);
}
public object ReadLocalValue(DependencyProperty dp)
{
return __Store.ReadLocalValue(dp);
}
public object GetAnimationBaseValue(DependencyProperty dp)
{
return __Store.GetAnimationBaseValue(dp);
}
public long RegisterPropertyChangedCallback(DependencyProperty dp, DependencyPropertyChangedCallback callback)
{
return __Store.RegisterPropertyChangedCallback(dp, callback);
}
public void UnregisterPropertyChangedCallback(DependencyProperty dp, long token)
{
__Store.UnregisterPropertyChangedCallback(dp, token);
}
private void __InitializeBinder()
{
if (BinderReferenceHolder.IsEnabled)
{
_refHolder = new BinderReferenceHolder(GetType(), this);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[EditorBrowsable(EditorBrowsableState.Never)]
public void ClearBindings()
{
__Store.ClearBindings();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[EditorBrowsable(EditorBrowsableState.Never)]
public void RestoreBindings()
{
__Store.RestoreBindings();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[EditorBrowsable(EditorBrowsableState.Never)]
public void ApplyCompiledBindings()
{
}
public override string ToString()
{
return GetType().FullName;
}
protected internal virtual void OnDataContextChanged(DependencyPropertyChangedEventArgs e)
{
this.DataContextChanged?.Invoke(null, new DataContextChangedEventArgs(DataContext));
}
protected internal virtual void OnTemplatedParentChanged(DependencyPropertyChangedEventArgs e)
{
__Store.SetTemplatedParent(e.NewValue as FrameworkElement);
}
public void SetBinding(object target, string dependencyProperty, BindingBase binding)
{
__Store.SetBinding(target, dependencyProperty, binding);
}
public void SetBinding(string dependencyProperty, BindingBase binding)
{
__Store.SetBinding(dependencyProperty, binding);
}
public void SetBinding(DependencyProperty dependencyProperty, BindingBase binding)
{
__Store.SetBinding(dependencyProperty, binding);
}
public void SetBindingValue(object value, [CallerMemberName] string propertyName = null)
{
__Store.SetBindingValue(value, propertyName);
}
public BindingExpression GetBindingExpression(DependencyProperty dependencyProperty)
{
return __Store.GetBindingExpression(dependencyProperty);
}
public void ResumeBindings()
{
__Store.ResumeBindings();
}
public void SuspendBindings()
{
__Store.SuspendBindings();
}
}
| 26.092511 | 424 | 0.794699 | [
"MIT"
] | ljcollins25/Codeground | src/UnoApp/UnoDecompile/Uno.UI/Windows.UI.Xaml.Controls/RatingItemInfo.cs | 5,923 | C# |
// Copyright (c) Alexandre Mutel. All rights reserved.
// Licensed under the BSD-Clause 2 license.
// See license.txt file in the project root for full license information.
namespace CppAst.CodeGen.CSharp
{
public class DefaultEnumItemConverter: ICSharpConverterPlugin
{
public void Register(CSharpConverter converter, CSharpConverterPipeline pipeline)
{
pipeline.EnumItemConverters.Add(ConvertEnumItem);
}
public static CSharpElement ConvertEnumItem(CSharpConverter converter, CppEnumItem cppEnumItem, CSharpElement context)
{
// If the context is not an enum, we don't support this scenario.
if (!(context is CSharpEnum csEnum)) return null;
var enumItemName = converter.GetCSharpName(cppEnumItem, context);
var csEnumItem = new CSharpEnumItem(enumItemName)
{
CppElement = cppEnumItem
};
csEnum.Members.Add(csEnumItem);
csEnumItem.Comment = converter.GetCSharpComment(cppEnumItem, context);
// Process any enum item value expression (e.g ENUM_ITEM = 1 << 2)
if (cppEnumItem.ValueExpression != null)
{
var integerValue = converter.ConvertExpression(cppEnumItem.ValueExpression, csEnumItem, csEnum.IntegerBaseType);
csEnumItem.Value = $"unchecked(({csEnum.IntegerBaseType}){(string.IsNullOrEmpty(integerValue) ? cppEnumItem.Value + "" : integerValue)})";
// Tag the enum has a flags
if (!csEnum.IsFlags && csEnumItem.Value.Contains("<<"))
{
csEnum.IsFlags = true;
}
}
if (converter.Options.GenerateEnumItemAsFields && context.Parent is CSharpClass csClass)
{
var csEnumItemAsField = new CSharpField(enumItemName)
{
Modifiers = CSharpModifiers.Const,
FieldType = csEnum,
Comment = csEnumItem.Comment,
InitValue = $"{csEnum.Name}.{csEnumItem.Name}"
};
converter.ApplyDefaultVisibility(csEnumItemAsField, csClass);
csClass.Members.Add(csEnumItemAsField);
}
return csEnumItem;
}
}
} | 41.385965 | 154 | 0.597711 | [
"BSD-2-Clause"
] | StephenHodgson/CppAst.CodeGen | src/CppAst.CodeGen/CSharp/Plugins/DefaultEnumItemConverter.cs | 2,361 | 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 Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System.Threading.Tasks;
namespace BasicLinkedApp;
public class Startup
{
public void Configure(IApplicationBuilder app)
{
app.UseMiddleware<HelloWorldMiddleware>();
}
}
public class HelloWorldMiddleware
{
public HelloWorldMiddleware(RequestDelegate next)
{
}
public Task InvokeAsync(HttpContext context)
{
return context.Response.WriteAsync("Hello World");
}
}
| 20.4375 | 71 | 0.724771 | [
"MIT"
] | AndrewTriesToCode/aspnetcore | src/Hosting/test/testassets/BasicLinkedApp/Startup.cs | 654 | C# |
using System;
using Microsoft.EntityFrameworkCore.Migrations;
namespace P03_SalesDatabase.Data.Migrations
{
public partial class SalesAddDateDefault : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AlterColumn<DateTime>(
name: "Date",
table: "Sales",
nullable: false,
defaultValueSql: " GETDATE()",
oldClrType: typeof(DateTime));
migrationBuilder.AlterColumn<string>(
name: "Description",
table: "Products",
nullable: true,
defaultValue: "No description",
oldClrType: typeof(string),
oldNullable: true);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.AlterColumn<DateTime>(
name: "Date",
table: "Sales",
nullable: false,
oldClrType: typeof(DateTime),
oldDefaultValueSql: " GETDATE()");
migrationBuilder.AlterColumn<string>(
name: "Description",
table: "Products",
nullable: true,
oldClrType: typeof(string),
oldNullable: true,
oldDefaultValue: "No description");
}
}
}
| 31.511111 | 71 | 0.530324 | [
"MIT"
] | nikolayvutov/Database-Fundamentals | 02.Database-Advanced/04.Code-First/SalesDatabase/Data/Migrations/20180709202719_SalesAddDateDefault.cs | 1,420 | C# |
using System;
using System.Xml.Serialization;
namespace Aop.Api.Domain
{
/// <summary>
/// AlipayCommerceEducateEdumigrateMigrateserviceModifyModel Data Structure.
/// </summary>
[Serializable]
public class AlipayCommerceEducateEdumigrateMigrateserviceModifyModel : AopObject
{
/// <summary>
/// 调用的服务名称 操作类型 + 具体服务名称
/// </summary>
[XmlElement("handler")]
public string Handler { get; set; }
/// <summary>
/// 迁移服务的具体参数 JSON结构
/// </summary>
[XmlElement("params")]
public string Params { get; set; }
}
}
| 25.56 | 86 | 0.58216 | [
"Apache-2.0"
] | 554393109/alipay-sdk-net-all | AlipaySDKNet.Standard/Domain/AlipayCommerceEducateEdumigrateMigrateserviceModifyModel.cs | 695 | C# |
#region Using
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Reflection;
using PocoGenerator.Generators.Interfaces;
using PocoGenerator.Models;
using RazorEngine;
using RazorEngine.Templating;
#endregion
namespace PocoGenerator.Generators
{
public class MsSqlGenerator : IGenerator
{
private GenerationOptions _options;
private MsSqlTypeConvertion _typeConverter = new MsSqlTypeConvertion();
public void LoadOptions(GenerationOptions options)
{
_options = options;
if (!Directory.Exists(_options.OutputPath))
Directory.CreateDirectory(_options.OutputPath);
}
public void Generate()
{
var tables = GetDatabaseTables();
PopulateTableFields(tables);
GenerateFiles(tables);
}
public List<SqlTable> GetDatabaseTables()
{
var result = new List<SqlTable>();
var data = GetDbTablesFromSql();
if (data != null && data.Rows.Count > 0)
{
foreach (DataRow row in data.Rows)
{
SqlTable table = new SqlTable
{
Name = Convert.ToString(row["TABLE_NAME"]),
ClassName = Utility.GetClassName(Convert.ToString(row["TABLE_NAME"]))
};
result.Add(table);
}
}
return result;
}
public void PopulateTableFields(List<SqlTable> tables)
{
var query = @"SELECT
c.name 'Column Name',
t.Name 'Data type',
isc.CHARACTER_MAXIMUM_LENGTH 'Max Length',
c.precision ,
c.scale ,
c.is_nullable,
ISNULL(i.is_primary_key, 0) 'Primary Key'
FROM
sys.columns c
join
information_schema.columns isc on isc.COLUMN_NAME = c.name and isc.table_name = '{0}'
INNER JOIN
sys.types t ON c.user_type_id = t.user_type_id
LEFT OUTER JOIN
sys.index_columns ic ON ic.object_id = c.object_id AND ic.column_id = c.column_id
LEFT OUTER JOIN
sys.indexes i ON ic.object_id = i.object_id AND ic.index_id = i.index_id
WHERE
c.object_id = OBJECT_ID(isc.TABLE_SCHEMA + '.{0}')";
foreach (SqlTable table in tables)
{
var fieldData = ExecuteSelectQuery(string.Format(query, table.Name));
if (fieldData != null)
{
foreach (DataRow row in fieldData.Rows)
{
int length;
var field = new SqlField();
field.Name = (string) row["Column Name"];
field.DbType = (string) row["Data type"];
field.Type = _typeConverter.GetType(field.DbType);
field.IsPrimaryKey = (bool) row["Primary Key"];
field.Length = int.TryParse(Convert.ToString(row["Max Length"]), out length) ? length : 0;
table.Fields.Add(field);
}
}
}
}
private void GenerateFiles(List<SqlTable> tables)
{
string template = GetTemplate();
foreach (SqlTable table in tables)
{
var model = new TemplateData();
model.Namespace = _options.Namespace;
model.Table = table;
model.NamespaceImports = new List<string>();
model.NamespaceImports.AddRange(_options.Using);
model.GenerateDapperExtentionsMapperClass = _options.GenerateDapperExtentionsMapperClass;
var result = Engine.Razor.RunCompile(new LoadedTemplateSource(template), "PocoGenerator.Templates.PocoTemplate.cshtml", typeof (TemplateData), model);
var fileName = string.Format(_options.OutputFileExtention, table.Name);
var savePath = string.Format("{0}\\{1}", _options.OutputPath.TrimEnd('\\'), fileName);
File.WriteAllText(savePath, result);
}
}
private string GetTemplate()
{
var assembly = Assembly.GetExecutingAssembly();
var resourceName = "PocoGenerator.Templates.PocoTemplate.cshtml";
using (Stream stream = assembly.GetManifestResourceStream(resourceName))
{
using (StreamReader reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
}
}
private DataTable GetDbTablesFromSql()
{
string query = string.Format("SELECT * FROM information_schema.tables WHERE TABLE_CATALOG = '{0}' AND TABLE_TYPE = 'BASE TABLE'", _options.DatabaseName);
var tables = ExecuteSelectQuery(query);
return tables;
}
private DataTable ExecuteSelectQuery(string Query)
{
DataTable data = new DataTable();
using (SqlConnection connection = new SqlConnection(_options.ConnectionString))
{
connection.Open();
using (SqlCommand cmd = new SqlCommand(Query, connection))
{
SqlDataReader dr = cmd.ExecuteReader();
data.Load(dr);
dr.Close();
}
}
return data;
}
}
} | 34.350575 | 166 | 0.512632 | [
"MIT"
] | ockertv/PocoGenerator | src/PocoGenerator/Generators/MsSqlGenerator.cs | 5,979 | C# |
#region Apache License Version 2.0
/*----------------------------------------------------------------
Copyright 2019 Jeffrey Su & Suzhou Senparc Network Technology Co.,Ltd.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the
License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
either express or implied. See the License for the specific language governing permissions
and limitations under the License.
Detail: https://github.com/JeffreySu/WeiXinMPSDK/blob/master/license.md
----------------------------------------------------------------*/
#endregion Apache License Version 2.0
/*----------------------------------------------------------------
Copyright (C) 2019 Senparc
文件名:GetWeAnalysisAppidWeeklyVisitTrendResultJson.cs
文件功能描述:小程序“数据分析”接口 - 访问趋势:周趋势 返回结果
创建标识:Senparc - 20180101
----------------------------------------------------------------*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Senparc.Weixin.Entities;
namespace Senparc.Weixin.WxOpen.AdvancedAPIs.DataCube
{
/// <summary>
/// 小程序“数据分析”接口 - 访问趋势:周趋势 返回结果
/// </summary>
public class GetWeAnalysisAppidWeeklyVisitTrendResultJson : WxJsonResult
{
public List<GetWeAnalysisAppidWeeklyVisitTrendResultJson_list> list { get; set; }
}
/// <summary>
/// 小程序“数据分析”接口 - 访问趋势:周趋势 返回结果 - list
/// </summary>
public class GetWeAnalysisAppidWeeklyVisitTrendResultJson_list
{
/// <summary>
/// 时间,如:"20170306-20170312"
/// </summary>
public string ref_date { get; set; }
/// <summary>
/// 打开次数(自然周内汇总)
/// </summary>
public int session_cnt { get; set; }
/// <summary>
/// 访问次数(自然周内汇总)
/// </summary>
public int visit_pv { get; set; }
/// <summary>
/// 访问人数(自然周内去重)
/// </summary>
public int visit_uv { get; set; }
/// <summary>
/// 新用户数(自然周内去重)
/// </summary>
public int visit_uv_new { get; set; }
/// <summary>
/// 人均停留时长 (浮点型,单位:秒)
/// </summary>
public double stay_time_uv { get; set; }
/// <summary>
/// 次均停留时长 (浮点型,单位:秒)
/// </summary>
public double stay_time_session { get; set; }
/// <summary>
/// 平均访问深度 (浮点型)
/// </summary>
public double visit_depth { get; set; }
}
}
| 30.988636 | 90 | 0.56509 | [
"Apache-2.0"
] | 370041597/WeiXinMPSDK | src/Senparc.Weixin.WxOpen/src/Senparc.Weixin.WxOpen/Senparc.Weixin.WxOpen/AdvancedAPIs/DataCube/DataCubeJson/GetWeAnalysisAppidWeeklyVisitTrendResultJson.cs | 3,079 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("04.DragonArmyMy")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("04.DragonArmyMy")]
[assembly: AssemblyCopyright("Copyright © 2018")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("1e3cd893-9442-40ca-914e-5bf7247fb4ca")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.783784 | 84 | 0.747496 | [
"MIT"
] | delian1986/C-SoftUni-repo | Fundamentals of Programming/07. Exam Preparation/SampleExam/04.DragonArmyMy/Properties/AssemblyInfo.cs | 1,401 | C# |
//-----------------------------------------------------------------------------
// Filename: RTPTestStreamSink.cs
//
// Description: Sink for sending RTP streams to for diagnsotic or measuremnent
// purposes.
//
// History:
// 24 May 2005 Aaron Clauson Created.
//
// License:
// Aaron Clauson
//-----------------------------------------------------------------------------
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using SIPSorcery.Sys;
using log4net;
#if UNITTEST
using NUnit.Framework;
#endif
namespace SIPSorcery.Net
{
public delegate void RTPSinkClosed(Guid streamId, Guid callId);
public delegate void RTPDataReceived(Guid streamId, byte[] rtpPayload, IPEndPoint remoteEndPoint);
public delegate void RTPDataSent(Guid streamId, byte[] rtpPayload, IPEndPoint remoteEndPoint);
public delegate void RTPRemoteEndPointChanged(Guid streamId, IPEndPoint remoteEndPoint);
public delegate void RTCPSampleReadyDelegate(RTCPReport rtcpReport);
public delegate void RTCPReportRecievedDelegate(RTPSink rtpSink, RTCPReportPacket rtcpReportPacket);
/// <summary>
/// Threads used:
/// 1. ListenerThread to listen for incoming RTP packets on the listener socket,
/// 2. ListenerTimeoutThread shuts down the stream if a packet is not received in NO_RTP_TIMEOUT or if the stream's lifetime
/// exceeds RTPMaxStayAlive (and RTPMaxStayAlive has been set > 0),
/// 3. SenderThread sends RTP packets to remote socket.
/// </summary>
public class RTPSink
{
public const int RTP_PORTRANGE_START = 12000;
public const int RTP_PORTRANGE_END = 17000;
public const int NO_RTP_TIMEOUT = 30; // Seconds of no RTP after which the connection will be closed.
public const int RTCP_SAMPLE_WINDOW = 5; // Number of seconds at which to rollover RTCP measurements
public const int RTP_HEADER_SIZE = 12; // Number of bytes used in RTP packet for RTP header.
public const int RTP_BASEFRAME_SIZE = 15; // This should only be set in increments of 15ms because the timing resolution of Windows/.Net revolves around this figure. This means
// that even if it is set at 10, 20 or 40 it will ultimately end up being more like 15, 30 or 60.
public const int RTP_DEFAULTPACKET_SIZE = 160; // Corresponds to the default payload size for a 20ms g711 packet. Not a good idea to go
// over 1460 as Ethernet MTU = 1500. (12B RTP header, 8B UDP Header, 20B IP Header, TOTAL = 40B).
//public const int DATAGRAM_MAX_SIZE = 1460;
public const int TIMESTAMP_FACTOR = 100;
public const int TYPEOFSERVICE_RTPSEND = 47;
private static string m_typeOfService = AppState.GetConfigSetting("RTPPacketTypeOfService");
private ArrayList m_rtpChannels = new ArrayList(); // Use SetRTPChannels to adjust. List of the current RTPHeader's representing an
// individual RTP stream being sent between the two end points on this sink.
// It is the number of calls to emulate (each channel will be RTPFrameSize ms frames at RTPPacketSendSize of data). Only one channel
// is used to take packet interarrival measurements from but the data transfer rates are measurments across all data.
private int m_rtpPacketSendSize = RTP_DEFAULTPACKET_SIZE; // Bytes of data to put in RTP packet payload.
public int RTPPacketSendSize
{
get{ return m_rtpPacketSendSize; }
set
{
if(value < 0)
{
m_rtpPacketSendSize = 0;
}
else
{
m_rtpPacketSendSize = value;
/*if(value < DATAGRAM_MAX_SIZE)
{
m_rtpPacketSendSize = value;
}
else
{
m_rtpPacketSendSize = DATAGRAM_MAX_SIZE;
}*/
}
}
}
public int RTPFrameSize = RTP_BASEFRAME_SIZE;
public int RTPMaxStayAlive = 0; // If > 0 this specifies the maximum number of seconds the RTP stream will send for, after that time it will self destruct.
private int m_channels = 1; // This is a feature that will burst each RTP packet m_channels times, it's a way of duplicating simultaneous calls.
public int RTPChannels
{
get{ return m_channels; }
set
{
if(value < 1)
{
logger.Info("Changing RTP channels from " + m_channels + " to 1, requested value was " + value + ".");
m_channels = 1;
}
else if(value != m_channels)
{
logger.Info("Changing RTP channels from " + m_channels + " to " + value + ".");
m_channels = value;
}
}
}
private static ILog logger = AppState.GetLogger("rtp");
private IPEndPoint m_streamEndPoint;
private DateTime m_lastRTPReceivedTime = DateTime.MinValue;
private DateTime m_lastRTPSentTime = DateTime.MinValue;
private DateTime m_startRTPReceiveTime = DateTime.MinValue;
private DateTime m_startRTPSendTime = DateTime.MinValue;
// Used to time the receiver to close the connection if no data is received during a certain amount of time (NO_RTP_TIMEOUT).
private ManualResetEvent m_lastPacketReceived = new ManualResetEvent(false);
private UdpClient m_udpListener;
private IPEndPoint m_localEndPoint;
//private uint m_syncSource;
public bool StopListening = false;
public bool ShuttingDown = false;
public bool Sending = false;
public bool LogArrivals = false; // Whether to log packet arrival events.
public bool StopIfNoData = true;
public event RTPSinkClosed ListenerClosed;
public event RTPSinkClosed SenderClosed;
public event RTPDataReceived DataReceived;
public event RTPDataSent DataSent;
public event RTPRemoteEndPointChanged RemoteEndPointChanged;
public event RTCPSampleReadyDelegate RTCPReportReady;
public event RTCPReportRecievedDelegate RTCPReportReceived;
private RTCPReportSampler m_rtcpSampler = null;
public uint LastReceivedReportNumber = 0; // The report number of the last RTCP report received from the remote end.
#region Properties.
private Guid m_streamId = Guid.NewGuid();
public Guid StreamId
{
get{ return m_streamId; }
}
private Guid m_callDescriptorId;
public Guid CallDescriptorId
{
get{ return m_callDescriptorId; }
set{ m_callDescriptorId = value; }
}
private long m_packetsSent = 0;
public long PacketsSent
{
get{ return m_packetsSent; }
}
private long m_packetsReceived = 0;
public long PacketsReceived
{
get{ return m_packetsReceived; }
}
private long m_bytesSent = 0;
public long BytesSent
{
get{ return m_bytesSent; }
}
private long m_bytesReceived = 0;
public long BytesReceived
{
get{ return m_bytesReceived; }
}
//private MemoryStream m_rtpStream = new MemoryStream();
// Info only variables to validate what the RCTP report is producing.
//private DateTime m_sampleStartTime = DateTime.MinValue;
//private int m_samplePackets;
//private int m_sampleBytes;
private UInt16 m_sampleStartSeqNo;
public int ListenPort
{
get{ return m_localEndPoint.Port; }
}
public IPEndPoint ClientEndPoint
{
get{ return m_localEndPoint; }
}
public IPEndPoint RemoteEndPoint
{
get{ return m_streamEndPoint; }
}
#endregion
public RTPSink(IPAddress localAddress, ArrayList inUsePorts)
{
m_udpListener = NetServices.CreateRandomUDPListener(localAddress, RTP_PORTRANGE_START, RTP_PORTRANGE_END, inUsePorts, out m_localEndPoint);
int typeOfService = TYPEOFSERVICE_RTPSEND;
// If a setting has been supplied in the config file use that.
Int32.TryParse(m_typeOfService, out typeOfService);
try
{
m_udpListener.Client.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.TypeOfService, typeOfService);
logger.Debug("Setting RTP packet ToS to " + m_typeOfService + ".");
}
catch (Exception excp)
{
logger.Warn("Exception setting IP type of service for RTP packet to " + typeOfService + ". " + excp.Message);
}
logger.Info("RTPSink established on " + m_localEndPoint.Address.ToString() + ":" + m_localEndPoint.Port + ".");
//receiveLogger.Info("Send Time,Send Timestamp,Receive Time,Receive Timestamp,Receive Offset(ms),Timestamp Diff,SeqNum,Bytes");
//sendLogger.Info("Send Time,Send Timestamp,Send Offset(ms),SeqNum,Bytes");
}
public RTPSink(IPEndPoint localEndPoint)
{
m_localEndPoint = localEndPoint;
m_udpListener = new UdpClient(m_localEndPoint);
int typeOfService = TYPEOFSERVICE_RTPSEND;
// If a setting has been supplied in the config file use that.
Int32.TryParse(m_typeOfService, out typeOfService);
try
{
m_udpListener.Client.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.TypeOfService, typeOfService);
logger.Debug("Setting RTP packet ToS to " + m_typeOfService + ".");
}
catch (Exception excp)
{
logger.Warn("Exception setting IP type of service for RTP packet to " + typeOfService + ". " + excp.Message);
}
logger.Info("RTPSink established on " + m_localEndPoint.Address.ToString() + ":" + m_localEndPoint.Port + ".");
//receiveLogger.Info("Receive Time,Receive Offset (ms),SeqNum,Bytes");
//sendLogger.Info("Send Time,Send Offset (ms),SeqNum,Bytes");
}
public void StartListening()
{
try
{
Thread rtpListenerThread = new Thread(new ThreadStart(Listen));
rtpListenerThread.Start();
if (StopIfNoData)
{
// If the stream should be shutdown after receiving no data for the timeout period then this thread gets started to mointor receives.
Thread rtpListenerTimeoutThread = new Thread(new ThreadStart(ListenerTimeout));
rtpListenerTimeoutThread.Start();
}
}
catch(Exception excp)
{
logger.Error("Exception Starting RTP Listener Threads. " + excp.Message);
throw excp;
}
}
private void Listen()
{
try
{
UdpClient udpSvr = m_udpListener;
if (udpSvr == null)
{
logger.Error("The UDP server was not correctly initialised in the RTP sink when attempting to start the listener, the RTP stream has not been intialised.");
return;
}
else
{
logger.Debug("RTP Listener now listening on " + m_localEndPoint.Address + ":" + m_localEndPoint.Port + ".");
}
IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
byte[] rcvdBytes = null;
m_startRTPReceiveTime = DateTime.MinValue;
m_lastRTPReceivedTime = DateTime.MinValue;
DateTime previousRTPReceiveTime = DateTime.MinValue;
uint previousTimestamp = 0;
UInt16 sequenceNumber = 0;
UInt16 previousSeqNum = 0;
uint senderSendSpacing = 0;
uint lastSenderSendSpacing = 0;
while (!StopListening)
{
rcvdBytes = null;
try
{
rcvdBytes = udpSvr.Receive(ref remoteEndPoint);
}
catch
{
//logger.Warn("Remote socket closed on receive. Last RTP received " + m_lastRTPReceivedTime.ToString("dd MMM yyyy HH:mm:ss") + ", last RTP successfull send " + m_lastRTPSentTime.ToString("dd MMM yyyy HH:mm:ss") + ".");
}
if (rcvdBytes != null && rcvdBytes.Length > 0)
{
// Check whether this is an RTCP report.
UInt16 firstWord = BitConverter.ToUInt16(rcvdBytes, 0);
if (BitConverter.IsLittleEndian)
{
firstWord = NetConvert.DoReverseEndian(firstWord);
}
ushort packetType = 0;
if (BitConverter.IsLittleEndian)
{
packetType = Convert.ToUInt16(firstWord & 0x00ff);
}
if (packetType == RTCPHeader.RTCP_PACKET_TYPE)
{
logger.Debug("RTP Listener received remote RTCP report from " + remoteEndPoint + ".");
try
{
RTCPPacket rtcpPacket = new RTCPPacket(rcvdBytes);
RTCPReportPacket rtcpReportPacket = new RTCPReportPacket(rtcpPacket.Reports);
if (RTCPReportReceived != null)
{
RTCPReportReceived(this, rtcpReportPacket);
}
}
catch (Exception rtcpExcp)
{
logger.Error("Exception processing remote RTCP report. " + rtcpExcp.Message);
}
continue;
}
// Channel statistics.
DateTime rtpReceiveTime = DateTime.Now;
if (m_startRTPReceiveTime == DateTime.MinValue)
{
m_startRTPReceiveTime = rtpReceiveTime;
//m_sampleStartTime = rtpReceiveTime;
}
previousRTPReceiveTime = new DateTime(m_lastRTPReceivedTime.Ticks);
m_lastRTPReceivedTime = rtpReceiveTime;
m_packetsReceived++;
m_bytesReceived += rcvdBytes.Length;
previousSeqNum = sequenceNumber;
// This stops the thread running the ListenerTimeout method from deciding the strema has recieved no RTP and therefore should be shutdown.
m_lastPacketReceived.Set();
// Let whoever has subscribed that an RTP packet has been received.
if (DataReceived != null)
{
try
{
DataReceived(m_streamId, rcvdBytes, remoteEndPoint);
}
catch (Exception excp)
{
logger.Error("Exception RTPSink DataReceived. " + excp.Message);
}
}
if (m_packetsReceived % 500 == 0)
{
logger.Debug("Total packets received from " + remoteEndPoint.ToString() + " " + m_packetsReceived + ", bytes " + NumberFormatter.ToSIByteFormat(m_bytesReceived, 2) + ".");
}
try
{
RTPPacket rtpPacket = new RTPPacket(rcvdBytes);
uint syncSource = rtpPacket.Header.SyncSource;
uint timestamp = rtpPacket.Header.Timestamp;
sequenceNumber = rtpPacket.Header.SequenceNumber;
//logger.Debug("seqno=" + rtpPacket.Header.SequenceNumber + ", timestamp=" + timestamp);
if (previousRTPReceiveTime != DateTime.MinValue)
{
//uint senderSendSpacing = rtpPacket.Header.Timestamp - previousTimestamp;
// Need to cope with cases where the timestamp has looped, if this timestamp is < last timesatmp and there is a large difference in them then it's because the timestamp counter has looped.
lastSenderSendSpacing = senderSendSpacing;
senderSendSpacing = (Math.Abs(timestamp - previousTimestamp) > (uint.MaxValue / 2)) ? timestamp + uint.MaxValue - previousTimestamp : timestamp - previousTimestamp;
if (previousTimestamp > timestamp)
{
logger.Error("BUG: Listener previous timestamp (" + previousTimestamp + ") > timestamp (" + timestamp + "), last seq num=" + previousSeqNum + ", seqnum=" + sequenceNumber + ".");
// Cover for this bug until it's nailed down.
senderSendSpacing = lastSenderSendSpacing;
}
double senderSpacingMilliseconds = (double)senderSendSpacing / (double)TIMESTAMP_FACTOR;
double interarrivalReceiveTime = m_lastRTPReceivedTime.Subtract(previousRTPReceiveTime).TotalMilliseconds;
#region RTCP reporting.
if (m_rtcpSampler == null)
{
//resultsLogger.Info("First Packet: " + rtpPacket.Header.SequenceNumber + "," + m_arrivalTime.ToString("HH:mm:fff"));
m_rtcpSampler = new RTCPReportSampler(m_streamId, syncSource, remoteEndPoint, rtpPacket.Header.SequenceNumber, m_lastRTPReceivedTime, rcvdBytes.Length);
m_rtcpSampler.RTCPReportReady += new RTCPSampleReadyDelegate(m_rtcpSampler_RTCPReportReady);
m_rtcpSampler.StartSampling();
}
else
{
//m_receiverReports[syncSource].RecordRTPReceive(rtpPacket.Header.SequenceNumber, sendTime, rtpReceiveTime, rcvdBytes.Length);
// Transit time is calculated by knowing that the sender sent a packet at a certain time after the last send and the receiver received a pakcet a certain time after the last receive.
// The difference in these two times is the jitter present. The transit time can change with each transimission and as this methid relies on two sends two packet
// arrivals to calculate the transit time it's not going to be perfect (you'd need synchronised NTP clocks at each end to be able to be accurate).
// However if used tor an average calculation it should be pretty close.
//double transitTime = Math.Abs(interarrivalReceiveTime - senderSpacingMilliseconds);
uint jitter = (interarrivalReceiveTime - senderSpacingMilliseconds > 0) ? Convert.ToUInt32(interarrivalReceiveTime - senderSpacingMilliseconds) : 0;
if(jitter > 75)
{
logger.Debug("seqno=" + rtpPacket.Header.SequenceNumber + ", timestmap=" + timestamp + ", ts-prev=" + previousTimestamp + ", receive spacing=" + interarrivalReceiveTime + ", send spacing=" + senderSpacingMilliseconds + ", jitter=" + jitter);
}
else
{
//logger.Debug("seqno=" + rtpPacket.Header.SequenceNumber + ", receive spacing=" + interarrivalReceiveTime + ", timestamp=" + timestamp + ", transit time=" + transitTime);
}
m_rtcpSampler.RecordRTPReceive(m_lastRTPReceivedTime, rtpPacket.Header.SequenceNumber, rcvdBytes.Length, jitter);
}
#endregion
}
else
{
logger.Debug("RTPSink Listen SyncSource=" + rtpPacket.Header.SyncSource + ".");
}
previousTimestamp = timestamp;
}
catch (Exception excp)
{
logger.Error("Received data was not a valid RTP packet. " + excp.Message);
}
#region Switching endpoint if required to cope with NAT.
// If a packet is recieved from an endpoint that wasn't expected treat the stream as being NATted and switch the endpoint to the socket on the NAT server.
try
{
if (m_streamEndPoint != null && m_streamEndPoint.Address != null && remoteEndPoint != null && remoteEndPoint.Address != null && (m_streamEndPoint.Address.ToString() != remoteEndPoint.Address.ToString() || m_streamEndPoint.Port != remoteEndPoint.Port))
{
logger.Debug("Expecting RTP on " + IPSocket.GetSocketString(m_streamEndPoint) + " but received on " + IPSocket.GetSocketString(remoteEndPoint) + ", now sending to " + IPSocket.GetSocketString(remoteEndPoint) + ".");
m_streamEndPoint = remoteEndPoint;
if (RemoteEndPointChanged != null)
{
try
{
RemoteEndPointChanged(m_streamId, remoteEndPoint);
}
catch (Exception changeExcp)
{
logger.Error("Exception RTPListener Changing Remote EndPoint. " + changeExcp.Message);
}
}
}
}
catch (Exception setSendExcp)
{
logger.Error("Exception RTPListener setting SendTo Socket. " + setSendExcp.Message);
}
#endregion
}
else if (!StopListening) // Empty packet was received possibly indicating connection closure so check for timeout.
{
double noRTPRcvdDuration = (m_lastRTPReceivedTime != DateTime.MinValue) ? DateTime.Now.Subtract(m_lastRTPReceivedTime).TotalSeconds : 0;
double noRTPSentDuration = (m_lastRTPSentTime != DateTime.MinValue) ? DateTime.Now.Subtract(m_lastRTPSentTime).TotalSeconds : 0;
//logger.Warn("Remote socket closed on receive on " + m_localEndPoint.Address.ToString() + ":" + + m_localEndPoint.Port + ", reinitialising. No rtp for " + noRTPRcvdDuration + "s. last rtp " + m_lastRTPReceivedTime.ToString("dd MMM yyyy HH:mm:ss") + ".");
// If this check is not done then the stream will never time out if it doesn't receive the first packet.
if (m_lastRTPReceivedTime == DateTime.MinValue)
{
m_lastRTPReceivedTime = DateTime.Now;
}
remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
if ((noRTPRcvdDuration > NO_RTP_TIMEOUT || noRTPSentDuration > NO_RTP_TIMEOUT) && StopIfNoData)
{
logger.Warn("Disconnecting RTP listener on " + m_localEndPoint.ToString() + " due to not being able to send or receive any RTP for " + NO_RTP_TIMEOUT + "s.");
Shutdown();
}
}
}
}
catch (Exception excp)
{
logger.Error("Exception Listen RTPSink: " + excp.Message);
}
finally
{
#region Shut down socket.
Shutdown();
if (ListenerClosed != null)
{
try
{
ListenerClosed(m_streamId, m_callDescriptorId);
}
catch (Exception excp)
{
logger.Error("Exception RTPSink ListenerClosed. " + excp.Message);
}
}
#endregion
}
}
private void m_rtcpSampler_RTCPReportReady(RTCPReport rtcpReport)
{
if (rtcpReport != null && RTCPReportReady != null)
{
try
{
RTCPReportReady(rtcpReport);
rtcpReport.LastReceivedReportNumber = LastReceivedReportNumber;
//if (rtcpReport.ReportNumber % 3 != 0)
//{
SendRTCPReport(RTCPReportTypesEnum.RTCP, rtcpReport.GetBytes());
//}
}
catch (Exception excp)
{
logger.Error("Exception m_rtcpSampler_RTCPReportReady. " + excp.Message);
}
}
}
/// <summary>
/// Sends an RTCP report to the remote agent.
/// </summary>
/// <param name="rtcpReport"></param>
public void SendRTCPReport(RTCPReportTypesEnum reportType, byte[] reportData)
{
try
{
RTCPPacket rtcpPacket = new RTCPPacket(0, 0, 0, 0, 0);
RTCPReportPacket rtcpReportPacket = new RTCPReportPacket(reportType, reportData);
byte[] rtcpReportPacketBytes = rtcpReportPacket.GetBytes();
byte[] rtcpReportBytes = rtcpPacket.GetBytes(rtcpReportPacketBytes);
m_udpListener.Send(rtcpReportBytes, rtcpReportBytes.Length, m_streamEndPoint);
}
catch (Exception excp)
{
logger.Error("Exception SendRTCPReport. " + excp.Message);
}
}
private void ListenerTimeout()
{
try
{
logger.Debug("Listener timeout thread started for RTP stream " + m_streamId);
// Wait for the first RTP packet to be received.
m_lastPacketReceived.WaitOne();
// Once we've got one packet only allow a maximum of NO_RTP_TIMEOUT between packets before shutting the stream down.
while(!StopListening)
{
if(!m_lastPacketReceived.WaitOne(NO_RTP_TIMEOUT*1000, false))
{
logger.Debug("RTP Listener did not receive any packets for " + NO_RTP_TIMEOUT + "s, shutting down stream.");
Shutdown();
break;
}
// Shutdown the socket even if there is still RTP but the stay alive limit has been exceeded.
if(RTPMaxStayAlive > 0 && DateTime.Now.Subtract(m_startRTPSendTime).TotalSeconds > RTPMaxStayAlive)
{
logger.Warn("Shutting down RTPSink due to passing RTPMaxStayAlive time.");
Shutdown();
break;
}
m_lastPacketReceived.Reset();
}
}
catch(Exception excp)
{
logger.Error("Exception ListenerTimeout. " + excp.Message);
throw excp;
}
}
public void StartSending(IPEndPoint serverEndPoint)
{
m_streamEndPoint = serverEndPoint;
Thread rtpSenderThread = new Thread(new ThreadStart(Send));
rtpSenderThread.Start();
}
private void Send()
{
try
{
int payloadSize = RTPPacketSendSize;
RTPPacket rtpPacket = new RTPPacket(RTPPacketSendSize);
byte[] rtpBytes = rtpPacket.GetBytes();
RTPHeader rtpHeader = new RTPHeader();
rtpHeader.SequenceNumber = (UInt16)65000; //Convert.ToUInt16(Crypto.GetRandomInt(0, UInt16.MaxValue));
uint sendTimestamp = uint.MaxValue - 5000;
uint lastSendTimestamp = sendTimestamp;
UInt16 lastSeqNum = 0;
logger.Debug("RTP send stream starting to " + IPSocket.GetSocketString(m_streamEndPoint) + " with payload size " + payloadSize + " bytes.");
Sending = true;
m_startRTPSendTime = DateTime.MinValue;
m_lastRTPSentTime = DateTime.MinValue;
m_sampleStartSeqNo = rtpHeader.SequenceNumber;
DateTime lastRTPSendAttempt = DateTime.Now;
while (m_udpListener != null && !StopListening)
{
// This may be changed by the listener so it needs to be set each iteration.
IPEndPoint dstEndPoint = m_streamEndPoint;
//logger.Info("Sending RTP packet to " + dstEndPoint.Address + ":" + dstEndPoint.Port);
if (payloadSize != m_rtpPacketSendSize)
{
payloadSize = m_rtpPacketSendSize;
logger.Info("Changing RTP payload to " + payloadSize);
rtpPacket = new RTPPacket(RTP_HEADER_SIZE + m_rtpPacketSendSize);
rtpBytes = rtpPacket.GetBytes();
}
try
{
if (m_startRTPSendTime == DateTime.MinValue)
{
m_startRTPSendTime = DateTime.Now;
rtpHeader.MarkerBit = 0;
logger.Debug("RTPSink Send SyncSource=" + rtpPacket.Header.SyncSource + ".");
}
else
{
lastSendTimestamp = sendTimestamp;
double milliSinceLastSend = DateTime.Now.Subtract(m_lastRTPSentTime).TotalMilliseconds;
sendTimestamp = Convert.ToUInt32((lastSendTimestamp + (milliSinceLastSend * TIMESTAMP_FACTOR)) % uint.MaxValue);
if (lastSendTimestamp > sendTimestamp)
{
logger.Error("RTP Sender previous timestamp (" + lastSendTimestamp + ") > timestamp (" + sendTimestamp + ") ms since last send=" + milliSinceLastSend + ", lastseqnum=" + lastSeqNum + ", seqnum=" + rtpHeader.SequenceNumber + ".");
}
if (DateTime.Now.Subtract(m_lastRTPSentTime).TotalMilliseconds > 75)
{
logger.Debug("delayed send: " + rtpHeader.SequenceNumber + ", time since last send " + DateTime.Now.Subtract(m_lastRTPSentTime).TotalMilliseconds + "ms.");
}
}
rtpHeader.Timestamp = sendTimestamp;
byte[] rtpHeaderBytes = rtpHeader.GetBytes();
Array.Copy(rtpHeaderBytes, 0, rtpBytes, 0, rtpHeaderBytes.Length);
// Send RTP packets and any extra channels required to emulate mutliple calls.
for (int channelCount = 0; channelCount < m_channels; channelCount++)
{
//logger.Debug("Send rtp getting wallclock timestamp for " + DateTime.Now.ToString("dd MMM yyyy HH:mm:ss:fff"));
//DateTime sendTime = DateTime.Now;
//rtpHeader.Timestamp = RTPHeader.GetWallclockUTCStamp(sendTime);
//logger.Debug(rtpHeader.SequenceNumber + "," + rtpHeader.Timestamp);
m_udpListener.Send(rtpBytes, rtpBytes.Length, dstEndPoint);
m_lastRTPSentTime = DateTime.Now;
m_packetsSent++;
m_bytesSent += rtpBytes.Length;
if (m_packetsSent % 500 == 0)
{
logger.Debug("Total packets sent to " + dstEndPoint.ToString() + " " + m_packetsSent + ", bytes " + NumberFormatter.ToSIByteFormat(m_bytesSent, 2) + ".");
}
//sendLogger.Info(m_lastRTPSentTime.ToString("dd MMM yyyy HH:mm:ss:fff") + "," + m_lastRTPSentTime.Subtract(m_startRTPSendTime).TotalMilliseconds.ToString("0") + "," + rtpHeader.SequenceNumber + "," + rtpBytes.Length);
//sendLogger.Info(rtpHeader.SequenceNumber + "," + DateTime.Now.ToString("dd MMM yyyy HH:mm:ss:fff"));
if (DataSent != null)
{
try
{
DataSent(m_streamId, rtpBytes, dstEndPoint);
}
catch (Exception excp)
{
logger.Error("Exception RTPSink DataSent. " + excp.Message);
}
}
lastSeqNum = rtpHeader.SequenceNumber;
if (rtpHeader.SequenceNumber == UInt16.MaxValue)
{
//logger.Debug("RTPSink looping the sequence number in sample.");
rtpHeader.SequenceNumber = 0;
}
else
{
rtpHeader.SequenceNumber++;
}
}
}
catch (Exception excp)
{
logger.Error("Exception RTP Send. " + excp.GetType() + ". " + excp.Message);
if (excp.GetType() == typeof(SocketException))
{
logger.Error("socket exception errorcode=" + ((SocketException)excp).ErrorCode + ".");
}
logger.Warn("Remote socket closed on send. Last RTP recevied " + m_lastRTPReceivedTime.ToString("dd MMM yyyy HH:mm:ss") + ", last RTP successfull send " + m_lastRTPSentTime.ToString("dd MMM yyyy HH:mm:ss") + ".");
}
Thread.Sleep(RTPFrameSize);
#region Check for whether the stream has timed out on a send or receive and if so shut down the stream.
double noRTPRcvdDuration = (m_lastRTPReceivedTime != DateTime.MinValue) ? DateTime.Now.Subtract(m_lastRTPReceivedTime).TotalSeconds : 0;
double noRTPSentDuration = (m_lastRTPSentTime != DateTime.MinValue) ? DateTime.Now.Subtract(m_lastRTPSentTime).TotalSeconds : 0;
double testDuration = DateTime.Now.Subtract(m_startRTPSendTime).TotalSeconds;
if ((
noRTPRcvdDuration > NO_RTP_TIMEOUT ||
noRTPSentDuration > NO_RTP_TIMEOUT ||
(m_lastRTPReceivedTime == DateTime.MinValue && testDuration > NO_RTP_TIMEOUT)) // If the test request comes from a private or unreachable IP address then no RTP will ever be received.
&& StopIfNoData)
{
logger.Warn("Disconnecting RTP stream on " + m_localEndPoint.Address.ToString() + ":" + m_localEndPoint.Port + " due to not being able to send any RTP for " + NO_RTP_TIMEOUT + "s.");
StopListening = true;
}
// Shutdown the socket even if there is still RTP but the stay alive limit has been exceeded.
if (RTPMaxStayAlive > 0 && DateTime.Now.Subtract(m_startRTPSendTime).TotalSeconds > RTPMaxStayAlive)
{
logger.Warn("Shutting down RTPSink due to passing RTPMaxStayAlive time.");
Shutdown();
StopListening = true;
}
#endregion
}
}
catch (Exception excp)
{
logger.Error("Exception Send RTPSink: " + excp.Message);
}
finally
{
#region Shut down socket.
Shutdown();
if (SenderClosed != null)
{
try
{
SenderClosed(m_streamId, m_callDescriptorId);
}
catch (Exception excp)
{
logger.Error("Exception RTPSink SenderClosed. " + excp.Message);
}
}
#endregion
}
}
public void Shutdown()
{
StopListening = true;
if(!ShuttingDown)
{
ShuttingDown = true;
try
{
m_lastPacketReceived.Set();
if (m_rtcpSampler != null)
{
m_rtcpSampler.Shutdown();
}
if (m_udpListener != null)
{
m_udpListener.Close();
}
}
catch(Exception excp)
{
logger.Warn("Exception RTPSink Shutdown (shutting down listener). " + excp.Message);
}
}
}
}
}
| 44.838671 | 281 | 0.536707 | [
"BSD-3-Clause"
] | Rehan-Mirza/sipsorcery | sipsorcery-core/SIPSorcery.Net/RTP/RTPSink.cs | 37,799 | C# |
using UnityEngine;
namespace Com.LuisPedroFonseca.ProCamera2D.Platformer
{
[RequireComponent(typeof(CharacterController))]
public class PlayerInput : MonoBehaviour
{
public Transform Body;
// Player Handling
public float gravity = 20;
public float runSpeed = 12;
public float acceleration = 30;
public float jumpHeight = 12;
public int jumpsAllowed = 2;
private float currentSpeed;
private Vector3 amountToMove;
int totalJumps;
CharacterController _characterController;
void Start()
{
_characterController = GetComponent<CharacterController>();
}
void Update()
{
// Reset acceleration upon collision
if ((_characterController.collisionFlags & CollisionFlags.Sides) != 0)
{
currentSpeed = 0;
}
// If player is touching the ground
if ((_characterController.collisionFlags & CollisionFlags.Below) != 0)
{
amountToMove.y = -1f;
totalJumps = 0;
}
else
{
amountToMove.y -= gravity * Time.deltaTime;
}
// Jump
if ((Input.GetKeyDown(KeyCode.W) ||
Input.GetKeyDown(KeyCode.Space) ||
Input.GetKeyDown(KeyCode.UpArrow))
&& totalJumps < jumpsAllowed)
{
totalJumps++;
amountToMove.y = jumpHeight;
}
// Input
var targetSpeed = Input.GetAxis("Horizontal0") * runSpeed;
currentSpeed = IncrementTowards(currentSpeed, targetSpeed, acceleration);
// Reset z
if (transform.position.z != 0)
{
amountToMove.z = -transform.position.z;
}
// Set amount to move
amountToMove.x = currentSpeed;
if(amountToMove.x != 0)
Body.localScale = new Vector2(Mathf.Sign(amountToMove.x) * Mathf.Abs(Body.localScale.x), Body.localScale.y);
_characterController.Move(amountToMove * Time.deltaTime);
}
// Increase n towards target by speed
private float IncrementTowards(float n, float target, float a)
{
if (n == target)
{
return n;
}
else
{
float dir = Mathf.Sign(target - n);
n += a * Time.deltaTime * dir;
return (dir == Mathf.Sign(target - n)) ? n : target;
}
}
}
}
| 29.076087 | 124 | 0.514393 | [
"MIT"
] | AlexandrKlimkin/StickmanWars | Assets/ProCamera2D/Examples/Platformer/Scripts/Player/PlayerInput.cs | 2,675 | C# |
namespace Imagin.Common.Data
{
public enum DateTimeFormat
{
Picker,
Relative,
UpDown
}
} | 13.888889 | 30 | 0.552 | [
"BSD-2-Clause"
] | fritzmark/Imagin.NET | Imagin.Common/Data/Formats/DateTimeFormat.cs | 127 | C# |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="AllocateExportSlotsToExperiments.cs" company="Rare Crowds Inc">
// Copyright 2012-2013 Rare Crowds, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SellSideAllocation
{
/// <summary>
/// Class for allocated export slots to experimental nodes according to their ExperimentalPriorityScore
/// </summary>
internal class AllocateExportSlotsToExperiments
{
/// <summary>
/// Will distribute export slots among the nodes according to their ExperimentalPriorityScore
/// </summary>
/// <param name="tier">a node whose children have an ExperimentalPriorityScore and who have a NumberOfEligibleNodes == 1</param>
/// <returns>the tier with the ExportSlots populated</returns>
internal static Node AllocateSlots(Node tier)
{
// choose among eligible unchosen nodes according to their ExperimentalPriorityScore
var experimentalNodes = tier
.ChildNodes
.OrderByDescending(node => node.ExperimentalPriorityScore)
.Take(tier.ExportSlots);
foreach (var node in experimentalNodes)
{
node.ExportSlots = 1;
}
return tier;
}
}
}
| 41.433962 | 137 | 0.583333 | [
"Apache-2.0"
] | bewood/OpenAdStack | DynamicAllocation/SellSideAllocationEngine/AllocateExportSlotsToExperiments.cs | 2,198 | C# |
using System;
namespace SPICA.Serialization.Attributes
{
[AttributeUsage(AttributeTargets.Field)]
class RepeatPointerAttribute : Attribute { }
}
| 19.375 | 48 | 0.767742 | [
"Unlicense"
] | AkelaSnow/SPICA | SPICA/Serialization/Attributes/RepeatPointerAttribute.cs | 157 | C# |
using System;
using System.Collections.Generic;
using BenchmarkDotNet.Attributes;
namespace Collections.Pooled.Benchmarks.PooledQueue
{
#if NETCOREAPP2_2
[CoreJob]
#elif NET472
[ClrJob]
#endif
[MemoryDiagnoser]
public class Queue_Peek : QueueBase
{
[Benchmark(Baseline = true)]
public void QueuePeek()
{
if (Type == QueueType.Int)
{
int result;
for (int i = 0; i < N; i++)
{
result = intQueue.Peek();
}
}
else
{
string result;
for (int i = 0; i < N; i++)
{
result = stringQueue.Peek();
}
}
}
[Benchmark]
public void PooledPeek()
{
if (Type == QueueType.Int)
{
int result;
for (int i = 0; i < N; i++)
{
result = intPooled.Peek();
}
}
else
{
string result;
for (int i = 0; i < N; i++)
{
result = stringPooled.Peek();
}
}
}
[Params(10000, 100000, 1000000)]
public int N;
[Params(QueueType.Int, QueueType.String)]
public QueueType Type;
private Queue<int> intQueue;
private Queue<string> stringQueue;
private PooledQueue<int> intPooled;
private PooledQueue<string> stringPooled;
private int[] numbers;
private string[] strings;
[GlobalSetup]
public void GlobalSetup()
{
numbers = CreateArray(N);
if (Type == QueueType.String)
{
strings = Array.ConvertAll(numbers, x => x.ToString());
}
}
[IterationSetup]
public void IterationSetup()
{
if (Type == QueueType.Int)
{
intQueue = new Queue<int>(numbers);
intPooled = new PooledQueue<int>(numbers);
}
else
{
stringQueue = new Queue<string>(strings);
stringPooled = new PooledQueue<string>(strings);
}
}
[IterationCleanup]
public void IterationCleanup()
{
intPooled?.Dispose();
stringPooled?.Dispose();
}
}
}
| 24.298077 | 71 | 0.436486 | [
"MIT"
] | ipavel83/Collections.Pooled | Collections.Pooled.Benchmarks/PooledQueue/Queue.Peek.cs | 2,529 | C# |
/*
AspxCommerce® - http://www.aspxcommerce.com
Copyright (c) 2011-2015 by AspxCommerce
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 OF OTHER DEALINGS IN THE SOFTWARE.
*/
using System;
using SageFrame.Web;
using AspxCommerce.Core;
using SageFrame.Core;
public partial class Modules_AspxCommerce_AspxTagsManagement_AllTags : BaseAdministrationUserControl
{
public int StoreID, PortalID;
public string UserName, CultureName;
public string NoImageAllTagsPath;
public string NewItemTagRss, RssFeedUrl;
protected void page_init(object sender, EventArgs e)
{
try
{
UserModuleID = SageUserModuleID;
InitializeJS();
}
catch (Exception ex)
{
ProcessException(ex);
}
}
protected void Page_Load(object sender, EventArgs e)
{
try
{
if (!IsPostBack)
{
IncludeCss("AllTags", "/Templates/" + TemplateName + "/css/GridView/tablesort.css", "/Templates/" + TemplateName + "/css/MessageBox/style.css", "/Templates/" + TemplateName + "/css/PopUp/style.css");
IncludeJs("AllTags", "/js/MessageBox/jquery.easing.1.3.js", "/js/MessageBox/alertbox.js","/js/PopUp/custom.js", "/js/GridView/jquery.grid.js", "/js/GridView/SagePaging.js",
"/js/GridView/jquery.global.js", "/js/GridView/jquery.dateFormat.js", "/js/FormValidation/jquery.validate.js", "/Modules/AspxCommerce/AspxTagsManagement/js/AllTags.js", "/js/CurrencyFormat/jquery.formatCurrency-1.4.0.js",
"/js/CurrencyFormat/jquery.formatCurrency.all.js");
StoreID = GetStoreID;
PortalID = GetPortalID;
UserName = GetUsername;
CultureName = GetCurrentCultureName;
StoreSettingConfig ssc = new StoreSettingConfig();
NoImageAllTagsPath = ssc.GetStoreSettingsByKey(StoreSetting.DefaultProductImageURL, StoreID, PortalID, CultureName);
NewItemTagRss = ssc.GetStoreSettingsByKey(StoreSetting.NewItemTagRss, StoreID, PortalID, CultureName);
if(NewItemTagRss.ToLower()=="true")
{
RssFeedUrl = ssc.GetStoreSettingsByKey(StoreSetting.RssFeedURL, StoreID, PortalID, CultureName);
}
}
IncludeLanguageJS();
}
catch (Exception ex)
{
ProcessException(ex);
}
}
private void InitializeJS()
{
Page.ClientScript.RegisterClientScriptInclude("JTablesorter", ResolveUrl("~/js/GridView/jquery.tablesorter.js"));
Page.ClientScript.RegisterClientScriptInclude("Paging", ResolveUrl("~/js/Paging/jquery.pagination.js"));
}
public string UserModuleID { get; set; }
}
| 41.21978 | 249 | 0.677686 | [
"MIT"
] | AspxCommerce/AspxCommerce2.7 | SageFrame/Modules/AspxCommerce/AspxTagsManagement/AllTags.ascx.cs | 3,754 | C# |
using NHapi.Base.Parser;
using NHapi.Base;
using NHapi.Base.Log;
using System;
using System.Collections.Generic;
using NHapi.Model.V281.Segment;
using NHapi.Model.V281.Datatype;
using NHapi.Base.Model;
namespace NHapi.Model.V281.Group
{
///<summary>
///Represents the ORL_O43_SPECIMEN Group. A Group is an ordered collection of message
/// segments that can repeat together or be optionally in/excluded together.
/// This Group contains the following elements:
///<ol>
///<li>0: SPM (Specimen) </li>
///<li>1: ORL_O43_SPECIMEN_OBSERVATION (a Group object) optional repeating</li>
///<li>2: NTE (Notes and Comments) optional repeating</li>
///<li>3: ORL_O43_SPECIMEN_CONTAINER (a Group object) repeating</li>
///</ol>
///</summary>
[Serializable]
public class ORL_O43_SPECIMEN : AbstractGroup {
///<summary>
/// Creates a new ORL_O43_SPECIMEN Group.
///</summary>
public ORL_O43_SPECIMEN(IGroup parent, IModelClassFactory factory) : base(parent, factory){
try {
this.add(typeof(SPM), true, false);
this.add(typeof(ORL_O43_SPECIMEN_OBSERVATION), false, true);
this.add(typeof(NTE), false, true);
this.add(typeof(ORL_O43_SPECIMEN_CONTAINER), true, true);
} catch(HL7Exception e) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error creating ORL_O43_SPECIMEN - this is probably a bug in the source code generator.", e);
}
}
///<summary>
/// Returns SPM (Specimen) - creates it if necessary
///</summary>
public SPM SPM {
get{
SPM ret = null;
try {
ret = (SPM)this.GetStructure("SPM");
} catch(HL7Exception e) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e);
throw new System.Exception("An unexpected error ocurred",e);
}
return ret;
}
}
///<summary>
/// Returns first repetition of ORL_O43_SPECIMEN_OBSERVATION (a Group object) - creates it if necessary
///</summary>
public ORL_O43_SPECIMEN_OBSERVATION GetSPECIMEN_OBSERVATION() {
ORL_O43_SPECIMEN_OBSERVATION ret = null;
try {
ret = (ORL_O43_SPECIMEN_OBSERVATION)this.GetStructure("SPECIMEN_OBSERVATION");
} catch(HL7Exception e) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e);
throw new System.Exception("An unexpected error ocurred",e);
}
return ret;
}
///<summary>
///Returns a specific repetition of ORL_O43_SPECIMEN_OBSERVATION
/// * (a Group object) - creates it if necessary
/// throws HL7Exception if the repetition requested is more than one
/// greater than the number of existing repetitions.
///</summary>
public ORL_O43_SPECIMEN_OBSERVATION GetSPECIMEN_OBSERVATION(int rep) {
return (ORL_O43_SPECIMEN_OBSERVATION)this.GetStructure("SPECIMEN_OBSERVATION", rep);
}
/**
* Returns the number of existing repetitions of ORL_O43_SPECIMEN_OBSERVATION
*/
public int SPECIMEN_OBSERVATIONRepetitionsUsed {
get{
int reps = -1;
try {
reps = this.GetAll("SPECIMEN_OBSERVATION").Length;
} catch (HL7Exception e) {
string message = "Unexpected error accessing data - this is probably a bug in the source code generator.";
HapiLogFactory.GetHapiLog(GetType()).Error(message, e);
throw new System.Exception(message);
}
return reps;
}
}
/**
* Enumerate over the ORL_O43_SPECIMEN_OBSERVATION results
*/
public IEnumerable<ORL_O43_SPECIMEN_OBSERVATION> SPECIMEN_OBSERVATIONs
{
get
{
for (int rep = 0; rep < SPECIMEN_OBSERVATIONRepetitionsUsed; rep++)
{
yield return (ORL_O43_SPECIMEN_OBSERVATION)this.GetStructure("SPECIMEN_OBSERVATION", rep);
}
}
}
///<summary>
///Adds a new ORL_O43_SPECIMEN_OBSERVATION
///</summary>
public ORL_O43_SPECIMEN_OBSERVATION AddSPECIMEN_OBSERVATION()
{
return this.AddStructure("SPECIMEN_OBSERVATION") as ORL_O43_SPECIMEN_OBSERVATION;
}
///<summary>
///Removes the given ORL_O43_SPECIMEN_OBSERVATION
///</summary>
public void RemoveSPECIMEN_OBSERVATION(ORL_O43_SPECIMEN_OBSERVATION toRemove)
{
this.RemoveStructure("SPECIMEN_OBSERVATION", toRemove);
}
///<summary>
///Removes the ORL_O43_SPECIMEN_OBSERVATION at the given index
///</summary>
public void RemoveSPECIMEN_OBSERVATIONAt(int index)
{
this.RemoveRepetition("SPECIMEN_OBSERVATION", index);
}
///<summary>
/// Returns first repetition of NTE (Notes and Comments) - creates it if necessary
///</summary>
public NTE GetNTE() {
NTE ret = null;
try {
ret = (NTE)this.GetStructure("NTE");
} catch(HL7Exception e) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e);
throw new System.Exception("An unexpected error ocurred",e);
}
return ret;
}
///<summary>
///Returns a specific repetition of NTE
/// * (Notes and Comments) - creates it if necessary
/// throws HL7Exception if the repetition requested is more than one
/// greater than the number of existing repetitions.
///</summary>
public NTE GetNTE(int rep) {
return (NTE)this.GetStructure("NTE", rep);
}
/**
* Returns the number of existing repetitions of NTE
*/
public int NTERepetitionsUsed {
get{
int reps = -1;
try {
reps = this.GetAll("NTE").Length;
} catch (HL7Exception e) {
string message = "Unexpected error accessing data - this is probably a bug in the source code generator.";
HapiLogFactory.GetHapiLog(GetType()).Error(message, e);
throw new System.Exception(message);
}
return reps;
}
}
/**
* Enumerate over the NTE results
*/
public IEnumerable<NTE> NTEs
{
get
{
for (int rep = 0; rep < NTERepetitionsUsed; rep++)
{
yield return (NTE)this.GetStructure("NTE", rep);
}
}
}
///<summary>
///Adds a new NTE
///</summary>
public NTE AddNTE()
{
return this.AddStructure("NTE") as NTE;
}
///<summary>
///Removes the given NTE
///</summary>
public void RemoveNTE(NTE toRemove)
{
this.RemoveStructure("NTE", toRemove);
}
///<summary>
///Removes the NTE at the given index
///</summary>
public void RemoveNTEAt(int index)
{
this.RemoveRepetition("NTE", index);
}
///<summary>
/// Returns first repetition of ORL_O43_SPECIMEN_CONTAINER (a Group object) - creates it if necessary
///</summary>
public ORL_O43_SPECIMEN_CONTAINER GetSPECIMEN_CONTAINER() {
ORL_O43_SPECIMEN_CONTAINER ret = null;
try {
ret = (ORL_O43_SPECIMEN_CONTAINER)this.GetStructure("SPECIMEN_CONTAINER");
} catch(HL7Exception e) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e);
throw new System.Exception("An unexpected error ocurred",e);
}
return ret;
}
///<summary>
///Returns a specific repetition of ORL_O43_SPECIMEN_CONTAINER
/// * (a Group object) - creates it if necessary
/// throws HL7Exception if the repetition requested is more than one
/// greater than the number of existing repetitions.
///</summary>
public ORL_O43_SPECIMEN_CONTAINER GetSPECIMEN_CONTAINER(int rep) {
return (ORL_O43_SPECIMEN_CONTAINER)this.GetStructure("SPECIMEN_CONTAINER", rep);
}
/**
* Returns the number of existing repetitions of ORL_O43_SPECIMEN_CONTAINER
*/
public int SPECIMEN_CONTAINERRepetitionsUsed {
get{
int reps = -1;
try {
reps = this.GetAll("SPECIMEN_CONTAINER").Length;
} catch (HL7Exception e) {
string message = "Unexpected error accessing data - this is probably a bug in the source code generator.";
HapiLogFactory.GetHapiLog(GetType()).Error(message, e);
throw new System.Exception(message);
}
return reps;
}
}
/**
* Enumerate over the ORL_O43_SPECIMEN_CONTAINER results
*/
public IEnumerable<ORL_O43_SPECIMEN_CONTAINER> SPECIMEN_CONTAINERs
{
get
{
for (int rep = 0; rep < SPECIMEN_CONTAINERRepetitionsUsed; rep++)
{
yield return (ORL_O43_SPECIMEN_CONTAINER)this.GetStructure("SPECIMEN_CONTAINER", rep);
}
}
}
///<summary>
///Adds a new ORL_O43_SPECIMEN_CONTAINER
///</summary>
public ORL_O43_SPECIMEN_CONTAINER AddSPECIMEN_CONTAINER()
{
return this.AddStructure("SPECIMEN_CONTAINER") as ORL_O43_SPECIMEN_CONTAINER;
}
///<summary>
///Removes the given ORL_O43_SPECIMEN_CONTAINER
///</summary>
public void RemoveSPECIMEN_CONTAINER(ORL_O43_SPECIMEN_CONTAINER toRemove)
{
this.RemoveStructure("SPECIMEN_CONTAINER", toRemove);
}
///<summary>
///Removes the ORL_O43_SPECIMEN_CONTAINER at the given index
///</summary>
public void RemoveSPECIMEN_CONTAINERAt(int index)
{
this.RemoveRepetition("SPECIMEN_CONTAINER", index);
}
}
}
| 30.118644 | 154 | 0.700394 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | AMCN41R/nHapi | src/NHapi.Model.V281/Group/ORL_O43_SPECIMEN.cs | 8,885 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using AgateLib.Drivers;
using Tao.Sdl;
namespace AgateSDL
{
using Audio;
using Input;
class Reporter : AgateDriverReporter
{
public override IEnumerable<AgateDriverInfo> ReportDrivers()
{
if (SdlInstalled() == false)
yield break;
yield return new AgateDriverInfo(
AudioTypeID.SDL,
typeof(SDL_Audio),
"SDL with SDL_mixer",
300);
yield return new AgateDriverInfo(
InputTypeID.SDL,
typeof(SDL_Input),
"SDL Input",
300);
}
private bool SdlInstalled()
{
try
{
Sdl.SDL_QuitSubSystem(Sdl.SDL_INIT_AUDIO);
SdlMixer.Mix_CloseAudio();
return true;
}
catch(DllNotFoundException)
{
return false;
}
}
}
}
| 22.875 | 69 | 0.468124 | [
"MIT"
] | dtsudo/DT-Danmaku | Dependencies/AgateLib/Agate031/Source/Drivers/AgateSDL/Reporter.cs | 1,100 | C# |
using System.Text.RegularExpressions;
using Abp.Extensions;
namespace SuperRocket.AspNetCoreAngular.Validation
{
public static class ValidationHelper
{
public const string EmailRegex = @"^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$";
public static bool IsEmail(string value)
{
if (value.IsNullOrEmpty())
{
return false;
}
var regex = new Regex(EmailRegex);
return regex.IsMatch(value);
}
}
}
| 23.545455 | 91 | 0.53668 | [
"MIT"
] | dystudio/SuperRocket.AspNetCoreAngular | aspnet-core/src/SuperRocket.AspNetCoreAngular.Core/Validation/ValidationHelper.cs | 520 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace KPU_Assembler
{
public partial class LowLevelAssemblyVisitor<Result> : LowLevelAssemblyBaseVisitor<Result>
{
/// <summary>
/// JNZ
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public override Result VisitJNZ(LowLevelAssemblyParser.JNZContext context)
{
assembly.Add("11000001 ; JNZ" + context.JumpLabel().GetText());
return base.VisitJNZ(context);
}
}
}
| 25.5 | 94 | 0.630719 | [
"MIT"
] | KPU-RISC/KPU | Assembler/KPU.Assembler/LowLevel/JNZ.cs | 614 | C# |
using ApiServer.BLL.IBLL;
using ApiServer.Model.Entity;
using ApiServer.Model.Model;
using ApiServer.Model.Model.MsgModel;
using ApiServer.Model.Model.Nodes;
using ApiServer.Model.Model.ViewModel;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace ApiServer.Controllers
{
/// <summary>
/// 菜单管理
/// </summary>
[Route("api/[controller]")]
public class SysMenuController : BaseController
{
private readonly ISysMenuService _sysMenuService;
/// <summary>
///
/// </summary>
/// <param name="sysMenuService"></param>
public SysMenuController(ISysMenuService sysMenuService)
{
_sysMenuService = sysMenuService;
}
/// <summary>
/// 菜单管理:查询
/// </summary>
/// <param name="pairs"></param>
/// <returns></returns>
[HttpPost]
[Route("tree")]
public async Task<IActionResult> Tree([FromForm] Dictionary<string, string> pairs)
{
string menuNameLike = (string)pairs["menuNameLike"];
bool? menuStatus = null;
if (!string.IsNullOrWhiteSpace(pairs["menuStatus"]))
{
menuStatus = Convert.ToBoolean(pairs["menuStatus"]);
}
return Ok(await Task.FromResult(_sysMenuService.GetMenuTree(menuNameLike, menuStatus)));
}
/// <summary>
/// 菜单管理:修改
/// </summary>
/// <param name="sysMenu"></param>
/// <returns></returns>
[HttpPost]
[Route("update")]
public async Task<IActionResult> Update([FromBody] SysMenu sysMenu)
{
var sys_menu = sysMenu.BuildAdapter().AdaptToType<sys_menu>();
return Ok(await Task.FromResult(_sysMenuService.UpdateMenu(sys_menu)));
}
/// <summary>
/// 菜单管理:新增
/// </summary>
/// <param name="sysMenu"></param>
/// <returns></returns>
[HttpPost]
[Route("add")]
public async Task<IActionResult> Add([FromBody] SysMenu sysMenu)
{
var sys_menu = sysMenu.BuildAdapter().AdaptToType<sys_menu>();
return Ok(await Task.FromResult(_sysMenuService.AddMenu(sys_menu)));
}
/// <summary>
/// 菜单管理:删除
/// </summary>
/// <param name="sysMenu"></param>
/// <returns></returns>
[HttpPost]
[Route("delete")]
public async Task<IActionResult> Delete([FromBody] SysMenu sysMenu)
{
var sys_menu = sysMenu.BuildAdapter().AdaptToType<sys_menu>();
return Ok(await Task.FromResult(_sysMenuService.DeleteMenu(sys_menu)));
}
/// <summary>
/// 角色管理:菜单树展示(勾选项、展开项)
/// </summary>
/// <param name="roleId"></param>
/// <returns></returns>
[HttpPost]
[Route("checkedtree")]
public async Task<IActionResult> CheckedTree([FromForm] long roleId)
{
MsgModel msg = new MsgModel
{
isok = true,
message = "获取成功!"
};
Dictionary<string, object> dict = new Dictionary<string, object>
{
{ "tree", _sysMenuService.GetMenuTree("", default).data },
{ "expandedKeys", _sysMenuService.GetExpandedKeys() },
{ "checkedKeys", _sysMenuService.GetCheckedKeys(roleId) }
};
msg.data = dict;
return Ok(await Task.FromResult(msg));
}
/// <summary>
/// 角色管理:保存菜单勾选结果
/// </summary>
/// <param name="roleCheckedIds"></param>
/// <returns></returns>
[HttpPost]
[Route("savekeys")]
public async Task<IActionResult> SaveKeys([FromBody] RoleCheckedIds roleCheckedIds)
{
return Ok(await Task.FromResult(_sysMenuService.SaveCheckedKeys(roleCheckedIds.RoleId, roleCheckedIds.CheckedIds)));
}
/// <summary>
/// 系统左侧菜单栏加载,根据登录用户名加载它可以访问的菜单项
/// </summary>
/// <param name="userName"></param>
/// <returns></returns>
[HttpPost]
[Route("tree/user")]
public async Task<IActionResult> UserTree([FromForm] string userName)
{
return Ok(await Task.FromResult(_sysMenuService.GetMenuTreeByUsername(userName))); ;
}
/// <summary>
/// 菜单管理:更新菜单禁用状态
/// </summary>
/// <param name="menuId"></param>
/// <param name="status"></param>
/// <returns></returns>
[HttpPost]
[Route("status/change")]
public async Task<IActionResult> Update([FromForm] long menuId, bool status)
{
return Ok(await Task.FromResult(_sysMenuService.UpdateStatus(menuId, status)));
}
}
}
| 31.044304 | 128 | 0.556983 | [
"MIT"
] | jinjupeng/Item.ApiServer | ApiServer/Controllers/SysMenuController.cs | 5,125 | C# |
using CookPopularCSharpToolkit.Windows;
using System;
using System.Globalization;
using System.Windows.Data;
using System.Windows.Markup;
/*
* Copyright (c) 2021 All Rights Reserved.
* Description:WaveProgressBarConverter
* Author: Chance_写代码的厨子
* Create Time:2021-03-15 16:37:20
*/
namespace CookPopularControl.Communal
{
[MarkupExtensionReturnType(typeof(double))]
public class ProgressBarValueToTranslateTransformY : MarkupExtensionBase, IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is double v)
{
return -v / 100D;
}
return double.NaN;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
| 25.305556 | 103 | 0.670692 | [
"Apache-2.0"
] | Muzsor/CookPopularControl | CookPopularControl/Communal/Converters/WaveProgressBarConverters.cs | 931 | C# |
using System;
using Box2D;
namespace Dorothy.Game
{
public delegate void SensorHandler(Unit sensorUnit, Unit sensedUnit);
public class Sensor : IDisposable
{
private int _max;
private int _count;
private Unit[] _sensedUnit;
private bool _enable = true;
private Fixture _fixture;
private Unit _unit;
public event SensorHandler UnitEnter;
public event SensorHandler UnitLeave;
public int SensedCount
{
get { return _count; }
}
public bool Enable
{
set
{
_enable = value;
if (value == false)
{
this.Clear();
}
}
get { return _enable; }
}
public Unit Parent
{
get { return _unit; }
}
public bool IsDisposed
{
get { return (_fixture == null); }
}
public Sensor(Unit unit, Fixture fixture, int maxSense)
{
_unit = unit;
_fixture = fixture;
_fixture.SetUserData(this);
_max = maxSense;
_sensedUnit = new Unit[maxSense];
_count = 0;
}
public bool Add(Unit unit)
{
if (_count < _max - 1)
{
_sensedUnit[_count] = unit;
_count++;
if (UnitEnter != null)
{
UnitEnter(_unit, unit);
}
return true;
}
return false;
}
public bool Remove(Unit unit)
{
for (int i = 0; i < _count; i++)
{
if (_sensedUnit[i] == unit)
{
int last = _count - 1;
if (i != last)
{
_sensedUnit[i] = _sensedUnit[_count - 1];
}
_count--;
if (UnitLeave != null)
{
UnitLeave(_unit, unit);
}
return true;
}
}
return false;
}
public bool Contains(Unit unit)
{
for (int i = 0; i < _count; i++)
{
if (_sensedUnit[i] == unit)
{
return true;
}
}
return false;
}
public void Clear()
{
_count = 0;
}
public Unit GetSensedUnit(int subScript)
{
return _sensedUnit[subScript];
}
public void Dispose()
{
if (_fixture != null)
{
_unit.Body.DestroyFixture(_fixture);
_fixture = null;
_unit = null;
}
}
}
}
| 17.711864 | 71 | 0.549282 | [
"MIT"
] | IppClub/Dorothy-Xna | Dorothy/Game/Sensor.cs | 2,092 | C# |
using Akka.Actor;
using Neo.Ledger;
using Neo.Network.P2P.Payloads;
using Neo.Properties;
using Neo.SmartContract;
using Neo.Wallets;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace Neo.UI
{
partial class DeveloperToolsForm
{
private ContractParametersContext context;
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (listBox1.SelectedIndex < 0) return;
listBox2.Items.Clear();
if (Program.CurrentWallet == null) return;
UInt160 hash = ((string)listBox1.SelectedItem).ToScriptHash();
var parameters = context.GetParameters(hash);
if (parameters == null)
{
var parameterList = Program.CurrentWallet.GetAccount(hash).Contract.ParameterList ?? Blockchain.Singleton.Store.GetContracts()[hash].ParameterList;
if (parameterList != null)
{
var pList = new List<ContractParameter>();
for (int i = 0; i < parameterList.Length; i++)
{
pList.Add(new ContractParameter(parameterList[i]));
context.Add(Program.CurrentWallet.GetAccount(hash).Contract, i, null);
}
}
}
listBox2.Items.AddRange(context.GetParameters(hash).ToArray());
button4.Visible = context.Completed;
}
private void listBox2_SelectedIndexChanged(object sender, EventArgs e)
{
if (listBox2.SelectedIndex < 0) return;
textBox1.Text = listBox2.SelectedItem.ToString();
textBox2.Clear();
}
private void button1_Click(object sender, EventArgs e)
{
string input = InputBox.Show("ParametersContext", "ParametersContext");
if (string.IsNullOrEmpty(input)) return;
try
{
context = ContractParametersContext.Parse(input);
}
catch (FormatException ex)
{
MessageBox.Show(ex.Message);
return;
}
listBox1.Items.Clear();
listBox2.Items.Clear();
textBox1.Clear();
textBox2.Clear();
listBox1.Items.AddRange(context.ScriptHashes.Select(p => p.ToAddress()).ToArray());
button2.Enabled = true;
button4.Visible = context.Completed;
}
private void button2_Click(object sender, EventArgs e)
{
InformationBox.Show(context.ToString(), "ParametersContext", "ParametersContext");
}
private void button3_Click(object sender, EventArgs e)
{
if (listBox1.SelectedIndex < 0) return;
if (listBox2.SelectedIndex < 0) return;
ContractParameter parameter = (ContractParameter)listBox2.SelectedItem;
parameter.SetValue(textBox2.Text);
listBox2.Items[listBox2.SelectedIndex] = parameter;
textBox1.Text = textBox2.Text;
button4.Visible = context.Completed;
}
private void button4_Click(object sender, EventArgs e)
{
context.Verifiable.Witnesses = context.GetWitnesses();
IInventory inventory = (IInventory)context.Verifiable;
RelayResultReason reason = Program.NeoSystem.Blockchain.Ask<RelayResultReason>(inventory).Result;
if (reason == RelayResultReason.Succeed)
{
InformationBox.Show(inventory.Hash.ToString(), Strings.RelaySuccessText, Strings.RelaySuccessTitle);
}
else
{
MessageBox.Show($"Transaction cannot be broadcast: {reason}");
}
}
}
}
| 37.203883 | 163 | 0.586378 | [
"MIT"
] | edmhs/neo-gui | neo-gui/UI/DeveloperToolsForm.ContractParameters.cs | 3,832 | C# |
//Copyright (C) 2005 Richard J. Northedge
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//This file is based on the NameContextGenerator.java source file found in the
//original java implementation of OpenNLP. That source file contains the following header:
//Copyright (C) 2003 Thomas Morton
//
//This library is free software; you can redistribute it and/or
//modify it under the terms of the GNU Lesser General Public
//License as published by the Free Software Foundation; either
//version 2.1 of the License, or (at your option) any later version.
//
//This library is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU Lesser General Public License for more details.
//
//You should have received a copy of the GNU Lesser General Public
//License along with this program; if not, write to the Free Software
//Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
using System;
using System.Collections.Generic;
namespace OpenNLP.Tools.NameFind
{
/// <summary>
/// Context generator for the name find tool.
/// </summary>
public interface INameContextGenerator : OpenNLP.Tools.Util.IBeamSearchContextGenerator
{
/// <summary>
/// Returns the contexts for chunking of the specified index.
/// </summary>
/// <param name="tokenIndex">
/// The index of the token in the specified tokens array for which the context should be constructed.
/// </param>
/// <param name="tokens">
/// The tokens of the sentence.
/// </param>
/// <param name="previousDecisions">
/// The previous decisions made in the tagging of this sequence. Only indices less than tokenIndex will be examined.
/// </param>
/// <param name="previousTags">
/// A mapping between tokens and the previous outcome for these tokens.
/// </param>
/// <returns>
/// An array of predictive contexts on which a model basis its decisions.
/// </returns>
string[] GetContext(int tokenIndex, List<string> tokens, List<string> previousDecisions, IDictionary<string, string> previousTags);
}
}
| 43.641791 | 134 | 0.71751 | [
"MIT"
] | arghyabiswas/bnlp | DBNLP/OpenNLP/Tools/NameFind/INameContextGenerator.cs | 2,924 | C# |
using MetalUp.FunctionalLibrary;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace FunctionalLibraryTest
{
[TestClass]
public class Sort : TestBase
{
#region Ascending
[TestMethod]
public void Sort1()
{
var list = FList.New(7,1,4,6,3,2,5);
var actual = FList.Sort(list);
var expected = FList.New(1,2,3,4,5,6,7);
Assert.AreEqual(expected, actual);
}
[TestMethod]
public void Sort2()
{
var list = FList.New(1, 4, 6, 3, 2, 5);
var actual = FList.Sort(list);
var expected = FList.New(1, 2, 3, 4, 5, 6);
Assert.AreEqual(expected, actual);
}
[TestMethod]
public void Sort3()
{
var list = FList.New(3,3, 4, 4, 3);
var actual = FList.Sort(list);
var expected = FList.New(3,3,3,4,4);
Assert.AreEqual(expected, actual);
}
[TestMethod]
public void Sort4()
{
var list = FList.New(3);
var actual = FList.Sort(list);
var expected = FList.New(3);
Assert.AreEqual(expected, actual);
}
[TestMethod]
public void Sort5()
{
var list = FList.Empty<int>();
var actual = FList.Sort(list);
var expected = FList.Empty<int>();
Assert.AreEqual(expected, actual);
}
#endregion
#region Descending
[TestMethod]
public void Sort6()
{
var list = FList.New(7, 1, 4, 6, 3, 2, 5);
var actual = FList.Sort(list,true);
var expected = FList.New(7,6,5,4,3,2,1);
Assert.AreEqual(expected, actual);
}
[TestMethod]
public void Sort7()
{
var list = FList.New(1, 4, 6, 3, 2, 5);
var actual = FList.Sort(list,true);
var expected = FList.New(6,5,4,3,2,1);
Assert.AreEqual(expected, actual);
}
[TestMethod]
public void Sort8()
{
var list = FList.New(3, 3, 4, 4, 3);
var actual = FList.Sort(list, true);
var expected = FList.New(4,4,3, 3, 3);
Assert.AreEqual(expected, actual);
}
[TestMethod]
public void Sort9()
{
var list = FList.New("Zoe", "Amy", "Ali", "Max", "Adi");
var actual = FList.Sort(list);
var expected = FList.New("Adi", "Ali", "Amy", "Max", "Zoe");
Assert.AreEqual(expected, actual);
}
[TestMethod]
public void Sort10()
{
var list = FList.New("Zoe", "Amy", "Ali", "Max", "Adi");
var actual = FList.Sort(list, true);
var expected = FList.New("Zoe", "Max", "Amy", "Ali", "Adi");
Assert.AreEqual(expected, actual);
}
#endregion
[TestMethod]
public void Sort1String()
{
var list = "7146325";
var actual = FList.Sort(list);
var expected = "1234567";
Assert.AreEqual(expected, actual.ToString());
}
}
}
| 28.460177 | 72 | 0.484453 | [
"MIT"
] | MetalUp/FunctionalLibrary | FunctionalLibraryTest/Sort.cs | 3,218 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("FamilyTreeInCSharp")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("FamilyTreeInCSharp")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("8dcee402-c9d8-4678-a901-27fc0962b63e")]
// 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")]
[assembly: AssemblyFileVersion("1.0.0")]
| 37.837838 | 84 | 0.750714 | [
"MIT"
] | kvprasoon/SHiPS | samples/FamilyTreeInCSharp/Properties/AssemblyInfo.cs | 1,403 | C# |
using Newtonsoft.Json;
using PaisleyPark.Models;
using Prism.Commands;
using Prism.Mvvm;
using System;
using System.Windows;
using System.Windows.Input;
namespace PaisleyPark.ViewModels
{
public class ImportHotkeyViewModel : BindableBase
{
public string ImportText { get; set; }
public bool? DialogResult { get; set; } = false;
public ICommand ImportCommand { get; private set; }
private readonly static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
public Models.Hotkey ImportedHotkey;
public ImportHotkeyViewModel()
{
ImportCommand = new DelegateCommand(OnImport);
}
private void OnImport()
{
logger.Info("Importing JSON");
try
{
// Deserialize JSON into Preset object.
ImportedHotkey = JsonConvert.DeserializeObject<Models.Hotkey>(ImportText);
// Checking validity purely by the name being specified. Could use a more robust check but this is good enough.
if (ImportedHotkey.Name == null || ImportedHotkey.Name.Trim() == string.Empty)
{
MessageBox.Show("This does not resemble a valid preset. Could not import successfully.", "Paisley Park", MessageBoxButton.OK, MessageBoxImage.Error);
return;
}
MessageBox.Show("Imported Preset " + ImportedHotkey.Name + "!", "Paisley Park", MessageBoxButton.OK, MessageBoxImage.Exclamation);
DialogResult = true;
}
// Likely not a JSON string.
catch (Exception ex)
{
logger.Error(ex, "Error trying to import JSON\n{0}", ImportText);
MessageBox.Show("Invalid input, this is not valid JSON. Could not import preset.", "Paisley Park", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
}
}
| 31.132075 | 154 | 0.724242 | [
"MIT"
] | MGlolenstine/PaisleyPark | PaisleyPark/ViewModels/ImportHotkeyViewModel.cs | 1,652 | 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 EnumLocalization.Resources {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
public class OrderStatusResources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal OrderStatusResources() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
public static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("EnumLocalization.Resources.OrderStatusResources", typeof(OrderStatusResources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
public static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Looks up a localized string similar to Anulowane.
/// </summary>
public static string Canceled {
get {
return ResourceManager.GetString("Canceled", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Zrealizowane.
/// </summary>
public static string Completed {
get {
return ResourceManager.GetString("Completed", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Utworzone.
/// </summary>
public static string Created {
get {
return ResourceManager.GetString("Created", resourceCulture);
}
}
}
}
| 40.351648 | 203 | 0.590686 | [
"MIT"
] | danielplawgo/EnumLocalization | EnumLocalization/EnumLocalization/Resources/OrderStatusResources.Designer.cs | 3,674 | 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("Sandbox")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Sandbox")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("4994edf6-d505-4d66-80f0-9c7e7759c8e2")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.444444 | 84 | 0.739614 | [
"MIT"
] | ehailey1/treehopper-sdk | NET/Apps/Sandbox/Properties/AssemblyInfo.cs | 1,351 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using DevIO.Business.Intefaces;
using DevIO.Business.Models;
using DevIO.Data.Context;
using Microsoft.EntityFrameworkCore;
namespace DevIO.Data.Repository
{
public abstract class Repository<TEntity> : IRepository<TEntity> where TEntity : Entity, new()
{
protected readonly MeuDbContext Db;
protected readonly DbSet<TEntity> DbSet;
protected Repository(MeuDbContext db)
{
Db = db;
DbSet = db.Set<TEntity>();
}
public async Task<IEnumerable<TEntity>> Buscar(Expression<Func<TEntity, bool>> predicate)
{
return await DbSet.AsNoTracking().Where(predicate).ToListAsync();
}
public virtual async Task<TEntity> ObterPorId(Guid id)
{
return await DbSet.FindAsync(id);
}
public virtual async Task<List<TEntity>> ObterTodos()
{
return await DbSet.ToListAsync();
}
public virtual async Task Adicionar(TEntity entity)
{
DbSet.Add(entity);
await SaveChanges();
}
public virtual async Task Atualizar(TEntity entity)
{
DbSet.Update(entity);
await SaveChanges();
}
public virtual async Task Remover(Guid id)
{
DbSet.Remove(new TEntity { Id = id });
await SaveChanges();
}
public async Task<int> SaveChanges()
{
return await Db.SaveChangesAsync();
}
public void Dispose()
{
Db?.Dispose();
}
}
} | 25.626866 | 98 | 0.5894 | [
"MIT"
] | AndreFrateschi/ProjetoBaseCore | src/DevIO.Data/Repository/Repository.cs | 1,719 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
namespace DataAccessLayer.Abstract
{
public interface IRepository<T>
{
List<T> List();
void Insert(T p);
T Get(Expression<Func<T, bool>> filter);
void Delete(T p);
void Update(T p);
List<T> List(Expression<Func<T, bool>> filter);
}
}
| 17.307692 | 55 | 0.64 | [
"MIT"
] | RabiaSalman/MvcProject | MvcProjeKampi/MvcProje/DataAccessLayer/Abstract/IRepository.cs | 452 | C# |
using System;
using System.Linq;
using System.Collections.Generic;
//abc188_c
namespace _3
{
class Program
{
static void Main(string[] args)
{
var n = long.Parse(Console.ReadLine());
var a = Console.ReadLine().Split()
.Select((x,i) => (index:i,value:long.Parse(x.ToString())))
.ToList();
var len = a.Count();
while(len > 2){
for(var i = 0; i < len / 2; i++){
var x = a[i];
var y = a[i+1];
if(x.value > y.value){
a.Remove(y);
}else{
a.Remove(x);
}
}
len /= 2;
}
Console.WriteLine(a.OrderBy(v => v.value).First().index + 1);
}
}
}
| 24.828571 | 74 | 0.383199 | [
"CC0-1.0"
] | curryudon08/Atcoder | VirtualContest/008/3/Program.cs | 871 | C# |
namespace Any.Core.Domain.Catalog
{
/// <summary>
/// Product review approved event
/// </summary>
public class ProductReviewApprovedEvent
{
/// <summary>
/// Ctor
/// </summary>
/// <param name="productReview">Product review</param>
public ProductReviewApprovedEvent(ProductReview productReview)
{
ProductReview = productReview;
}
/// <summary>
/// Product review
/// </summary>
public ProductReview ProductReview { get; }
}
} | 25.090909 | 70 | 0.561594 | [
"MIT"
] | BoyFaceGirl/AnyFx | Libraries/Any.Core/Domain/Catalog/Events.cs | 552 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using XrmSpeedyUI;
namespace XrmSpeedy.Controls
{
public partial class Connection_SQLServer : UserControl
{
public Connection_SQLServer()
{
InitializeComponent();
}
private void chkConnectionIntegrated_CheckedChanged(object sender, EventArgs e)
{
if (chkConnectionIntegrated.Checked)
{
txtConnectionUsername.Clear();
txtConnectionUsername.Enabled = false;
txtConnectionPassword.Clear();
txtConnectionPassword.Enabled = false;
}
else
{
txtConnectionUsername.Enabled = true;
txtConnectionPassword.Enabled = true;
}
SetConnectionString();
}
private void SetConnectionString()
{
string conn = string.Empty;
if (!chkConnectionIntegrated.Checked)
conn = string.Format("Data Source={0};Initial Catalog={1};Persist Security Info=True;User ID={2};Password={3}",
txtConnectionServer.Text.Trim(), txtConnectionDatabase.Text.Trim(), txtConnectionUsername.Text.Trim(), txtConnectionPassword.Text.Trim());
else
conn = string.Format("Data Source={0};Initial Catalog={1};Integrated Security=SSPI;", txtConnectionServer.Text.Trim(),
txtConnectionDatabase.Text.Trim());
frmMain parent = (frmMain)this.Parent.Parent;
parent.ConnectionString = conn;
}
private void txtConnectionServer_Validated(object sender, EventArgs e)
{
SetConnectionString();
}
private void txtConnectionDatabase_Validated(object sender, EventArgs e)
{
SetConnectionString();
}
private void txtConnectionUsername_Validated(object sender, EventArgs e)
{
SetConnectionString();
}
private void txtConnectionPassword_Validated(object sender, EventArgs e)
{
SetConnectionString();
}
}
}
| 31.232877 | 158 | 0.609211 | [
"MIT"
] | devkeydet/migrate2cds | XrmSpeedyUI/Controls/Connection_SQLServer.cs | 2,282 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Composition;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Utilities;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.GenerateMember.GenerateConstructor;
using Microsoft.CodeAnalysis.GenerateType;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Options;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
using Microsoft.CodeAnalysis.Utilities;
using System.Collections.Immutable;
namespace Microsoft.CodeAnalysis.CSharp.GenerateType
{
[ExportLanguageService(typeof(IGenerateTypeService), LanguageNames.CSharp), Shared]
internal class CSharpGenerateTypeService :
AbstractGenerateTypeService<CSharpGenerateTypeService, SimpleNameSyntax, ObjectCreationExpressionSyntax, ExpressionSyntax, TypeDeclarationSyntax, ArgumentSyntax>
{
private static readonly SyntaxAnnotation s_annotation = new SyntaxAnnotation();
protected override string DefaultFileExtension => ".cs";
protected override ExpressionSyntax GetLeftSideOfDot(SimpleNameSyntax simpleName)
{
return simpleName.GetLeftSideOfDot();
}
protected override bool IsInCatchDeclaration(ExpressionSyntax expression)
{
return expression.IsParentKind(SyntaxKind.CatchDeclaration);
}
protected override bool IsArrayElementType(ExpressionSyntax expression)
{
return expression.IsParentKind(SyntaxKind.ArrayType) &&
expression.Parent.IsParentKind(SyntaxKind.ArrayCreationExpression);
}
protected override bool IsInValueTypeConstraintContext(
SemanticModel semanticModel,
ExpressionSyntax expression,
CancellationToken cancellationToken)
{
if (expression is TypeSyntax && expression.IsParentKind(SyntaxKind.TypeArgumentList))
{
var typeArgumentList = (TypeArgumentListSyntax)expression.Parent;
var symbolInfo = semanticModel.GetSymbolInfo(typeArgumentList.Parent, cancellationToken);
var symbol = symbolInfo.GetAnySymbol();
if (symbol.IsConstructor())
{
symbol = symbol.ContainingType;
}
var parameterIndex = typeArgumentList.Arguments.IndexOf((TypeSyntax)expression);
if (symbol is INamedTypeSymbol type)
{
type = type.OriginalDefinition;
var typeParameter = parameterIndex < type.TypeParameters.Length ? type.TypeParameters[parameterIndex] : null;
return typeParameter != null && typeParameter.HasValueTypeConstraint;
}
if (symbol is IMethodSymbol method)
{
method = method.OriginalDefinition;
var typeParameter = parameterIndex < method.TypeParameters.Length ? method.TypeParameters[parameterIndex] : null;
return typeParameter != null && typeParameter.HasValueTypeConstraint;
}
}
return false;
}
protected override bool IsInInterfaceList(ExpressionSyntax expression)
{
if (expression is TypeSyntax &&
expression.Parent is BaseTypeSyntax &&
expression.Parent.IsParentKind(SyntaxKind.BaseList) &&
((BaseTypeSyntax)expression.Parent).Type == expression)
{
var baseList = (BaseListSyntax)expression.Parent.Parent;
// If it's after the first item, then it's definitely an interface.
if (baseList.Types[0] != expression.Parent)
{
return true;
}
// If it's in the base list of an interface or struct, then it's definitely an
// interface.
return
baseList.IsParentKind(SyntaxKind.InterfaceDeclaration) ||
baseList.IsParentKind(SyntaxKind.StructDeclaration);
}
if (expression is TypeSyntax &&
expression.IsParentKind(SyntaxKind.TypeConstraint) &&
expression.Parent.IsParentKind(SyntaxKind.TypeParameterConstraintClause))
{
var typeConstraint = (TypeConstraintSyntax)expression.Parent;
var constraintClause = (TypeParameterConstraintClauseSyntax)typeConstraint.Parent;
var index = constraintClause.Constraints.IndexOf(typeConstraint);
// If it's after the first item, then it's definitely an interface.
return index > 0;
}
return false;
}
protected override bool TryGetNameParts(ExpressionSyntax expression, out IList<string> nameParts)
{
nameParts = new List<string>();
return expression.TryGetNameParts(out nameParts);
}
protected override bool TryInitializeState(
SemanticDocument document,
SimpleNameSyntax simpleName,
CancellationToken cancellationToken,
out GenerateTypeServiceStateOptions generateTypeServiceStateOptions)
{
generateTypeServiceStateOptions = new GenerateTypeServiceStateOptions();
if (simpleName.IsVar)
{
return false;
}
if (SyntaxFacts.IsAliasQualifier(simpleName))
{
return false;
}
// Never offer if we're in a using directive, unless its a static using. The feeling here is that it's highly
// unlikely that this would be a location where a user would be wanting to generate
// something. They're really just trying to reference something that exists but
// isn't available for some reason (i.e. a missing reference).
var usingDirectiveSyntax = simpleName.GetAncestorOrThis<UsingDirectiveSyntax>();
if (usingDirectiveSyntax != null && usingDirectiveSyntax.StaticKeyword.Kind() != SyntaxKind.StaticKeyword)
{
return false;
}
ExpressionSyntax nameOrMemberAccessExpression = null;
if (simpleName.IsRightSideOfDot())
{
// This simplename comes from the cref
if (simpleName.IsParentKind(SyntaxKind.NameMemberCref))
{
return false;
}
nameOrMemberAccessExpression = generateTypeServiceStateOptions.NameOrMemberAccessExpression = (ExpressionSyntax)simpleName.Parent;
// If we're on the right side of a dot, then the left side better be a name (and
// not an arbitrary expression).
var leftSideExpression = simpleName.GetLeftSideOfDot();
if (!leftSideExpression.IsKind(
SyntaxKind.QualifiedName,
SyntaxKind.IdentifierName,
SyntaxKind.AliasQualifiedName,
SyntaxKind.GenericName,
SyntaxKind.SimpleMemberAccessExpression))
{
return false;
}
}
else
{
nameOrMemberAccessExpression = generateTypeServiceStateOptions.NameOrMemberAccessExpression = simpleName;
}
// BUG(5712): Don't offer generate type in an enum's base list.
if (nameOrMemberAccessExpression.Parent is BaseTypeSyntax &&
nameOrMemberAccessExpression.Parent.IsParentKind(SyntaxKind.BaseList) &&
((BaseTypeSyntax)nameOrMemberAccessExpression.Parent).Type == nameOrMemberAccessExpression &&
nameOrMemberAccessExpression.Parent.Parent.IsParentKind(SyntaxKind.EnumDeclaration))
{
return false;
}
// If we can guarantee it's a type only context, great. Otherwise, we may not want to
// provide this here.
var semanticModel = document.SemanticModel;
if (!SyntaxFacts.IsInNamespaceOrTypeContext(nameOrMemberAccessExpression))
{
// Don't offer Generate Type in an expression context *unless* we're on the left
// side of a dot. In that case the user might be making a type that they're
// accessing a static off of.
var syntaxTree = semanticModel.SyntaxTree;
var start = nameOrMemberAccessExpression.SpanStart;
var tokenOnLeftOfStart = syntaxTree.FindTokenOnLeftOfPosition(start, cancellationToken);
var isExpressionContext = syntaxTree.IsExpressionContext(start, tokenOnLeftOfStart, attributes: true, cancellationToken: cancellationToken, semanticModelOpt: semanticModel);
var isStatementContext = syntaxTree.IsStatementContext(start, tokenOnLeftOfStart, cancellationToken);
var isExpressionOrStatementContext = isExpressionContext || isStatementContext;
// Delegate Type Creation is not allowed in Non Type Namespace Context
generateTypeServiceStateOptions.IsDelegateAllowed = false;
if (!isExpressionOrStatementContext)
{
return false;
}
if (!simpleName.IsLeftSideOfDot() && !simpleName.IsInsideNameOf())
{
if (nameOrMemberAccessExpression == null || !nameOrMemberAccessExpression.IsKind(SyntaxKind.SimpleMemberAccessExpression) || !simpleName.IsRightSideOfDot())
{
return false;
}
var leftSymbol = semanticModel.GetSymbolInfo(((MemberAccessExpressionSyntax)nameOrMemberAccessExpression).Expression, cancellationToken).Symbol;
var token = simpleName.GetLastToken().GetNextToken();
// We let only the Namespace to be left of the Dot
if (leftSymbol == null ||
!leftSymbol.IsKind(SymbolKind.Namespace) ||
!token.IsKind(SyntaxKind.DotToken))
{
return false;
}
else
{
generateTypeServiceStateOptions.IsMembersWithModule = true;
generateTypeServiceStateOptions.IsTypeGeneratedIntoNamespaceFromMemberAccess = true;
}
}
// Global Namespace
if (!generateTypeServiceStateOptions.IsTypeGeneratedIntoNamespaceFromMemberAccess &&
!SyntaxFacts.IsInNamespaceOrTypeContext(simpleName))
{
var token = simpleName.GetLastToken().GetNextToken();
if (token.IsKind(SyntaxKind.DotToken) &&
simpleName.Parent == token.Parent)
{
generateTypeServiceStateOptions.IsMembersWithModule = true;
generateTypeServiceStateOptions.IsTypeGeneratedIntoNamespaceFromMemberAccess = true;
}
}
}
var fieldDeclaration = simpleName.GetAncestor<FieldDeclarationSyntax>();
if (fieldDeclaration != null &&
fieldDeclaration.Parent is CompilationUnitSyntax &&
document.Document.SourceCodeKind == SourceCodeKind.Regular)
{
return false;
}
// Check to see if Module could be an option in the Type Generation in Cross Language Generation
var nextToken = simpleName.GetLastToken().GetNextToken();
if (simpleName.IsLeftSideOfDot() ||
nextToken.IsKind(SyntaxKind.DotToken))
{
if (simpleName.IsRightSideOfDot())
{
if (simpleName.Parent is QualifiedNameSyntax parent)
{
var leftSymbol = semanticModel.GetSymbolInfo(parent.Left, cancellationToken).Symbol;
if (leftSymbol != null && leftSymbol.IsKind(SymbolKind.Namespace))
{
generateTypeServiceStateOptions.IsMembersWithModule = true;
}
}
}
}
if (SyntaxFacts.IsInNamespaceOrTypeContext(nameOrMemberAccessExpression))
{
if (nextToken.IsKind(SyntaxKind.DotToken))
{
// In Namespace or Type Context we cannot have Interface, Enum, Delegate as part of the Left Expression of a QualifiedName
generateTypeServiceStateOptions.IsDelegateAllowed = false;
generateTypeServiceStateOptions.IsInterfaceOrEnumNotAllowedInTypeContext = true;
generateTypeServiceStateOptions.IsMembersWithModule = true;
}
// case: class Goo<T> where T: MyType
if (nameOrMemberAccessExpression.GetAncestors<TypeConstraintSyntax>().Any())
{
generateTypeServiceStateOptions.IsClassInterfaceTypes = true;
return true;
}
// Events
if (nameOrMemberAccessExpression.GetAncestors<EventFieldDeclarationSyntax>().Any() ||
nameOrMemberAccessExpression.GetAncestors<EventDeclarationSyntax>().Any())
{
// Case : event goo name11
// Only Delegate
if (simpleName.Parent != null && !(simpleName.Parent is QualifiedNameSyntax))
{
generateTypeServiceStateOptions.IsDelegateOnly = true;
return true;
}
// Case : event SomeSymbol.goo name11
if (nameOrMemberAccessExpression is QualifiedNameSyntax)
{
// Only Namespace, Class, Struct and Module are allowed to contain Delegate
// Case : event Something.Mytype.<Delegate> Identifier
if (nextToken.IsKind(SyntaxKind.DotToken))
{
if (nameOrMemberAccessExpression.Parent != null && nameOrMemberAccessExpression.Parent is QualifiedNameSyntax)
{
return true;
}
else
{
Contract.Fail("Cannot reach this point");
}
}
else
{
// Case : event Something.<Delegate> Identifier
generateTypeServiceStateOptions.IsDelegateOnly = true;
return true;
}
}
}
}
else
{
// MemberAccessExpression
if ((nameOrMemberAccessExpression.IsKind(SyntaxKind.SimpleMemberAccessExpression) || (nameOrMemberAccessExpression.Parent != null && nameOrMemberAccessExpression.IsParentKind(SyntaxKind.SimpleMemberAccessExpression)))
&& nameOrMemberAccessExpression.IsLeftSideOfDot())
{
// Check to see if the expression is part of Invocation Expression
ExpressionSyntax outerMostMemberAccessExpression = null;
if (nameOrMemberAccessExpression.IsKind(SyntaxKind.SimpleMemberAccessExpression))
{
outerMostMemberAccessExpression = nameOrMemberAccessExpression;
}
else
{
Debug.Assert(nameOrMemberAccessExpression.IsParentKind(SyntaxKind.SimpleMemberAccessExpression));
outerMostMemberAccessExpression = (ExpressionSyntax)nameOrMemberAccessExpression.Parent;
}
outerMostMemberAccessExpression = outerMostMemberAccessExpression.GetAncestorsOrThis<ExpressionSyntax>().SkipWhile(n => n != null && n.IsKind(SyntaxKind.SimpleMemberAccessExpression)).FirstOrDefault();
if (outerMostMemberAccessExpression != null && outerMostMemberAccessExpression is InvocationExpressionSyntax)
{
generateTypeServiceStateOptions.IsEnumNotAllowed = true;
}
}
}
// Cases:
// // 1 - Function Address
// var s2 = new MyD2(goo);
// // 2 - Delegate
// MyD1 d = null;
// var s1 = new MyD2(d);
// // 3 - Action
// Action action1 = null;
// var s3 = new MyD2(action1);
// // 4 - Func
// Func<int> lambda = () => { return 0; };
// var s4 = new MyD3(lambda);
if (nameOrMemberAccessExpression.Parent is ObjectCreationExpressionSyntax)
{
var objectCreationExpressionOpt = generateTypeServiceStateOptions.ObjectCreationExpressionOpt = (ObjectCreationExpressionSyntax)nameOrMemberAccessExpression.Parent;
// Enum and Interface not Allowed in Object Creation Expression
generateTypeServiceStateOptions.IsInterfaceOrEnumNotAllowedInTypeContext = true;
if (objectCreationExpressionOpt.ArgumentList != null)
{
if (objectCreationExpressionOpt.ArgumentList.CloseParenToken.IsMissing)
{
return false;
}
// Get the Method symbol for the Delegate to be created
if (generateTypeServiceStateOptions.IsDelegateAllowed &&
objectCreationExpressionOpt.ArgumentList.Arguments.Count == 1 &&
objectCreationExpressionOpt.ArgumentList.Arguments[0].Expression.Kind() != SyntaxKind.DeclarationExpression)
{
generateTypeServiceStateOptions.DelegateCreationMethodSymbol = GetMethodSymbolIfPresent(semanticModel, objectCreationExpressionOpt.ArgumentList.Arguments[0].Expression, cancellationToken);
}
else
{
generateTypeServiceStateOptions.IsDelegateAllowed = false;
}
}
if (objectCreationExpressionOpt.Initializer != null)
{
foreach (var expression in objectCreationExpressionOpt.Initializer.Expressions)
{
var simpleAssignmentExpression = expression as AssignmentExpressionSyntax;
if (simpleAssignmentExpression == null)
{
continue;
}
var name = simpleAssignmentExpression.Left as SimpleNameSyntax;
if (name == null)
{
continue;
}
generateTypeServiceStateOptions.PropertiesToGenerate.Add(name);
}
}
}
if (generateTypeServiceStateOptions.IsDelegateAllowed)
{
// MyD1 z1 = goo;
if (nameOrMemberAccessExpression.Parent.IsKind(SyntaxKind.VariableDeclaration))
{
var variableDeclaration = (VariableDeclarationSyntax)nameOrMemberAccessExpression.Parent;
if (variableDeclaration.Variables.Count != 0)
{
var firstVarDeclWithInitializer = variableDeclaration.Variables.FirstOrDefault(var => var.Initializer != null && var.Initializer.Value != null);
if (firstVarDeclWithInitializer != null && firstVarDeclWithInitializer.Initializer != null && firstVarDeclWithInitializer.Initializer.Value != null)
{
generateTypeServiceStateOptions.DelegateCreationMethodSymbol = GetMethodSymbolIfPresent(semanticModel, firstVarDeclWithInitializer.Initializer.Value, cancellationToken);
}
}
}
// var w1 = (MyD1)goo;
if (nameOrMemberAccessExpression.Parent.IsKind(SyntaxKind.CastExpression))
{
var castExpression = (CastExpressionSyntax)nameOrMemberAccessExpression.Parent;
if (castExpression.Expression != null)
{
generateTypeServiceStateOptions.DelegateCreationMethodSymbol = GetMethodSymbolIfPresent(semanticModel, castExpression.Expression, cancellationToken);
}
}
}
return true;
}
private IMethodSymbol GetMethodSymbolIfPresent(SemanticModel semanticModel, ExpressionSyntax expression, CancellationToken cancellationToken)
{
if (expression == null)
{
return null;
}
var memberGroup = semanticModel.GetMemberGroup(expression, cancellationToken);
if (memberGroup.Length != 0)
{
return memberGroup.ElementAt(0).IsKind(SymbolKind.Method) ? (IMethodSymbol)memberGroup.ElementAt(0) : null;
}
var expressionType = semanticModel.GetTypeInfo(expression, cancellationToken).Type;
if (expressionType.IsDelegateType())
{
return ((INamedTypeSymbol)expressionType).DelegateInvokeMethod;
}
var expressionSymbol = semanticModel.GetSymbolInfo(expression, cancellationToken).Symbol;
if (expressionSymbol.IsKind(SymbolKind.Method))
{
return (IMethodSymbol)expressionSymbol;
}
return null;
}
private Accessibility DetermineAccessibilityConstraint(
State state,
SemanticModel semanticModel,
CancellationToken cancellationToken)
{
return semanticModel.DetermineAccessibilityConstraint(
state.NameOrMemberAccessExpression as TypeSyntax, cancellationToken);
}
protected override ImmutableArray<ITypeParameterSymbol> GetTypeParameters(
State state,
SemanticModel semanticModel,
CancellationToken cancellationToken)
{
if (state.SimpleName is GenericNameSyntax)
{
var genericName = (GenericNameSyntax)state.SimpleName;
var typeArguments = state.SimpleName.Arity == genericName.TypeArgumentList.Arguments.Count
? genericName.TypeArgumentList.Arguments.OfType<SyntaxNode>().ToList()
: Enumerable.Repeat<SyntaxNode>(null, state.SimpleName.Arity);
return this.GetTypeParameters(state, semanticModel, typeArguments, cancellationToken);
}
return ImmutableArray<ITypeParameterSymbol>.Empty;
}
protected override bool TryGetArgumentList(ObjectCreationExpressionSyntax objectCreationExpression, out IList<ArgumentSyntax> argumentList)
{
if (objectCreationExpression != null && objectCreationExpression.ArgumentList != null)
{
argumentList = objectCreationExpression.ArgumentList.Arguments.ToList();
return true;
}
argumentList = null;
return false;
}
protected override IList<ParameterName> GenerateParameterNames(
SemanticModel semanticModel, IList<ArgumentSyntax> arguments, CancellationToken cancellationToken)
{
return semanticModel.GenerateParameterNames(arguments, reservedNames: null, cancellationToken: cancellationToken);
}
public override string GetRootNamespace(CompilationOptions options)
{
return string.Empty;
}
protected override bool IsInVariableTypeContext(ExpressionSyntax expression)
{
return false;
}
protected override INamedTypeSymbol DetermineTypeToGenerateIn(SemanticModel semanticModel, SimpleNameSyntax simpleName, CancellationToken cancellationToken)
{
return semanticModel.GetEnclosingNamedType(simpleName.SpanStart, cancellationToken);
}
protected override Accessibility GetAccessibility(State state, SemanticModel semanticModel, bool intoNamespace, CancellationToken cancellationToken)
{
var accessibility = DetermineDefaultAccessibility(state, semanticModel, intoNamespace, cancellationToken);
if (!state.IsTypeGeneratedIntoNamespaceFromMemberAccess)
{
var accessibilityConstraint = DetermineAccessibilityConstraint(state, semanticModel, cancellationToken);
if (accessibilityConstraint == Accessibility.Public ||
accessibilityConstraint == Accessibility.Internal)
{
accessibility = accessibilityConstraint;
}
}
return accessibility;
}
protected override ITypeSymbol DetermineArgumentType(SemanticModel semanticModel, ArgumentSyntax argument, CancellationToken cancellationToken)
{
return argument.DetermineParameterType(semanticModel, cancellationToken);
}
protected override bool IsConversionImplicit(Compilation compilation, ITypeSymbol sourceType, ITypeSymbol targetType)
{
return compilation.ClassifyConversion(sourceType, targetType).IsImplicit;
}
public override async Task<Tuple<INamespaceSymbol, INamespaceOrTypeSymbol, Location>> GetOrGenerateEnclosingNamespaceSymbolAsync(
INamedTypeSymbol namedTypeSymbol, string[] containers, Document selectedDocument, SyntaxNode selectedDocumentRoot, CancellationToken cancellationToken)
{
var compilationUnit = (CompilationUnitSyntax)selectedDocumentRoot;
var semanticModel = await selectedDocument.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
if (containers.Length != 0)
{
// Search the NS declaration in the root
var containerList = new List<string>(containers);
var enclosingNamespace = GetDeclaringNamespace(containerList, 0, compilationUnit);
if (enclosingNamespace != null)
{
var enclosingNamespaceSymbol = semanticModel.GetSymbolInfo(enclosingNamespace.Name, cancellationToken);
if (enclosingNamespaceSymbol.Symbol != null)
{
return Tuple.Create((INamespaceSymbol)enclosingNamespaceSymbol.Symbol,
(INamespaceOrTypeSymbol)namedTypeSymbol,
enclosingNamespace.CloseBraceToken.GetLocation());
}
}
}
var globalNamespace = semanticModel.GetEnclosingNamespace(0, cancellationToken);
var rootNamespaceOrType = namedTypeSymbol.GenerateRootNamespaceOrType(containers);
var lastMember = compilationUnit.Members.LastOrDefault();
Location afterThisLocation = null;
if (lastMember != null)
{
afterThisLocation = semanticModel.SyntaxTree.GetLocation(new TextSpan(lastMember.Span.End, 0));
}
else
{
afterThisLocation = semanticModel.SyntaxTree.GetLocation(new TextSpan());
}
return Tuple.Create(globalNamespace,
rootNamespaceOrType,
afterThisLocation);
}
private NamespaceDeclarationSyntax GetDeclaringNamespace(List<string> containers, int indexDone, CompilationUnitSyntax compilationUnit)
{
foreach (var member in compilationUnit.Members)
{
var namespaceDeclaration = GetDeclaringNamespace(containers, 0, member);
if (namespaceDeclaration != null)
{
return namespaceDeclaration;
}
}
return null;
}
private NamespaceDeclarationSyntax GetDeclaringNamespace(List<string> containers, int indexDone, SyntaxNode localRoot)
{
var namespaceDecl = localRoot as NamespaceDeclarationSyntax;
if (namespaceDecl == null || namespaceDecl.Name is AliasQualifiedNameSyntax)
{
return null;
}
List<string> namespaceContainers = new List<string>();
GetNamespaceContainers(namespaceDecl.Name, namespaceContainers);
if (namespaceContainers.Count + indexDone > containers.Count ||
!IdentifierMatches(indexDone, namespaceContainers, containers))
{
return null;
}
indexDone = indexDone + namespaceContainers.Count;
if (indexDone == containers.Count)
{
return namespaceDecl;
}
foreach (var member in namespaceDecl.Members)
{
var resultant = GetDeclaringNamespace(containers, indexDone, member);
if (resultant != null)
{
return resultant;
}
}
return null;
}
private bool IdentifierMatches(int indexDone, List<string> namespaceContainers, List<string> containers)
{
for (int i = 0; i < namespaceContainers.Count; ++i)
{
if (namespaceContainers[i] != containers[indexDone + i])
{
return false;
}
}
return true;
}
private void GetNamespaceContainers(NameSyntax name, List<string> namespaceContainers)
{
if (name is QualifiedNameSyntax qualifiedName)
{
GetNamespaceContainers(qualifiedName.Left, namespaceContainers);
namespaceContainers.Add(qualifiedName.Right.Identifier.ValueText);
}
else
{
Debug.Assert(name is SimpleNameSyntax);
namespaceContainers.Add(((SimpleNameSyntax)name).Identifier.ValueText);
}
}
internal override bool TryGetBaseList(ExpressionSyntax expression, out TypeKindOptions typeKindValue)
{
typeKindValue = TypeKindOptions.AllOptions;
if (expression == null)
{
return false;
}
var node = expression as SyntaxNode;
while (node != null)
{
if (node is BaseListSyntax)
{
if (node.Parent != null && (node.Parent is InterfaceDeclarationSyntax || node.Parent is StructDeclarationSyntax))
{
typeKindValue = TypeKindOptions.Interface;
return true;
}
typeKindValue = TypeKindOptions.BaseList;
return true;
}
node = node.Parent;
}
return false;
}
internal override bool IsPublicOnlyAccessibility(ExpressionSyntax expression, Project project)
{
if (expression == null)
{
return false;
}
if (GeneratedTypesMustBePublic(project))
{
return true;
}
var node = expression as SyntaxNode;
SyntaxNode previousNode = null;
while (node != null)
{
// Types in BaseList, Type Constraint or Member Types cannot be of more restricted accessibility than the declaring type
if ((node is BaseListSyntax || node is TypeParameterConstraintClauseSyntax) &&
node.Parent != null &&
node.Parent is TypeDeclarationSyntax)
{
if (node.Parent is TypeDeclarationSyntax typeDecl)
{
if (typeDecl.GetModifiers().Any(m => m.Kind() == SyntaxKind.PublicKeyword))
{
return IsAllContainingTypeDeclsPublic(typeDecl);
}
else
{
// The Type Decl which contains the BaseList does not contain Public
return false;
}
}
Contract.Fail("Cannot reach this point");
}
if ((node is EventDeclarationSyntax || node is EventFieldDeclarationSyntax) &&
node.Parent != null &&
node.Parent is TypeDeclarationSyntax)
{
// Make sure the GFU is not inside the Accessors
if (previousNode != null && previousNode is AccessorListSyntax)
{
return false;
}
// Make sure that Event Declaration themselves are Public in the first place
if (!node.GetModifiers().Any(m => m.Kind() == SyntaxKind.PublicKeyword))
{
return false;
}
return IsAllContainingTypeDeclsPublic(node);
}
previousNode = node;
node = node.Parent;
}
return false;
}
private bool IsAllContainingTypeDeclsPublic(SyntaxNode node)
{
// Make sure that all the containing Type Declarations are also Public
var containingTypeDeclarations = node.GetAncestors<TypeDeclarationSyntax>();
if (containingTypeDeclarations.Count() == 0)
{
return true;
}
else
{
return containingTypeDeclarations.All(typedecl => typedecl.GetModifiers().Any(m => m.Kind() == SyntaxKind.PublicKeyword));
}
}
internal override bool IsGenericName(SimpleNameSyntax simpleName)
{
if (simpleName == null)
{
return false;
}
var genericName = simpleName as GenericNameSyntax;
return genericName != null;
}
internal override bool IsSimpleName(ExpressionSyntax expression)
{
return expression is SimpleNameSyntax;
}
internal override async Task<Solution> TryAddUsingsOrImportToDocumentAsync(Solution updatedSolution, SyntaxNode modifiedRoot, Document document, SimpleNameSyntax simpleName, string includeUsingsOrImports, CancellationToken cancellationToken)
{
// Nothing to include
if (string.IsNullOrWhiteSpace(includeUsingsOrImports))
{
return updatedSolution;
}
SyntaxNode root = null;
if (modifiedRoot == null)
{
root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
}
else
{
root = modifiedRoot;
}
if (root is CompilationUnitSyntax compilationRoot)
{
var usingDirective = SyntaxFactory.UsingDirective(SyntaxFactory.ParseName(includeUsingsOrImports));
// Check if the usings is already present
if (compilationRoot.Usings.Where(n => n != null && n.Alias == null)
.Select(n => n.Name.ToString())
.Any(n => n.Equals(includeUsingsOrImports)))
{
return updatedSolution;
}
// Check if the GFU is triggered from the namespace same as the usings namespace
if (await IsWithinTheImportingNamespaceAsync(document, simpleName.SpanStart, includeUsingsOrImports, cancellationToken).ConfigureAwait(false))
{
return updatedSolution;
}
var documentOptions = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false);
var placeSystemNamespaceFirst = documentOptions.GetOption(GenerationOptions.PlaceSystemNamespaceFirst);
var addedCompilationRoot = compilationRoot.AddUsingDirectives(new[] { usingDirective }, placeSystemNamespaceFirst, Formatter.Annotation);
updatedSolution = updatedSolution.WithDocumentSyntaxRoot(document.Id, addedCompilationRoot, PreservationMode.PreserveIdentity);
}
return updatedSolution;
}
private ITypeSymbol GetPropertyType(
SimpleNameSyntax propertyName,
SemanticModel semanticModel,
ITypeInferenceService typeInference,
CancellationToken cancellationToken)
{
if (propertyName.Parent is AssignmentExpressionSyntax parentAssignment)
{
return typeInference.InferType(
semanticModel, parentAssignment.Left, objectAsDefault: true, cancellationToken: cancellationToken);
}
if (propertyName.Parent is IsPatternExpressionSyntax isPatternExpression)
{
return typeInference.InferType(
semanticModel, isPatternExpression.Expression, objectAsDefault: true, cancellationToken: cancellationToken);
}
return null;
}
private IPropertySymbol CreatePropertySymbol(
SimpleNameSyntax propertyName, ITypeSymbol propertyType)
{
return CodeGenerationSymbolFactory.CreatePropertySymbol(
attributes: ImmutableArray<AttributeData>.Empty,
accessibility: Accessibility.Public,
modifiers: new DeclarationModifiers(),
explicitInterfaceImplementations: default,
name: propertyName.Identifier.ValueText,
type: propertyType,
refKind: RefKind.None,
parameters: default,
getMethod: s_accessor,
setMethod: s_accessor,
isIndexer: false);
}
private static readonly IMethodSymbol s_accessor = CodeGenerationSymbolFactory.CreateAccessorSymbol(
attributes: default,
accessibility: Accessibility.Public,
statements: default);
internal override bool TryGenerateProperty(
SimpleNameSyntax propertyName,
SemanticModel semanticModel,
ITypeInferenceService typeInference,
CancellationToken cancellationToken,
out IPropertySymbol property)
{
property = null;
var propertyType = GetPropertyType(propertyName, semanticModel, typeInference, cancellationToken);
if (propertyType == null || propertyType is IErrorTypeSymbol)
{
property = CreatePropertySymbol(propertyName, semanticModel.Compilation.ObjectType);
return property != null;
}
property = CreatePropertySymbol(propertyName, propertyType);
return property != null;
}
internal override IMethodSymbol GetDelegatingConstructor(
SemanticDocument document,
ObjectCreationExpressionSyntax objectCreation,
INamedTypeSymbol namedType,
ISet<IMethodSymbol> candidates,
CancellationToken cancellationToken)
{
var model = document.SemanticModel;
var oldNode = objectCreation
.AncestorsAndSelf(ascendOutOfTrivia: false)
.Where(node => SpeculationAnalyzer.CanSpeculateOnNode(node))
.LastOrDefault();
var typeNameToReplace = objectCreation.Type;
var newTypeName = namedType.GenerateTypeSyntax();
var newObjectCreation = objectCreation.WithType(newTypeName).WithAdditionalAnnotations(s_annotation);
var newNode = oldNode.ReplaceNode(objectCreation, newObjectCreation);
var speculativeModel = SpeculationAnalyzer.CreateSpeculativeSemanticModelForNode(oldNode, newNode, model);
if (speculativeModel != null)
{
newObjectCreation = (ObjectCreationExpressionSyntax)newNode.GetAnnotatedNodes(s_annotation).Single();
var symbolInfo = speculativeModel.GetSymbolInfo(newObjectCreation, cancellationToken);
var parameterTypes = newObjectCreation.ArgumentList.Arguments.Select(
a => a.DetermineParameterType(speculativeModel, cancellationToken)).ToList();
return GenerateConstructorHelpers.GetDelegatingConstructor(
document, symbolInfo, candidates, namedType, parameterTypes);
}
return null;
}
}
}
| 44.334728 | 249 | 0.587156 | [
"Apache-2.0"
] | DaiMichael/roslyn | src/Features/CSharp/Portable/GenerateType/CSharpGenerateTypeService.cs | 42,386 | C# |
using Capital.GSG.FX.Data.Core.AccountPortfolio;
using Capital.GSG.FX.Data.Core.ContractData;
using Capital.GSG.FX.Utils.Core;
using static StratedgemeMonitor.Utils.FormatUtils;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
namespace StratedgemeMonitor.Models.PnLs
{
public class PnLModel
{
[Display(Name = "Last Update (HKT)")]
[DisplayFormat(DataFormatString = "{0:dd/MM HH:mm:ss zzz}")]
public DateTimeOffset LastUpdate { get; set; }
public Dictionary<Cross, PnLPerCrossModel> PerCrossPnLs { get; set; }
[Display(Name = "Fees (USD)")]
[DisplayFormat(DataFormatString = "{0:N0}")]
public double TotalFees { get; set; }
[Display(Name = "RG PnL (USD)")]
[DisplayFormat(DataFormatString = "{0:N2}")]
public double TotalGrossRealized { get; set; }
[Display(Name = "UG PnL (USD)")]
[DisplayFormat(DataFormatString = "{0:N2}")]
public double TotalGrossUnrealized { get; set; }
[Display(Name = "Total Net")]
[DisplayFormat(DataFormatString = "{0:N2}")]
public double TotalNet => TotalNetRealized + TotalGrossUnrealized;
[Display(Name = "RN PnL (USD)")]
[DisplayFormat(DataFormatString = "{0:N2}")]
public double TotalNetRealized { get; set; }
[Display(Name = "Trades Cnt")]
[DisplayFormat(DataFormatString = "{0:N0}")]
public double TotalTradesCount { get; set; }
[Display(Name = "UP PnL")]
[DisplayFormat(DataFormatString = "{0:N1}")]
public double TotalPipsUnrealized => (!PerCrossPnLs.IsNullOrEmpty() && PerCrossPnLs.Values.Count(p => p != null) > 0) ? PerCrossPnLs.Values.Where(p => p != null).Select(p => p.PipsUnrealized).Sum() : 0;
}
public class PnLPerCrossModel
{
[Display(Name = "Pair")]
public Cross Cross { get; set; }
[Display(Name = "Pos")]
[DisplayFormat(DataFormatString = "{0:N0}K")]
public double PositionSize { get; set; }
[Display(Name = "RG PnL")]
[DisplayFormat(DataFormatString = "{0:N2}")]
public double GrossRealized { get; set; }
[Display(Name = "UG PnL")]
[DisplayFormat(DataFormatString = "{0:N2}")]
public double GrossUnrealized { get; set; }
[Display(Name = "RN PnL")]
[DisplayFormat(DataFormatString = "{0:N2}")]
public double NetRealized { get; set; }
[Display(Name = "Fees")]
[DisplayFormat(DataFormatString = "{0:N0}")]
public double TotalFees { get; set; }
[Display(Name = "Trades")]
[DisplayFormat(DataFormatString = "{0:N0}")]
public int TradesCount { get; set; }
[Display(Name = "PO (HKT)")]
[DisplayFormat(DataFormatString = "{0:HH:mm:ss}")]
public DateTimeOffset? PositionOpenTime { get; set; }
[Display(Name = "Pos Duration")]
[DisplayFormat(DataFormatString = @"{0:hh\:mm\:ss}")]
public TimeSpan? PositionOpenDuration => (PositionOpenTime.HasValue) ? DateTimeOffset.Now.Subtract(PositionOpenTime.Value) : (TimeSpan?)null;
[Display(Name = "PO Price")]
public string PositionOpenPrice { get; set; }
[Display(Name = "UP PnL")]
[DisplayFormat(DataFormatString = "{0:N1}")]
public double PipsUnrealized { get; set; }
}
internal static class PnLModelExtensions
{
private static PnLPerCrossModel ToPnLPerCrossModel(this PnLPerCross pnl)
{
if (pnl == null)
return null;
return new PnLPerCrossModel()
{
Cross = pnl.Cross,
GrossRealized = pnl.GrossRealized,
GrossUnrealized = pnl.GrossUnrealized,
NetRealized = pnl.NetRealized,
PipsUnrealized = pnl.PipsUnrealized,
PositionOpenPrice = FormatRate(pnl.Cross, pnl.PositionOpenPrice),
PositionOpenTime = pnl.PositionOpenTime.HasValue ? pnl.PositionOpenTime.Value.ToLocalTime() : (DateTimeOffset?)null,
PositionSize = pnl.PositionSize / 1000,
TotalFees = pnl.TotalFees,
TradesCount = pnl.TradesCount
};
}
private static List<PnLPerCrossModel> ToPnLPerCrossModels(this IEnumerable<PnLPerCross> pnls)
{
return pnls?.Select(p => p.ToPnLPerCrossModel()).ToList();
}
public static PnLModel ToPnLModel(this IEnumerable<PnL> pnls)
{
if (pnls.IsNullOrEmpty())
return new PnLModel();
pnls = pnls.Where(p => (p.Broker == Broker.IB) ? !p.Account.Contains("F") : true); // Ignore IB institutional account as they mess up statistics
if (pnls.IsNullOrEmpty())
return new PnLModel();
// Combine all pnls (temporary solution)
var combinedPerCross = pnls.Select(p => p.PerCrossPnLs.AsEnumerable()).Aggregate((cur, next) => cur.Concat(next)).GroupBy(p => p.Cross).Select(g => new PnLPerCross()
{
Cross = g.Key,
GrossRealized = g.Select(p => p.GrossRealized).Sum(),
GrossUnrealized = g.Select(p => p.GrossUnrealized).Sum(),
PipsUnrealized = g.Select(p => p.PipsUnrealized).Sum(),
PositionOpenPrice = g.Select(p => p.PositionOpenPrice)?.FirstOrDefault(),
PositionOpenTime = g.Select(p => p.PositionOpenTime)?.FirstOrDefault(),
PositionSize = g.Select(p => p.PositionSize).Sum(),
TotalFees = g.Select(p => p.TotalFees).Sum(),
TradesCount = g.Select(p => p.TradesCount).Sum() / g.Count() // TODO: find a nicer solution
}).ToList();
var combinedPnl = new PnL()
{
Account = "Total",
Broker = Broker.UNKNOWN,
LastUpdate = pnls.Select(p => p.LastUpdate).Max(),
PerCrossPnLs = combinedPerCross
};
return combinedPnl.ToPnLModel();
}
public static PnLModel ToPnLModel(this PnL pnl)
{
if (pnl == null)
return new PnLModel();
// We want to display the pairs in a specific order
Dictionary<Cross, PnLPerCrossModel> pnlPerCrossDict = new Dictionary<Cross, PnLPerCrossModel>
{
{ Cross.EURUSD, pnl.PerCrossPnLs.FirstOrDefault(p => p.Cross == Cross.EURUSD).ToPnLPerCrossModel() },
{ Cross.USDJPY, pnl.PerCrossPnLs.FirstOrDefault(p => p.Cross == Cross.USDJPY).ToPnLPerCrossModel() },
{ Cross.GBPUSD, pnl.PerCrossPnLs.FirstOrDefault(p => p.Cross == Cross.GBPUSD).ToPnLPerCrossModel() },
{ Cross.AUDUSD, pnl.PerCrossPnLs.FirstOrDefault(p => p.Cross == Cross.AUDUSD).ToPnLPerCrossModel() },
{ Cross.USDCAD, pnl.PerCrossPnLs.FirstOrDefault(p => p.Cross == Cross.USDCAD).ToPnLPerCrossModel() },
{ Cross.USDCHF, pnl.PerCrossPnLs.FirstOrDefault(p => p.Cross == Cross.USDCHF).ToPnLPerCrossModel() },
{ Cross.NZDUSD, pnl.PerCrossPnLs.FirstOrDefault(p => p.Cross == Cross.NZDUSD).ToPnLPerCrossModel() }
};
// Add other pairs, if any
var pnls = pnl.PerCrossPnLs.OrderBy(p => p.Cross.ToString());
foreach (var pnlPerCross in pnls)
{
if (!pnlPerCrossDict.ContainsKey(pnlPerCross.Cross))
pnlPerCrossDict.Add(pnlPerCross.Cross, pnlPerCross.ToPnLPerCrossModel());
}
return new PnLModel()
{
LastUpdate = pnl.LastUpdate.ToLocalTime(),
PerCrossPnLs = pnlPerCrossDict,
TotalFees = pnl.TotalFees,
TotalGrossRealized = pnl.TotalGrossRealized,
TotalGrossUnrealized = pnl.TotalGrossUnrealized,
TotalNetRealized = pnl.TotalNetRealized,
TotalTradesCount = pnl.TotalTradesCount
};
}
}
}
| 41.620513 | 210 | 0.590069 | [
"MIT"
] | gsgfintech/monitoring-aspnetcore | StratedgemeMonitor/Models/PnLs/PnLModel.cs | 8,118 | C# |
using System;
namespace Nethereum.JsonRpc.Client
{
public class RpcClientTimeoutException : Exception
{
public RpcClientTimeoutException(string message) : base(message)
{
}
public RpcClientTimeoutException(string message, Exception innerException) : base(message, innerException)
{
}
}
} | 20.705882 | 114 | 0.664773 | [
"MIT"
] | 6ara6aka/Nethereum | src/Nethereum.JsonRpc.Client/RpcClientTimeoutException.cs | 354 | C# |
using LVK.Tests.Framework;
using NUnit.Framework;
namespace LVK.Storage.Addressable.PathBased.Tests
{
[TestFixture]
public class PublicApiTests : PublicApiTestsBase<ServicesBootstrapper>
{
}
} | 19.090909 | 74 | 0.757143 | [
"MIT"
] | FeatureToggleStudy/LVK | tests/LVK.Storage.Addressable.PathBased.Tests/PublicApiTests.cs | 210 | C# |
using BepuPhysics.Collidables;
using BepuPhysics.CollisionDetection;
using System;
using System.Collections.Generic;
using System.Numerics;
using System.Text;
namespace BepuPlugin
{
public class CollisionEvent
{
CollidableReference eventSource;
CollidablePair pair;
Vector3 contactOffset;
Vector3 contactNormal;
float depth;
int featureId;
int contactIndex;
int workerIndex;
public CollidableReference EventSource => eventSource;
public CollidablePair Pair => pair;
public Vector3 ContactOffset => contactOffset;
public Vector3 ContactNormal => contactNormal;
public float Depth => depth;
public int FeatureId => featureId;
public int ContactIndex => contactIndex;
public int WorkerIndex => workerIndex;
internal void Update(CollidableReference eventSource, CollidablePair pair,
in Vector3 contactOffset, in Vector3 contactNormal, float depth, int featureId, int contactIndex, int workerIndex)
{
this.eventSource = eventSource;
this.pair = pair;
this.contactOffset = contactOffset;
this.contactNormal = contactNormal;
this.depth = depth;
this.featureId = featureId;
this.contactIndex = contactIndex;
this.workerIndex = workerIndex;
}
}
}
| 32.136364 | 126 | 0.659123 | [
"MIT"
] | AnomalousMedical/Adventure | BepuPlugin/Collision/CollisionEvent.cs | 1,416 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.CommandLine;
using System.CommandLine.Invocation;
using System.IO;
using Newtonsoft.Json;
namespace TranscriptConverter
{
public class ConvertTranscriptHandler
{
/// <summary>
/// Creates the convert command.
/// </summary>
/// <returns>The created command.</returns>
public Command Create()
{
var cmd = new Command("convert", "Converts transcript files into test script to be executed by the TranscriptTestRunner");
cmd.AddArgument(new Argument<string>("source"));
cmd.AddOption(new Option<string>("--target", "Path to the target test script file."));
cmd.Handler = CommandHandler.Create<string, string>((source, target) =>
{
try
{
Console.WriteLine("{0}: {1}", "Converting source transcript", source);
var testScript = Converter.ConvertTranscript(source);
Console.WriteLine("Finished conversion");
var targetPath = string.IsNullOrEmpty(target) ? source.Replace(".transcript", ".json", StringComparison.InvariantCulture) : target;
WriteTestScript(testScript, targetPath);
Console.WriteLine("{0}: {1}", "Test script saved as", targetPath);
}
catch (FileNotFoundException e)
{
Console.WriteLine("{0}: {1}", "Error", e.Message);
}
catch (DirectoryNotFoundException e)
{
Console.WriteLine("{0}: {1}", "Error", e.Message);
}
});
return cmd;
}
/// <summary>
/// Writes the test script content to the path set in the target argument.
/// </summary>
private static void WriteTestScript(TestScript testScript, string targetScript)
{
var json = JsonConvert.SerializeObject(
testScript,
Formatting.Indented,
new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
});
using var streamWriter = new StreamWriter(Path.GetFullPath(targetScript));
streamWriter.Write(json);
}
}
}
| 34.619718 | 151 | 0.555736 | [
"MIT"
] | QPC-database/botframework-components | tests/functional/Libraries/TranscriptConverter/ConvertTranscriptHandler.cs | 2,460 | C# |
using Microsoft.AspNetCore.DataProtection;
using Microsoft.Extensions.DependencyInjection;
using NUnit.Framework;
namespace Ruzzie.Common.Security.UnitTests
{
[TestFixture]
public class EncryptionServiceTests
{
[Test]
[TestCase("1")]
[TestCase("p@assW0Rd!")]
[TestCase("097898787870973209384lsjallkajsd9q08lasdh;)()90skdj98q7sjc")]
public void SmokeTest(string inputStringToTest)
{
// add data protection services: meh!
var serviceCollection = new ServiceCollection();
serviceCollection.AddDataProtection();
var services = serviceCollection.BuildServiceProvider();
var dataProtectionProvider = services.GetService<IDataProtectionProvider>();
var copyOfInput = inputStringToTest;
//Never store the keys this way, this is for testing only
var keyOne = "ZjcxZGI2M2RkYTg3YmQ1YzM4ZWQ4MWEwN2FmZjU4OGNmMmFhM2I0YjUyNzNhYTEzN2I5N2E0OWEyMzVlNDhhMg==";
var keyTwo = "OTA5MWI3NzRlMDkxYTY4ZjJmNTdlMDc0YTY0MzY1MGY1ZWMwZWE2ODc1NTU3Njk1NDU5NzUwMzFkNTUxYTNlYQ==";
EncryptionKeys keys = new EncryptionKeys(keyOne,keyTwo);
IEncryptionService service = new EncryptionService(keys, dataProtectionProvider);
var encryptString = service.EncryptString(ref inputStringToTest);
Assert.That(encryptString.Length, Is.GreaterThan(0));
string evilString = service.DecryptString(encryptString);
Assert.That(evilString, Is.EqualTo(copyOfInput));
}
}
} | 42.594595 | 116 | 0.699239 | [
"MIT"
] | Ruzzie/Ruzzie.Common.Security | source/Ruzzie.Common.Security.UnitTests/EncryptionServiceTests.cs | 1,576 | C# |
using System;
using Newtonsoft.Json;
using System.Xml.Serialization;
namespace Essensoft.AspNetCore.Payment.Alipay.Domain
{
/// <summary>
/// KoubeiTradeTicketTicketcodeQueryModel Data Structure.
/// </summary>
[Serializable]
public class KoubeiTradeTicketTicketcodeQueryModel : AlipayObject
{
/// <summary>
/// 口碑门店id
/// </summary>
[JsonProperty("shop_id")]
[XmlElement("shop_id")]
public string ShopId { get; set; }
/// <summary>
/// 12位的券码,券码为纯数字,且唯一不重复
/// </summary>
[JsonProperty("ticket_code")]
[XmlElement("ticket_code")]
public string TicketCode { get; set; }
}
}
| 25 | 69 | 0.605714 | [
"MIT"
] | Aosir/Payment | src/Essensoft.AspNetCore.Payment.Alipay/Domain/KoubeiTradeTicketTicketcodeQueryModel.cs | 744 | C# |
using System;
using System.Collections.Generic;
namespace TerritoryTools.Web.MainSite.Models
{
public class AssignmentHistoryReport
{
public List<AssignmentRecord> Records = new List<AssignmentRecord>();
}
public class AssignmentRecord
{
public string TerritoryNumber { get; set; }
public DateTime? Date { get; set; }
public string PublisherName { get; set; }
public string CheckedOut { get; set; }
public string CheckedIn { get; set; }
public string Note { get; set; }
}
} | 27.75 | 77 | 0.652252 | [
"MIT"
] | territorytools/territory-tools | Web/MainSite/Models/AssignmentHistoryReport.cs | 555 | C# |
// Copyright (c) 2021 .NET Foundation and Contributors. All rights reserved.
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for full license information.
using System.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("IntegrationTests.XamarinForms.UWP")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("IntegrationTests.XamarinForms.UWP")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: ComVisible(false)]
| 41.826087 | 77 | 0.777547 | [
"MIT"
] | Awsmolak/ReactiveUI | integrationtests/IntegrationTests.XamarinForms.UWP/Properties/AssemblyInfo.cs | 965 | C# |
/*
* MIT License
*
* Copyright (c) 2019 plexdata.de
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
using NUnit.Framework;
using Plexdata.CfgParser.Entities;
using System;
namespace Plexdata.CfgParser.Tests.Entities
{
[TestFixture]
[TestOf(nameof(ConfigHeader))]
public class ConfigHeaderTests
{
[Test]
[TestCase(0, "")]
[TestCase(1, "# comment-0")]
[TestCase(2, "# comment-0# comment-1")]
[TestCase(3, "# comment-0# comment-1# comment-2")]
public void Append_VariousItems_ResultIsExpected(Int32 count, String expected)
{
ConfigHeader instance = new ConfigHeader();
for (Int32 index = 0; index < count; index++)
{
instance.Append($"comment-{index}");
}
String actual = String.Empty;
foreach (ConfigComment comment in instance.Comments)
{
actual += comment.ToOutput();
}
Assert.AreEqual(expected, actual);
}
[Test]
[TestCase(0, "")]
[TestCase(1, "# comment-0")]
[TestCase(2, "# comment-1# comment-0")]
[TestCase(3, "# comment-2# comment-1# comment-0")]
public void Prepend_VariousItems_ResultIsExpected(Int32 count, String expected)
{
ConfigHeader instance = new ConfigHeader();
for (Int32 index = 0; index < count; index++)
{
instance.Prepend($"comment-{index}");
}
String actual = String.Empty;
foreach (ConfigComment comment in instance.Comments)
{
actual += comment.ToOutput();
}
Assert.AreEqual(expected, actual);
}
[Test]
[TestCase(5, 3, "# comment-0# comment-1# comment-2# comment-insert# comment-3# comment-4")]
[TestCase(5, 10, "# comment-0# comment-1# comment-2# comment-3# comment-4# comment-insert")]
[TestCase(5, -10, "# comment-insert# comment-0# comment-1# comment-2# comment-3# comment-4")]
public void Insert_VariousItems_ResultIsExpected(Int32 count, Int32 insert, String expected)
{
ConfigHeader instance = new ConfigHeader();
for (Int32 index = 0; index < count; index++)
{
instance.Append($"comment-{index}");
}
instance.Insert(insert, "comment-insert");
String actual = String.Empty;
foreach (ConfigComment comment in instance.Comments)
{
actual += comment.ToOutput();
}
Assert.AreEqual(expected, actual);
}
[Test]
public void Insert_CommentInvalid_ThrowsArgumentNullException()
{
ConfigHeader instance = new ConfigHeader();
ConfigComment comment = null;
Assert.Throws<ArgumentNullException>(() => { instance.Insert(0, comment); });
}
[Test]
public void Remove_CommentTextNotFound_ResultIsNull()
{
ConfigHeader instance = new ConfigHeader();
instance[0] = new ConfigComment("comment-0");
instance[1] = new ConfigComment("comment-1");
instance[2] = new ConfigComment("comment-2");
instance[3] = new ConfigComment("comment-3");
instance[4] = new ConfigComment("comment-4");
Assert.IsNull(instance.Remove("CommentTextNotFound"));
}
[Test]
[TestCase("comment-2")]
[TestCase("COMMENT-2")]
[TestCase("Comment-2")]
public void Remove_CommentTextFound_ResultIsNotNull(String value)
{
ConfigHeader instance = new ConfigHeader();
instance[0] = new ConfigComment("comment-0");
instance[1] = new ConfigComment("comment-1");
instance[2] = new ConfigComment("comment-2");
instance[3] = new ConfigComment("comment-3");
instance[4] = new ConfigComment("comment-4");
Assert.IsNotNull(instance.Remove(value));
}
[Test]
public void Remove_CommentIndexNotFound_ResultIsNull()
{
ConfigHeader instance = new ConfigHeader();
instance[0] = new ConfigComment("comment-0");
instance[1] = new ConfigComment("comment-1");
instance[2] = new ConfigComment("comment-2");
instance[3] = new ConfigComment("comment-3");
instance[4] = new ConfigComment("comment-4");
Assert.IsNull(instance.Remove(5));
}
[Test]
public void Remove_CommentIndexFound_ResultIsNotNull()
{
ConfigHeader instance = new ConfigHeader();
instance[0] = new ConfigComment("comment-0");
instance[1] = new ConfigComment("comment-1");
instance[2] = new ConfigComment("comment-2");
instance[3] = new ConfigComment("comment-3");
instance[4] = new ConfigComment("comment-4");
Assert.IsNotNull(instance.Remove(2));
}
[Test]
public void Find_CommentTextNotFound_ResultIsNull()
{
ConfigHeader instance = new ConfigHeader();
instance[0] = new ConfigComment("comment-0");
instance[1] = new ConfigComment("comment-1");
instance[2] = new ConfigComment("comment-2");
instance[3] = new ConfigComment("comment-3");
instance[4] = new ConfigComment("comment-4");
Assert.IsNull(instance.Find("CommentTextNotFound"));
}
[Test]
[TestCase("comment-2")]
[TestCase("COMMENT-2")]
[TestCase("Comment-2")]
public void Find_CommentTextFound_ResultIsNotNull(String value)
{
ConfigHeader instance = new ConfigHeader();
instance[0] = new ConfigComment("comment-0");
instance[1] = new ConfigComment("comment-1");
instance[2] = new ConfigComment("comment-2");
instance[3] = new ConfigComment("comment-3");
instance[4] = new ConfigComment("comment-4");
Assert.IsNotNull(instance.Find(value));
}
[Test]
public void ToOutput_FiveComments_ResultIsAsExpected()
{
ConfigHeader instance = new ConfigHeader();
instance[0] = new ConfigComment("comment-0");
instance[1] = new ConfigComment("comment-1");
instance[2] = new ConfigComment("comment-2");
instance[3] = new ConfigComment("comment-3");
instance[4] = new ConfigComment("comment-4");
String actual = String.Join(String.Empty, instance.ToOutput());
Assert.AreEqual("# comment-0# comment-1# comment-2# comment-3# comment-4", actual);
}
[Test]
public void IndexArrayAccessor_SetInvalidValue_ThrowsArgumentNullException()
{
ConfigHeader instance = new ConfigHeader();
Assert.Throws<ArgumentNullException>(() => instance[0] = null);
}
[Test]
public void IndexArrayAccessor_AppendValidValue_ResultIsValueAppended()
{
ConfigHeader instance = new ConfigHeader();
instance[0] = new ConfigComment("comment-1");
instance[1] = new ConfigComment("comment-2");
instance[2] = new ConfigComment("comment-3");
ConfigComment comment = new ConfigComment("appended-comment");
instance[1000] = comment;
Assert.AreSame(comment, instance[3]);
}
[Test]
public void IndexArrayAccessor_PrependValidValue_ResultIsValuePrepended()
{
ConfigHeader instance = new ConfigHeader();
instance[0] = new ConfigComment("comment-1");
instance[1] = new ConfigComment("comment-2");
instance[2] = new ConfigComment("comment-3");
ConfigComment comment = new ConfigComment("prepended-comment");
instance[-1000] = comment;
Assert.AreSame(comment, instance[0]);
}
[Test]
public void IndexArrayAccessor_ReplaceValidValue_ResultIsValueReplaced()
{
ConfigHeader instance = new ConfigHeader();
instance[0] = new ConfigComment("comment-1");
instance[1] = new ConfigComment("comment-2");
instance[2] = new ConfigComment("comment-3");
ConfigComment comment = new ConfigComment("replaced-comment");
instance[1] = comment;
Assert.AreSame(comment, instance[1]);
}
[Test]
public void KeyArrayAccessor_SetInvalidValue_ThrowsArgumentNullException()
{
ConfigHeader instance = new ConfigHeader();
Assert.Throws<ArgumentNullException>(() => instance["comment"] = null);
}
[Test]
[TestCase(null)]
[TestCase("")]
[TestCase(" ")]
public void KeyArrayAccessor_GetValueWithInvalidKey_ThrowsArgumentException(String key)
{
ConfigHeader instance = new ConfigHeader();
ConfigComment comment;
Assert.Throws<ArgumentException>(() => comment = instance[key]);
}
[Test]
[TestCase(null)]
[TestCase("")]
[TestCase(" ")]
public void KeyArrayAccessor_SetValueWithInvalidKey_ThrowsArgumentException(String key)
{
ConfigHeader instance = new ConfigHeader();
Assert.Throws<ArgumentException>(() => instance[key] = new ConfigComment());
}
[Test]
public void KeyArrayAccessor_AppendValidValue_ResultIsValueAppended()
{
ConfigHeader instance = new ConfigHeader();
instance[0] = new ConfigComment("comment-1");
instance[1] = new ConfigComment("comment-2");
instance[2] = new ConfigComment("comment-3");
ConfigComment comment = new ConfigComment("appended-comment");
instance["comment-not-known"] = comment;
Assert.AreSame(comment, instance[3]);
}
[Test]
public void KeyArrayAccessor_AppendEmptyValue_ResultIsValueAppendedWithKey()
{
ConfigHeader instance = new ConfigHeader();
instance[0] = new ConfigComment("comment-1");
instance[1] = new ConfigComment("comment-2");
instance[2] = new ConfigComment("comment-3");
ConfigComment comment = new ConfigComment();
instance["comment-42"] = comment;
Assert.AreSame(comment, instance[3]);
Assert.AreEqual("comment-42", instance[3].Text);
Assert.AreEqual("comment-42", comment.Text);
}
[Test]
public void KeyArrayAccessor_ReplaceValidValue_ResultIsValueReplaced()
{
ConfigHeader instance = new ConfigHeader();
instance[0] = new ConfigComment("comment-1");
instance[1] = new ConfigComment("comment-2");
instance[2] = new ConfigComment("comment-3");
ConfigComment comment = new ConfigComment("replaced-comment");
instance["comment-2"] = comment;
Assert.AreSame(comment, instance[1]);
}
[Test]
public void KeyArrayAccessor_ReplaceEmptyValue_ResultIsValueReplacedWithKey()
{
ConfigHeader instance = new ConfigHeader();
instance[0] = new ConfigComment("comment-1");
instance[1] = new ConfigComment("comment-2");
instance[2] = new ConfigComment("comment-3");
ConfigComment comment = new ConfigComment();
instance["comment-2"] = comment;
Assert.AreSame(comment, instance[1]);
Assert.AreEqual("comment-2", instance[1].Text);
Assert.AreEqual("comment-2", comment.Text);
}
}
}
| 34.318302 | 101 | 0.592286 | [
"MIT"
] | akesseler/Plexdata.CfgParser | code/src/Plexdata.CfgParser.NET.Tests/Entities/ConfigHeaderTests.cs | 12,940 | 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.Reflection;
namespace Microsoft.EntityFrameworkCore.Infrastructure
{
/// <summary>
/// <para>
/// Extension methods for <see cref="MethodInfo" />.
/// </para>
/// <para>
/// This type is typically used by database providers (and other extensions). It is generally
/// not used in application code.
/// </para>
/// </summary>
/// <remarks>
/// See <see href="https://aka.ms/efcore-docs-providers">Implementation of database providers and extensions</see> for more information.
/// </remarks>
public static class MethodInfoExtensions
{
private static readonly string _efTypeName = typeof(EF).FullName!;
/// <summary>
/// Returns <see langword="true" /> if the given method is <see cref="EF.Property{TProperty}" />.
/// </summary>
/// <param name="methodInfo"> The method. </param>
/// <returns> <see langword="true" /> if the method is <see cref="EF.Property{TProperty}" />; <see langword="false" /> otherwise. </returns>
public static bool IsEFPropertyMethod(this MethodInfo? methodInfo)
=> Equals(methodInfo, EF.PropertyMethod)
// fallback to string comparison because MethodInfo.Equals is not
// always true in .NET Native even if methods are the same
|| methodInfo?.IsGenericMethod == true
&& methodInfo.Name == nameof(EF.Property)
&& methodInfo.DeclaringType?.FullName == _efTypeName;
}
}
| 44.763158 | 148 | 0.614932 | [
"MIT"
] | MessiDaGod/efcore | src/EFCore/Infrastructure/MethodInfoExtensions.cs | 1,701 | C# |
// ***********************************************************************
// Copyright (c) Charlie Poole and TestCentric GUI contributors.
// Licensed under the MIT License. See LICENSE file in root directory.
// ***********************************************************************
using NUnit.Framework;
using NSubstitute;
namespace TestCentric.Gui.Presenters
{
using Views;
using Model;
using Controls;
public class StatusBarPresenterTests
{
private IStatusBarView _view;
private ITestModel _model;
private StatusBarPresenter _presenter;
[SetUp]
public void CreatePresenter()
{
_view = Substitute.For<IStatusBarView>();
_model = Substitute.For<ITestModel>();
_presenter = new StatusBarPresenter(_view, _model);
}
[TearDown]
public void RemovePresenter()
{
//if (_presenter != null)
// _presenter.Dispose();
_presenter = null;
}
//[Test]
//public void WhenProjectIsUnloaded_ProgressBar_IsInitialized()
//{
// _settings.IsProjectLoaded.Returns(false);
// _settings.IsTestLoaded.Returns(false);
// _settings.IsTestRunning.Returns(false);
// _settings.ProjectUnloaded += Raise.Event<TestEventHandler>(new TestEventArgs(TestAction.ProjectUnloaded, "Dummy"));
// _view.Received().Initialize(100);
//}
[Test]
public void WhenTestsAreUnloaded_StatusBar_IsInitialized()
{
_model.HasTests.Returns(false);
_model.IsTestRunning.Returns(false);
_model.Events.TestUnloaded += Raise.Event<TestEventHandler>(new TestEventArgs());
_view.Received().OnTestUnloaded();
}
[Test]
public void WhenTestRunBegins_StatusBar_IsInitialized()
{
_model.HasTests.Returns(true);
_model.IsTestRunning.Returns(true);
_model.Events.RunStarting += Raise.Event<RunStartingEventHandler>(new RunStartingEventArgs(1234));
_view.Received().OnRunStarting(1234);
}
[Test]
public void WhenTestCaseCompletes_CountIsIncremented()
{
var result = new ResultNode(XmlHelper.CreateXmlNode("<test-case id='1'/>"));
_model.Events.TestFinished += Raise.Event<TestResultEventHandler>(new TestResultEventArgs(result));
_view.Received().OnTestPassed();
}
[Test]
public void WhenTestsFinish_TestResultsAreCalculated()
{
var result = new ResultNode(XmlHelper.CreateXmlNode("<test-run/>"));
_model.Events.RunFinished += Raise.Event<TestResultEventHandler>(new TestResultEventArgs(result));
_view.Received().OnRunFinished(0);
_view.Received().OnTestRunSummaryCompiled(Arg.Compat.Any<string>());
}
//[Test]
//public void WhenTestSuiteCompletes_ProgressIsNotIncremented()
//{
// int priorValue = _view.Progress;
// var suiteResult = new ResultNode(XmlHelper.CreateXmlNode("<test-suite id='1'/>"));
// _settings.SuiteFinished += Raise.Event<TestResultEventHandler>(new TestResultEventArgs(suiteResult));
// Assert.That(_view.Progress, Is.EqualTo(priorValue));
//}
//[Test]
//public void WhenTestSuiteCompletes_ResultIsPostedToView()
//{
// int priorValue = _view.Progress;
// var suiteResult = new ResultNode(XmlHelper.CreateTopLevelElement("test-suite"));
// _settings.TestFinished += Raise.Event<TestEventHandler>(new TestEventArgs(TestAction.TestFinished, suiteResult));
// Assert.That(_view.Progress, Is.EqualTo(priorValue));
//}
static object[] statusTestCases = new object[] {
new object[] { ProgressBarStatus.Success, ResultState.Failure, ProgressBarStatus.Failure },
new object[] { ProgressBarStatus.Warning, ResultState.Failure, ProgressBarStatus.Failure },
new object[] { ProgressBarStatus.Failure, ResultState.Failure, ProgressBarStatus.Failure },
new object[] { ProgressBarStatus.Success, ResultState.Error, ProgressBarStatus.Failure },
new object[] { ProgressBarStatus.Warning, ResultState.Error, ProgressBarStatus.Failure },
new object[] { ProgressBarStatus.Failure, ResultState.Error, ProgressBarStatus.Failure },
new object[] { ProgressBarStatus.Success, ResultState.NotRunnable, ProgressBarStatus.Failure },
new object[] { ProgressBarStatus.Warning, ResultState.NotRunnable, ProgressBarStatus.Failure },
new object[] { ProgressBarStatus.Failure, ResultState.NotRunnable, ProgressBarStatus.Failure },
new object[] { ProgressBarStatus.Success, ResultState.Ignored, ProgressBarStatus.Warning },
new object[] { ProgressBarStatus.Warning, ResultState.Ignored, ProgressBarStatus.Warning },
new object[] { ProgressBarStatus.Failure, ResultState.Ignored, ProgressBarStatus.Failure },
new object[] { ProgressBarStatus.Success, ResultState.Inconclusive, ProgressBarStatus.Success },
new object[] { ProgressBarStatus.Warning, ResultState.Inconclusive, ProgressBarStatus.Warning },
new object[] { ProgressBarStatus.Failure, ResultState.Inconclusive, ProgressBarStatus.Failure },
new object[] { ProgressBarStatus.Success, ResultState.Skipped, ProgressBarStatus.Success },
new object[] { ProgressBarStatus.Warning, ResultState.Skipped, ProgressBarStatus.Warning },
new object[] { ProgressBarStatus.Failure, ResultState.Skipped, ProgressBarStatus.Failure },
new object[] { ProgressBarStatus.Success, ResultState.Success, ProgressBarStatus.Success },
new object[] { ProgressBarStatus.Warning, ResultState.Success, ProgressBarStatus.Warning },
new object[] { ProgressBarStatus.Failure, ResultState.Success, ProgressBarStatus.Failure }
};
//[TestCaseSource("statusTestCases")]
//public void BarShowsProperStatus(TestProgressBarStatus priorStatus, ResultState resultState, TestProgressBarStatus expectedStatus)
//{
// _view.Status = priorStatus;
// var doc = new XmlDocument();
// if (resultState.Label == string.Empty)
// doc.LoadXml(string.Format("<test-case id='1' suiteResult='{0}'/>", resultState.Status));
// else
// doc.LoadXml(string.Format("<test-case id='1' suiteResult='{0}' label='{1}'/>", resultState.Status, resultState.Label));
// var suiteResult = new ResultNode(doc.FirstChild);
// _settings.IsProjectLoaded.Returns(true);
// _settings.IsTestLoaded.Returns(true);
// _settings.LoadedTests.Returns(suiteResult);
// _settings.TestLoaded += Raise.Event<TestEventHandler>(new TestEventArgs(TestAction.TestLoaded, "Dummy", suiteResult));
// _settings.TestFinished += Raise.Event<TestResultEventHandler>(new TestResultEventArgs(TestAction.TestFinished, suiteResult));
// Assert.That(_view.Status, Is.EqualTo(expectedStatus));
//}
}
}
| 45.91195 | 140 | 0.64411 | [
"MIT"
] | YashUoM/testcentric-gui | src/Experimental/tests/Presenters/StatusBarPresenterTests.cs | 7,300 | C# |
using System;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Routing;
namespace jaytwo.ejson.example.AspNet4_6_1
{
public class Global : System.Web.HttpApplication
{
protected void Application_Start(object sender, EventArgs e)
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
EjsonConfig.ConfigureEjsonAppSecrets();
}
}
} | 30.1 | 70 | 0.699336 | [
"MIT"
] | jakegough/jaytwo.ejson | examples/jaytwo.ejson.example.AspNet4_6_1/Global.asax.cs | 604 | C# |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
// The core npc decision manager system. Used by AI actors as it evaluates conditions
// and executes responses when those conditions are met
[System.Serializable]
public class npcDecisionMgr{
public List<npcInteraction> interactions;
public void init()
{
foreach (npcInteraction e in interactions)
{
e.init ();
}
}
public void eval()
{
foreach (npcInteraction e in interactions)
{
e.eval();
}
}
}
| 18.214286 | 86 | 0.723529 | [
"MIT"
] | rosco-y/Geography-Quest | GeographyQuest/Assets/(ImportedSources)/Chapter6/npcDecisionMgr.cs | 512 | C# |
namespace UIControls.Core
{
public class Constants
{
public const string AppDataDirName = @"TortoiseRally";
}
}
| 14.75 | 56 | 0.737288 | [
"MIT"
] | azarkevich/TortoiseRally | UIControls/Core/Constants.cs | 120 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Net;
using System.IO;
namespace KdGoldAPI
{
public class KdApiSearchDemo
{
//电商ID
private string EBusinessID = "1237100";
//电商加密私钥,快递鸟提供,注意保管,不要泄漏
private string AppKey = "518a73d8-1f7f-441a-b644-33e77b49d846";
//请求url
private string ReqURL = "http://api.kdniao.com/Ebusiness/EbusinessOrderHandle.aspx";
/// <summary>
/// Json方式 查询订单物流轨迹
/// </summary>
/// <returns></returns>
public string getOrderTracesByJson()
{
string requestData = "{'OrderCode':'','ShipperCode':'SF','LogisticCode':'589707398027'}";
Dictionary<string, string> param = new Dictionary<string, string>();
param.Add("RequestData", HttpUtility.UrlEncode(requestData, Encoding.UTF8));
param.Add("EBusinessID", EBusinessID);
param.Add("RequestType", "1002");
string dataSign = encrypt(requestData, AppKey, "UTF-8");
param.Add("DataSign", HttpUtility.UrlEncode(dataSign, Encoding.UTF8));
param.Add("DataType", "2");
string result = sendPost(ReqURL, param);
//根据公司业务处理返回的信息......
return result;
}
/// <summary>
/// Post方式提交数据,返回网页的源代码
/// </summary>
/// <param name="url">发送请求的 URL</param>
/// <param name="param">请求的参数集合</param>
/// <returns>远程资源的响应结果</returns>
private string sendPost(string url, Dictionary<string, string> param)
{
string result = "";
StringBuilder postData = new StringBuilder();
if (param != null && param.Count > 0)
{
foreach (var p in param)
{
if (postData.Length > 0)
{
postData.Append("&");
}
postData.Append(p.Key);
postData.Append("=");
postData.Append(p.Value);
}
}
byte[] byteData = Encoding.GetEncoding("UTF-8").GetBytes(postData.ToString());
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.ContentType = "application/x-www-form-urlencoded";
request.Referer = url;
request.Accept = "*/*";
request.Timeout = 30 * 1000;
request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)";
request.Method = "POST";
request.ContentLength = byteData.Length;
Stream stream = request.GetRequestStream();
stream.Write(byteData, 0, byteData.Length);
stream.Flush();
stream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream backStream = response.GetResponseStream();
StreamReader sr = new StreamReader(backStream, Encoding.GetEncoding("UTF-8"));
result = sr.ReadToEnd();
sr.Close();
backStream.Close();
response.Close();
request.Abort();
}
catch (Exception ex)
{
result = ex.Message;
}
return result;
}
///<summary>
///电商Sign签名
///</summary>
///<param name="content">内容</param>
///<param name="keyValue">Appkey</param>
///<param name="charset">URL编码 </param>
///<returns>DataSign签名</returns>
private string encrypt(String content, String keyValue, String charset)
{
if (keyValue != null)
{
return base64(MD5(content + keyValue, charset), charset);
}
return base64(MD5(content, charset), charset);
}
///<summary>
/// 字符串MD5加密
///</summary>
///<param name="str">要加密的字符串</param>
///<param name="charset">编码方式</param>
///<returns>密文</returns>
private string MD5(string str, string charset)
{
byte[] buffer = System.Text.Encoding.GetEncoding(charset).GetBytes(str);
try
{
System.Security.Cryptography.MD5CryptoServiceProvider check;
check = new System.Security.Cryptography.MD5CryptoServiceProvider();
byte[] somme = check.ComputeHash(buffer);
string ret = "";
foreach (byte a in somme)
{
if (a < 16)
ret += "0" + a.ToString("X");
else
ret += a.ToString("X");
}
return ret.ToLower();
}
catch
{
throw;
}
}
/// <summary>
/// base64编码
/// </summary>
/// <param name="str">内容</param>
/// <param name="charset">编码方式</param>
/// <returns></returns>
private string base64(String str, String charset)
{
return Convert.ToBase64String(System.Text.Encoding.GetEncoding(charset).GetBytes(str));
}
}
}
| 35.134615 | 182 | 0.505017 | [
"MIT"
] | wannvmi/Kdniao.Core | official-demo/KdApiSearchDemo(.NET)/KdApiSearchDemo.cs | 5,725 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 어셈블리의 일반 정보는 다음 특성 집합을 통해 제어됩니다.
// 어셈블리와 관련된 정보를 수정하려면
// 이 특성 값을 변경하십시오.
[assembly: AssemblyTitle("MobileServer")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("MobileServer")]
[assembly: AssemblyCopyright("Copyright © 2012")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// ComVisible을 false로 설정하면 이 어셈블리의 형식이 COM 구성 요소에
// 표시되지 않습니다. COM에서 이 어셈블리의 형식에 액세스하려면
// 해당 형식에 대해 ComVisible 특성을 true로 설정하십시오.
[assembly: ComVisible(false)]
// 이 프로젝트가 COM에 노출되는 경우 다음 GUID는 typelib의 ID를 나타냅니다.
[assembly: Guid("37ce3b10-bba4-47eb-8b24-fab6eb6017b8")]
// 어셈블리의 버전 정보는 다음 네 가지 값으로 구성됩니다.
//
// 주 버전
// 부 버전
// 빌드 번호
// 수정 버전
//
// 모든 값을 지정하거나 아래와 같이 '*'를 사용하여 빌드 번호 및 수정 버전이 자동으로
// 지정되도록 할 수 있습니다.
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 29.513514 | 57 | 0.67674 | [
"MIT"
] | shlee322/Netronics | example/Mobile/Server/Properties/AssemblyInfo.cs | 1,529 | C# |
// Copyright (c) Zolution Software Ltd. All rights reserved.
// Licensed under the MIT License, see LICENSE.txt in the solution root for license information
using System;
namespace Rezolver.Options
{
/// <summary>
/// A suggested base class to use for custom container options to be read/written through extensions
/// such as <see cref="TargetContainerExtensions.SetOption{TOption}(ITargetContainer, TOption)"/>,
/// <see cref="TargetContainerExtensions.GetOptions{TOption, TService}(ITargetContainer)"/> and the various
/// overloads.S
///
/// The type of the option value is the argument to the <typeparamref name="TOption"/> type parameter.
///
/// Options must currently be objects - the ability to use callbacks to get options might be added at a
/// future date.
/// </summary>
/// <typeparam name="TOption">The underlying option value type - e.g. <see cref="bool"/>, <see cref="string"/>,
/// <see cref="Uri"/> or whatever</typeparam>
/// <remarks>
/// **This type is creatable only through inheritance.**
///
///
/// Options in Rezolver are achieved by using registrations in the <see cref="ITargetContainer"/> that
/// is to be configured (and, in turn, which might then configure any <see cref="Container"/>s built from
/// that target container).
///
/// Since options often take the form of primitive types - e.g <see cref="bool"/>, <see cref="string"/> etc - this
/// means it's impossible to register multiple options which control different things which have the same underlying
/// type if we registered them directly.
///
/// This class is offered as a way around this. Options (e.g. <see cref="AllowMultiple"/>) are derived from this type,
/// with the argument to the <typeparamref name="TOption"/> type parameter set to the underlying type of the option value.
///
/// Thus - each distinct option is a different type, which then means that an <see cref="ITargetContainer"/> can distinguish
/// between them.
///
/// ---
///
/// ### Note:
///
/// Whilst Rezolver uses this type for most of its configurable options, you don't need to use it. Any type can be used as
/// an option.</remarks>
[System.Diagnostics.DebuggerDisplay("Value = {Value}")]
public class ContainerOption<TOption>
{
/// <summary>
/// The underlying value wrapped by this option.
/// </summary>
public TOption Value { get; protected set; }
/// <summary>
/// Inheritance constructor.
/// </summary>
protected ContainerOption() { }
/// <summary>
/// Implicit casting operator to convert to the option value type from an instance of <see cref="ContainerOption{TOption}"/>.
///
/// All derived types are encouraged to have a similar casting operator from <typeparamref name="TOption" /> to <see cref="ContainerOption{TOption}"/>
/// (for example, see <see cref="EnableEnumerableInjection"/>).
/// </summary>
/// <param name="option">The option object to be cast to <typeparamref name="TOption" /> (by reading its <see cref="Value"/> property).
///
/// Note that if this is <c>null</c>, then the return value will be the default for <typeparamref name="TOption" /></param>
public static implicit operator TOption(ContainerOption<TOption> option)
{
return option != null ? option.Value : default;
}
/// <summary>
/// Provides a textual representation of the value of this option and its underlying type.
/// </summary>
/// <returns>A string in the form <code>"{Value} ({typeof(TOption)})"</code></returns>
public override string ToString()
{
return $"{Value} ({typeof(TOption)})";
}
}
}
| 46.795181 | 158 | 0.639289 | [
"MIT"
] | LordZoltan/Rezolver | src/Rezolver/Options/ContainerOption`1.cs | 3,886 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Vibrant.Tsdb
{
public class AggregatedField
{
public AggregatedField()
{
}
public AggregatedField( string field, AggregationFunction function )
{
Field = field;
Function = function;
}
public string Field { get; set; }
public AggregationFunction Function { get; set; }
}
}
| 17.740741 | 74 | 0.645094 | [
"MIT"
] | MikaelGRA/Tsdb | src/Vibrant.Tsdb/AggregatedField.cs | 481 | C# |
namespace CBEApp.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class Upgraded_To_Abp_v4_7_0 : DbMigration
{
public override void Up()
{
DropIndex("dbo.AbpSettings", new[] { "TenantId" });
DropIndex("dbo.AbpSettings", new[] { "UserId" });
CreateIndex("dbo.AbpSettings", new[] { "TenantId", "Name", "UserId" }, unique: true);
}
public override void Down()
{
DropIndex("dbo.AbpSettings", new[] { "TenantId", "Name", "UserId" });
CreateIndex("dbo.AbpSettings", "UserId");
CreateIndex("dbo.AbpSettings", "TenantId");
}
}
}
| 30.652174 | 97 | 0.553191 | [
"MIT"
] | MikeGitIt/CBEApp | src/CBEApp.EntityFramework/Migrations/201907021413234_Upgraded_To_Abp_v4_7_0.cs | 705 | C# |
using UnityEngine;
namespace UniTools.IO
{
public abstract class BaseScriptablePath : ScriptableObject
{
[SerializeField] private string m_value = default;
public string Value
{
set => m_value = value;
}
public override string ToString()
{
return m_value;
}
}
} | 18.736842 | 63 | 0.567416 | [
"MIT"
] | UniToolsTeam/unitools-io | Editor/Path/BaseScriptablePath.cs | 356 | C# |
using Kingmaker.Blueprints.Items.Armors;
using Kingmaker.Blueprints.JsonSystem;
using Kingmaker.UnitLogic.Mechanics.Conditions;
namespace TabletopTweaks.NewComponents {
[TypeId("5e7a0461a88943ea862df008d52e2cff")]
public class ContextConditionHasFreeHand : ContextCondition {
public override string GetConditionCaption() {
return "Check if caster has a free hand";
}
public override bool CheckCondition() {
var secondaryHand = Target.Unit.Body.CurrentHandsEquipmentSet.SecondaryHand;
var primaryHand = Target.Unit.Body.CurrentHandsEquipmentSet.PrimaryHand;
bool hasFreeHand = true;
if (secondaryHand.HasShield) {
var maybeShield = secondaryHand.MaybeShield;
hasFreeHand = maybeShield.Blueprint.Type.ProficiencyGroup == ArmorProficiencyGroup.Buckler ? true : false;
}
if (!secondaryHand.HasWeapon || secondaryHand.MaybeWeapon == Target.Unit.Body.EmptyHandWeapon) {
if (primaryHand.HasWeapon) {
hasFreeHand = primaryHand.MaybeWeapon.HoldInTwoHands ? false : hasFreeHand;
}
}
return hasFreeHand;
}
}
}
| 42.689655 | 122 | 0.661551 | [
"MIT"
] | 1onepower/WrathMods-TabletopTweaks | TabletopTweaks/NewComponents/ContextConditionHasFreeHand.cs | 1,240 | C# |
using AngleSharp;
using System;
using System.Threading.Tasks;
namespace Demo03.Tables
{
class Program
{
static async Task Main()
{
var source = @"<!DOCTYPE html>
<table>
<tr><br></invalid-tag>
<th>One</th>
<td>Two</td>
</tr>
<iframe></iframe>
</table>
<tr></tr><div></div>";
var context = BrowsingContext.New();
var document = await context.OpenAsync(res => res
.Content(source)
.Address("http://localhost:1234/demo03"));
Console.WriteLine(document.ToHtml());
Console.ReadKey();
}
}
}
| 21.322581 | 62 | 0.511346 | [
"MIT"
] | AngleSharp/AngleSharp.Demos.DotnetConf | Demo03.Tables/Program.cs | 663 | C# |
using UnityEngine;
using UnityEditor;
using UnityEngine.ProBuilder;
namespace UnityEditor.ProBuilder
{
/// <inheritdoc />
/// <summary>
/// Inspector for working with lightmap UV generation params.
/// </summary>
[CanEditMultipleObjects]
sealed class UnwrapParametersEditor : Editor
{
SerializedProperty m_UnwrapParametersProperty;
GUIContent m_UnwrapParametersContent = new GUIContent("Lightmap UV Settings", "Settings for how Unity unwraps the UV2 (lightmap) UVs");
void OnEnable()
{
m_UnwrapParametersProperty = serializedObject.FindProperty("m_UnwrapParameters");
}
public override void OnInspectorGUI()
{
#if UNITY_2019_1_OR_NEWER
if (!serializedObject.isValid)
return;
#else
if (serializedObject.targetObject == null)
return;
#endif
serializedObject.Update();
EditorGUILayout.PropertyField(m_UnwrapParametersProperty, m_UnwrapParametersContent, true);
serializedObject.ApplyModifiedProperties();
}
}
}
| 31 | 144 | 0.643418 | [
"MIT"
] | ArcaneWizard/Codeday_Test | threeMusks/Library/PackageCache/com.unity.probuilder@4.4.0/Editor/EditorCore/UnwrapParametersEditor.cs | 1,147 | C# |
//
// Gendarme.Rules.Performance.RemoveUnneededFinalizerRule
//
// Authors:
// Sebastien Pouliot <sebastien@ximian.com>
//
// Copyright (C) 2005,2008 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Globalization;
using Mono.Cecil;
using Mono.Cecil.Cil;
using Gendarme.Framework;
using Gendarme.Framework.Helpers;
using Gendarme.Framework.Rocks;
namespace Gendarme.Rules.Performance {
// similar to findbugs
// FI: Empty finalizer should be deleted (FI_EMPTY)
// FI: Finalizer does nothing but call superclass finalizer (FI_USELESS)
// FI: Finalizer only nulls fields (FI_FINALIZER_ONLY_NULLS_FIELDS)
/// <summary>
/// This rule looks for types that have an empty finalizer (a.k.a. destructor in C# or
/// <c>Finalize</c> method). Finalizers that simply set fields to null are considered to be
/// empty because this does not help the garbage collection. You should remove the empty
/// finalizer to alleviate pressure on the garbage collector and finalizer thread.
/// </summary>
/// <example>
/// Bad example (empty):
/// <code>
/// class Bad {
/// ~Bad ()
/// {
/// }
/// }
/// </code>
/// </example>
/// <example>
/// Bad example (only nulls fields):
/// <code>
/// class Bad {
/// object o;
///
/// ~Bad ()
/// {
/// o = null;
/// }
/// }
/// </code>
/// </example>
/// <example>
/// Good example:
/// <code>
/// class Good {
/// object o;
/// }
/// </code>
/// </example>
/// <remarks>Prior to Gendarme 2.2 this rule was named EmptyDestructorRule</remarks>
[Problem ("The type has an useless (empty or only nullifying fields) finalizer.")]
[Solution ("Remove the finalizer from this type to reduce the GC workload.")]
[FxCopCompatibility ("Microsoft.Performance", "CA1821:RemoveEmptyFinalizers")]
public class RemoveUnneededFinalizerRule : Rule, ITypeRule {
public RuleResult CheckType (TypeDefinition type)
{
// rule applies only to type with a finalizer
MethodDefinition finalizer = type.GetMethod (MethodSignatures.Finalize);
if (finalizer == null)
return RuleResult.DoesNotApply;
// rule applies
// finalizer is present, look if it has any code within it
// i.e. look if is does anything else than calling it's base class
int nullify_fields = 0;
foreach (Instruction ins in finalizer.Body.Instructions) {
switch (ins.OpCode.Code) {
case Code.Call:
case Code.Callvirt:
// it's empty if we're calling the base class finalizer
MethodReference mr = (ins.Operand as MethodReference);
if ((mr == null) || !mr.IsFinalizer ())
return RuleResult.Success;
break;
case Code.Nop:
case Code.Leave:
case Code.Leave_S:
case Code.Ldarg_0:
case Code.Endfinally:
case Code.Ret:
case Code.Ldnull:
// ignore
break;
case Code.Stfld:
// considered as empty as long as it's only to nullify them
if (ins.Previous.OpCode.Code == Code.Ldnull) {
nullify_fields++;
continue;
}
return RuleResult.Success;
default:
// finalizer isn't empty (normal)
return RuleResult.Success;
}
}
// finalizer is empty (bad / useless)
string msg = nullify_fields == 0 ? String.Empty :
String.Format (CultureInfo.InvariantCulture,
"Contains {0} fields being nullified needlessly", nullify_fields);
Runner.Report (type, Severity.Medium, Confidence.Normal, msg);
return RuleResult.Failure;
}
}
}
| 31.711268 | 92 | 0.692427 | [
"MIT"
] | JAD-SVK/Gendarme | rules/Gendarme.Rules.Performance/RemoveUnneededFinalizerRule.cs | 4,503 | C# |
// ==========================================================================
// Squidex Headless CMS
// ==========================================================================
// Copyright (c) Squidex UG (haftungsbeschraenkt)
// All rights reserved. Licensed under the MIT license.
// ==========================================================================
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using FakeItEasy;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Options;
using Squidex.Domain.Apps.Core.HandleRules;
using Squidex.Domain.Apps.Core.Rules.EnrichedEvents;
using Squidex.Domain.Apps.Core.Rules.Triggers;
using Squidex.Domain.Apps.Core.Scripting;
using Squidex.Domain.Apps.Core.TestHelpers;
using Squidex.Domain.Apps.Events;
using Squidex.Domain.Apps.Events.Comments;
using Squidex.Domain.Apps.Events.Contents;
using Squidex.Infrastructure;
using Squidex.Infrastructure.EventSourcing;
using Squidex.Shared.Users;
using Xunit;
namespace Squidex.Domain.Apps.Entities.Comments
{
public class CommentTriggerHandlerTests
{
private readonly IScriptEngine scriptEngine = A.Fake<IScriptEngine>();
private readonly IUserResolver userResolver = A.Fake<IUserResolver>();
private readonly IRuleTriggerHandler sut;
public CommentTriggerHandlerTests()
{
A.CallTo(() => scriptEngine.Evaluate(A<ScriptVars>._, "true", default))
.Returns(true);
A.CallTo(() => scriptEngine.Evaluate(A<ScriptVars>._, "false", default))
.Returns(false);
sut = new CommentTriggerHandler(scriptEngine, userResolver);
}
[Fact]
public void Should_return_false_when_asking_for_snapshot_support()
{
Assert.False(sut.CanCreateSnapshotEvents);
}
[Fact]
public async Task Should_create_enriched_events()
{
var user1 = UserMocks.User("1");
var user2 = UserMocks.User("2");
var users = new List<IUser> { user1, user2 };
var userIds = users.Select(x => x.Id).ToArray();
var envelope = Envelope.Create<AppEvent>(new CommentCreated { Mentions = userIds });
A.CallTo(() => userResolver.QueryManyAsync(userIds))
.Returns(users.ToDictionary(x => x.Id));
var result = await sut.CreateEnrichedEventsAsync(envelope);
Assert.Equal(2, result.Count);
var enrichedEvent1 = result[0] as EnrichedCommentEvent;
var enrichedEvent2 = result[1] as EnrichedCommentEvent;
Assert.Equal(user1, enrichedEvent1!.MentionedUser);
Assert.Equal(user2, enrichedEvent2!.MentionedUser);
Assert.Equal("UserMentioned", enrichedEvent1.Name);
Assert.Equal("UserMentioned", enrichedEvent2.Name);
}
[Fact]
public async Task Should_not_create_enriched_events_when_users_cannot_be_resolved()
{
var user1 = UserMocks.User("1");
var user2 = UserMocks.User("2");
var users = new List<IUser> { user1, user2 };
var userIds = users.Select(x => x.Id).ToArray();
var envelope = Envelope.Create<AppEvent>(new CommentCreated { Mentions = userIds });
var result = await sut.CreateEnrichedEventsAsync(envelope);
Assert.Empty(result);
}
[Fact]
public async Task Should_not_create_enriched_events_when_mentions_is_null()
{
var envelope = Envelope.Create<AppEvent>(new CommentCreated { Mentions = null });
var result = await sut.CreateEnrichedEventsAsync(envelope);
Assert.Empty(result);
A.CallTo(() => userResolver.QueryManyAsync(A<string[]>._))
.MustNotHaveHappened();
}
[Fact]
public async Task Should_not_create_enriched_events_when_mentions_is_empty()
{
var envelope = Envelope.Create<AppEvent>(new CommentCreated { Mentions = Array.Empty<string>() });
var result = await sut.CreateEnrichedEventsAsync(envelope);
Assert.Empty(result);
A.CallTo(() => userResolver.QueryManyAsync(A<string[]>._))
.MustNotHaveHappened();
}
[Fact]
public async Task Should_skip_udated_event()
{
var envelope = Envelope.Create<AppEvent>(new CommentUpdated());
var result = await sut.CreateEnrichedEventsAsync(envelope);
Assert.Empty(result);
A.CallTo(() => userResolver.QueryManyAsync(A<string[]>._))
.MustNotHaveHappened();
}
[Fact]
public async Task Should_skip_deleted_event()
{
var envelope = Envelope.Create<AppEvent>(new CommentDeleted());
var result = await sut.CreateEnrichedEventsAsync(envelope);
Assert.Empty(result);
A.CallTo(() => userResolver.QueryManyAsync(A<string[]>._))
.MustNotHaveHappened();
}
[Fact]
public void Should_not_trigger_precheck_when_event_type_not_correct()
{
TestForCondition(string.Empty, trigger =>
{
var result = sut.Trigger(new ContentCreated(), trigger, DomainId.NewGuid());
Assert.False(result);
});
}
[Fact]
public void Should_trigger_precheck_when_event_type_correct()
{
TestForCondition(string.Empty, trigger =>
{
var result = sut.Trigger(new CommentCreated(), trigger, DomainId.NewGuid());
Assert.True(result);
});
}
[Fact]
public void Should_not_trigger_check_when_event_type_not_correct()
{
TestForCondition(string.Empty, trigger =>
{
var result = sut.Trigger(new EnrichedContentEvent(), trigger);
Assert.False(result);
});
}
[Fact]
public void Should_trigger_check_when_condition_is_empty()
{
TestForCondition(string.Empty, trigger =>
{
var result = sut.Trigger(new EnrichedCommentEvent(), trigger);
Assert.True(result);
});
}
[Fact]
public void Should_trigger_check_when_condition_matchs()
{
TestForCondition("true", trigger =>
{
var result = sut.Trigger(new EnrichedCommentEvent(), trigger);
Assert.True(result);
});
}
[Fact]
public void Should_not_trigger_check_when_condition_does_not_matchs()
{
TestForCondition("false", trigger =>
{
var result = sut.Trigger(new EnrichedCommentEvent(), trigger);
Assert.False(result);
});
}
[Fact]
public void Should_trigger_check_when_email_is_correct()
{
TestForRealCondition("event.mentionedUser.email == '1@email.com'", (handler, trigger) =>
{
var user = UserMocks.User("1", "1@email.com");
var result = handler.Trigger(new EnrichedCommentEvent { MentionedUser = user }, trigger);
Assert.True(result);
});
}
[Fact]
public void Should_not_trigger_check_when_email_is_correct()
{
TestForRealCondition("event.mentionedUser.email == 'other@squidex.io'", (handler, trigger) =>
{
var user = UserMocks.User("1");
var result = handler.Trigger(new EnrichedCommentEvent { MentionedUser = user }, trigger);
Assert.False(result);
});
}
[Fact]
public void Should_trigger_check_when_text_is_urgent()
{
TestForRealCondition("event.text.indexOf('urgent') >= 0", (handler, trigger) =>
{
var text = "Hey man, this is really urgent.";
var result = handler.Trigger(new EnrichedCommentEvent { Text = text }, trigger);
Assert.True(result);
});
}
[Fact]
public void Should_not_trigger_check_when_text_is_not_urgent()
{
TestForRealCondition("event.text.indexOf('urgent') >= 0", (handler, trigger) =>
{
var text = "Hey man, just an information for you.";
var result = handler.Trigger(new EnrichedCommentEvent { Text = text }, trigger);
Assert.False(result);
});
}
private void TestForRealCondition(string condition, Action<IRuleTriggerHandler, CommentTrigger> action)
{
var trigger = new CommentTrigger
{
Condition = condition
};
var memoryCache = new MemoryCache(Options.Create(new MemoryCacheOptions()));
var handler = new CommentTriggerHandler(new JintScriptEngine(memoryCache), userResolver);
action(handler, trigger);
}
private void TestForCondition(string condition, Action<CommentTrigger> action)
{
var trigger = new CommentTrigger
{
Condition = condition
};
action(trigger);
if (string.IsNullOrWhiteSpace(condition))
{
A.CallTo(() => scriptEngine.Evaluate(A<ScriptVars>._, condition, default))
.MustNotHaveHappened();
}
else
{
A.CallTo(() => scriptEngine.Evaluate(A<ScriptVars>._, condition, default))
.MustHaveHappened();
}
}
}
}
| 32.60596 | 111 | 0.571849 | [
"MIT"
] | Maruf520/squidex | backend/tests/Squidex.Domain.Apps.Entities.Tests/Comments/CommentTriggerHandlerTests.cs | 9,849 | C# |
using Microsoft.Data.Entity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ToDoList.Models
{
public class EFItemRepository : IItemRepository
{
ToDoListContext db = new ToDoListContext();
public EFItemRepository(ToDoListContext connection = null)
{
if (connection == null)
{
this.db = new ToDoListContext();
}
else
{
this.db = connection;
}
}
public IQueryable<Item> Items
{
get
{
return db.Items;
}
}
public Item Edit(Item item)
{
db.Entry(item).State = EntityState.Modified;
db.SaveChanges();
return item;
}
public void Remove(Item item)
{
db.Items.Remove(item);
db.SaveChanges();
}
public Item Save(Item item)
{
db.Items.Add(item);
db.SaveChanges();
return item;
}
public void Dispose()
{
db.Database.ExecuteSqlCommand("TRUNCATE TABLE [Items]");
}
}
}
| 20.435484 | 68 | 0.482242 | [
"MIT"
] | jaywhang83/ToDoWithXUnit | src/ToDoList/Models/Repositories/EFItemRepository.cs | 1,269 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the securityhub-2018-10-26.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Amazon.SecurityHub.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.SecurityHub.Model.Internal.MarshallTransformations
{
/// <summary>
/// AwsApiGatewayCanarySettings Marshaller
/// </summary>
public class AwsApiGatewayCanarySettingsMarshaller : IRequestMarshaller<AwsApiGatewayCanarySettings, JsonMarshallerContext>
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="requestObject"></param>
/// <param name="context"></param>
/// <returns></returns>
public void Marshall(AwsApiGatewayCanarySettings requestObject, JsonMarshallerContext context)
{
if(requestObject.IsSetDeploymentId())
{
context.Writer.WritePropertyName("DeploymentId");
context.Writer.Write(requestObject.DeploymentId);
}
if(requestObject.IsSetPercentTraffic())
{
context.Writer.WritePropertyName("PercentTraffic");
context.Writer.Write(requestObject.PercentTraffic);
}
if(requestObject.IsSetStageVariableOverrides())
{
context.Writer.WritePropertyName("StageVariableOverrides");
context.Writer.WriteObjectStart();
foreach (var requestObjectStageVariableOverridesKvp in requestObject.StageVariableOverrides)
{
context.Writer.WritePropertyName(requestObjectStageVariableOverridesKvp.Key);
var requestObjectStageVariableOverridesValue = requestObjectStageVariableOverridesKvp.Value;
context.Writer.Write(requestObjectStageVariableOverridesValue);
}
context.Writer.WriteObjectEnd();
}
if(requestObject.IsSetUseStageCache())
{
context.Writer.WritePropertyName("UseStageCache");
context.Writer.Write(requestObject.UseStageCache);
}
}
/// <summary>
/// Singleton Marshaller.
/// </summary>
public readonly static AwsApiGatewayCanarySettingsMarshaller Instance = new AwsApiGatewayCanarySettingsMarshaller();
}
} | 38.147727 | 129 | 0.649389 | [
"Apache-2.0"
] | philasmar/aws-sdk-net | sdk/src/Services/SecurityHub/Generated/Model/Internal/MarshallTransformations/AwsApiGatewayCanarySettingsMarshaller.cs | 3,357 | C# |
namespace Atata
{
/// <summary>
/// Represents the button control. Default search is performed by the content and value (button by content text and input by value attribute). Handles any input element with type="button", type="submit", type="reset" or button element.
/// </summary>
/// <typeparam name="TNavigateTo">The type of the page object to navigate to.</typeparam>
/// <typeparam name="TOwner">The type of the owner page object.</typeparam>
/// <seealso cref="Button{TOwner}" />
/// <seealso cref="INavigable{TNavigateTo, TOwner}" />
public class Button<TNavigateTo, TOwner> : Button<TOwner>, INavigable<TNavigateTo, TOwner>
where TNavigateTo : PageObject<TNavigateTo>
where TOwner : PageObject<TOwner>
{
}
}
| 48.75 | 240 | 0.680769 | [
"Apache-2.0"
] | Artemyj/atata | src/Atata/Components/Button`2.cs | 782 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace Police_Database_System
{
public partial class Cases_UserControl : UserControl
{
private static Cases_UserControl _instance;
public static Cases_UserControl Instance
{
get
{
if (_instance == null)
{
_instance = new Cases_UserControl();
}
return _instance;
}
}
public Cases_UserControl()
{
InitializeComponent();
}
SqlConnection Connect = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\DatabasePC.mdf;Integrated Security=True");
private void refresh_DataGridView()
{
try
{
SqlCommand cmd = new SqlCommand("ShowAllCasedata_SP", Connect);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter DA = new SqlDataAdapter(cmd);
DataSet DS = new DataSet();
DA.Fill(DS);
Connect.Open();
try
{
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(" <<<<<INVALID SQL OPERATION>>>>>: \n" + ex);
}
Connect.Close();
Case_dataGridView.DataSource = DS.Tables[0];
this.Case_dataGridView.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
this.Case_dataGridView.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
this.Case_dataGridView.Columns[2].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
this.Case_dataGridView.Columns[3].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
this.Case_dataGridView.Columns[4].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
this.Case_dataGridView.Columns[5].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
catch (Exception ex)
{
MessageBox.Show("" + ex);
}
}
private void AddNewbutton_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand("Cases_SP", Connect);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Case_ID", caseid_textBox.Text);
cmd.Parameters.AddWithValue("@Case_Status", CaseStatus_textBox.Text);
cmd.Parameters.AddWithValue("@Case_Detail", CaseDetail_textBox.Text);
cmd.Parameters.AddWithValue("@Section_of_law", Sec_textBox.Text);
cmd.Parameters.AddWithValue("@Officer_ID", Officer_textBox.Text);
Connect.Open();
try
{
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(" <<<<<INVALID SQL OPERATION>>>>>: \n" + ex);
}
Connect.Close();
refresh_DataGridView();
}
private void label1_Click(object sender, EventArgs e)
{
}
private void Searchbutton_Click(object sender, EventArgs e)
{
try
{
SqlCommand cmd = new SqlCommand("SearchCase_SP", Connect);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Case_ID", Case_textBox.Text);
SqlDataAdapter DA = new SqlDataAdapter(cmd);
DataSet DS = new DataSet();
DA.Fill(DS);
Connect.Open();
try
{
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(" <<<<<INVALID SQL OPERATION>>>>>: \n" + ex);
}
Connect.Close();
Case_dataGridView.DataSource = DS.Tables[0];
this.Case_dataGridView.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
this.Case_dataGridView.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
this.Case_dataGridView.Columns[2].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
this.Case_dataGridView.Columns[3].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
this.Case_dataGridView.Columns[4].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
this.Case_dataGridView.Columns[5].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
catch (Exception ex)
{
MessageBox.Show("" + ex);
}
}
private void button6_Click(object sender, EventArgs e)
{
try
{
SqlCommand cmd = new SqlCommand("CaseDelete_SP", Connect);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Case_ID", Case_textBox.Text);
Connect.Open();
try
{
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(" <<<<<INVALID SQL OPERATION>>>>>: \n" + ex);
}
Connect.Close();
refresh_DataGridView();
}
catch (Exception ex)
{
MessageBox.Show("" + ex);
}
}
private void button8_Click(object sender, EventArgs e)
{
caseid_textBox.Text =" ";
CaseStatus_textBox.Text =" ";
CaseDetail_textBox.Text =" ";
Sec_textBox.Text =" ";
Officer_textBox.Text =" ";
}
private void Cases_UserControl_Load(object sender, EventArgs e)
{
refresh_DataGridView();
}
}
}
| 34.638743 | 163 | 0.509069 | [
"Apache-2.0"
] | Ashwin1398/Police-Management-System | Cases_UserControl.cs | 6,618 | C# |
using System;
using JasperHttp.Routing;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace JasperHttp
{
internal class RegisterJasperStartupFilter : IStartupFilter
{
private readonly JasperHttpOptions _options;
public RegisterJasperStartupFilter(JasperHttpOptions options)
{
_options = options;
}
public Action<IApplicationBuilder> Configure(Action<IApplicationBuilder> next)
{
return app =>
{
var httpSettings = app.ApplicationServices.GetRequiredService<JasperHttpOptions>();
if (!httpSettings.Enabled)
{
next(app);
return;
}
var logger = app.ApplicationServices.GetRequiredService<ILogger<JasperHttpOptions>>();
app.Use(inner =>
{
return c =>
{
try
{
return inner(c);
}
catch (Exception e)
{
logger.LogError(e,
$"Failed during an HTTP request for {c.Request.Method}: {c.Request.Path}");
c.Response.StatusCode = 500;
return c.Response.WriteAsync(e.ToString());
}
};
});
next(app);
if (!app.HasJasperBeenApplied())
Router.BuildOut(app).Run(c =>
{
c.Response.StatusCode = 404;
c.Response.Headers["status-description"] = "Resource Not Found";
return c.Response.WriteAsync("Resource Not Found");
});
};
}
}
}
| 33.16129 | 107 | 0.475195 | [
"MIT"
] | JasperFx/JasperHttp | src/JasperHttp/RegisterJasperStartupFilter.cs | 2,056 | C# |
namespace HostGame
{
public static class CLRManagerSettings
{
public static int BucketGCFrequency { get; set; } = -1; //1200;
}
} | 21.428571 | 71 | 0.633333 | [
"MIT"
] | SanielX/CLR-Update-Manager | Runtime/CLRMangerSettings.cs | 152 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Emit;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.RuntimeMembers;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CSharp
{
/// <summary>
/// Contains methods related to synthesizing bound nodes in initial binding
/// form that needs lowering, primarily method bodies for compiler-generated methods.
/// </summary>
internal static partial class MethodBodySynthesizer
{
internal static ImmutableArray<BoundStatement> ConstructScriptConstructorBody(
BoundStatement loweredBody,
MethodSymbol constructor,
SynthesizedSubmissionFields previousSubmissionFields,
CSharpCompilation compilation)
{
// Script field initializers have to be emitted after the call to the base constructor because they can refer to "this" instance.
//
// Unlike regular field initializers, initializers of global script variables can access "this" instance.
// If the base class had a constructor that initializes its state a global variable would access partially initialized object.
// For this reason Script class must always derive directly from a class that has no state (System.Object).
CSharpSyntaxNode syntax = loweredBody.Syntax;
// base constructor call:
Debug.Assert((object)constructor.ContainingType.BaseTypeNoUseSiteDiagnostics == null || constructor.ContainingType.BaseTypeNoUseSiteDiagnostics.SpecialType == SpecialType.System_Object);
var objectType = constructor.ContainingAssembly.GetSpecialType(SpecialType.System_Object);
BoundExpression receiver = new BoundThisReference(syntax, constructor.ContainingType) { WasCompilerGenerated = true };
BoundStatement baseConstructorCall =
new BoundExpressionStatement(syntax,
new BoundCall(syntax,
receiverOpt: receiver,
method: objectType.InstanceConstructors.First(),
arguments: ImmutableArray<BoundExpression>.Empty,
argumentNamesOpt: ImmutableArray<string>.Empty,
argumentRefKindsOpt: ImmutableArray<RefKind>.Empty,
isDelegateCall: false,
expanded: false,
invokedAsExtensionMethod: false,
argsToParamsOpt: ImmutableArray<int>.Empty,
resultKind: LookupResultKind.Viable,
type: objectType)
{ WasCompilerGenerated = true })
{ WasCompilerGenerated = true };
var boundStatements = ImmutableArray.Create(baseConstructorCall);
if (constructor.IsSubmissionConstructor)
{
// submission initialization:
var submissionInitStatements = MakeSubmissionInitialization(syntax, constructor, previousSubmissionFields, compilation);
boundStatements = boundStatements.Concat(submissionInitStatements);
}
return boundStatements.Concat(ImmutableArray.Create(loweredBody));
}
/// <summary>
/// Generates a submission initialization part of a Script type constructor that represents an interactive submission.
/// </summary>
/// <remarks>
/// The constructor takes a parameter of type Roslyn.Scripting.Session - the session reference.
/// It adds the object being constructed into the session by calling Microsoft.CSharp.RuntimeHelpers.SessionHelpers.SetSubmission,
/// and retrieves strongly typed references on all previous submission script classes whose members are referenced by this submission.
/// The references are stored to fields of the submission (<paramref name="synthesizedFields"/>).
/// </remarks>
private static ImmutableArray<BoundStatement> MakeSubmissionInitialization(CSharpSyntaxNode syntax, MethodSymbol submissionConstructor, SynthesizedSubmissionFields synthesizedFields, CSharpCompilation compilation)
{
Debug.Assert(submissionConstructor.ParameterCount == 2);
var statements = new List<BoundStatement>(2 + synthesizedFields.Count);
var submissionArrayReference = new BoundParameter(syntax, submissionConstructor.Parameters[0]) { WasCompilerGenerated = true };
var intType = compilation.GetSpecialType(SpecialType.System_Int32);
var objectType = compilation.GetSpecialType(SpecialType.System_Object);
var thisReference = new BoundThisReference(syntax, submissionConstructor.ContainingType) { WasCompilerGenerated = true };
var slotIndex = compilation.GetSubmissionSlotIndex();
Debug.Assert(slotIndex >= 0);
// <submission_array>[<slot_index] = this;
statements.Add(new BoundExpressionStatement(syntax,
new BoundAssignmentOperator(syntax,
new BoundArrayAccess(syntax,
submissionArrayReference,
ImmutableArray.Create<BoundExpression>(new BoundLiteral(syntax, ConstantValue.Create(slotIndex), intType) { WasCompilerGenerated = true }),
objectType)
{ WasCompilerGenerated = true },
thisReference,
RefKind.None,
thisReference.Type)
{ WasCompilerGenerated = true })
{ WasCompilerGenerated = true });
var hostObjectField = synthesizedFields.GetHostObjectField();
if ((object)hostObjectField != null)
{
// <host_object> = (<host_object_type>)<submission_array>[0]
statements.Add(
new BoundExpressionStatement(syntax,
new BoundAssignmentOperator(syntax,
new BoundFieldAccess(syntax, thisReference, hostObjectField, ConstantValue.NotAvailable) { WasCompilerGenerated = true },
BoundConversion.Synthesized(syntax,
new BoundArrayAccess(syntax,
submissionArrayReference,
ImmutableArray.Create<BoundExpression>(new BoundLiteral(syntax, ConstantValue.Create(0), intType) { WasCompilerGenerated = true } ),
objectType),
Conversion.ExplicitReference,
false,
true,
ConstantValue.NotAvailable,
hostObjectField.Type
),
hostObjectField.Type)
{ WasCompilerGenerated = true })
{ WasCompilerGenerated = true });
}
foreach (var field in synthesizedFields.FieldSymbols)
{
var targetScriptType = (ImplicitNamedTypeSymbol)field.Type;
var targetSubmissionIndex = targetScriptType.DeclaringCompilation.GetSubmissionSlotIndex();
Debug.Assert(targetSubmissionIndex >= 0);
// this.<field> = (<target_script_type>)<submission_array>[<target_submission_index>];
statements.Add(
new BoundExpressionStatement(syntax,
new BoundAssignmentOperator(syntax,
new BoundFieldAccess(syntax, thisReference, field, ConstantValue.NotAvailable) { WasCompilerGenerated = true },
BoundConversion.Synthesized(syntax,
new BoundArrayAccess(syntax,
submissionArrayReference,
ImmutableArray.Create<BoundExpression>(new BoundLiteral(syntax, ConstantValue.Create(targetSubmissionIndex), intType) { WasCompilerGenerated = true }),
objectType)
{ WasCompilerGenerated = true },
Conversion.ExplicitReference,
false,
true,
ConstantValue.NotAvailable,
targetScriptType
),
targetScriptType
)
{ WasCompilerGenerated = true })
{ WasCompilerGenerated = true });
}
return statements.AsImmutableOrNull();
}
/// <summary>
/// Construct a body for an auto-property accessor (updating or returning the backing field).
/// </summary>
internal static BoundBlock ConstructAutoPropertyAccessorBody(SourceMethodSymbol accessor)
{
Debug.Assert(accessor.MethodKind == MethodKind.PropertyGet || accessor.MethodKind == MethodKind.PropertySet);
var property = (SourcePropertySymbol)accessor.AssociatedSymbol;
CSharpSyntaxNode syntax = property.CSharpSyntaxNode;
BoundExpression thisReference = null;
if (!accessor.IsStatic)
{
var thisSymbol = accessor.ThisParameter;
thisReference = new BoundThisReference(syntax, thisSymbol.Type) { WasCompilerGenerated = true };
}
var field = property.BackingField;
var fieldAccess = new BoundFieldAccess(syntax, thisReference, field, ConstantValue.NotAvailable) { WasCompilerGenerated = true };
BoundStatement statement;
if (accessor.MethodKind == MethodKind.PropertyGet)
{
statement = new BoundReturnStatement(syntax, fieldAccess) { WasCompilerGenerated = true };
}
else
{
Debug.Assert(accessor.MethodKind == MethodKind.PropertySet);
var parameter = accessor.Parameters[0];
statement = new BoundExpressionStatement(
syntax,
new BoundAssignmentOperator(
syntax,
fieldAccess,
new BoundParameter(syntax, parameter) { WasCompilerGenerated = true },
property.Type)
{ WasCompilerGenerated = true })
{ WasCompilerGenerated = true };
}
statement = new BoundSequencePoint(accessor.SyntaxNode, statement) { WasCompilerGenerated = true };
return new BoundBlock(syntax, ImmutableArray<LocalSymbol>.Empty, ImmutableArray.Create<BoundStatement>(statement)) { WasCompilerGenerated = true };
}
/// <summary>
/// Generate an accessor for a field-like event.
/// </summary>
internal static BoundBlock ConstructFieldLikeEventAccessorBody(SourceEventSymbol eventSymbol, bool isAddMethod, CSharpCompilation compilation, DiagnosticBag diagnostics)
{
Debug.Assert(eventSymbol.HasAssociatedField);
return eventSymbol.IsWindowsRuntimeEvent
? ConstructFieldLikeEventAccessorBody_WinRT(eventSymbol, isAddMethod, compilation, diagnostics)
: ConstructFieldLikeEventAccessorBody_Regular(eventSymbol, isAddMethod, compilation, diagnostics);
}
/// <summary>
/// Generate a thread-safe accessor for a WinRT field-like event.
///
/// Add:
/// return EventRegistrationTokenTable<Event>.GetOrCreateEventRegistrationTokenTable(ref _tokenTable).AddEventHandler(value);
///
/// Remove:
/// EventRegistrationTokenTable<Event>.GetOrCreateEventRegistrationTokenTable(ref _tokenTable).RemoveEventHandler(value);
/// </summary>
internal static BoundBlock ConstructFieldLikeEventAccessorBody_WinRT(SourceEventSymbol eventSymbol, bool isAddMethod, CSharpCompilation compilation, DiagnosticBag diagnostics)
{
CSharpSyntaxNode syntax = eventSymbol.CSharpSyntaxNode;
MethodSymbol accessor = isAddMethod ? eventSymbol.AddMethod : eventSymbol.RemoveMethod;
Debug.Assert((object)accessor != null);
FieldSymbol field = eventSymbol.AssociatedField;
Debug.Assert((object)field != null);
NamedTypeSymbol fieldType = (NamedTypeSymbol)field.Type;
Debug.Assert(fieldType.Name == "EventRegistrationTokenTable");
MethodSymbol getOrCreateMethod = (MethodSymbol)Binder.GetWellKnownTypeMember(
compilation,
WellKnownMember.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T__GetOrCreateEventRegistrationTokenTable,
diagnostics,
syntax: syntax);
if ((object)getOrCreateMethod == null)
{
Debug.Assert(diagnostics.HasAnyErrors());
return null;
}
getOrCreateMethod = getOrCreateMethod.AsMember(fieldType);
WellKnownMember processHandlerMember = isAddMethod
? WellKnownMember.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T__AddEventHandler
: WellKnownMember.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T__RemoveEventHandler;
MethodSymbol processHandlerMethod = (MethodSymbol)Binder.GetWellKnownTypeMember(
compilation,
processHandlerMember,
diagnostics,
syntax: syntax);
if ((object)processHandlerMethod == null)
{
Debug.Assert(diagnostics.HasAnyErrors());
return null;
}
processHandlerMethod = processHandlerMethod.AsMember(fieldType);
// _tokenTable
BoundFieldAccess fieldAccess = new BoundFieldAccess(
syntax,
field.IsStatic ? null : new BoundThisReference(syntax, accessor.ThisParameter.Type),
field,
constantValueOpt: null)
{ WasCompilerGenerated = true };
// EventRegistrationTokenTable<Event>.GetOrCreateEventRegistrationTokenTable(ref _tokenTable)
BoundCall getOrCreateCall = BoundCall.Synthesized(
syntax,
receiverOpt: null,
method: getOrCreateMethod,
arg0: fieldAccess);
// value
BoundParameter parameterAccess = new BoundParameter(
syntax,
accessor.Parameters.Single());
// EventRegistrationTokenTable<Event>.GetOrCreateEventRegistrationTokenTable(ref _tokenTable).AddHandler(value) // or RemoveHandler
BoundCall processHandlerCall = BoundCall.Synthesized(
syntax,
receiverOpt: getOrCreateCall,
method: processHandlerMethod,
arg0: parameterAccess);
if (isAddMethod)
{
// {
// return EventRegistrationTokenTable<Event>.GetOrCreateEventRegistrationTokenTable(ref _tokenTable).AddHandler(value);
// }
BoundStatement returnStatement = BoundReturnStatement.Synthesized(syntax, processHandlerCall);
return BoundBlock.SynthesizedNoLocals(syntax, returnStatement);
}
else
{
// {
// EventRegistrationTokenTable<Event>.GetOrCreateEventRegistrationTokenTable(ref _tokenTable).RemoveHandler(value);
// return;
// }
BoundStatement callStatement = new BoundExpressionStatement(syntax, processHandlerCall);
BoundStatement returnStatement = new BoundReturnStatement(syntax, expressionOpt: null);
return BoundBlock.SynthesizedNoLocals(syntax, callStatement, returnStatement);
}
}
/// <summary>
/// Generate a thread-safe accessor for a regular field-like event.
///
/// DelegateType tmp0 = _event; //backing field
/// DelegateType tmp1;
/// DelegateType tmp2;
/// do {
/// tmp1 = tmp0;
/// tmp2 = (DelegateType)Delegate.Combine(tmp1, value); //Remove for -=
/// tmp0 = Interlocked.CompareExchange<DelegateType>(ref _event, tmp2, tmp1);
/// } while ((object)tmp0 != (object)tmp1);
///
/// Note, if System.Threading.Interlocked.CompareExchange<T> is not available,
/// we emit the following code and mark the method Synchronized (unless it is a struct).
///
/// _event = (DelegateType)Delegate.Combine(_event, value); //Remove for -=
///
/// </summary>
internal static BoundBlock ConstructFieldLikeEventAccessorBody_Regular(SourceEventSymbol eventSymbol, bool isAddMethod, CSharpCompilation compilation, DiagnosticBag diagnostics)
{
CSharpSyntaxNode syntax = eventSymbol.CSharpSyntaxNode;
TypeSymbol delegateType = eventSymbol.Type;
MethodSymbol accessor = isAddMethod ? eventSymbol.AddMethod : eventSymbol.RemoveMethod;
ParameterSymbol thisParameter = accessor.ThisParameter;
TypeSymbol boolType = compilation.GetSpecialType(SpecialType.System_Boolean);
SpecialMember updateMethodId = isAddMethod ? SpecialMember.System_Delegate__Combine : SpecialMember.System_Delegate__Remove;
MethodSymbol updateMethod = (MethodSymbol)compilation.GetSpecialTypeMember(updateMethodId);
BoundStatement @return = new BoundReturnStatement(syntax,
expressionOpt: null)
{ WasCompilerGenerated = true };
if (updateMethod == null)
{
MemberDescriptor memberDescriptor = SpecialMembers.GetDescriptor(updateMethodId);
diagnostics.Add(new CSDiagnostic(new CSDiagnosticInfo(ErrorCode.ERR_MissingPredefinedMember,
memberDescriptor.DeclaringTypeMetadataName,
memberDescriptor.Name),
syntax.Location));
return new BoundBlock(syntax,
locals: ImmutableArray<LocalSymbol>.Empty,
statements: ImmutableArray.Create<BoundStatement>(@return))
{ WasCompilerGenerated = true };
}
Binder.ReportUseSiteDiagnostics(updateMethod, diagnostics, syntax);
BoundThisReference fieldReceiver = eventSymbol.IsStatic ?
null :
new BoundThisReference(syntax, thisParameter.Type) { WasCompilerGenerated = true };
BoundFieldAccess boundBackingField = new BoundFieldAccess(syntax,
receiver: fieldReceiver,
fieldSymbol: eventSymbol.AssociatedField,
constantValueOpt: null)
{ WasCompilerGenerated = true };
BoundParameter boundParameter = new BoundParameter(syntax,
parameterSymbol: accessor.Parameters[0])
{ WasCompilerGenerated = true };
BoundExpression delegateUpdate;
MethodSymbol compareExchangeMethod = (MethodSymbol)compilation.GetWellKnownTypeMember(WellKnownMember.System_Threading_Interlocked__CompareExchange_T);
if ((object)compareExchangeMethod == null)
{
// (DelegateType)Delegate.Combine(_event, value)
delegateUpdate = BoundConversion.SynthesizedNonUserDefined(syntax,
operand: BoundCall.Synthesized(syntax,
receiverOpt: null,
method: updateMethod,
arguments: ImmutableArray.Create<BoundExpression>(boundBackingField, boundParameter)),
kind: ConversionKind.ExplicitReference,
type: delegateType);
// _event = (DelegateType)Delegate.Combine(_event, value);
BoundStatement eventUpdate = new BoundExpressionStatement(syntax,
expression: new BoundAssignmentOperator(syntax,
left: boundBackingField,
right: delegateUpdate,
type: delegateType)
{ WasCompilerGenerated = true })
{ WasCompilerGenerated = true };
return new BoundBlock(syntax,
locals: ImmutableArray<LocalSymbol>.Empty,
statements: ImmutableArray.Create<BoundStatement>(
eventUpdate,
@return))
{ WasCompilerGenerated = true };
}
compareExchangeMethod = compareExchangeMethod.Construct(ImmutableArray.Create<TypeSymbol>(delegateType));
Binder.ReportUseSiteDiagnostics(compareExchangeMethod, diagnostics, syntax);
GeneratedLabelSymbol loopLabel = new GeneratedLabelSymbol("loop");
const int numTemps = 3;
LocalSymbol[] tmps = new LocalSymbol[numTemps];
BoundLocal[] boundTmps = new BoundLocal[numTemps];
for (int i = 0; i < numTemps; i++)
{
tmps[i] = new SynthesizedLocal(accessor, delegateType, SynthesizedLocalKind.LoweringTemp);
boundTmps[i] = new BoundLocal(syntax, tmps[i], null, delegateType);
}
// tmp0 = _event;
BoundStatement tmp0Init = new BoundExpressionStatement(syntax,
expression: new BoundAssignmentOperator(syntax,
left: boundTmps[0],
right: boundBackingField,
type: delegateType)
{ WasCompilerGenerated = true })
{ WasCompilerGenerated = true };
// LOOP:
BoundStatement loopStart = new BoundLabelStatement(syntax,
label: loopLabel)
{ WasCompilerGenerated = true };
// tmp1 = tmp0;
BoundStatement tmp1Update = new BoundExpressionStatement(syntax,
expression: new BoundAssignmentOperator(syntax,
left: boundTmps[1],
right: boundTmps[0],
type: delegateType)
{ WasCompilerGenerated = true })
{ WasCompilerGenerated = true };
// (DelegateType)Delegate.Combine(tmp1, value)
delegateUpdate = BoundConversion.SynthesizedNonUserDefined(syntax,
operand: BoundCall.Synthesized(syntax,
receiverOpt: null,
method: updateMethod,
arguments: ImmutableArray.Create<BoundExpression>(boundTmps[1], boundParameter)),
kind: ConversionKind.ExplicitReference,
type: delegateType);
// tmp2 = (DelegateType)Delegate.Combine(tmp1, value);
BoundStatement tmp2Update = new BoundExpressionStatement(syntax,
expression: new BoundAssignmentOperator(syntax,
left: boundTmps[2],
right: delegateUpdate,
type: delegateType)
{ WasCompilerGenerated = true })
{ WasCompilerGenerated = true };
// Interlocked.CompareExchange<DelegateType>(ref _event, tmp2, tmp1)
BoundExpression compareExchange = BoundCall.Synthesized(syntax,
receiverOpt: null,
method: compareExchangeMethod,
arguments: ImmutableArray.Create<BoundExpression>(boundBackingField, boundTmps[2], boundTmps[1]));
// tmp0 = Interlocked.CompareExchange<DelegateType>(ref _event, tmp2, tmp1);
BoundStatement tmp0Update = new BoundExpressionStatement(syntax,
expression: new BoundAssignmentOperator(syntax,
left: boundTmps[0],
right: compareExchange,
type: delegateType)
{ WasCompilerGenerated = true })
{ WasCompilerGenerated = true };
// tmp0 == tmp1 // i.e. exit when they are equal, jump to start otherwise
BoundExpression loopExitCondition = new BoundBinaryOperator(syntax,
operatorKind: BinaryOperatorKind.ObjectEqual,
left: boundTmps[0],
right: boundTmps[1],
constantValueOpt: null,
methodOpt: null,
resultKind: LookupResultKind.Viable,
type: boolType)
{ WasCompilerGenerated = true };
// branchfalse (tmp0 == tmp1) LOOP
BoundStatement loopEnd = new BoundConditionalGoto(syntax,
condition: loopExitCondition,
jumpIfTrue: false,
label: loopLabel)
{ WasCompilerGenerated = true };
return new BoundBlock(syntax,
locals: tmps.AsImmutable(),
statements: ImmutableArray.Create<BoundStatement>(
tmp0Init,
loopStart,
tmp1Update,
tmp2Update,
tmp0Update,
loopEnd,
@return))
{ WasCompilerGenerated = true };
}
internal static BoundBlock ConstructDestructorBody(CSharpSyntaxNode syntax, MethodSymbol method, BoundBlock block)
{
Debug.Assert(method.MethodKind == MethodKind.Destructor);
Debug.Assert(syntax.Kind() == SyntaxKind.Block);
// If this is a destructor and a base type has a Finalize method (see GetBaseTypeFinalizeMethod for exact
// requirements), then we need to call that method in a finally block. Otherwise, just return block as-is.
// NOTE: the Finalize method need not be a destructor or be overridden by the current method.
MethodSymbol baseTypeFinalize = GetBaseTypeFinalizeMethod(method);
if ((object)baseTypeFinalize != null)
{
BoundStatement baseFinalizeCall = new BoundSequencePointWithSpan( //sequence point to mimic Dev10
syntax,
new BoundExpressionStatement(
syntax,
BoundCall.Synthesized(
syntax,
new BoundBaseReference(
syntax,
method.ContainingType)
{ WasCompilerGenerated = true },
baseTypeFinalize)
)
{ WasCompilerGenerated = true },
((BlockSyntax)syntax).CloseBraceToken.Span);
return new BoundBlock(
syntax,
ImmutableArray<LocalSymbol>.Empty,
ImmutableArray.Create<BoundStatement>(
new BoundTryStatement(
syntax,
block,
ImmutableArray<BoundCatchBlock>.Empty,
new BoundBlock(
syntax,
ImmutableArray<LocalSymbol>.Empty,
ImmutableArray.Create<BoundStatement>(
baseFinalizeCall)
)
{ WasCompilerGenerated = true }
)
{ WasCompilerGenerated = true }));
}
return block;
}
/// <summary>
/// Look for a base type method named "Finalize" that is protected (or protected internal), has no parameters,
/// and returns void. It doesn't need to be virtual or a destructor.
/// </summary>
/// <remarks>
/// You may assume that this would share code and logic with PEMethodSymbol.OverridesRuntimeFinalizer,
/// but FUNCBRECCS::bindDestructor has its own loop that performs these checks (differently).
/// </remarks>
private static MethodSymbol GetBaseTypeFinalizeMethod(MethodSymbol method)
{
NamedTypeSymbol baseType = method.ContainingType.BaseTypeNoUseSiteDiagnostics;
while ((object)baseType != null)
{
foreach (Symbol member in baseType.GetMembers(WellKnownMemberNames.DestructorName))
{
if (member.Kind == SymbolKind.Method)
{
MethodSymbol baseTypeMethod = (MethodSymbol)member;
Accessibility accessibility = baseTypeMethod.DeclaredAccessibility;
if ((accessibility == Accessibility.ProtectedOrInternal || accessibility == Accessibility.Protected) &&
baseTypeMethod.ParameterCount == 0 &&
baseTypeMethod.Arity == 0 && // NOTE: the native compiler doesn't check this, so it broken IL.
baseTypeMethod.ReturnsVoid) // NOTE: not checking for virtual
{
return baseTypeMethod;
}
}
}
baseType = baseType.BaseTypeNoUseSiteDiagnostics;
}
return null;
}
}
}
| 49.580858 | 221 | 0.591526 | [
"Apache-2.0"
] | pottereric/roslyn | src/Compilers/CSharp/Portable/Compiler/MethodBodySynthesizer.cs | 30,048 | C# |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Linq;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Graphics.UserInterface;
using osu.Game.Online.Multiplayer;
using osu.Game.Online.Rooms;
namespace osu.Game.Screens.OnlinePlay.Multiplayer.Match.Playlist
{
/// <summary>
/// The multiplayer playlist, containing lists to show the items from a <see cref="MultiplayerRoom"/> in both gameplay-order and historical-order.
/// </summary>
public class MultiplayerPlaylist : MultiplayerRoomComposite
{
public readonly Bindable<MultiplayerPlaylistDisplayMode> DisplayMode = new Bindable<MultiplayerPlaylistDisplayMode>();
/// <summary>
/// Invoked when an item requests to be edited.
/// </summary>
public Action<PlaylistItem> RequestEdit;
private MultiplayerQueueList queueList;
private MultiplayerHistoryList historyList;
private bool firstPopulation = true;
[BackgroundDependencyLoader]
private void load()
{
const float tab_control_height = 25;
InternalChildren = new Drawable[]
{
new OsuTabControl<MultiplayerPlaylistDisplayMode>
{
RelativeSizeAxes = Axes.X,
Height = tab_control_height,
Current = { BindTarget = DisplayMode }
},
new Container
{
RelativeSizeAxes = Axes.Both,
Padding = new MarginPadding { Top = tab_control_height + 5 },
Masking = true,
Children = new Drawable[]
{
queueList = new MultiplayerQueueList
{
RelativeSizeAxes = Axes.Both,
SelectedItem = { BindTarget = SelectedItem },
RequestEdit = item => RequestEdit?.Invoke(item)
},
historyList = new MultiplayerHistoryList
{
RelativeSizeAxes = Axes.Both,
Alpha = 0,
SelectedItem = { BindTarget = SelectedItem }
}
}
}
};
}
protected override void LoadComplete()
{
base.LoadComplete();
DisplayMode.BindValueChanged(onDisplayModeChanged, true);
}
private void onDisplayModeChanged(ValueChangedEvent<MultiplayerPlaylistDisplayMode> mode)
{
historyList.FadeTo(mode.NewValue == MultiplayerPlaylistDisplayMode.History ? 1 : 0, 100);
queueList.FadeTo(mode.NewValue == MultiplayerPlaylistDisplayMode.Queue ? 1 : 0, 100);
}
protected override void OnRoomUpdated()
{
base.OnRoomUpdated();
if (Room == null)
{
historyList.Items.Clear();
queueList.Items.Clear();
firstPopulation = true;
return;
}
if (firstPopulation)
{
foreach (var item in Room.Playlist)
addItemToLists(item);
firstPopulation = false;
}
}
protected override void PlaylistItemAdded(MultiplayerPlaylistItem item)
{
base.PlaylistItemAdded(item);
addItemToLists(item);
}
protected override void PlaylistItemRemoved(long item)
{
base.PlaylistItemRemoved(item);
removeItemFromLists(item);
}
protected override void PlaylistItemChanged(MultiplayerPlaylistItem item)
{
base.PlaylistItemChanged(item);
removeItemFromLists(item.ID);
addItemToLists(item);
}
private void addItemToLists(MultiplayerPlaylistItem item)
{
var apiItem = Playlist.Single(i => i.ID == item.ID);
if (item.Expired)
historyList.Items.Add(apiItem);
else
queueList.Items.Add(apiItem);
}
private void removeItemFromLists(long item)
{
queueList.Items.RemoveAll(i => i.ID == item);
historyList.Items.RemoveAll(i => i.ID == item);
}
}
}
| 34.309353 | 151 | 0.534703 | [
"MIT"
] | Henry-YSLin/osu | osu.Game/Screens/OnlinePlay/Multiplayer/Match/Playlist/MultiplayerPlaylist.cs | 4,631 | C# |
using System;
namespace ROB.XrmToolBoxPlugins.SecurityRoleMerge
{
public class RoleOptions
{
public int Value { get; set; }
public string Name { get; set; }
public Guid ID { get; set; }
//public string ID { get; set; }
public RoleOptions(int value, string name, Guid id)
{
Value = value;
Name = name;
ID =id;
}
}
} | 22.157895 | 59 | 0.527316 | [
"MIT"
] | arirobbins/ROB.XrmToolBoxPlugins.SecurityRoleMerge | ROB.XrmToolBoxPlugins.SecurityRoleMerge.Tool/RoleOptions.cs | 423 | C# |
using System.Collections.Generic;
using CoDLuaDecompiler.Decompiler.Analyzers.Havok;
namespace CoDLuaDecompiler.Decompiler.Analyzers
{
public class HavokAnalyzerList : IAnalyzerList
{
public List<IAnalyzer> GetAnalyzers()
{
return new List<IAnalyzer>()
{
new LabelApplyAnalyzer(),
new UnneededReturnAnalyzer(),
new VarargListAssignmentAnalyzer(),
new MultiBoolAssignmentAnalyzer(),
new RedundantAssignmentsAnalyzer(),
new ConditionalJumpsAnalyzer(),
new ConditionalAssignmentsAnalyzer(),
new ControlFlowIntegrityAnalyzer(),
new UnusedLabelsAnalyzer(),
new RemovingDataAnalyzer(),
new TestsetAnalyzer(),
new OrAndOperatorAnalyzer(),
new TernaryOperatorAnalyzer(),
new ConstructCfgAnalyzer(),
new IndeterminateArgumentsAnalyzer(),
new Lua51LoopsAnalyzer(),
new ConvertToSsaAnalyzer(),
// Data flow passes
new DeadAssignmentsAnalyzer(),
new UnusedPhiFunctionsAnalyzer(),
new ExpressionPropagationAnalyzer(),
new ListInitializersAnalyzer(),
// CFG passes
new CompoundConditionalsAnalyzer(),
new LoopsAnalyzer(),
new LoopConditionalsAnalyzer(),
new TwoWayConditionalsAnalyzer(),
new IfElseFollowChainAnalyzer(),
new DeadAssignmentsAnalyzer(),
new ExpressionPropagationAnalyzer(),
new LivenessNoInterferenceAnalyzer(),
// Convert out of SSA and rename variables
new SSADropSubscriptsAnalyzer(),
new LocalDeclarationsAnalyzer(),
new RenameVariablesAnalyzer(),
new ParenthesizeAnalyzer(),
new WidgetEmptyLinesAnalyzer(),
new InlineClosuresAnalyzer(),
new MultipleNotsAnalyzer(),
new UnnecessaryReturnsAnalyzer(),
new ConvertToASTAnalyzer(),
};
}
}
} | 35.076923 | 58 | 0.560965 | [
"MIT"
] | EricYoong/CoDLuaDecompiler | CoDLuaDecompiler.Decompiler/Analyzers/HavokAnalyzerList.cs | 2,280 | C# |
// -------------------------------------------------------------------------
// Copyright © 2021 Province of British Columbia
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// -------------------------------------------------------------------------
using System;
using System.IO;
using System.Net;
using System.Reflection;
using EMBC.ESS.Engines.Search;
using EMBC.ESS.Managers.Admin;
using EMBC.ESS.Managers.Metadata;
using EMBC.ESS.Managers.Reports;
using EMBC.ESS.Managers.Submissions;
using EMBC.ESS.Resources.Cases;
using EMBC.ESS.Resources.Contacts;
using EMBC.ESS.Resources.Metadata;
using EMBC.ESS.Resources.Print;
using EMBC.ESS.Resources.Reports;
using EMBC.ESS.Resources.Suppliers;
using EMBC.ESS.Resources.Tasks;
using EMBC.ESS.Resources.Team;
using EMBC.ESS.Utilities.Cache;
using EMBC.ESS.Utilities.Dynamics;
using EMBC.ESS.Utilities.Messaging;
using EMBC.ESS.Utilities.Notifications;
using EMBC.ESS.Utilities.PdfGenerator;
using EMBC.ESS.Utilities.Transformation;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.Diagnostics.HealthChecks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Diagnostics.HealthChecks;
using Microsoft.Extensions.Hosting;
using Serilog;
using Serilog.Events;
using StackExchange.Redis;
namespace EMBC.ESS
{
public class Startup
{
private const string HealthCheckReadyTag = "ready";
private const string HealthCheckAliveTag = "alive";
private readonly IConfiguration configuration;
public Startup(IConfiguration configuration)
{
this.configuration = configuration;
}
public void ConfigureServices(IServiceCollection services)
{
var redisConnectionString = configuration.GetValue<string>("REDIS_CONNECTIONSTRING", null);
var dataProtectionPath = configuration.GetValue<string>("KEY_RING_PATH", null);
if (!string.IsNullOrEmpty(redisConnectionString))
{
services.AddStackExchangeRedisCache(options =>
{
options.Configuration = redisConnectionString;
options.InstanceName = Assembly.GetExecutingAssembly().GetName().Name;
});
services.AddDataProtection()
.SetApplicationName(Assembly.GetExecutingAssembly().GetName().Name)
.PersistKeysToStackExchangeRedis(ConnectionMultiplexer.Connect(redisConnectionString), "data-protection-keys");
}
else
{
services.AddDistributedMemoryCache();
var dpBuilder = services.AddDataProtection()
.SetApplicationName(Assembly.GetExecutingAssembly().GetName().Name);
if (!string.IsNullOrEmpty(dataProtectionPath)) dpBuilder.PersistKeysToFileSystem(new DirectoryInfo(dataProtectionPath));
}
services.Configure<MessageHandlerRegistryOptions>(opts => { });
services.AddSingleton<MessageHandlerRegistry>();
services.AddGrpc(opts =>
{
opts.EnableDetailedErrors = true;
});
services.AddHealthChecks()
.AddCheck("ESS API ready hc", () => HealthCheckResult.Healthy("API ready"), new[] { HealthCheckReadyTag })
.AddCheck("ESS API live hc", () => HealthCheckResult.Healthy("API alive"), new[] { HealthCheckAliveTag });
services.AddAutoMapper((sp, cfg) => { cfg.ConstructServicesUsing(t => sp.GetRequiredService(t)); }, typeof(Startup));
services
.AddAdminManager()
.AddMetadataManager()
.AddReportsManager()
.AddSubmissionManager();
services
.AddSearchEngine();
services
.AddTeamRepository()
.AddMetadataRepository()
.AddContactRepository()
.AddCaseRepository()
.AddTaskRepository()
.AddSupplierRepository()
.AddReportRepository()
.AddPrint();
services
.AddDynamics(configuration)
.AddCache()
.AddTransformator()
.AddNotificationSenders(configuration)
.AddPdfGenerator(configuration);
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseSerilogRequestLogging(opts =>
{
opts.GetLevel = ExcludeHealthChecks;
opts.EnrichDiagnosticContext = (diagCtx, httpCtx) =>
{
diagCtx.Set("User", httpCtx.User.Identity?.Name);
diagCtx.Set("Host", httpCtx.Request.Host);
diagCtx.Set("UserAgent", httpCtx.Request.Headers["User-Agent"].ToString());
diagCtx.Set("RemoteIP", httpCtx.Connection.RemoteIpAddress.ToString());
diagCtx.Set("ConnectionId", httpCtx.Connection.Id);
diagCtx.Set("Forwarded", httpCtx.Request.Headers["Forwarded"].ToString());
diagCtx.Set("ContentLength", httpCtx.Response.ContentLength);
};
});
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapGrpcService<DispatcherService>();
endpoints.MapHealthChecks("/hc/ready", new HealthCheckOptions() { Predicate = check => check.Tags.Contains(HealthCheckReadyTag) });
endpoints.MapHealthChecks("/hc/live", new HealthCheckOptions() { Predicate = check => check.Tags.Contains(HealthCheckAliveTag) });
endpoints.MapHealthChecks("/hc/startup", new HealthCheckOptions() { Predicate = _ => false });
});
}
//inspired by https://andrewlock.net/using-serilog-aspnetcore-in-asp-net-core-3-excluding-health-check-endpoints-from-serilog-request-logging/
private static LogEventLevel ExcludeHealthChecks(HttpContext ctx, double _, Exception ex) =>
ex != null
? LogEventLevel.Error
: ctx.Response.StatusCode >= (int)HttpStatusCode.InternalServerError
? LogEventLevel.Error
: ctx.Request.Path.StartsWithSegments("/hc", StringComparison.InvariantCultureIgnoreCase)
? LogEventLevel.Verbose
: LogEventLevel.Information;
}
}
| 42.00578 | 150 | 0.624329 | [
"Apache-2.0"
] | rafaelponcedeleon/embc-ess-mod | ess/src/API/EMBC.ESS/Startup.cs | 7,270 | C# |
// <auto-generated />
using System;
using DigitalReceipt.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
namespace DigitalReceipt.Data.Migrations
{
[DbContext(typeof(ApplicationDbContext))]
partial class ApplicationDbContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "3.1.9")
.HasAnnotation("Relational:MaxIdentifierLength", 128)
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("DigitalReceipt.Data.Models.Company", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(100)")
.HasMaxLength(100);
b.HasKey("Id");
b.ToTable("Companies");
});
modelBuilder.Entity("DigitalReceipt.Data.Models.Product", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("Barcode")
.IsRequired()
.HasColumnType("nvarchar(30)")
.HasMaxLength(30);
b.Property<int?>("Category")
.HasColumnType("int");
b.Property<decimal>("Discount")
.HasColumnType("decimal(18,2)");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(100)")
.HasMaxLength(100);
b.Property<decimal>("Price")
.HasColumnType("decimal(18,2)");
b.HasKey("Id");
b.ToTable("Products");
});
modelBuilder.Entity("DigitalReceipt.Data.Models.Receipt", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("CashierName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("ClientNumber")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("CompanyAddress")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int>("CompanyId")
.HasColumnType("int");
b.Property<DateTime>("CreatedOn")
.HasColumnType("datetime2");
b.Property<DateTime>("Date")
.HasColumnType("datetime2");
b.Property<string>("FiscalNumber")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("IdFiscalNumber")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<DateTime?>("ModifiedOn")
.HasColumnType("datetime2");
b.Property<string>("Number")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("StoreAddress")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("StoreName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("TaxNumber")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("UIC")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("UserId")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.HasKey("Id");
b.HasIndex("CompanyId");
b.HasIndex("UserId");
b.ToTable("Receipts");
});
modelBuilder.Entity("DigitalReceipt.Data.Models.ReceiptProduct", b =>
{
b.Property<int>("ReceiptId")
.HasColumnType("int");
b.Property<int>("ProductId")
.HasColumnType("int");
b.Property<int>("Quantity")
.HasColumnType("int");
b.HasKey("ReceiptId", "ProductId");
b.HasIndex("ProductId");
b.ToTable("ReceiptProducts");
});
modelBuilder.Entity("DigitalReceipt.Data.Models.User", b =>
{
b.Property<string>("Id")
.HasColumnType("nvarchar(450)");
b.Property<int>("AccessFailedCount")
.HasColumnType("int");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("nvarchar(max)");
b.Property<string>("Email")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<bool>("EmailConfirmed")
.HasColumnType("bit");
b.Property<bool>("LockoutEnabled")
.HasColumnType("bit");
b.Property<DateTimeOffset?>("LockoutEnd")
.HasColumnType("datetimeoffset");
b.Property<string>("NormalizedEmail")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<string>("NormalizedUserName")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<string>("PasswordHash")
.HasColumnType("nvarchar(max)");
b.Property<string>("PhoneNumber")
.HasColumnType("nvarchar(max)");
b.Property<bool>("PhoneNumberConfirmed")
.HasColumnType("bit");
b.Property<int?>("Preferences")
.HasColumnType("int");
b.Property<string>("SecurityStamp")
.HasColumnType("nvarchar(max)");
b.Property<bool>("TwoFactorEnabled")
.HasColumnType("bit");
b.Property<string>("UserName")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.HasKey("Id");
b.HasIndex("NormalizedEmail")
.HasName("EmailIndex");
b.HasIndex("NormalizedUserName")
.IsUnique()
.HasName("UserNameIndex")
.HasFilter("[NormalizedUserName] IS NOT NULL");
b.ToTable("AspNetUsers");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b =>
{
b.Property<string>("Id")
.HasColumnType("nvarchar(450)");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("nvarchar(max)");
b.Property<string>("Name")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<string>("NormalizedName")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.HasKey("Id");
b.HasIndex("NormalizedName")
.IsUnique()
.HasName("RoleNameIndex")
.HasFilter("[NormalizedName] IS NOT NULL");
b.ToTable("AspNetRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("ClaimType")
.HasColumnType("nvarchar(max)");
b.Property<string>("ClaimValue")
.HasColumnType("nvarchar(max)");
b.Property<string>("RoleId")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.HasKey("Id");
b.HasIndex("RoleId");
b.ToTable("AspNetRoleClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("ClaimType")
.HasColumnType("nvarchar(max)");
b.Property<string>("ClaimValue")
.HasColumnType("nvarchar(max)");
b.Property<string>("UserId")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("AspNetUserClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.Property<string>("LoginProvider")
.HasColumnType("nvarchar(450)");
b.Property<string>("ProviderKey")
.HasColumnType("nvarchar(450)");
b.Property<string>("ProviderDisplayName")
.HasColumnType("nvarchar(max)");
b.Property<string>("UserId")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.HasKey("LoginProvider", "ProviderKey");
b.HasIndex("UserId");
b.ToTable("AspNetUserLogins");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.Property<string>("UserId")
.HasColumnType("nvarchar(450)");
b.Property<string>("RoleId")
.HasColumnType("nvarchar(450)");
b.HasKey("UserId", "RoleId");
b.HasIndex("RoleId");
b.ToTable("AspNetUserRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.Property<string>("UserId")
.HasColumnType("nvarchar(450)");
b.Property<string>("LoginProvider")
.HasColumnType("nvarchar(450)");
b.Property<string>("Name")
.HasColumnType("nvarchar(450)");
b.Property<string>("Value")
.HasColumnType("nvarchar(max)");
b.HasKey("UserId", "LoginProvider", "Name");
b.ToTable("AspNetUserTokens");
});
modelBuilder.Entity("DigitalReceipt.Data.Models.Receipt", b =>
{
b.HasOne("DigitalReceipt.Data.Models.Company", "Company")
.WithMany("Receipts")
.HasForeignKey("CompanyId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.HasOne("DigitalReceipt.Data.Models.User", "User")
.WithMany("Receipts")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
});
modelBuilder.Entity("DigitalReceipt.Data.Models.ReceiptProduct", b =>
{
b.HasOne("DigitalReceipt.Data.Models.Product", "Product")
.WithMany("Receipts")
.HasForeignKey("ProductId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.HasOne("DigitalReceipt.Data.Models.Receipt", "Receipt")
.WithMany("Products")
.HasForeignKey("ReceiptId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.HasOne("DigitalReceipt.Data.Models.User", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.HasOne("DigitalReceipt.Data.Models.User", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.HasOne("DigitalReceipt.Data.Models.User", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.HasOne("DigitalReceipt.Data.Models.User", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
});
#pragma warning restore 612, 618
}
}
}
| 37.367946 | 125 | 0.450707 | [
"MIT"
] | NaskoVasilev/DigitalReceipt | server/DigitalReceipt/DigitalReceipt.Data/Migrations/ApplicationDbContextModelSnapshot.cs | 16,556 | C# |
// Copyright 2022 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.BigQuery.DataTransfer.V1.Snippets
{
// [START bigquerydatatransfer_v1_generated_DataTransferService_StartManualTransferRuns_async]
using Google.Cloud.BigQuery.DataTransfer.V1;
using System.Threading.Tasks;
public sealed partial class GeneratedDataTransferServiceClientSnippets
{
/// <summary>Snippet for StartManualTransferRunsAsync</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 StartManualTransferRunsRequestObjectAsync()
{
// Create client
DataTransferServiceClient dataTransferServiceClient = await DataTransferServiceClient.CreateAsync();
// Initialize request argument(s)
StartManualTransferRunsRequest request = new StartManualTransferRunsRequest
{
ParentAsTransferConfigName = TransferConfigName.FromProjectTransferConfig("[PROJECT]", "[TRANSFER_CONFIG]"),
RequestedTimeRange = new StartManualTransferRunsRequest.Types.TimeRange(),
};
// Make the request
StartManualTransferRunsResponse response = await dataTransferServiceClient.StartManualTransferRunsAsync(request);
}
}
// [END bigquerydatatransfer_v1_generated_DataTransferService_StartManualTransferRuns_async]
}
| 45.565217 | 125 | 0.727099 | [
"Apache-2.0"
] | AlexandrTrf/google-cloud-dotnet | apis/Google.Cloud.BigQuery.DataTransfer.V1/Google.Cloud.BigQuery.DataTransfer.V1.GeneratedSnippets/DataTransferServiceClient.StartManualTransferRunsRequestObjectAsyncSnippet.g.cs | 2,096 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace Eventual.EventStore.Services
{
public class TypedEventStreamCommit
{
#region Attributes
private Guid aggregateId;
private Type aggregateType;
private int workingCopyVersion;
private string correlationId;
private string causationId;
private Dictionary<string, string> metadata;
private IEnumerable<Event> changes;
#endregion
#region Constructors
public TypedEventStreamCommit(Guid aggregateId, Type aggregateType, int workingCopyVersion, string correlationId, string causationId,
Dictionary<string, string> metadata, IEnumerable<Event> changes)
{
this.AggregateId = aggregateId;
this.AggregateType = aggregateType;
this.WorkingCopyVersion = workingCopyVersion;
this.CorrelationId = correlationId;
this.CausationId = causationId;
this.Metadata = metadata;
this.Changes = changes;
}
#endregion
#region Properties
public Guid AggregateId
{
get
{
return this.aggregateId;
}
private set
{
//TODO: Add validation code
this.aggregateId = value;
}
}
public Type AggregateType
{
get
{
return this.aggregateType;
}
private set
{
//TODO: Add validation code
this.aggregateType = value;
}
}
//TODO: Add here new property "AggregateState" for supporting snapshots (but maybe it should be treated from the upper layer -repository-, since it must be parsed and deserialized to the current aggregate specific schema).
public int WorkingCopyVersion
{
get
{
return this.workingCopyVersion;
}
private set
{
//TODO: Add validation code
this.workingCopyVersion = value;
}
}
public string CorrelationId
{
get
{
return this.correlationId;
}
private set
{
//TODO: Add validation code
this.correlationId = value;
}
}
public string CausationId
{
get
{
return this.causationId;
}
private set
{
//TODO: Add validation code
this.causationId = value;
}
}
public Dictionary<string, string> Metadata
{
get
{
return this.metadata;
}
private set
{
//TODO: Add validation code
this.metadata = value;
}
}
public IEnumerable<Event> Changes
{
get
{
return this.changes;
}
private set
{
//TODO: Add validation code
this.changes = value;
}
}
#endregion
}
}
| 24.903704 | 230 | 0.489887 | [
"MIT"
] | robertorodes/Eventual | source/Eventual.EventStore/Services/TypedEventStreamCommit.cs | 3,364 | C# |
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
#pragma warning disable 1591
namespace IdentityServer4.FreeSql.Entities
{
public class ClientScope
{
public int Id { get; set; }
public string Scope { get; set; }
public int ClientId { get; set; }
public Client Client { get; set; }
}
} | 27.058824 | 107 | 0.667391 | [
"MIT"
] | xinguisoft/IdentityServer4.FreeSql | src/IdentityServer4.FreeSql/Entities/ClientScope.cs | 462 | C# |
namespace Discordia.Embeds
{
using System;
public abstract class EmbedUrlAttribute : EmbedAttribute
{
private Uri _uri;
public EmbedUrlAttribute(string value)
{
Value = value;
}
protected EmbedUrlAttribute()
{
_uri = null;
}
public string Value
{
get => _uri?.ToString();
set
{
try
{
_uri = new Uri(value);
}
catch (UriFormatException ue)
{
throw new Exception($"Embedded string '{value}' is not a valid Url");
}
}
}
}
} | 20.828571 | 89 | 0.418381 | [
"Unlicense",
"MIT"
] | Imbaker1234/CityOfHiddenApes.Discord | Embeds/EmbedUrlAttribute.cs | 731 | C# |
namespace DotNetBungieAPI.Generated.Models.User.Models;
public class GetCredentialTypesForAccountResponse
{
[JsonPropertyName("credentialType")]
public BungieCredentialType? CredentialType { get; set; }
[JsonPropertyName("credentialDisplayName")]
public string? CredentialDisplayName { get; set; }
[JsonPropertyName("isPublic")]
public bool? IsPublic { get; set; }
[JsonPropertyName("credentialAsString")]
public string? CredentialAsString { get; set; }
}
| 28.941176 | 61 | 0.743902 | [
"MIT"
] | EndGameGl/DotNetBungieAPI | DotNetBungieAPI.Generated/Models/User/Models/GetCredentialTypesForAccountResponse.cs | 492 | C# |
/*
* Copyright (C) Sportradar AG. See LICENSE for full license governing this code
*/
using System.Diagnostics.Contracts;
namespace Sportradar.OddsFeed.SDK.Common.Internal
{
/// <summary>
/// Class providing access to <see cref="ITimeProvider"/>
/// </summary>
/// <remarks>
/// The implementation is not thread safe and <see cref="ITimeProvider"/> provided by
/// this type should not be switched in when the SDK is running (i.e. only in unit tests)
/// </remarks>
public static class TimeProviderAccessor
{
/// <summary>
/// Gets a <see cref="ITimeProvider"/> providing access to the current time
/// </summary>
public static ITimeProvider Current { get; private set; }
static TimeProviderAccessor()
{
Current = new RealTimeProvider();
}
/// <summary>
/// Sets the <see cref="ITimeProvider"/> provided by the <see cref="TimeProviderAccessor"/>
/// </summary>
/// <param name="timeProvider"></param>
public static void SetTimeProvider(ITimeProvider timeProvider)
{
Contract.Ensures(timeProvider != null);
Current = timeProvider;
}
}
} | 33.162162 | 99 | 0.615322 | [
"Apache-2.0"
] | Furti87/UnifiedOddsSdkNet | src/Sportradar.OddsFeed.SDK.Common/Internal/TimeProviderAccessor.cs | 1,229 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace WinFormForRS
{
public partial class Form5 : Form
{
protected override CreateParams CreateParams
{
get
{
CreateParams cp = base.CreateParams;
cp.ExStyle |= 0x02000000; // Turn on WS_EX_COMPOSITED
return cp;
}
}
public Form5()
{
InitializeComponent();
this.BackColor = Color.FromArgb(233, 247, 255);
pictureBox1.Image = Program.w_source_img;
textBox1.Text = Convert.ToString(Program.rainwater_collection_width_top_L);
textBox2.Text = Convert.ToString(Program.rainwater_collection_width_bottom_L);
textBox3.Text = Convert.ToString(Program.rainwater_collection_deep_H);
textBox4.Text = Convert.ToString(Program.rainwater_collection_space_X);
textBox5.Text = Convert.ToString(Program.flooded_S);
}
private void button1_Click(object sender, EventArgs e)
{
DialogResult dr = MessageBox.Show("是否退出?", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
if (dr == DialogResult.OK)
{
System.Environment.Exit(System.Environment.ExitCode);
this.Dispose();
this.Close();
}
}
private void button3_Click(object sender, EventArgs e)
{
Form7 form = new Form7();
form.Show();
this.Dispose();
this.Close();
}
private void button2_Click(object sender, EventArgs e)
{
// 保存数据到txt中
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "文本文件(*.txt)|*.txt";
sfd.FilterIndex = 1;
sfd.RestoreDirectory = true;
sfd.FileName = "蓄水沟数据";
if (sfd.ShowDialog() == DialogResult.OK)
{
string localFilePath = sfd.FileName.ToString();
string fileNameExt = localFilePath.Substring(localFilePath.LastIndexOf("\\") + 1);
string top_L = Convert.ToString(Program.rainwater_collection_width_top_L);
string bottom_L = Convert.ToString(Program.rainwater_collection_width_bottom_L);
string flood_S = Convert.ToString(Math.Round(Program.flooded_S,0,MidpointRounding.AwayFromZero));
string deep_H = Convert.ToString(Program.rainwater_collection_deep_H);
string space_X = Convert.ToString(Program.rainwater_collection_space_X);
StreamWriter train_Data = new StreamWriter(localFilePath);
string temp = null;
temp = string.Format("蓄水沟上宽\t{0}", top_L);
train_Data.WriteLine(temp);
temp = string.Format("蓄水沟下宽\t{0}", bottom_L);
train_Data.WriteLine(temp);
temp = string.Format("蓄水沟深度\t{0}", deep_H);
train_Data.WriteLine(temp);
temp = string.Format("蓄水沟间距\t{0}", space_X);
train_Data.WriteLine(temp);
temp = string.Format("淹没区面积\t{0}", flood_S);
train_Data.WriteLine(temp);
train_Data.Close();
}
}
private void Form5_FormClosing(object sender, FormClosingEventArgs e)
{
DialogResult dr = MessageBox.Show("是否退出?", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
if (dr == DialogResult.OK)
{
System.Environment.Exit(System.Environment.ExitCode);
this.Dispose();
this.Close();
}
else
{
e.Cancel = true;
}
}
private void button4_Click(object sender, EventArgs e)
{
Form4 form = new Form4();
form.Show();
this.Dispose();
this.Close();
}
}
}
| 35.409836 | 118 | 0.550463 | [
"MIT"
] | alexfeng/RainWaterStoreForm | WinFormForRS/WinFormForRS/Form5.cs | 4,434 | C# |
namespace AspNetCoreBoilerplateApplication1
{
using System.IO;
using System.Linq;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
public sealed class Program
{
private const string HostingJsonFileName = "hosting.json";
public static void Main(string[] args)
{
var configuration = new ConfigurationBuilder()
.AddJsonFile(HostingJsonFileName, optional: true, reloadOnChange: true)
.AddEnvironmentVariables()
.AddCommandLine(args)
.Build();
IHostingEnvironment hostingEnvironment = null;
var host = new WebHostBuilder()
.UseConfiguration(configuration)
.UseContentRoot(Directory.GetCurrentDirectory())
.ConfigureServices(
services =>
{
hostingEnvironment = services
.Where(x => x.ServiceType == typeof(IHostingEnvironment))
.Select(x => (IHostingEnvironment)x.ImplementationInstance)
.First();
})
.UseKestrel(
options =>
{
// Do not add the Server HTTP header when using the Kestrel Web Server.
options.AddServerHeader = false;
if (hostingEnvironment.IsDevelopment())
{
// Use a self-signed certificate to enable 'dotnet run' to work in development.
// This will give a browser security warning which you can safely ignore.
options.UseHttps("DevelopmentCertificate.pfx", "password");
}
})
.UseAzureAppServices()
.UseIISIntegration()
.UseStartup<Startup>()
.Build();
host.Run();
}
}
} | 39.365385 | 107 | 0.504641 | [
"MIT"
] | jramos-br/PlayGround | VS2017-15.9.18/CS/AspNetCoreBoilerplateApplication1/AspNetCoreBoilerplateApplication1/Program.cs | 2,049 | C# |
using System;
using System.Collections.Generic;
using Common.Messages.Interfaces;
namespace Common.Messages.Services
{
public sealed class MessageService : IMassageService
{
private static volatile MessageService _instance;
private static object _syncRoot = new object();
private Dictionary<Type, List<Object>> _Subscribers = new Dictionary<Type, List<object>>();
private MessageService() { }
public static MessageService Instance
{
get
{
if (_instance == null)
{
lock (_syncRoot)
{
if (_instance == null)
_instance = new MessageService();
}
}
return _instance;
}
}
public void Publish<TMessage>(TMessage message)
{
if (_Subscribers.ContainsKey(typeof(TMessage)))
{
var handlers = _Subscribers[typeof(TMessage)];
foreach (Action<TMessage> handler in handlers)
{
handler.Invoke(message);
}
}
}
public void Publish(object message)
{
var messageType = message.GetType();
if (_Subscribers.ContainsKey(messageType))
{
var handlers = _Subscribers[messageType];
foreach (var handler in handlers)
{
var actionType = handler.GetType();
var invoke = actionType.GetMethod("Invoke", new Type[] { messageType });
invoke.Invoke(handler, new Object[] { message });
}
}
}
public void Subscribe<TMessage>(Action<TMessage> handler)
{
if (_Subscribers.ContainsKey(typeof(TMessage)))
{
var handlers = _Subscribers[typeof(TMessage)];
handlers.Add(handler);
}
else
{
var handlers = new List<object>();
handlers.Add(handler);
_Subscribers[typeof(TMessage)] = handlers;
}
}
public void Unsubscribe<TMessage>(Action<TMessage> handler)
{
if (_Subscribers.ContainsKey(typeof(TMessage)))
{
var handelers = _Subscribers[typeof(TMessage)];
handelers.Remove(handler);
if (handelers.Count == 0)
{
_Subscribers.Remove(typeof(TMessage));
}
}
}
}
}
| 30.781609 | 99 | 0.486184 | [
"Unlicense"
] | guldmann/Sharp-tail | Src/Sharp-tail/Common/Messages/Services/MessageService.cs | 2,680 | C# |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Xml;
using System.Xml.Serialization;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Storage;
using Boku.Base;
using Boku.Common;
using Boku.Input;
namespace Boku.Programming
{
/// <summary>
/// Filter that returns a positive action a matching string is said by another character.
///
/// </summary>
public class SaidFilter : Filter
{
const int kMaxCount = 10;
[XmlAttribute]
public string text;
public override ProgrammingElement Clone()
{
SaidFilter clone = new SaidFilter();
CopyTo(clone);
return clone;
}
protected void CopyTo(SaidFilter clone)
{
base.CopyTo(clone);
clone.text = this.text;
}
public override bool MatchTarget(Reflex reflex, SensorTarget sensorTarget)
{
bool result = false;
// Try matching each line.
for (int i = 0; i < reflex.Data.saidStrings.Count; i++)
{
bool atBeginning = reflex.Data.saidMode == 0;
if (SaidStringManager.MatchText(sensorTarget.GameThing as GameActor, reflex.Data.saidStrings[i], atBeginning))
{
result = true;
break;
}
}
return result;
}
public override bool MatchAction(Reflex reflex, out object param)
{
param = null;
return true;
}
} // end of class SaidFilter
} // end of namespace Boku.Programming
| 25.693333 | 126 | 0.601453 | [
"MIT"
] | Yash-Codemaster/KoduGameLab | main/Boku/Programming/SaidFilter.cs | 1,927 | C# |
// <copyright file="GroupMember.cs" company="Microsoft">
// Copyright (c) Microsoft. All rights reserved.
// </copyright>
namespace Microsoft.Teams.Apps.NewHireOnboarding.Models.Graph
{
using System.Collections.Generic;
using Microsoft.Teams.Apps.NewHireOnboarding.Models.SharePoint;
using Newtonsoft.Json;
/// <summary>
/// Model class for Security group member for Microsoft Graph Api.
/// </summary>
public class GroupMember
{
/// <summary>
/// Gets or sets odataContext.
/// </summary>
[JsonProperty("@odata.context")]
public string OdataContext { get; set; }
/// <summary>
/// Gets or sets list of security group members.
/// </summary>
#pragma warning disable CA2227 // Getting error to make collection property as read only but needs to assign values.
[JsonProperty("value")]
public List<UserProfileDetail> SecurityGroupMembers { get; set; }
#pragma warning restore CA2227 // Getting error to make collection property as read only but needs to assign values.
}
}
| 36.129032 | 117 | 0.653571 | [
"MIT"
] | v-chetsh/at-arm-test-local | Source/Microsoft.Teams.Apps.NewHireOnboarding/Models/Graph/GroupMember.cs | 1,122 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Part3 - AsyncAwait")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Part3 - AsyncAwait")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("63d0d940-5c52-4391-b5ed-8d6ca0952849")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.081081 | 84 | 0.74308 | [
"MIT"
] | keigezellig/devicemonitor | Part3/Properties/AssemblyInfo.cs | 1,412 | C# |
using System.Collections.Generic;
namespace Shade.Alby
{
public class SquareCell : Cell
{
private readonly SquareGrid grid;
private CellConnector northConnector;
private CellConnector southConnector;
private CellConnector eastConnector;
private CellConnector westConnector;
public SquareCell(SquareGrid grid, GridPosition position)
: base(position) { this.grid = grid; }
public SquareCell NorthNeighbor { get { return grid.GetCellOrNull(Position.X, Position.Y - 1); }}
public SquareCell SouthNeighbor { get { return grid.GetCellOrNull(Position.X, Position.Y + 1); } }
public SquareCell WestNeighbor { get { return grid.GetCellOrNull(Position.X - 1, Position.Y); } }
public SquareCell EastNeighbor { get { return grid.GetCellOrNull(Position.X + 1, Position.Y); }}
public CellConnector NorthConnector { get { return northConnector; }}
public CellConnector SouthConnector { get { return southConnector; }}
public CellConnector EastConnector { get { return eastConnector; }}
public CellConnector WestConnector { get { return westConnector; }}
public void SetNorthConnector(CellConnector connector) { northConnector = connector; }
public void SetSouthConnector(CellConnector connector) { southConnector = connector; }
public void SetEastConnector(CellConnector connector) { eastConnector = connector; }
public void SetWestConnector(CellConnector connector) { westConnector = connector; }
public override IReadOnlyCollection<CellConnector> Connectors
{
get
{
var result = new List<CellConnector>(4);
if (NorthConnector != null)
result.Add(NorthConnector);
if (SouthConnector != null)
result.Add(SouthConnector);
if (EastConnector != null)
result.Add(EastConnector);
if (WestConnector != null)
result.Add(WestConnector);
return result;
}
}
}
} | 41.2 | 104 | 0.667961 | [
"BSD-2-Clause"
] | miyu/libalby | SquareCell.cs | 2,062 | C# |
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
namespace HatcheryManagement
{
public interface IKatlaRepository
{
KatlaFish GetByID(int id);
List<KatlaFish> GetAll();
void Insert(KatlaFish t);
void Delete(int id);
void Update(KatlaFish t, int idx);
// void Save();
}
}
| 20.166667 | 42 | 0.641873 | [
"MIT"
] | Koushik-Sarker-Seemanto/HatcheryManagement | IKatlaRepository.cs | 363 | C# |
namespace Vidly.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class AddRentalModel : DbMigration
{
public override void Up()
{
CreateTable(
"dbo.Rentals",
c => new
{
Id = c.Int(nullable: false, identity: true),
DateRented = c.DateTime(nullable: false),
DateReturned = c.DateTime(),
Customer_Id = c.Int(nullable: false),
Movie_Id = c.Int(nullable: false),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.Customers", t => t.Customer_Id, cascadeDelete: true)
.ForeignKey("dbo.Movies", t => t.Movie_Id, cascadeDelete: true)
.Index(t => t.Customer_Id)
.Index(t => t.Movie_Id);
}
public override void Down()
{
DropForeignKey("dbo.Rentals", "Movie_Id", "dbo.Movies");
DropForeignKey("dbo.Rentals", "Customer_Id", "dbo.Customers");
DropIndex("dbo.Rentals", new[] { "Movie_Id" });
DropIndex("dbo.Rentals", new[] { "Customer_Id" });
DropTable("dbo.Rentals");
}
}
}
| 34.789474 | 85 | 0.475038 | [
"MIT"
] | imranaskem/Vidly | Vidly/Migrations/201701151948033_AddRentalModel.cs | 1,322 | C# |
using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo("HoneyBear.Spy.Serilog.Autofac")] | 34.333333 | 63 | 0.834951 | [
"MIT"
] | eoin55/HoneyBear.Spy | Src/HoneyBear.Spy.Serilog/Properties/FriendlyAssemblyInfo.cs | 103 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System;
using System.ComponentModel;
namespace Azure.ResourceManager.AppPlatform.Models
{
/// <summary> Power state of the Service. </summary>
public readonly partial struct PowerState : IEquatable<PowerState>
{
private readonly string _value;
/// <summary> Initializes a new instance of <see cref="PowerState"/>. </summary>
/// <exception cref="ArgumentNullException"> <paramref name="value"/> is null. </exception>
public PowerState(string value)
{
_value = value ?? throw new ArgumentNullException(nameof(value));
}
private const string RunningValue = "Running";
private const string StoppedValue = "Stopped";
/// <summary> Running. </summary>
public static PowerState Running { get; } = new PowerState(RunningValue);
/// <summary> Stopped. </summary>
public static PowerState Stopped { get; } = new PowerState(StoppedValue);
/// <summary> Determines if two <see cref="PowerState"/> values are the same. </summary>
public static bool operator ==(PowerState left, PowerState right) => left.Equals(right);
/// <summary> Determines if two <see cref="PowerState"/> values are not the same. </summary>
public static bool operator !=(PowerState left, PowerState right) => !left.Equals(right);
/// <summary> Converts a string to a <see cref="PowerState"/>. </summary>
public static implicit operator PowerState(string value) => new PowerState(value);
/// <inheritdoc />
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object obj) => obj is PowerState other && Equals(other);
/// <inheritdoc />
public bool Equals(PowerState other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase);
/// <inheritdoc />
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode() => _value?.GetHashCode() ?? 0;
/// <inheritdoc />
public override string ToString() => _value;
}
}
| 43.038462 | 129 | 0.660411 | [
"MIT"
] | damodaravadhani/azure-sdk-for-net | sdk/appplatform/Azure.ResourceManager.AppPlatform/src/Generated/Models/PowerState.cs | 2,238 | C# |
// Copyright (c) MOSA Project. Licensed under the New BSD License.
// This code was generated by an automated template.
using Mosa.Compiler.Framework.IR;
namespace Mosa.Compiler.Framework.Transform.Auto.IR.ConstantFolding
{
/// <summary>
/// Sub32
/// </summary>
public sealed class Sub32 : BaseTransformation
{
public Sub32() : base(IRInstruction.Sub32)
{
}
public override bool Match(Context context, TransformContext transformContext)
{
if (!IsResolvedConstant(context.Operand1))
return false;
if (!IsResolvedConstant(context.Operand2))
return false;
return true;
}
public override void Transform(Context context, TransformContext transformContext)
{
var result = context.Result;
var t1 = context.Operand1;
var t2 = context.Operand2;
var e1 = transformContext.CreateConstant(Sub32(To32(t1), To32(t2)));
context.SetInstruction(IRInstruction.Move32, result, e1);
}
}
}
| 22.285714 | 84 | 0.723291 | [
"BSD-3-Clause"
] | Arakis/MOSA-Project | Source/Mosa.Compiler.Framework/Transform/Auto/IR/ConstantFolding/Sub32.cs | 936 | 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.Ads.GoogleAds.V8.Services.Snippets
{
using Google.Ads.GoogleAds.V8.Services;
public sealed partial class GeneratedCustomerUserAccessInvitationServiceClientStandaloneSnippets
{
/// <summary>Snippet for MutateCustomerUserAccessInvitation</summary>
/// <remarks>
/// This snippet has been automatically generated for illustrative purposes only.
/// It may require modifications to work in your environment.
/// </remarks>
public void MutateCustomerUserAccessInvitationRequestObject()
{
// Create client
CustomerUserAccessInvitationServiceClient customerUserAccessInvitationServiceClient = CustomerUserAccessInvitationServiceClient.Create();
// Initialize request argument(s)
MutateCustomerUserAccessInvitationRequest request = new MutateCustomerUserAccessInvitationRequest
{
CustomerId = "",
Operation = new CustomerUserAccessInvitationOperation(),
};
// Make the request
MutateCustomerUserAccessInvitationResponse response = customerUserAccessInvitationServiceClient.MutateCustomerUserAccessInvitation(request);
}
}
}
| 43.348837 | 152 | 0.718348 | [
"Apache-2.0"
] | googleapis/googleapis-gen | google/ads/googleads/v8/googleads-csharp/Google.Ads.GoogleAds.V8.Services.StandaloneSnippets/CustomerUserAccessInvitationServiceClient.MutateCustomerUserAccessInvitationRequestObjectSnippet.g.cs | 1,864 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Data;
namespace VariationGeneration
{
public class ViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propname)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propname));
}
}
private DataTable queryresult;
public DataTable QueryResult
{
get { return queryresult; }
set
{
if (queryresult != value)
{
queryresult = value;
OnPropertyChanged("QueryResult");
}
}
}
}
}
| 26.028571 | 79 | 0.535675 | [
"Apache-2.0"
] | lwfwind/CVG | ViewModel.cs | 913 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.