content stringlengths 23 1.05M |
|---|
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
namespace ManejoFicheros
{
class Documento
{
StreamWriter documento;
public Documento(string nombre, string texto)
{
documento = new StreamWriter(nombre);
documento.WriteLine(texto);
documento.Close();
}
}
}
|
using DevExpress.ExpressApp;
using DevExpress.ExpressApp.Actions;
using DevExpress.ExpressApp.DC;
using DevExpress.Persistent.Base;
using DevExpress.Xpo;
using CIIP.Persistent.BaseImpl;
using System.Linq;
using DevExpress.ExpressApp.Model;
using System.IO;
using System.Collections.Generic;
using Newtonsoft.Json;
namespace CIIP.Designer
{
//系统起动后,必须选择一个项目才可以继续.
//启动按钮:
//1.先运行生成按project,
//2.运行StartupFile
//3.startupFile如何知道生成的文件?
//生成按钮:生成project,内容包含bo文件
//起动文件中配置了自动读取dll模块的方法
[XafDisplayName("项目管理")]
[DefaultClassOptions]
[JsonObject(MemberSerialization.OptIn)]
public class Project : NameObject
{
public static string ApplicationStartupPath { get; set; }
public Project(Session s) : base(s)
{
}
protected override void OnChanged(string propertyName, object oldValue, object newValue)
{
base.OnChanged(propertyName, oldValue, newValue);
if (propertyName == nameof(Name) || propertyName == nameof(ProjectPath))
{
WinProjectPath = Path.Combine(ProjectPath + "", Name + "", "Win");
WinStartupFile = Path.Combine(WinProjectPath + "", "CIIP.Client.Win.Exe");
WebProjectPath = Path.Combine(ProjectPath + "", Name + "", "Web");
}
}
public override void AfterConstruction()
{
base.AfterConstruction();
ProjectPath = ApplicationStartupPath;
WinStartupFile = ApplicationStartupPath + "\\CIIP.Client.Win.Exe";
var module = new BusinessModule(Session);
module.Name = "<<自动生成>>";
module.OutputPath = "<<自动生成>>";
var refModule = new ReferenceModule(Session);
refModule.Module = module;
this.Modules.Add(module);
this.ReferencedModules.Add(refModule);
}
/// <summary>
/// 是否是本系统生成的
/// </summary>
[XafDisplayName("定制生成")]
[ToolTip("选中时为定系统生成的,否则为存在的dll导入的.")]
[ModelDefault("AllowEdit", "False")]
public bool Generated
{
get { return GetPropertyValue<bool>(nameof(Generated)); }
set { SetPropertyValue(nameof(Generated), value); }
}
/// <summary>
/// 在windows下调试时使用哪个起动文件
/// </summary>
[XafDisplayName("起动文件")]
public string WinStartupFile
{
get { return GetPropertyValue<string>(nameof(WinStartupFile)); }
set { SetPropertyValue(nameof(WinStartupFile), value); }
}
[XafDisplayName("项目路径")]
public string WinProjectPath
{
get { return GetPropertyValue<string>(nameof(WinProjectPath)); }
set { SetPropertyValue(nameof(WinProjectPath), value); }
}
[XafDisplayName("项目路径")]
public string WebProjectPath
{
get { return GetPropertyValue<string>(nameof(WebProjectPath)); }
set { SetPropertyValue(nameof(WebProjectPath), value); }
}
/// <summary>
/// 路径:生成dll时保存到如下路径中去.
/// </summary>
[XafDisplayName("项目路径")]
public string ProjectPath
{
get { return GetPropertyValue<string>(nameof(ProjectPath)); }
set { SetPropertyValue(nameof(ProjectPath), value); }
}
protected override void OnSaving()
{
base.OnSaving();
if (!string.IsNullOrEmpty(Name))
{
foreach (var item in Modules)
{
if (item.Name == "<<自动生成>>")
{
item.Name = Name;
item.OutputPath = Path.Combine(ProjectPath + "", Name + "", Name + ".dll");
}
}
}
}
protected override void OnSaved()
{
base.OnSaved();
//如果启动文件缺少,则复复制.
var source = Path.Combine(ApplicationStartupPath, @"StartupFile\Win");
//DirectoryInfo fi = new DirectoryInfo(source);
//var files = fi.EnumerateFiles("*.*", SearchOption.AllDirectories);
if (!File.Exists(WinStartupFile))
{
//File.Copy(ApplicationStartupPath)
DirectoryCopy(source, WinProjectPath, true);
}
//如果是新建的项目,则立即建立对应的module info cfg文件.
File.WriteAllText(Path.Combine(WinProjectPath, "ModulesInfo.cfg"), Newtonsoft.Json.JsonConvert.SerializeObject(ReferencedModules.ToArray()));
File.WriteAllText(Path.Combine(WinProjectPath, "app.module"), Newtonsoft.Json.JsonConvert.SerializeObject(this));
}
private static void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs)
{
// Get the subdirectories for the specified directory.
DirectoryInfo dir = new DirectoryInfo(sourceDirName);
if (!dir.Exists)
{
throw new DirectoryNotFoundException(
"Source directory does not exist or could not be found: "
+ sourceDirName);
}
DirectoryInfo[] dirs = dir.GetDirectories();
// If the destination directory doesn't exist, create it.
if (!Directory.Exists(destDirName))
{
Directory.CreateDirectory(destDirName);
}
// Get the files in the directory and copy them to the new location.
FileInfo[] files = dir.GetFiles();
foreach (FileInfo file in files)
{
string temppath = Path.Combine(destDirName, file.Name);
file.CopyTo(temppath, false);
}
// If copying subdirectories, copy them and their contents to new location.
if (copySubDirs)
{
foreach (DirectoryInfo subdir in dirs)
{
string temppath = Path.Combine(destDirName, subdir.Name);
DirectoryCopy(subdir.FullName, temppath, copySubDirs);
}
}
}
[Association, DevExpress.Xpo.Aggregated, XafDisplayName("引用模块")]
public XPCollection<ReferenceModuleBase> ReferencedModules
{
get
{
return GetCollection<ReferenceModuleBase>(nameof(ReferencedModules));
//使用json去对应的目录去读取
//if (_modules == null)
//{
// _modules = new List<BusinessModuleInfo>();
// var rst = BusinessModuleInfo.GetModules(Path.Combine(WinProjectPath, "BusinessModules.cfg"));
// if (rst != null)
// {
// _modules.AddRange(rst);
// }
//}
//return _modules;
}
}
[XafDisplayName("模块")]
[Association, DevExpress.Xpo.Aggregated]
public XPCollection<BusinessModule> Modules
{
get
{
return GetCollection<BusinessModule>(nameof(Modules));
}
}
[JsonProperty]
[XafDisplayName("报表模块")]
public bool WinReport
{
get { return GetPropertyValue<bool>(nameof(WinReport)); }
set { SetPropertyValue(nameof(WinReport), value); }
}
[JsonProperty]
public bool WinValidation
{
get { return GetPropertyValue<bool>(nameof(WinValidation)); }
set { SetPropertyValue(nameof(WinValidation), value); }
}
[JsonProperty]
[XafDisplayName("变更记录")]
public bool WinAuditTrail
{
get { return GetPropertyValue<bool>(nameof(WinAuditTrail)); }
set { SetPropertyValue(nameof(WinAuditTrail), value); }
}
[JsonProperty]
[XafDisplayName("图表列表")]
public bool WinChart
{
get { return GetPropertyValue<bool>(nameof(WinChart)); }
set { SetPropertyValue(nameof(WinChart), value); }
}
[JsonProperty]
[XafDisplayName("克隆模块")]
public bool WinClone
{
get { return GetPropertyValue<bool>(nameof(WinClone)); }
set { SetPropertyValue(nameof(WinClone), value); }
}
[JsonProperty]
[XafDisplayName("外观控制")]
public bool WinConditionalAppearance
{
get { return GetPropertyValue<bool>(nameof(WinConditionalAppearance)); }
set { SetPropertyValue(nameof(WinConditionalAppearance), value); }
}
[JsonProperty]
[XafDisplayName("Dashboard")]
public bool WinDashboard
{
get { return GetPropertyValue<bool>(nameof(WinDashboard)); }
set { SetPropertyValue(nameof(WinDashboard), value); }
}
[JsonProperty]
[XafDisplayName("文件附件")]
public bool WinFileAttachment
{
get { return GetPropertyValue<bool>(nameof(WinFileAttachment)); }
set { SetPropertyValue(nameof(WinFileAttachment), value); }
}
[JsonProperty]
[XafDisplayName("HTML控件")]
public bool WinHtmlPropertyEditor
{
get { return GetPropertyValue<bool>(nameof(WinHtmlPropertyEditor)); }
set { SetPropertyValue(nameof(WinHtmlPropertyEditor), value); }
}
[JsonProperty]
[XafDisplayName("KPI模块")]
public bool WinKPI
{
get { return GetPropertyValue<bool>(nameof(WinKPI)); }
set { SetPropertyValue(nameof(WinKPI), value); }
}
[JsonProperty]
[XafDisplayName("提醒模块")]
public bool WinNotifications
{
get { return GetPropertyValue<bool>(nameof(WinNotifications)); }
set { SetPropertyValue(nameof(WinNotifications), value); }
}
[JsonProperty]
[XafDisplayName("Word编辑")]
public bool WinOffice
{
get { return GetPropertyValue<bool>(nameof(WinOffice)); }
set { SetPropertyValue(nameof(WinOffice), value); }
}
[JsonProperty]
[XafDisplayName("透视图表")]
public bool WinPivotChart
{
get { return GetPropertyValue<bool>(nameof(WinPivotChart)); }
set { SetPropertyValue(nameof(WinPivotChart), value); }
}
[JsonProperty]
[XafDisplayName("透视列表")]
public bool WinPivotGrid
{
get { return GetPropertyValue<bool>(nameof(WinPivotGrid)); }
set { SetPropertyValue(nameof(WinPivotGrid), value); }
}
[JsonProperty]
[XafDisplayName("状态机")]
public bool WinStateMachine
{
get { return GetPropertyValue<bool>(nameof(WinStateMachine)); }
set { SetPropertyValue(nameof(WinStateMachine), value); }
}
[JsonProperty]
[XafDisplayName("树形列表")]
public bool WinTreeListEditor
{
get { return GetPropertyValue<bool>(nameof(WinTreeListEditor)); }
set { SetPropertyValue(nameof(WinTreeListEditor), value); }
}
[JsonProperty]
[XafDisplayName("视图切换")]
public bool WinViewVariant
{
get { return GetPropertyValue<bool>(nameof(WinViewVariant)); }
set { SetPropertyValue(nameof(WinViewVariant), value); }
}
[JsonProperty]
[XafDisplayName("日程安排")]
public bool WinScheduler
{
get { return GetPropertyValue<bool>(nameof(WinScheduler)); }
set { SetPropertyValue(nameof(WinScheduler), value); }
}
[JsonProperty]
[XafDisplayName("报表模块")]
public bool WebReport
{
get { return GetPropertyValue<bool>(nameof(WebReport)); }
set { SetPropertyValue(nameof(WebReport), value); }
}
[JsonProperty]
[XafDisplayName("变更记录")]
public bool WebAuditTrail
{
get { return GetPropertyValue<bool>(nameof(WebAuditTrail)); }
set { SetPropertyValue(nameof(WebAuditTrail), value); }
}
[JsonProperty]
[XafDisplayName("图表列表")]
public bool WebChart
{
get { return GetPropertyValue<bool>(nameof(WebChart)); }
set { SetPropertyValue(nameof(WebChart), value); }
}
[JsonProperty]
[XafDisplayName("克隆模块")]
public bool WebClone
{
get { return GetPropertyValue<bool>(nameof(WebClone)); }
set { SetPropertyValue(nameof(WebClone), value); }
}
[JsonProperty]
[XafDisplayName("外观控制")]
public bool WebConditionalAppearance
{
get { return GetPropertyValue<bool>(nameof(WebConditionalAppearance)); }
set { SetPropertyValue(nameof(WebConditionalAppearance), value); }
}
[JsonProperty]
[XafDisplayName("Dashboard")]
public bool WebDashboard
{
get { return GetPropertyValue<bool>(nameof(WebDashboard)); }
set { SetPropertyValue(nameof(WebDashboard), value); }
}
[JsonProperty]
[XafDisplayName("文件附件")]
public bool WebFileAttachment
{
get { return GetPropertyValue<bool>(nameof(WebFileAttachment)); }
set { SetPropertyValue(nameof(WebFileAttachment), value); }
}
[JsonProperty]
[XafDisplayName("HTML控件")]
public bool WebHtmlPropertyEditor
{
get { return GetPropertyValue<bool>(nameof(WebHtmlPropertyEditor)); }
set { SetPropertyValue(nameof(WebHtmlPropertyEditor), value); }
}
[JsonProperty]
[XafDisplayName("KPI模块")]
public bool WebKPI
{
get { return GetPropertyValue<bool>(nameof(WebKPI)); }
set { SetPropertyValue(nameof(WebKPI), value); }
}
[JsonProperty]
[XafDisplayName("提醒模块")]
public bool WebNotifications
{
get { return GetPropertyValue<bool>(nameof(WebNotifications)); }
set { SetPropertyValue(nameof(WebNotifications), value); }
}
[JsonProperty]
[XafDisplayName("Word编辑")]
public bool WebOffice
{
get { return GetPropertyValue<bool>(nameof(WebOffice)); }
set { SetPropertyValue(nameof(WebOffice), value); }
}
[JsonProperty]
[XafDisplayName("透视图表")]
public bool WebPivotChart
{
get { return GetPropertyValue<bool>(nameof(WebPivotChart)); }
set { SetPropertyValue(nameof(WebPivotChart), value); }
}
[JsonProperty]
[XafDisplayName("透视列表")]
public bool WebPivotGrid
{
get { return GetPropertyValue<bool>(nameof(WebPivotGrid)); }
set { SetPropertyValue(nameof(WebPivotGrid), value); }
}
[JsonProperty]
[XafDisplayName("状态机")]
public bool WebStateMachine
{
get { return GetPropertyValue<bool>(nameof(WebStateMachine)); }
set { SetPropertyValue(nameof(WebStateMachine), value); }
}
[JsonProperty]
[XafDisplayName("树形列表")]
public bool WebTreeListEditor
{
get { return GetPropertyValue<bool>(nameof(WebTreeListEditor)); }
set { SetPropertyValue(nameof(WebTreeListEditor), value); }
}
[JsonProperty]
[XafDisplayName("视图切换")]
public bool WebViewVariant
{
get { return GetPropertyValue<bool>(nameof(WebViewVariant)); }
set { SetPropertyValue(nameof(WebViewVariant), value); }
}
[JsonProperty]
[XafDisplayName("日程安排")]
public bool WebScheduler
{
get { return GetPropertyValue<bool>(nameof(WebScheduler)); }
set { SetPropertyValue(nameof(WebScheduler), value); }
}
}
public class ProjectViewController : ViewController
{
public ProjectViewController()
{
TargetObjectType = typeof(Project);
}
protected override void OnActivated()
{
base.OnActivated();
ObjectSpace.Committed += ObjectSpace_Committed;
}
protected override void OnDeactivated()
{
ObjectSpace.Committed -= ObjectSpace_Committed;
base.OnDeactivated();
}
private void ObjectSpace_Committed(object sender, System.EventArgs e)
{
Application.MainWindow?.GetController<SwitchProjectControllerBase>()?.CreateProjectItems();
}
}
public enum CompileAction
{
编译运行,
开始暂停,
运行,
编译
}
public abstract class SwitchProjectControllerBase : WindowController
{
public static Project CurrentProject { get; set; }
SingleChoiceAction switchProject;
public SwitchProjectControllerBase()
{
TargetWindowType = WindowType.Main;
switchProject = new SingleChoiceAction(this, "SwitchProject", "项目");
switchProject.Caption = "当前项目";
switchProject.Execute += SwitchProject_Execute;
switchProject.ItemType = SingleChoiceActionItemType.ItemIsOperation;
var compileProject = new SingleChoiceAction(this, "CompileProject", "项目");
compileProject.Caption = "生成";
compileProject.Items.Add(new ChoiceActionItem("生成运行", CompileAction.编译运行));
compileProject.Items.Add(new ChoiceActionItem("生成运行-开始时暂停", CompileAction.开始暂停));
compileProject.Items.Add(new ChoiceActionItem("生成项目", CompileAction.编译));
compileProject.Items.Add(new ChoiceActionItem("运行", CompileAction.运行));
compileProject.ItemType = SingleChoiceActionItemType.ItemIsOperation;
compileProject.Execute += CompileProject_Execute;
}
protected abstract void Compile(SingleChoiceActionExecuteEventArgs e);
private void CompileProject_Execute(object sender, SingleChoiceActionExecuteEventArgs e)
{
if (CurrentProject == null)
{
var msg = new MessageOptions();
msg.Duration = 3000;
msg.Message = "当前没有选中的项目!";
msg.Type = InformationType.Error;
msg.Win.Caption = "错误";
msg.Win.Type = WinMessageType.Flyout;
Application.ShowViewStrategy.ShowMessage(msg);// "", InformationType.Error, 3000, InformationPosition.Left);
return;
}
Compile(e);
}
protected override void OnActivated()
{
base.OnActivated();
CreateProjectItems();
}
protected abstract void ShowMessage(string msg);
public void CreateProjectItems()
{
switchProject.Items.Clear();
var os = Application.CreateObjectSpace();
var projects = os.GetObjectsQuery<Project>().ToList();
if (projects.Count == 0)
{
ShowMessage("当前系统还没有默认项目,请建立一个默认项目!");
var obj = os.CreateObject<Project>();
var view = Application.CreateDetailView(os, obj);
Application.ShowViewStrategy.ShowViewInPopupWindow(view, okButtonCaption: "创建项目", cancelDelegate: () => { Application.Exit(); }, cancelButtonCaption: "退出系统");
projects.Add(obj);
}
foreach (var item in projects)
{
switchProject.Items.Add(new ChoiceActionItem(item.Name, item));
}
switchProject.SelectedItem = switchProject.Items.FirstOrDefault();
SwitchProjectCore(switchProject.SelectedItem?.Data as Project);
}
private void SwitchProject_Execute(object sender, SingleChoiceActionExecuteEventArgs e)
{
SwitchProjectCore(e.SelectedChoiceActionItem?.Data as Project);
}
private void SwitchProjectCore(Project project)
{
CurrentProject = project;
if (CurrentProject != null)
{
switchProject.Caption = CurrentProject.Name;
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenORPG.Database.Enums;
using Server.Game.Entities;
namespace Server.Game.Combat
{
/// <summary>
/// A character stat is a vital part of the makeup of the <see cref="Character"/>.
/// These usually contain information like maximum and minimums, along with any modifiers.
/// </summary>
public class CharacterStat
{
public delegate void StatValueChanged(long oldValue, long newValue, StatTypes statType);
public event StatValueChanged CurrentValueChanged;
protected virtual void OnCurrentValueChanged(long oldvalue, long newvalue, StatTypes stattype)
{
StatValueChanged handler = CurrentValueChanged;
if (handler != null) handler(oldvalue, newvalue, stattype);
}
public event StatValueChanged MaximumValueChanged;
protected virtual void OnMaximumValueChanged(long oldvalue, long newvalue, StatTypes stattype)
{
StatValueChanged handler = MaximumValueChanged;
if (handler != null) handler(oldvalue, newvalue, stattype);
}
private long _maximumValue;
private long _currentValue;
public long MaximumValue
{
get { return _maximumValue; }
set
{
if (value != _maximumValue)
{
_maximumValue = value;
OnMaximumValueChanged(_maximumValue, value, StatType);
}
}
}
public long CurrentValue
{
get { return _currentValue; }
set
{
if (value > _maximumValue && _maximumValue != 0)
value = _maximumValue;
if (value == _currentValue)
return;
if (value != _currentValue)
{
_currentValue = value;
OnCurrentValueChanged(_currentValue, value, StatType);
}
}
}
public StatTypes StatType { get; private set; }
public CharacterStat(long maximumValue, long currentValue, StatTypes statType)
{
_maximumValue = maximumValue;
_currentValue = currentValue;
StatType = statType;
}
}
}
|
namespace Facade
{
public class CloudProvider
{
private string _url;
public CloudConnection Connect(string url)
{
_url = url;
System.Console.WriteLine($"Connecting to Cloud server {url}");
return new CloudConnection(url);
}
public BlobContainer GetContainer(string authToken, string containerName)
{
System.Console.WriteLine($"Accessing container {containerName}");
return new BlobContainer(authToken, containerName);
}
public string SaveBlob(BlobContainer container, string content)
{
System.Console.WriteLine($"Saving the blob {content} in the Container");
return _url + content;
}
}
} |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT License.
// See the LICENSE file in the project root for more information.
#pragma warning disable IDE0079 // Remove unnecessary suppression.
#pragma warning disable CA1062 // Omitting null checks for these. Will be non-null when moving to #nullable enable.
using System;
using System.Globalization;
namespace Reaqtive
{
/// <summary>
/// Provides a set of methods to perform state management operations.
/// </summary>
public static class StateManager
{
/// <summary>
/// Loads the state of the specified stateful operator from the specified state reader.
/// </summary>
/// <param name="reader">Reader to read operator state from.</param>
/// <param name="node">Operator whose state to read.</param>
public static void LoadState(this IOperatorStateReader reader, IStatefulOperator node)
{
var version = LoadVersionInfo(reader, node);
if (version != null)
{
node.LoadState(reader, version);
}
else
{
reader.Reset();
}
}
/// <summary>
/// Loads the state of the specified stateful operator using a reader obtained from the specified state reader factory.
/// </summary>
/// <param name="factory">Factory to create an operator state reader to read operator state from.</param>
/// <param name="node">Operator whose state to read.</param>
public static void LoadState(this IOperatorStateReaderFactory factory, IStatefulOperator node)
{
using var reader = factory.Create(node);
LoadState(reader, node);
}
/// <summary>
/// Saves the state of the specified stateful operator to the specified state writer.
/// </summary>
/// <param name="writer">Writer to write operator state to.</param>
/// <param name="node">Operator whose state to write.</param>
public static void SaveState(this IOperatorStateWriter writer, IStatefulOperator node)
{
SaveVersionInfo(writer, node);
node.SaveState(writer, node.Version);
}
/// <summary>
/// Saves the state of the specified stateful operator using a writer obtained from the specified state writer factory.
/// </summary>
/// <param name="factory">Factory to create an operator state writer to write operator state to.</param>
/// <param name="node">Operator whose state to write.</param>
public static void SaveState(this IOperatorStateWriterFactory factory, IStatefulOperator node)
{
using var writer = factory.Create(node);
SaveState(writer, node);
}
/// <summary>
/// Loads version information from the specified state reader and asserts that the version name tag matches with the specified versioned artifact's.
/// </summary>
/// <param name="reader">Reader to read version state from.</param>
/// <param name="versioned">Version artifact whose version name tag to compart to the version information read from the reader.</param>
/// <returns>The version number read from the state reader.</returns>
/// <exception cref="InvalidOperationException">Thrown if the state reader read a version name tag that doesn't match the name tag in the specified version artifact.</exception>
public static Version LoadVersionInfo(this IOperatorStateReader reader, IVersioned versioned)
{
// The call to TryRead will only ever return false if the operator is transitioning.
// Otherwise, the constructor call for the reader would have thrown.
if (!reader.TryRead<string>(out string name) || (versioned is ITransitioningOperator && versioned.Name != name))
{
return null;
}
if (versioned.Name != name)
{
throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "Failed to restore state for artifact '{0}' with expected tag '{1}'. State tag is '{2}'.", versioned.ToString(), versioned.Name, name));
}
var major = reader.Read<int>();
var minor = reader.Read<int>();
var build = reader.Read<int>();
var revision = reader.Read<int>();
return Versioning.GetVersion(major, minor, build, revision);
}
/// <summary>
/// Saves the version information of the specified versioned artifact to the specified operator state writer.
/// </summary>
/// <param name="writer">Write to write version information to.</param>
/// <param name="versioned">Versioned artifact whose version information to write to the state writer.</param>
public static void SaveVersionInfo(this IOperatorStateWriter writer, IVersioned versioned)
{
writer.Write<string>(versioned.Name);
writer.Write<int>(versioned.Version.Major);
writer.Write<int>(versioned.Version.Minor);
writer.Write<int>(versioned.Version.Build);
writer.Write<int>(versioned.Version.Revision);
}
}
}
|
using System.Collections.Generic;
using MSFramework.Domain.Event;
namespace MSFramework.Domain
{
public interface IEventSourcingAggregate
{
long Version { get; }
IEnumerable<IAggregateEvent> GetAggregateEvents();
void ClearAggregateEvents();
}
} |
using MediatR;
using WorkTimer.MediatR.Models;
using WorkTimer.MediatR.Responses;
namespace WorkTimer.MediatR.Requests {
public class GetWorkDayDetailsRequest : UserContext, IRequest<GetWorkDayDetailsResponse> {
public GetWorkDayDetailsRequest(int workDayId) {
WorkDayId = workDayId;
}
public int WorkDayId { get; set; }
}
} |
using System;
using System.IO;
namespace Horizon.XmlRpc.Client
{
public class XmlRpcRequestEventArgs : EventArgs
{
private Guid _guid;
private long _request;
private Stream _requestStream;
public XmlRpcRequestEventArgs(Guid guid, long request, Stream requestStream)
{
_guid = guid;
_request = request;
_requestStream = requestStream;
}
public Guid ProxyID
{
get { return _guid; }
}
public long RequestNum
{
get { return _request; }
}
public Stream RequestStream
{
get { return _requestStream; }
}
}
}
|
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
namespace TTController.Plugin.ScheduleTrigger
{
public class ScheduleConverter : JsonConverter<Schedule>
{
private readonly string Separator = " -> ";
private readonly string[] Formats = new string[] { @"d\.hh\:mm", @"hh\:mm", @"ss" };
public override void WriteJson(JsonWriter writer, Schedule value, JsonSerializer serializer)
{
var array = new JArray();
foreach (var (Start, End) in value.Entries)
{
var format = Formats[0];
if (Start.TotalMinutes < 1 && End.TotalMinutes < 1)
format = Formats[2];
else if (Start.TotalDays < 1 && End.TotalDays < 1)
format = Formats[1];
var start = Start.ToString(format);
var end = End.ToString(format);
array.Add($"{start}{Separator}{end}");
}
serializer.Serialize(writer, array);
}
public override Schedule ReadJson(JsonReader reader, Type objectType, Schedule existingValue, bool hasExistingValue,
JsonSerializer serializer)
{
var entries = new List<(TimeSpan Start, TimeSpan End)>();
var array = JArray.Load(reader);
foreach(var s in array.Values<string>())
{
var parts = s.Split(new string[] { Separator }, StringSplitOptions.RemoveEmptyEntries);
if (parts.Length != 2)
continue;
if (TimeSpan.TryParseExact(parts[0], Formats, null, out var start)
&& TimeSpan.TryParseExact(parts[1], Formats, null, out var end))
{
if (start < TimeSpan.Zero || end < TimeSpan.Zero)
throw new JsonReaderException($"Invalid negative time: \"{s}\"");
if (start >= end)
throw new JsonReaderException($"Start time must be before End time: \"{s}\"");
if (start.Days > 7 || end.Days > 7)
throw new JsonReaderException($"Invalid day number: \"{s}\"");
entries.Add((start, end));
}
}
return new Schedule(entries);
}
}
}
|
using System.IO;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace BinarySerialization.Test.Misc
{
[TestClass]
public class IOExceptionTest
{
[TestMethod]
public void ShouldThrowIOExceptionNotInvalidOperationExceptionTest()
{
var stream = new UnreadableStream();
var serializer = new BinarySerializer();
Assert.ThrowsException<IOException>(() => serializer.Deserialize<int>(stream));
}
}
} |
namespace Ignore
{
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
/// <summary>
/// A holder for a regex and replacer function.
/// The function is invoked if the input matches the regex.
/// </summary>
public class Replacer
{
private readonly string name;
private readonly Regex regex;
private readonly MatchEvaluator matchEvaluator;
public Replacer(string name, Regex regex, Func<Match, string> replacer)
{
this.name = name;
this.regex = regex;
matchEvaluator = new MatchEvaluator(replacer);
}
public string Invoke(string pattern)
{
return regex.Replace(pattern, matchEvaluator);
}
public override string ToString()
{
return name;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Turret : MonoBehaviour {
public float duration;
Collider[] detections = null;
[SerializeField]
float maxDistance;
[SerializeField]
LayerMask layer;
public Transform firePoint;
public float cadence;
public float damage;
float shotTime;
bool isOn;
Armor targetArmor;
Life targetHp;
public GameObject shotEffect;
int currentObjetive;
public bool active;
private void Awake()
{
detections = new Collider[15];
Invoke("FinishTurret", duration);
}
private void OnEnable()
{
Invoke("FinishTurret", duration);
active = true;
}
private void OnTriggerEnter(Collider other)
{
PerimetralCheck();
}
private void Update()
{
if(isOn == true)
{
if (currentObjetive < detections.Length)
{
gameObject.transform.LookAt(detections[currentObjetive].gameObject.transform.position);
FireIntruder();
}
else
{
isOn = false;
}
}
}
private void OnTriggerExit(Collider other)
{
PerimetralCheck();
}
// Chekea todos los enemigos del area designada y los acomoda en un array
public void PerimetralCheck()
{
Physics.OverlapSphereNonAlloc(transform.position, maxDistance, detections ,layer);
if(detections.Length > 0)
{
isOn = true;
}
else
{
isOn = false;
}
}
// Dispara al enemigo en la primera posicion del array de deteccion;
public void FireIntruder()
{
RaycastHit hitInfo;
if (Physics.Raycast(firePoint.position, firePoint.transform.forward, out hitInfo, maxDistance, layer))
{
targetHp = hitInfo.collider.GetComponent<Life>();
targetArmor = hitInfo.collider.GetComponent<Armor>();
if (targetHp.dead == false)
{
if (Time.time - shotTime > cadence)
{
Instantiate(shotEffect, firePoint.transform.position, firePoint.transform.rotation);
targetArmor.ApplyArmor(damage);
shotTime = Time.time;
}
}
}
else
{
currentObjetive += 1;
}
}
// Cunado finalisa el efecto de la torreta
public void FinishTurret()
{
gameObject.SetActive(false);
currentObjetive = 0;
}
private void OnDisable()
{
active = false;
}
}
|
using LagoVista.Uas.Core.Models;
using System;
using System.Collections.Generic;
using System.Text;
namespace LagoVista.Uas.Core
{
public interface IUasMessageAdapter
{
void UpdateUas(IUas uas, UasMessage message);
}
}
|
using Loris.Common.Domain.Interfaces;
using System;
using System.Linq;
using System.Linq.Expressions;
namespace Loris.Common.EF.Repository
{
public interface IRepository<TEntityId> : IDisposable where TEntityId : class, IEntityIdBase
{
TEntityId Get(params object[] Keys);
TEntityId Get(Expression<Func<TEntityId, bool>> where);
TEntityId Add(TEntityId obj);
bool Update(TEntityId obj);
bool Delete(TEntityId obj);
bool Delete(params object[] Keys);
bool Delete(Expression<Func<TEntityId, bool>> where);
IQueryable<TEntityId> Query();
IQueryable<TEntityId> Query(params Expression<Func<TEntityId, object>>[] includes);
IQueryable<TEntityId> QueryFast();
IQueryable<TEntityId> QueryFast(params Expression<Func<TEntityId, object>>[] includes);
}
}
|
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;
namespace Luminosity.Console.UI
{
public class MessageFilter : MonoBehaviour
{
[SerializeField]
private Toggle m_toggle;
[SerializeField]
private Text m_messageCountText;
[SerializeField]
private LogLevel m_logLevel;
[SerializeField]
private int m_maxMessageCount;
private int m_messageCount = 0;
public event UnityAction Changed;
public LogLevel LogLevel { get { return m_logLevel; } }
public bool IsOn
{
get { return m_toggle.isOn; }
set { m_toggle.isOn = value; }
}
public int MessageCount
{
get { return m_messageCount; }
set
{
value = Mathf.Max(value, 0);
if(value != m_messageCount)
{
m_messageCount = value;
if(m_messageCount > m_maxMessageCount)
{
m_messageCountText.text = string.Format("{0}+", m_maxMessageCount);
}
else
{
m_messageCountText.text = m_messageCount.ToString();
}
}
}
}
private void Awake()
{
m_toggle.onValueChanged.AddListener(isOn =>
{
if(Changed != null)
{
Changed();
}
});
}
private void Reset()
{
m_toggle = GetComponentInChildren<Toggle>();
m_logLevel = LogLevel.Debug;
}
}
} |
using System;
using System.ComponentModel;
using System.Drawing;
using DevComponents.DotNetBar.SuperGrid;
using PostSharp.Patterns.Contracts;
namespace ThreatsManager.Extensions.Panels
{
public class GridCellSuperTooltipProvider : Component, DevComponents.DotNetBar.ISuperTooltipInfoProvider
{
private GridCell _cell;
public GridCellSuperTooltipProvider([NotNull] GridCell cell)
{
_cell = cell;
}
public void Show()
{
DisplayTooltip?.Invoke(this, new EventArgs());
}
public void Hide()
{
HideTooltip?.Invoke(this, new EventArgs());
}
#region ISuperTooltipInfoProvider Members
public System.Drawing.Rectangle ComponentRectangle
{
get
{
Rectangle r = _cell.Bounds;
r.Location = _cell.SuperGrid.PointToScreen(_cell.Bounds.Location);
return r;
}
}
public event EventHandler DisplayTooltip;
public event EventHandler HideTooltip;
#endregion
}
} |
using System;
namespace argumentos {
class tratarArgumentos {
private string usuario;
private string password;
tratarArgumentos (string[] args) {
if (args[0] == "") {
Console.WriteLine("É necessário fornecer argumentos de login");
} else {
for (int i = 0; i < args.Length; i++) {
switch (args[i]) {
case "user": usuario = args[i+1];
break;
case "password": password = args[i+1];
break;
}
}
}
}
}
} |
using System.ComponentModel.DataAnnotations;
using McMaster.Extensions.CommandLineUtils;
using McMaster.Extensions.CommandLineUtils.Validation;
using Solitons.Samples.Database.Models;
namespace Solitons.Samples.Database.Validators
{
public sealed class SuperuserSettingsValidator : IOptionValidator
{
public ValidationResult GetValidationResult(CommandOption option, ValidationContext context)
{
if (option.HasValue())
{
try
{
var settings = SuperuserSettingsGroup.Parse(option.Value());
return ValidationResult.Success;
}
catch (Exception e)
{
return new ValidationResult($"Invalid superuser settings string. {e.Message}");
}
}
return ValidationResult.Success;
}
}
}
|
using System;
namespace Tmds.Linux
{
public unsafe struct iovec
{
public void* iov_base { get; set; }
public size_t iov_len { get; set; }
}
} |
using System.Collections.Generic;
using System.Linq;
using Vanjaro.Core.Data.Entities;
namespace Vanjaro.Core
{
public static partial class Factories
{
public class BlockFactory
{
internal static void AddUpdate(CustomBlock CustomBlock)
{
if (string.IsNullOrEmpty(CustomBlock.Html))
{
CustomBlock.Html = "";
}
CustomBlock.Category = CustomBlock.Category.ToLower();
if (CustomBlock.ID > 0)
{
CustomBlock.Update();
}
else
{
CustomBlock.Insert();
}
CacheFactory.Clear(CacheFactory.Keys.CustomBlock);
}
internal static void Delete(int PortalID, string Guid)
{
foreach (CustomBlock item in GetAll(PortalID).Where(p => p.Guid.ToLower() == Guid.ToLower()).ToList())
{
CustomBlock.Delete("where ID=@0", item.ID);
}
CacheFactory.Clear(CacheFactory.Keys.CustomBlock);
}
internal static CustomBlock Get(int PortalID, string Name)
{
string CacheKey = CacheFactory.GetCacheKey(CacheFactory.Keys.CustomBlock, PortalID, Name);
CustomBlock CustomBlock = CacheFactory.Get(CacheKey);
if (CustomBlock == null)
{
CustomBlock = CustomBlock.Query("where PortalID=@0 and Name=@1", PortalID, Name).FirstOrDefault();
CacheFactory.Set(CacheKey, CustomBlock);
}
return CustomBlock;
}
internal static List<CustomBlock> GetAll(int PortalID)
{
string CacheKey = CacheFactory.GetCacheKey(CacheFactory.Keys.CustomBlock + "ALL", PortalID);
List<CustomBlock> Custom_Block = CacheFactory.Get(CacheKey);
if (Custom_Block == null)
{
Custom_Block = CustomBlock.Query("where PortalID=@0", PortalID).ToList();
CacheFactory.Set(CacheKey, Custom_Block);
}
return Custom_Block;
}
}
}
} |
namespace FluentTc.Locators
{
public interface IBranchHavingBuilderFactory
{
BranchHavingBuilder CreateBranchHavingBuilder();
}
public class BranchHavingBuilderFactory : IBranchHavingBuilderFactory
{
public BranchHavingBuilder CreateBranchHavingBuilder()
{
return new BranchHavingBuilder();
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Tso : ScriptableObject {
public int[] a;
public int b;
public Tsoo sso;
}
|
#if UNITY_ANDROID && USE_GETSOCIAL_UI
using System;
using System.Diagnostics.CodeAnalysis;
using GetSocialSdk.Core;
namespace GetSocialSdk.Ui
{
[SuppressMessage("ReSharper", "UnusedMember.Local")]
public class ViewStateListener : JavaInterfaceProxy
{
private Action _onOpen, _onClose;
public ViewStateListener(Action onOpen, Action onClose) : base("im.getsocial.sdk.ui.ViewStateListener")
{
_onOpen = onOpen;
_onClose = onClose;
}
void onOpen()
{
if (_onOpen != null)
{
_onOpen();
}
}
void onClose()
{
if (_onClose != null)
{
_onClose();
}
}
}
}
#endif |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TheSpace;
public class StarInformation : MonoBehaviour
{
public List<GameObject> _stageLightStars;
public List<GameObject> _stageHeavyStars;
private int _lastStage;
private GameObject _activeStar;
[SerializeField] private GameObject _pauseMenu;
private void Start()
{
_activeStar = GameObject.FindGameObjectWithTag("Star");
}
private void Update()
{
if(Input.GetKeyDown(KeyCode.Escape))
{
if(_pauseMenu.activeSelf == false)
_pauseMenu.SetActive(true);
else
_pauseMenu.SetActive(false);
}
}
public void Back()
{
_pauseMenu.SetActive(false);
}
public void Exit()
{
GameObject.Destroy(GameObject.Find("DebugPanel"));
UnityEngine.SceneManagement.SceneManager.LoadScene(0);
}
}
|
using System;
using System.Configuration;
namespace ConsoleStock
{
public class ConfigurationHelper
{
public static string GetURLString()
{
return ConfigurationManager.AppSettings["StockUrl"].ToString();
}
}
}
|
using AutoWrapper.Base;
namespace AutoWrapper
{
public class AutoWrapperOptions :OptionBase
{
public bool UseCustomSchema { get; set; } = false;
}
public class AutoWrapperOptions<T> :OptionBase
{
}
}
|
using Prism.Commands;
using Prism.Mvvm;
using RecordLibrary.Models;
using RecordLibrary.Views;
using System.Windows.Input;
namespace RecordLibrary.ViewModels
{
/// <summary>
/// Interaction logic for the new record form
/// </summary>
public class AddRecordFormViewModel : BindableBase
{
private RecordCollectionViewmModel _RecordCollection;
public AddRecordFormViewModel(RecordCollectionViewmModel recordCollection)
{
_RecordCollection = recordCollection;
}
#region Commands
#region Add Record Command
private ICommand _OkCommand;
public ICommand OkCommand
{
get
{
if (_OkCommand == null)
{
_OkCommand = new DelegateCommand<AddRecordForm>((AddRecordForm) => Ok(AddRecordForm),
(AddRecordForm) => true);
}
return _OkCommand;
}
}
private void Ok(AddRecordForm window)
{
_RecordCollection.AddRecord(new Record()
{
Artist = window.Artist.Text,
ReleaseName = window.ReleaseName.Text,
ReleaseYear = window.ReleaseYear.Text
});
window.Close();
}
#endregion Add Record Command
#region Remove Record Command
private ICommand _CancelCommand;
public ICommand CancelCommand
{
get
{
if (_CancelCommand == null)
{
_CancelCommand = new DelegateCommand<AddRecordForm>((AddRecordForm) => Cancel(AddRecordForm),
(AddRecordForm) => true);
}
return _CancelCommand;
}
}
private void Cancel(AddRecordForm window)
{
window.Close();
}
#endregion Remove Record Command
#endregion Commands
}
} |
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using EPlast.BLL.DTO.City;
using EPlast.BLL.DTO.UserProfiles;
using EPlast.BLL.Interfaces.UserProfiles;
using EPlast.BLL.Services.Interfaces;
using EPlast.DataAccess.Entities;
using EPlast.DataAccess.Entities.UserEntities;
using EPlast.Resources;
using EPlast.WebApi.Controllers;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Routing;
using Moq;
using NUnit.Framework;
namespace EPlast.Tests.Controllers
{
internal class UserRenewalControllerTests
{
private Mock<IUserRenewalService> _mockUserRenewalService;
private Mock<IUserManagerService> _mockUserManagerService;
private Mock<HttpContext> _mockHttpContext = new Mock<HttpContext>();
private Mock<UserManager<User>> _mockUserManager;
private UserRenewalController _userRenewalController;
private ControllerContext _context;
[SetUp]
public void SetUp()
{
_mockUserRenewalService = new Mock<IUserRenewalService>();
_mockUserManagerService = new Mock<IUserManagerService>();
var mockUser = new Mock<IUserStore<User>>();
_mockUserManager =
new Mock<UserManager<User>>(mockUser.Object, null, null, null, null, null, null, null, null);
_mockHttpContext = new Mock<HttpContext>();
_mockHttpContext
.Setup(u => u.User.IsInRole(Roles.AdminAndCityHeadAndCityHeadDeputy))
.Returns(true);
_userRenewalController = new UserRenewalController(
_mockUserRenewalService.Object,
_mockUserManager.Object);
_context = new ControllerContext(
new ActionContext(
_mockHttpContext.Object, new RouteData(),
new ControllerActionDescriptor()));
}
[Test]
public void GetUserRenewalsForTable_ReturnsOkObjectResult()
{
//Arrange
_mockUserRenewalService
.Setup(r => r.GetUserRenewalsTableObject(It.IsAny<string>(),
It.IsAny<int>(), It.IsAny<int>()))
.Returns(new List<UserRenewalsTableObject>());
//Act
var result =
_userRenewalController.GetUserRenewalsForTable(It.IsAny<string>(),
It.IsAny<int>(), It.IsAny<int>());
var resultValue = (result as OkObjectResult)?.Value;
//Assert
_mockUserRenewalService.Verify();
Assert.IsNotNull(result);
Assert.IsInstanceOf<OkObjectResult>(result);
Assert.IsNotNull(resultValue);
Assert.IsInstanceOf<List<UserRenewalsTableObject>>(resultValue);
}
[Test]
public async Task FormerCheck_ReturnsOkObjectResult()
{
//Arrange
_mockUserManager
.Setup(u => u.FindByEmailAsync(It.IsAny<string>()))
.ReturnsAsync(new User());
_mockUserManager
.Setup(u => u.IsInRoleAsync(It.IsAny<User>(), It.IsAny<string>()))
.ReturnsAsync(true);
//Act
var result = await _userRenewalController.FormerCheck(It.IsAny<string>());
var resultValue = (result as OkObjectResult).Value;
//Assert
_mockUserManagerService.Verify();
Assert.IsNotNull(result);
Assert.IsInstanceOf<OkObjectResult>(result);
Assert.IsNotNull(resultValue);
Assert.IsInstanceOf<string>(resultValue);
}
[Test]
public async Task FormerCheck_ReturnsBadRequestResult()
{
//Arrange
_mockUserManager
.Setup(u => u.FindByEmailAsync(It.IsAny<string>()))
.ReturnsAsync(new User());
_mockUserManager
.Setup(u => u.IsInRoleAsync(It.IsAny<User>(), It.IsAny<string>()))
.ReturnsAsync(false);
//Act
var result = await _userRenewalController.FormerCheck(It.IsAny<string>());
//Assert
_mockUserManagerService.Verify();
Assert.IsNotNull(result);
Assert.IsInstanceOf<BadRequestObjectResult>(result);
}
[Test]
public async Task AddUserRenewal_ReturnsBadRequestResult()
{
//Arrange
_userRenewalController.ModelState.AddModelError("Bad request", "Cannot create renewal");
_mockUserRenewalService
.Setup(r => r.AddUserRenewalAsync(It.IsAny<UserRenewalDTO>()));
//Act
var result = await _userRenewalController.AddUserRenewalAsync(It.IsAny<UserRenewalDTO>());
//Assert
_mockUserRenewalService.Verify();
Assert.IsNotNull(result);
Assert.IsInstanceOf<BadRequestObjectResult>(result);
}
[Test]
public async Task AddUserRenewal_ThrowsException_ReturnsNotFound()
{
//Arrange
_mockUserRenewalService
.Setup(r => r.AddUserRenewalAsync(It.IsAny<UserRenewalDTO>()))
.Throws(new Exception());
_mockUserRenewalService
.Setup(r => r.IsValidUserRenewalAsync(It.IsAny<UserRenewalDTO>()))
.ReturnsAsync(true);
//Act
var result = await _userRenewalController.AddUserRenewalAsync(new UserRenewalDTO());
//Assert
Assert.IsInstanceOf<NotFoundResult>(result);
}
[Test]
public async Task AddUserRenewal_ReturnsNoContentResult()
{
//Arrange
_mockUserRenewalService
.Setup(r => r.AddUserRenewalAsync(It.IsAny<UserRenewalDTO>()));
_mockUserRenewalService
.Setup(r => r.IsValidUserRenewalAsync(It.IsAny<UserRenewalDTO>()))
.ReturnsAsync(true);
//Act
var result = await _userRenewalController.AddUserRenewalAsync(It.IsAny<UserRenewalDTO>());
//Assert
_mockUserRenewalService.Verify();
Assert.IsNotNull(result);
Assert.IsInstanceOf<NoContentResult>(result);
}
[Test]
public async Task RenewUser_ReturnsOkObjectResult()
{
//Arrange
_mockUserManager
.Setup(u => u.FindByIdAsync(It.IsAny<string>()))
.ReturnsAsync(new User());
_mockUserManager
.Setup(u => u.IsInRoleAsync(It.IsAny<User>(), It.IsAny<string>()))
.ReturnsAsync(true);
_mockUserRenewalService
.Setup(r => r.IsValidAdminAsync(It.IsAny<User>(), It.IsAny<int>()))
.ReturnsAsync(true);
_mockUserRenewalService
.Setup(r => r.RenewFormerMemberUserAsync(It.IsAny<UserRenewalDTO>()))
.ReturnsAsync(new CityMembersDTO());
_mockUserRenewalService
.Setup(r => r.SendRenewalConfirmationEmailAsync(It.IsAny<string>(), It.IsAny<int>()));
//Act
var result = await _userRenewalController.RenewUser(userRenewalDTO);
var resultValue = (result as OkObjectResult).Value;
//Assert
_mockUserRenewalService.Verify();
Assert.IsNotNull(result);
Assert.IsInstanceOf<OkObjectResult>(result);
Assert.IsNotNull(resultValue);
Assert.IsInstanceOf<CityMembersDTO>(resultValue);
}
[Test]
public async Task RenewUser_ReturnsBadRequestResult()
{
//Arrange
_userRenewalController.ModelState.AddModelError("Model", "Unable to apply the renewal");
_mockUserManager
.Setup(u => u.FindByIdAsync(It.IsAny<string>()))
.ReturnsAsync(new User());
_mockUserManager
.Setup(u => u.IsInRoleAsync(It.IsAny<User>(), It.IsAny<string>()))
.ReturnsAsync(true);
_mockUserRenewalService
.Setup(r => r.IsValidAdminAsync(It.IsAny<User>(), It.IsAny<int>()))
.ReturnsAsync(true);
_mockUserRenewalService
.Setup(r => r.RenewFormerMemberUserAsync(It.IsAny<UserRenewalDTO>()))
.ReturnsAsync(new CityMembersDTO());
_mockUserRenewalService
.Setup(r => r.SendRenewalConfirmationEmailAsync(It.IsAny<string>(), It.IsAny<int>()));
//Act
var result = await _userRenewalController.RenewUser(userRenewalDTO);
//Assert
_mockUserRenewalService.Verify();
Assert.IsNotNull(result);
Assert.IsInstanceOf<BadRequestObjectResult>(result);
}
[Test]
public async Task RenewUser_ReturnsBadRequestResultWrongTargetRole()
{
//Arrange
_mockUserManager
.Setup(u => u.FindByIdAsync(It.IsAny<string>()))
.ReturnsAsync(new User());
_mockUserManager
.Setup(u => u.IsInRoleAsync(It.IsAny<User>(), It.IsAny<string>()))
.ReturnsAsync(false);
_mockUserRenewalService
.Setup(r => r.IsValidAdminAsync(It.IsAny<User>(), It.IsAny<int>()))
.ReturnsAsync(true);
_mockUserRenewalService
.Setup(r => r.RenewFormerMemberUserAsync(It.IsAny<UserRenewalDTO>()))
.ReturnsAsync(new CityMembersDTO());
_mockUserRenewalService
.Setup(r => r.SendRenewalConfirmationEmailAsync(It.IsAny<string>(), It.IsAny<int>()));
//Act
var result = await _userRenewalController.RenewUser(userRenewalDTO);
//Assert
_mockUserRenewalService.Verify();
Assert.IsNotNull(result);
Assert.IsInstanceOf<BadRequestObjectResult>(result);
}
[Test]
public async Task RenewUser_ReturnsBadRequestResultUnfortunateRenewal()
{
//Arrange
_mockUserManager
.Setup(u => u.FindByIdAsync(It.IsAny<string>()))
.ReturnsAsync(new User());
_mockUserManager
.Setup(u => u.IsInRoleAsync(It.IsAny<User>(), It.IsAny<string>()))
.ReturnsAsync(true);
_mockUserRenewalService
.Setup(r => r.IsValidAdminAsync(It.IsAny<User>(), It.IsAny<int>()))
.ReturnsAsync(true);
_mockUserRenewalService
.Setup(r => r.RenewFormerMemberUserAsync(It.IsAny<UserRenewalDTO>()))
.ThrowsAsync(new ArgumentException());
_mockUserRenewalService
.Setup(r => r.SendRenewalConfirmationEmailAsync(It.IsAny<string>(), It.IsAny<int>()));
//Act
var result = await _userRenewalController.RenewUser(userRenewalDTO);
//Assert
_mockUserRenewalService.Verify();
Assert.IsNotNull(result);
Assert.IsInstanceOf<BadRequestObjectResult>(result);
}
[Test]
public async Task RenewUser_ReturnsUnauthorized()
{
//Arrange
_mockUserManager
.Setup(u => u.FindByIdAsync(It.IsAny<string>()))
.ReturnsAsync(new User());
_mockUserManager
.Setup(u => u.IsInRoleAsync(It.IsAny<User>(), It.IsAny<string>()))
.ReturnsAsync(true);
_mockUserRenewalService
.Setup(r => r.IsValidAdminAsync(It.IsAny<User>(), It.IsAny<int>()))
.ReturnsAsync(false);
_mockUserRenewalService
.Setup(r => r.RenewFormerMemberUserAsync(It.IsAny<UserRenewalDTO>()))
.ReturnsAsync(new CityMembersDTO());
_mockUserRenewalService
.Setup(r => r.SendRenewalConfirmationEmailAsync(It.IsAny<string>(), It.IsAny<int>()));
//Act
var result = await _userRenewalController.RenewUser(userRenewalDTO);
//Assert
_mockUserRenewalService.Verify();
Assert.IsNotNull(result);
Assert.IsInstanceOf<UnauthorizedResult>(result);
}
private readonly UserRenewalDTO userRenewalDTO = new UserRenewalDTO
{
Id = 1,
CityId = 13,
Approved = true,
UserId = "660c4f26-760d-46f9-b780-5b5c7c153b25",
RequestDate = new DateTime()
};
}
}
|
namespace Headless
{
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using Headless.Properties;
/// <summary>
/// The <see cref="ComponentsLocationValidator" />
/// class uses <see cref="Uri.GetComponents" /> to validate <see cref="Uri" /> locations.
/// </summary>
public abstract class ComponentsLocationValidator : ILocationValidator
{
/// <inheritdoc />
/// <exception cref="System.ArgumentNullException">
/// The <paramref name="expectedLocation" /> parameter is <c>null</c>.
/// </exception>
/// <exception cref="System.ArgumentException">
/// The <paramref name="expectedLocation" /> is a relative location where an absolute location is required.
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// The <paramref name="location" /> parameter is <c>null</c>.
/// </exception>
/// <exception cref="System.ArgumentException">
/// The <paramref name="location" /> is a relative location where an absolute location is required.
/// </exception>
public virtual bool Matches(Uri location, Uri expectedLocation)
{
ValidateParameters(expectedLocation, location);
var compareWith = VerificationParts;
StringComparison comparisonType;
if (CaseSensitive)
{
comparisonType = StringComparison.Ordinal;
}
else
{
comparisonType = StringComparison.OrdinalIgnoreCase;
}
var compareValue = string.Compare(
expectedLocation.GetComponents(compareWith, CompareFormat),
location.GetComponents(compareWith, CompareFormat),
comparisonType);
if (compareValue == 0)
{
return true;
}
return false;
}
/// <inheritdoc />
/// <exception cref="NotImplementedException">This method is not implemented.</exception>
public virtual bool Matches(Uri location, IEnumerable<Regex> matchingExpressions)
{
throw new NotImplementedException();
}
/// <summary>
/// Validates that appropriate parameters are supplied.
/// </summary>
/// <param name="expectedLocation">
/// The expected location.
/// </param>
/// <param name="actualLocation">
/// The actual location.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// The <paramref name="expectedLocation"/> parameter is <c>null</c>.
/// </exception>
/// <exception cref="System.ArgumentException">
/// The <paramref name="expectedLocation"/> is a relative location where an absolute location is required.
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// The <paramref name="actualLocation"/> parameter is <c>null</c>.
/// </exception>
/// <exception cref="System.ArgumentException">
/// The <paramref name="actualLocation"/> is a relative location where an absolute location is required.
/// </exception>
protected static void ValidateParameters(Uri expectedLocation, Uri actualLocation)
{
if (actualLocation == null)
{
throw new ArgumentNullException("actualLocation");
}
if (actualLocation.IsAbsoluteUri == false)
{
throw new ArgumentException(Resources.Uri_LocationMustBeAbsolute, "actualLocation");
}
if (expectedLocation == null)
{
throw new ArgumentNullException("expectedLocation");
}
if (expectedLocation.IsAbsoluteUri == false)
{
throw new ArgumentException(Resources.Uri_LocationMustBeAbsolute, "expectedLocation");
}
}
/// <summary>
/// Gets or sets a value indicating whether location matching is case sensitive.
/// </summary>
/// <value>
/// <c>true</c> if location matching is case sensitive; otherwise, <c>false</c>.
/// </value>
public bool CaseSensitive
{
get;
set;
}
/// <summary>
/// Gets or sets the compare format.
/// </summary>
/// <value>
/// The compare format.
/// </value>
public UriFormat CompareFormat
{
get;
set;
}
/// <inheritdoc />
public virtual LocationValidationType ValidationType
{
get
{
return LocationValidationType.UriOnly;
}
}
/// <summary>
/// Gets or sets the verification parts.
/// </summary>
/// <value>
/// The verification parts.
/// </value>
protected UriComponents VerificationParts
{
get;
set;
}
}
} |
#nullable enable
namespace Snittlistan.Web.Models
{
public class InviteUserEmail : EmailBase
{
public InviteUserEmail(string to, string subject, string activationUri)
: base("InviteUser", to, subject)
{
ActivationUri = activationUri;
}
public string ActivationUri { get; }
}
}
|
/// <summary>
/// 作者:刘泽华
/// 时间:2018年5月29日11点29分
/// </summary>
namespace KilyCore.Extension.ApplicationService.IocManager
{
public interface IAutoFacManager
{
void CompleteBuiler();
T Resolve<T>();
}
} |
using System;
namespace NetModular.Lib.Data.Abstractions.Attributes
{
/// <summary>
/// 表名称,指定实体类在数据库中对应的表名称
/// </summary>
[AttributeUsage(AttributeTargets.Class, Inherited = false)]
public class TableAttribute : Attribute
{
/// <summary>
/// 表名称
/// </summary>
public string Name { get; set; }
/// <summary>
/// 是否多租户
/// </summary>
public bool IsTenant { get; set; }
/// <summary>
/// 租户编号对应数据库列名称
/// </summary>
public string TenantIdColumnName { get; set; }
/// <summary>
/// 指定实体类在数据库中对应的表名称
/// </summary>
/// <param name="tableName">表名</param>
public TableAttribute(string tableName)
{
Name = tableName;
}
/// <summary>
/// 指定实体类在数据库中对应的表名称
/// </summary>
/// <param name="tableName">表名</param>
/// <param name="isTenant">是否多租户</param>
/// <param name="tenantIdColumnName">租户编号对应数据库列名称</param>
public TableAttribute(string tableName, bool isTenant = false, string tenantIdColumnName = "TenantId")
{
Name = tableName;
IsTenant = isTenant;
TenantIdColumnName = tenantIdColumnName.NotNull() ? tenantIdColumnName : "TenantId";
}
}
}
|
// Loosely coupled MVC solution structure (https://github.com/raste/LooselyCoupledStructure)
// Copyright (c) 2015 Georgi Kolev.
// Licensed under Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0).
using System.Collections.Generic;
using System.Linq;
using BL.Entities;
using BL.Services.Accounts;
namespace Web.Models.Home
{
public class HomeAccountsPartialViewModel
{
public List<User> Users { get; private set; }
public HomeAccountsPartialViewModel(IQueryable<Account> accounts)
{
Users = new List<User>();
var dbUsers = accounts
.Select(a => new { a.Username, a.Role })
.ToList();
if (dbUsers == null || dbUsers.Count == 0)
{
return;
}
Users = dbUsers
.Select(a => new User() { Username = a.Username, Role = a.Role })
.ToList();
}
public class User
{
public string Username { get; set; }
public Role Role { get; set; }
}
}
} |
using Unity.VisualScripting;
using UnityEngine;
namespace DNode {
public class DTexLevels : DTexUnaryPreserveAlphaBlitUnit {
private int _Blacks = Shader.PropertyToID("_Blacks");
private int _Shadows = Shader.PropertyToID("_Shadows");
private int _Mids = Shader.PropertyToID("_Mids");
private int _Highlights = Shader.PropertyToID("_Highlights");
private int _Whites = Shader.PropertyToID("_Whites");
[DoNotSerialize] public ValueInput Blacks;
[DoNotSerialize] public ValueInput Shadows;
[DoNotSerialize] public ValueInput Mids;
[DoNotSerialize] public ValueInput Highlights;
[DoNotSerialize] public ValueInput Whites;
protected override void Definition() {
base.Definition();
Blacks = ValueInput<float>("Blacks", 0.0f);
Shadows = ValueInput<float>("Shadows", 0.0f);
Mids = ValueInput<float>("Mids", 0.0f);
Highlights = ValueInput<float>("Highlights", 0.0f);
Whites = ValueInput<float>("Whites", 0.0f);
}
protected override string ShaderPath => "Hidden/TexLevels";
protected override void SetMaterialProperties(Flow flow, Material material) {
base.SetMaterialProperties(flow, material);
material.SetFloat(_Blacks, flow.GetValue<float>(Blacks));
material.SetFloat(_Shadows, flow.GetValue<float>(Shadows));
material.SetFloat(_Mids, flow.GetValue<float>(Mids));
material.SetFloat(_Highlights, flow.GetValue<float>(Highlights));
material.SetFloat(_Whites, flow.GetValue<float>(Whites));
}
}
}
|
using System;
using Microsoft.Azure.ServiceBus;
namespace SqlTransactionalOutbox.AzureServiceBus.Receiving
{
public class AzureServiceBusReceivingOptions
{
/// <summary>
///
/// </summary>
public bool FifoEnforcedReceivingEnabled { get; set; } = false;
public TimeSpan MaxAutoRenewDuration { get; set; } = TimeSpan.FromMinutes(5);
public RetryPolicy RetryPolicy { get; set; } = RetryPolicy.Default;
public int PrefetchCount { get; set; } = 0;
public int MaxConcurrentReceiversOrSessions { get; set; } = 1;
public TimeSpan? ClientOperationTimeout { get; set; } = null;
public TimeSpan? ConnectionIdleTimeout { get; set; } = null;
public bool ReleaseSessionWhenNoHandlerIsProvided { get; set; } = true;
/// <summary>
/// An hook/callback for handling informational logging.
/// </summary>
public Action<string> LogDebugCallback { get; set; } = null;
/// <summary>
/// A hook/callback for handling error/exception logging.
/// </summary>
public Action<Exception> LogErrorCallback { get; set; } = null;
}
}
|
using System;
using System.Collections.ObjectModel;
using System.Collections.Generic;
using System.Linq;
namespace Umbraco.Core.Models
{
/// <summary>
/// A macro's property collection
/// </summary>
public class MacroPropertyCollection : ObservableDictionary<string, IMacroProperty>
{
public MacroPropertyCollection()
: base(property => property.Alias)
{
}
}
} |
namespace NWrath.Logging
{
public interface IRollingFileAction
{
void Execute(RollingFileContext ctx);
}
} |
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Test : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
NetManager.AddEventListener(NetManager.NetEvent.ConnectSucc, OnConnectSucc);
NetManager.AddEventListener(NetManager.NetEvent.ConnectFail, OnConnectFail);
NetManager.AddEventListener(NetManager.NetEvent.Close, OnConnectClose);
NetManager.AddMsgListener("MsgMove", OnMsgMove);
}
private void OnMsgMove(MsgBase msgBase)
{
MsgMove msgMove = (MsgMove)msgBase;
Debug.Log($"OnMsgMove msg.x = {msgMove.x}");
Debug.Log($"OnMsgMove msg.y = {msgMove.y}");
Debug.Log($"OnMsgMove msg.z = {msgMove.z}");
}
private void OnConnectClose(string err)
{
Debug.Log("OnConnectClose");
}
private void OnConnectFail(string err)
{
Debug.Log($"OnConnectFail: {err}");
}
private void OnConnectSucc(string err)
{
Debug.Log("OnConnectSucc");
}
// Update is called once per frame
void Update()
{
NetManager.Update();
}
public void OnConnectClick()
{
NetManager.Connect("127.0.0.1", 8888);
}
public void OnCloseClick()
{
NetManager.Close();
}
public void OnMoveClick()
{
MsgMove msg = new MsgMove();
msg.x = 120;
msg.y = 123;
msg.z = -6;
NetManager.Send(msg);
}
}
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using Docker.DotNet;
using Microsoft.Azure.Management.ContainerInstance.Fluent;
using Microsoft.Azure.Management.ContainerInstance.Fluent.Models;
using Microsoft.Azure.Management.ContainerRegistry.Fluent;
using Microsoft.Azure.Management.ContainerRegistry.Fluent.Models;
using Microsoft.Azure.Management.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent.Authentication;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core;
using Microsoft.Azure.Management.Samples.Common;
using System;
namespace ManageWithAzureContainerRegistry
{
public class Program
{
private static readonly Region region = Region.USEast;
/**
* Azure Container Instance sample for managing container groups with private image repositories.
* - Create an Azure Container Registry to be used for holding the Docker images
* - If a local Docker engine cannot be found, create a Linux virtual machine that will host a Docker engine
* to be used for this sample
* - Use Docker DotNet to create a Docker client that will push an image to Azure Container Registry
* - Create a new container group with one container instance from the image that was pushed in the registry
*/
public static void RunSample(IAzure azure)
{
string rgName = SdkContext.RandomResourceName("rgACI", 15);
string acrName = SdkContext.RandomResourceName("acr", 20);
string aciName = SdkContext.RandomResourceName("acisample", 20);
string saName = SdkContext.RandomResourceName("sa", 20);
string dockerImageName = "microsoft/aci-helloworld";
string dockerImageTag = "latest";
string dockerContainerName = "sample-hello";
try
{
//=============================================================
// Create an Azure Container Registry to store and manage private Docker container images
Utilities.Log("Creating an Azure Container Registry");
IRegistry azureRegistry = azure.ContainerRegistries.Define(acrName)
.WithRegion(region)
.WithNewResourceGroup(rgName)
.WithBasicSku()
.WithRegistryNameAsAdminUser()
.Create();
Utilities.Print(azureRegistry);
var acrCredentials = azureRegistry.GetCredentials();
//=============================================================
// Create a Docker client that will be used to push/pull images to/from the Azure Container Registry
using (DockerClient dockerClient = DockerUtils.CreateDockerClient(azure, rgName, region))
{
var pullImgResult = dockerClient.Images.PullImage(
new Docker.DotNet.Models.ImagesPullParameters()
{
Parent = dockerImageName,
Tag = dockerImageTag
},
new Docker.DotNet.Models.AuthConfig());
Utilities.Log("List Docker images for: " + dockerClient.Configuration.EndpointBaseUri.AbsoluteUri);
var listImages = dockerClient.Images.ListImages(
new Docker.DotNet.Models.ImagesListParameters()
{
All = true
});
foreach (var img in listImages)
{
Utilities.Log("\tFound image " + img.RepoTags[0] + " (id:" + img.ID + ")");
}
var createContainerResult = dockerClient.Containers.CreateContainer(
new Docker.DotNet.Models.CreateContainerParameters()
{
Name = dockerContainerName,
Image = dockerImageName + ":" + dockerImageTag
});
Utilities.Log("List Docker containers for: " + dockerClient.Configuration.EndpointBaseUri.AbsoluteUri);
var listContainers = dockerClient.Containers.ListContainers(
new Docker.DotNet.Models.ContainersListParameters()
{
All = true
});
foreach (var container in listContainers)
{
Utilities.Log("\tFound container " + container.Names[0] + " (id:" + container.ID + ")");
}
//=============================================================
// Commit the new container
string privateRepoUrl = azureRegistry.LoginServerUrl + "/" + dockerContainerName;
Utilities.Log("Commiting image at: " + privateRepoUrl);
var commitContainerResult = dockerClient.Miscellaneous.CommitContainerChanges(
new Docker.DotNet.Models.CommitContainerChangesParameters()
{
ContainerID = dockerContainerName,
RepositoryName = privateRepoUrl,
Tag = dockerImageTag
});
//=============================================================
// Push the new Docker image to the Azure Container Registry
var pushImageResult = dockerClient.Images.PushImage(privateRepoUrl,
new Docker.DotNet.Models.ImagePushParameters()
{
ImageID = privateRepoUrl,
Tag = dockerImageTag
},
new Docker.DotNet.Models.AuthConfig()
{
Username = acrCredentials.Username,
Password = acrCredentials.AccessKeys[AccessKeyType.Primary],
ServerAddress = azureRegistry.LoginServerUrl
});
//=============================================================
// Create a container group with one container instance of default CPU core count and memory size
// using public Docker image "microsoft/aci-helloworld" and mounts a new file share as read/write
// shared container volume.
IContainerGroup containerGroup = azure.ContainerGroups.Define(aciName)
.WithRegion(region)
.WithNewResourceGroup(rgName)
.WithLinux()
.WithPrivateImageRegistry(azureRegistry.LoginServerUrl, acrCredentials.Username, acrCredentials.AccessKeys[AccessKeyType.Primary])
.WithoutVolume()
.DefineContainerInstance(aciName)
.WithImage(privateRepoUrl)
.WithExternalTcpPort(80)
.Attach()
.Create();
Utilities.Print(containerGroup);
//=============================================================
// Check the container instance logs
SdkContext.DelayProvider.Delay(15000);
string logContent = containerGroup.GetLogContent(aciName);
Utilities.Log($"Logs for container instance: {aciName}\n{logContent}");
}
}
finally
{
try
{
Utilities.Log("Deleting Resource Group: " + rgName);
azure.ResourceGroups.BeginDeleteByName(rgName);
Utilities.Log("Deleted Resource Group: " + rgName);
}
catch (Exception)
{
Utilities.Log("Did not create any resources in Azure. No clean up is necessary");
}
}
}
public static void Main(string[] args)
{
try
{
//=================================================================
// Authenticate
AzureCredentials credentials = SdkContext.AzureCredentialsFactory.FromFile(Environment.GetEnvironmentVariable("AZURE_AUTH_LOCATION"));
var azure = Azure
.Configure()
.WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
.Authenticate(credentials)
.WithDefaultSubscription();
// Print selected subscription
Utilities.Log("Selected subscription: " + azure.SubscriptionId);
RunSample(azure);
}
catch (Exception ex)
{
Utilities.Log(ex);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
namespace KeyStroker.Logic.Hotkeys {
public class Hotkey
{
public Hotkey(Key key, ModifierKeys modifiers)
{
_key = key;
_modifiers = modifiers;
}
private Key _key;
private ModifierKeys _modifiers;
public uint GetKey()
{
return (uint)KeyInterop.VirtualKeyFromKey(_key);
}
public uint GetModifiers()
{
uint retval = 0x0;
if (_modifiers == ModifierKeys.Alt)
retval += (uint)HotkeyModifier.ALT;
if (_modifiers == ModifierKeys.Control)
retval += (uint)HotkeyModifier.CTRL;
if (_modifiers == ModifierKeys.Shift)
retval += (uint)ModifierKeys.Shift;
if (_modifiers == ModifierKeys.Windows)
retval += (uint)HotkeyModifier.WIN;
return retval;
}
public override int GetHashCode()
{
return (int)GetKey() * (int)GetModifiers();
}
}
}
|
/*
Copyright © Bryan Apellanes 2015
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.Common;
using Bam.Net.Data;
using System.Data;
using Bam.Net.Configuration;
namespace Bam.Net.Javascript
{
[Proxy("sql")]
public abstract partial class JavaScriptSqlProvider : IConfigurable
{
public JavaScriptSqlProvider() { }
public Database Database
{
get;
set;
}
bool _initialized;
public void EnsureInitialized()
{
if(!_initialized)
{
_initialized = true;
Initialize();
}
}
/// <summary>
/// Initialize the database by instantiating it and setting the connection string.
/// </summary>
protected abstract void Initialize();
#region IConfigurable Members
[Exclude]
public virtual void Configure(IConfigurer configurer)
{
configurer.Configure(this);
this.CheckRequiredProperties();
}
[Exclude]
public virtual void Configure(object configuration)
{
this.CopyProperties(configuration);
this.CheckRequiredProperties();
}
#endregion
#region IHasRequiredProperties Members
public abstract string[] RequiredProperties { get; }
#endregion
}
}
|
using System;
using System.Collections.Generic;
using Fulcrum.Runtime;
using UnitTests.Queries.Location;
using UnitTests.Queries.Location.Additional;
using Xunit;
namespace UnitTests.Queries
{
public class QueryLocatorTests
{
[Fact]
public void Find_query_in_namespace()
{
var queryType = typeof(TestQuery);
var extractor = new QueryLocator();
extractor.AddQuerySource(queryType.Assembly, queryType.Namespace);
var locatedType = extractor.Find(queryType.Name, queryType.Namespace);
Assert.Equal(queryType, locatedType);
}
[Fact]
public void List_all_queries_in_assembly_via_multiple_namespaces()
{
var firstQueryType = typeof(TestQuery);
var secondQueryType = typeof(LocateThisQuery);
var extractor = new QueryLocator(firstQueryType.Assembly, firstQueryType.Namespace);
extractor.AddQuerySource(secondQueryType.Assembly, secondQueryType.Namespace);
var queries = extractor.ListAllQueryObjects();
var expectedQueries = new List<Type>()
{
typeof(TestQuery),
typeof(LocateThisQuery),
};
Assert.Equal(expectedQueries, queries);
}
[Fact]
public void List_all_queries_in_assembly_via_namespace_and_constructor()
{
var queryType = typeof(LocateThisQuery);
var extractor = new QueryLocator(queryType.Assembly, queryType.Namespace);
var queries = extractor.ListAllQueryObjects();
var expectedQueries = new List<Type>()
{
typeof(LocateThisQuery),
};
Assert.Equal(expectedQueries, queries);
}
[Fact]
public void List_all_queries_in_assembly_via_namespace_and_method()
{
var queryType = typeof(LocateThisQuery);
var extractor = new QueryLocator();
extractor.AddQuerySource(queryType.Assembly, queryType.Namespace);
var commands = extractor.ListAllQueryObjects();
var expectedCommands = new List<Type>()
{
typeof(LocateThisQuery),
};
Assert.Equal(expectedCommands, commands);
}
}
}
|
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
namespace OAHub.Passport.Services
{
public interface IJwtTokenService
{
string GenerateToken(string appid, string appsecret, string forUserId);
JwtSecurityToken ValidateToken(string encodedToken, string appId);
}
}
|
using System.Text.Json.Serialization;
namespace ldam.co.za.lib.Lightroom;
[JsonSerializable(typeof(AlbumAssetResponse))]
[JsonSerializable(typeof(AlbumsResponse))]
[JsonSerializable(typeof(AssetResponse))]
[JsonSerializable(typeof(CatalogResponse))]
[JsonSourceGenerationOptions(
PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase,
GenerationMode = JsonSourceGenerationMode.Metadata)]
public partial class LightroomSerializerContext : JsonSerializerContext
{
} |
// <copyright file="ServiceCollectionAppMetricsHealthCheckPublishingExtensions.cs" company="App Metrics Contributors">
// Copyright (c) App Metrics Contributors. All rights reserved.
// </copyright>
using System;
using App.Metrics.Extensions.Collectors;
using App.Metrics.Extensions.Collectors.HostedServices;
// ReSharper disable CheckNamespace
namespace Microsoft.Extensions.DependencyInjection
// ReSharper restore CheckNamespace
{
public static class ServiceCollectionAppMetricsCollectorsExtensions
{
/// <summary>
/// Adds a hosted service which collects system metrics such as CPU usage and memory working set.
/// </summary>
public static IServiceCollection AddAppMetricsSystemMetricsCollector(
this IServiceCollection services,
Action<MetricsSystemUsageCollectorOptions> optionsSetup = null)
{
var options = new MetricsSystemUsageCollectorOptions();
optionsSetup?.Invoke(options);
services.AddSingleton(options);
return services.AddHostedService<SystemUsageCollectorHostedService>();
}
/// <summary>
/// Adds a hosted service which collects GC events using the "Microsoft-Windows-DotNETRuntime" EventSource.
/// </summary>
public static IServiceCollection AddAppMetricsGcEventsMetricsCollector(
this IServiceCollection services,
Action<MetricsGcEventsCollectorOptions> optionsSetup = null)
{
var options = new MetricsGcEventsCollectorOptions();
optionsSetup?.Invoke(options);
services.AddSingleton(options);
return services.AddHostedService<GcEventsCollectorHostedService>();
}
/// <summary>
/// Adds hosted services to collect system usage and gc event metrics
/// </summary>
public static IServiceCollection AddAppMetricsCollectors(
this IServiceCollection services,
Action<MetricsSystemUsageCollectorOptions> systemUsageOptionsSetup = null,
Action<MetricsGcEventsCollectorOptions> gcEventsOptionsSetup = null)
{
services.AddAppMetricsSystemMetricsCollector(systemUsageOptionsSetup);
services.AddAppMetricsGcEventsMetricsCollector(gcEventsOptionsSetup);
return services;
}
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace MizeUP.Models
{
public class LevelModel
{
[Key]
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual char LevelType { get; set; }
public virtual InstitutionModel Institution { get; set; }
public virtual IList<StudentModel> Students { get; set; }
}
} |
using Stencil.Domain;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Stencil.Primary.Business.Direct
{
public partial interface IProductBusiness
{
IEnumerable<Product> GetAffectedProductsByTicketID(Guid ticket_id);
}
}
|
//-----------------------------------------------------------------------
// <copyright file="jet_recordlist.cs" company="Microsoft Corporation">
// Copyright (c) Microsoft Corporation.
// </copyright>
//-----------------------------------------------------------------------
namespace Microsoft.Isam.Esent.Interop
{
using System;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Runtime.InteropServices;
/// <summary>
/// The native version of the JET_RECORDLIST structure.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
[SuppressMessage(
"Microsoft.StyleCop.CSharp.NamingRules",
"SA1307:AccessibleFieldsMustBeginWithUpperCaseLetter",
Justification = "This should match the unmanaged API, which isn't capitalized.")]
internal struct NATIVE_RECORDLIST
{
/// <summary>
/// Size of the structure.
/// </summary>
public uint cbStruct;
/// <summary>
/// Temporary table containing the bookmarks.
/// </summary>
public IntPtr tableid;
/// <summary>
/// Number of records in the table.
/// </summary>
public uint cRecords;
/// <summary>
/// Column id of the column containing the record bookmarks.
/// </summary>
public uint columnidBookmark;
}
/// <summary>
/// Information about a temporary table containing information
/// about all indexes for a given table.
/// </summary>
[SuppressMessage(
"Microsoft.StyleCop.CSharp.NamingRules",
"SA1300:ElementMustBeginWithUpperCaseLetter",
Justification = "This should match the unmanaged API, which isn't capitalized.")]
public class JET_RECORDLIST
{
/// <summary>
/// Gets tableid of the temporary table. This should be closed
/// when the table is no longer needed.
/// </summary>
public JET_TABLEID tableid { get; internal set; }
/// <summary>
/// Gets the number of records in the temporary table.
/// </summary>
public int cRecords { get; internal set; }
/// <summary>
/// Gets the columnid of the column in the temporary table which
/// stores the bookmark of the record.
/// The column is of type JET_coltyp.Text.
/// </summary>
public JET_COLUMNID columnidBookmark { get; internal set; }
/// <summary>
/// Returns a <see cref="T:System.String"/> that represents the current <see cref="JET_INDEXLIST"/>.
/// </summary>
/// <returns>
/// A <see cref="T:System.String"/> that represents the current <see cref="JET_INDEXLIST"/>.
/// </returns>
public override string ToString()
{
return String.Format(
CultureInfo.InvariantCulture,
"JET_RECORDLIST(0x{0:x},{1} records)",
this.tableid,
this.cRecords);
}
/// <summary>
/// Sets the fields of the object from a native JET_RECORDLIST struct.
/// </summary>
/// <param name="value">
/// The native recordlist to set the values from.
/// </param>
internal void SetFromNativeRecordlist(NATIVE_RECORDLIST value)
{
this.tableid = new JET_TABLEID { Value = value.tableid };
this.cRecords = checked((int)value.cRecords);
this.columnidBookmark = new JET_COLUMNID { Value = value.columnidBookmark };
}
}
}
|
@{
var cdnLocation = "https://dev-cdn.nationalcareersservice.org.uk/nationalcareers_toolkit";
var queryStringVersion = @DateTime.Today.ToString("yyyy-mm-dd");
}
<link href="@cdnLocation/css/all.min.css?@queryStringVersion" rel="stylesheet" type="text/css" />
|
using MediatR;
using Nut.MediatR.ServiceLike;
namespace ServiceLikeSample.Sample.Basic;
[AsService("/basic")]
public class BasicRequest : IRequest<BasicResult>
{
public string Id { get; set; }
}
|
using System.ComponentModel;
namespace Eklee.Quiz.Api.Models
{
public class Status
{
[Description("Message")]
public string Message { get; set; }
}
}
|
using Example.Animals;
using NUnit.Framework;
namespace Example.Tests.NUnit2
{
[TestFixture]
[Category("TraitOnClass")]
[Property("RefSpec","ClassValue")]
public sealed class AnimalTests
{
[Test]
[Category("TraitOnMethod")]
public void The_Cat_Should_Meow()
{
// Given
var cat = new Cat();
// When
var result = cat.Talk();
// Then
Assert.AreEqual("Meow", result);
}
[Test]
[Category("TraitOnMethod")]
[Property("RefSpec","SomeRandomValue")]
public void The_Dog_Should_Bark()
{
// Given
var dog = new Dog();
// When
var result = dog.Talk();
// Then
Assert.AreEqual("Woof", result);
}
}
}
|
// ParameterData
using System;
using UnityEngine;
[Serializable]
public class ParameterData
{
[SerializeField]
public float _value;
[SerializeField]
public int _parameter;
[SerializeField]
public int _index = -1;
}
|
using DTD.Sort.Net.Enums;
using DTD.Sort.Net.Interfaces;
using System;
namespace DTD.Sort.Net.Algorithms
{
internal class MergeSort<T> : ISort<T> where T : IComparable<T>
{
public SortType Type => SortType.Merge;
public T[] Sort(T[] input, SortOrder sortOrder = SortOrder.Default)
{
var entries2 = new T[input.Length];
Sort(input, entries2, 0, input.Length - 1, sortOrder);
return input;
}
#region Constants
private const int mergesDefault = 6;
private const int insertionLimitDefault = 12;
#endregion
#region Properties
private int[] Positions { get; set; }
private int _merges;
private int Merges
{
get { return _merges; }
set
{
// A minimum of 2 merges are required
if (value > 1)
_merges = value;
else
throw new ArgumentOutOfRangeException();
if (Positions == null || Positions.Length != _merges)
Positions = new int[_merges];
}
}
private int InsertionLimit { get; set; }
#endregion
#region Constructors
public MergeSort(int merges, int insertionLimit)
{
Merges = merges;
InsertionLimit = insertionLimit;
}
public MergeSort()
: this(mergesDefault, insertionLimitDefault)
{
}
#endregion
#region Sort Methods
// Top-Down K-way Merge Sort
private void Sort(T[] entries1, T[] entries2, int first, int last, SortOrder order)
{
var length = last + 1 - first;
if (length < 2)
return;
else if (length < InsertionLimit)
{
new InsertionSort<T>().Sort(entries1, order);
return;
}
var left = first;
var size = ceiling(length, Merges);
for (var remaining = length; remaining > 0; remaining -= size, left += size)
{
var right = left + Math.Min(remaining, size) - 1;
Sort(entries1, entries2, left, right, order);
}
Merge(entries1, entries2, first, last);
Array.Copy(entries2, first, entries1, first, length);
}
#endregion
#region Merge Methods
private void Merge(T[] entries1, T[] entries2, int first, int last)
{
Array.Clear(Positions, 0, Merges);
// This implementation has a quadratic time dependency on the number of merges
for (var index = first; index <= last; index++)
entries2[index] = Remove(entries1, first, last);
}
private T Remove(T[] entries, int first, int last)
{
var entry = default(T);
var found = (int?)null;
var length = last + 1 - first;
var index = 0;
var left = first;
var size = ceiling(length, Merges);
for (var remaining = length; remaining > 0; remaining -= size, left += size, index++)
{
var position = Positions[index];
if (position < Math.Min(remaining, size))
{
var next = entries[left + position];
if (!found.HasValue || entry.CompareTo(next) > 0)
{
found = index;
entry = next;
}
}
}
// Remove entry
Positions[found.Value]++;
return entry;
}
#endregion
#region Math Methods
private static int ceiling(int numerator, int denominator)
{
return (numerator + denominator - 1) / denominator;
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace SwmSuite.Data.Common {
/// <summary>
/// enumerator defining the status for an overtime entry.
/// </summary>
public enum OvertimeStatus {
/// <summary>
/// Overtime entry is pending.
/// </summary>
Pending,
/// <summary>
/// Overtime entry is accepted.
/// </summary>
Accepted,
/// <summary>
/// Overtime entry is denied.
/// </summary>
Denied
}
}
|
using System;
using Microsoft.EntityFrameworkCore.Migrations;
namespace Ebd.Infra.Data.Migrations
{
public partial class Initial : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Bairro",
columns: table => new
{
BairroId = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Nome = table.Column<string>(type: "nvarchar(35)", maxLength: 35, nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Bairro", x => x.BairroId);
});
migrationBuilder.CreateTable(
name: "Pessoa",
columns: table => new
{
PessoaId = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Nome = table.Column<string>(type: "nvarchar(50)", maxLength: 50, nullable: false),
WhatsappIgualCelular = table.Column<bool>(type: "bit", nullable: false),
NascidoEm = table.Column<DateTime>(type: "datetime2", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Pessoa", x => x.PessoaId);
});
migrationBuilder.CreateTable(
name: "Revista",
columns: table => new
{
RevistaId = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Sumario = table.Column<string>(type: "nvarchar(60)", maxLength: 60, nullable: false),
Ano = table.Column<int>(type: "int", nullable: false),
Trimestre = table.Column<int>(type: "int", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Revista", x => x.RevistaId);
});
migrationBuilder.CreateTable(
name: "Turma",
columns: table => new
{
TurmaId = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Nome = table.Column<string>(type: "nvarchar(60)", maxLength: 60, nullable: false),
IdadeMinima = table.Column<int>(type: "int", nullable: false),
IdadeMaxima = table.Column<int>(type: "int", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Turma", x => x.TurmaId);
});
migrationBuilder.CreateTable(
name: "Contato",
columns: table => new
{
ContatoId = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Valor = table.Column<string>(type: "nvarchar(50)", maxLength: 50, nullable: false),
Tipo = table.Column<int>(type: "int", nullable: false),
Classificacao = table.Column<int>(type: "int", nullable: false),
PessoaId = table.Column<int>(type: "int", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Contato", x => x.ContatoId);
table.ForeignKey(
name: "FK_Contato_Pessoa_PessoaId",
column: x => x.PessoaId,
principalTable: "Pessoa",
principalColumn: "PessoaId",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "Endereco",
columns: table => new
{
EnderecoId = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Classificacao = table.Column<int>(type: "int", nullable: false),
Logradouro = table.Column<string>(type: "nvarchar(60)", maxLength: 60, nullable: false),
Numero = table.Column<string>(type: "nvarchar(6)", maxLength: 6, nullable: false),
Cep = table.Column<string>(type: "nvarchar(10)", maxLength: 10, nullable: false),
PessoaId = table.Column<int>(type: "int", nullable: false),
BairroId = table.Column<int>(type: "int", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Endereco", x => x.EnderecoId);
table.ForeignKey(
name: "FK_Endereco_Bairro_BairroId",
column: x => x.BairroId,
principalTable: "Bairro",
principalColumn: "BairroId",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_Endereco_Pessoa_PessoaId",
column: x => x.PessoaId,
principalTable: "Pessoa",
principalColumn: "PessoaId",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "Licao",
columns: table => new
{
LicaoId = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Titulo = table.Column<string>(type: "nvarchar(60)", maxLength: 60, nullable: false),
RevistaId = table.Column<int>(type: "int", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Licao", x => x.LicaoId);
table.ForeignKey(
name: "FK_Licao_Revista_RevistaId",
column: x => x.RevistaId,
principalTable: "Revista",
principalColumn: "RevistaId",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "Aluno",
columns: table => new
{
AlunoId = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
PessoaId = table.Column<int>(type: "int", nullable: false),
ResponsavelId = table.Column<int>(type: "int", nullable: true),
TurmaId = table.Column<int>(type: "int", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Aluno", x => x.AlunoId);
table.ForeignKey(
name: "FK_Aluno_Pessoa_PessoaId",
column: x => x.PessoaId,
principalTable: "Pessoa",
principalColumn: "PessoaId",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_Aluno_Pessoa_ResponsavelId",
column: x => x.ResponsavelId,
principalTable: "Pessoa",
principalColumn: "PessoaId",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_Aluno_Turma_TurmaId",
column: x => x.TurmaId,
principalTable: "Turma",
principalColumn: "TurmaId",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "Professor",
columns: table => new
{
ProfessorId = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
PessoaId = table.Column<int>(type: "int", nullable: false),
TurmaId = table.Column<int>(type: "int", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Professor", x => x.ProfessorId);
table.ForeignKey(
name: "FK_Professor_Pessoa_PessoaId",
column: x => x.PessoaId,
principalTable: "Pessoa",
principalColumn: "PessoaId",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_Professor_Turma_TurmaId",
column: x => x.TurmaId,
principalTable: "Turma",
principalColumn: "TurmaId",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "Chamada",
columns: table => new
{
ChamadaId = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
EstavaPresente = table.Column<bool>(type: "bit", nullable: false),
Data = table.Column<DateTime>(type: "datetime2", nullable: false),
AlunoId = table.Column<int>(type: "int", nullable: false),
LicaoId = table.Column<int>(type: "int", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Chamada", x => x.ChamadaId);
table.ForeignKey(
name: "FK_Chamada_Aluno_AlunoId",
column: x => x.AlunoId,
principalTable: "Aluno",
principalColumn: "AlunoId",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_Chamada_Licao_LicaoId",
column: x => x.LicaoId,
principalTable: "Licao",
principalColumn: "LicaoId",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_Aluno_PessoaId",
table: "Aluno",
column: "PessoaId");
migrationBuilder.CreateIndex(
name: "IX_Aluno_ResponsavelId",
table: "Aluno",
column: "ResponsavelId");
migrationBuilder.CreateIndex(
name: "IX_Aluno_TurmaId",
table: "Aluno",
column: "TurmaId");
migrationBuilder.CreateIndex(
name: "IX_Chamada_AlunoId",
table: "Chamada",
column: "AlunoId");
migrationBuilder.CreateIndex(
name: "IX_Chamada_LicaoId",
table: "Chamada",
column: "LicaoId");
migrationBuilder.CreateIndex(
name: "IX_Contato_PessoaId",
table: "Contato",
column: "PessoaId");
migrationBuilder.CreateIndex(
name: "IX_Endereco_BairroId",
table: "Endereco",
column: "BairroId");
migrationBuilder.CreateIndex(
name: "IX_Endereco_PessoaId",
table: "Endereco",
column: "PessoaId");
migrationBuilder.CreateIndex(
name: "IX_Licao_RevistaId",
table: "Licao",
column: "RevistaId");
migrationBuilder.CreateIndex(
name: "IX_Professor_PessoaId",
table: "Professor",
column: "PessoaId");
migrationBuilder.CreateIndex(
name: "IX_Professor_TurmaId",
table: "Professor",
column: "TurmaId");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Chamada");
migrationBuilder.DropTable(
name: "Contato");
migrationBuilder.DropTable(
name: "Endereco");
migrationBuilder.DropTable(
name: "Professor");
migrationBuilder.DropTable(
name: "Aluno");
migrationBuilder.DropTable(
name: "Licao");
migrationBuilder.DropTable(
name: "Bairro");
migrationBuilder.DropTable(
name: "Pessoa");
migrationBuilder.DropTable(
name: "Turma");
migrationBuilder.DropTable(
name: "Revista");
}
}
}
|
using System;
namespace EF.Essentials.Repository
{
public class EntityHasNoSlugException : Exception
{
public EntityHasNoSlugException(Type type) : base($"{type.FullName} does not implements IHasSlug")
{
}
}
}
|
using System;
namespace ScalableTeaching.DTO
{
public class UserDTO
{
public String Username { get; set; }
public String Mail { get; set; }
public String Sn { get; set; }
public String Gn { get; set; }
public String Cn { get; set; }
public String AccountType { get; set; }
}
}
|
#region File Description
//-----------------------------------------------------------------------------
// FixedCombat.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion
#region Using Statements
using System;
using System.Collections.Generic;
using System.IO;
using Microsoft.Xna.Framework.Content;
#endregion
namespace RolePlayingGameData
{
/// <summary>
/// The description of a fixed combat encounter in the world.
/// </summary>
public class FixedCombat : WorldObject
{
/// <summary>
/// The content name and quantities of the monsters in this encounter.
/// </summary>
private List<ContentEntry<Monster>> entries = new List<ContentEntry<Monster>>();
/// <summary>
/// The content name and quantities of the monsters in this encounter.
/// </summary>
public List<ContentEntry<Monster>> Entries
{
get { return entries; }
set { entries = value; }
}
#region Content Type Reader
/// <summary>
/// Reads a FixedCombat object from the content pipeline.
/// </summary>
public class FixedCombatReader : ContentTypeReader<FixedCombat>
{
/// <summary>
/// Reads a FixedCombat object from the content pipeline.
/// </summary>
protected override FixedCombat Read(ContentReader input,
FixedCombat existingInstance)
{
FixedCombat fixedCombat = existingInstance;
if (fixedCombat == null)
{
fixedCombat = new FixedCombat();
}
input.ReadRawObject<WorldObject>(fixedCombat as WorldObject);
fixedCombat.Entries.AddRange(
input.ReadObject<List<ContentEntry<Monster>>>());
foreach (ContentEntry<Monster> fixedCombatEntry in fixedCombat.Entries)
{
fixedCombatEntry.Content = input.ContentManager.Load<Monster>(
Path.Combine(@"Characters\Monsters",
fixedCombatEntry.ContentName));
}
return fixedCombat;
}
}
#endregion
}
}
|
using DGP.Genshin.MiHoYoAPI.GameRole;
using System;
namespace DGP.Genshin.DataModel.Cookie
{
public class CookieUserGameRole : IEquatable<CookieUserGameRole>
{
public CookieUserGameRole(string cookie, UserGameRole userGameRole)
{
Cookie = cookie;
UserGameRole = userGameRole;
}
public string Cookie { get; set; }
public UserGameRole UserGameRole { get; set; }
public bool Equals(CookieUserGameRole? other)
{
if (other == null)
{
return false;
}
return Cookie == other.Cookie && UserGameRole == other.UserGameRole;
}
public override bool Equals(object? obj)
{
return Equals(obj as CookieUserGameRole);
}
/// <summary>
/// 比较两个 <see cref="CookieUserGameRole"/> 是否相同
/// </summary>
/// <param name="left"></param>
/// <param name="right"></param>
/// <returns></returns>
public static bool operator ==(CookieUserGameRole? left, CookieUserGameRole? right)
{
if (left is null || right is null)
{
if (left is null && right is null)
{
return true;
}
return false;
}
else
{
return left.Equals(right);
}
}
public static bool operator !=(CookieUserGameRole? left, CookieUserGameRole? right)
{
if (left is null || right is null)
{
if (left is null && right is null)
{
return false;
}
return true;
}
else
{
return !left.Equals(right);
}
}
public override int GetHashCode()
{
return base.GetHashCode();
}
}
} |
using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;
[RequireComponent(typeof(TrackingPresenter))]
public class UIEvent : MonoBehaviour
{
[SerializeField] SendTracker sendTracker = null;
[SerializeField] TMP_InputField inputIP = null;
[SerializeField] TMP_InputField inputPort = null;
[SerializeField] TextMeshProUGUI textFpsButton = null;
[SerializeField] SendingLabelAnimation labelAnimation = null;
[SerializeField] uOscClientHelper uocHelper = null;
[SerializeField] Toggle toggleAdjustAbnormalPosition = null;
[SerializeField] Toggle toggleSmooth = null;
[SerializeField] Toggle toggleCoverUp = null;
private TrackingPresenter trackingPresenter = null;
private void Awake() {
trackingPresenter = GetComponent<TrackingPresenter>();
}
private IList<int> fpsList = new List<int>() {
72, 36, 18, 9
};
private int fpsIndex = 0;
private void Update()
{
if (sendTracker.IsSending)
{
labelAnimation.Run();
}
}
/// <summary>
/// STARTボタン処理
/// </summary>
public void OnStartButton()
{
bool status = !sendTracker.IsSending;
ChangeStatus(status);
}
private void ChangeStatus(bool status)
{
if (status)
{
uocHelper.ChangeOSCAddress(inputIP.text, Int32.Parse(inputPort.text));
UpdateSendTrackerInterval();
labelAnimation.StartAnimation();
}
else
{
labelAnimation.StopAnimation();
}
uocHelper.SetEnabled(status);
sendTracker.ChangeSendStatus(status);
}
private void UpdateSendTrackerInterval()
{
int interval = fpsIndex + 1;
sendTracker.SetInterval(interval);
}
/// <summary>
/// IPのテキスト変更処理
/// </summary>
public void OnChangeIP()
{
PlayerPrefs.SetString(PlayerPrefsKey.IP, inputIP.text);
ChangeStatus(false);
}
/// <summary>
/// Portのテキスト変更処理
/// </summary>
public void OnChangePort()
{
PlayerPrefs.SetString(PlayerPrefsKey.PORT, inputPort.text);
ChangeStatus(false);
}
/// <summary>
/// FPSの変更処理
/// </summary>
public void OnChangeFPS()
{
++fpsIndex;
if (fpsIndex >= fpsList.Count)
{
fpsIndex = 0;
}
PlayerPrefs.SetInt(PlayerPrefsKey.FPS_INDEX, fpsIndex);
textFpsButton.text = fpsList[fpsIndex].ToString();
UpdateSendTrackerInterval();
}
public void OnChangeAdjustAbnormalPosition()
{
PlayerPrefs.SetInt(PlayerPrefsKey.ADJUST_ABNORMAL_POSITION,
(toggleAdjustAbnormalPosition.isOn) ? 1 : 0);
trackingPresenter.ChangeAbnormalAdjustPosition(toggleAdjustAbnormalPosition.isOn);
}
public void OnChangeSmooth()
{
PlayerPrefs.SetInt(PlayerPrefsKey.SMOOTH,
(toggleSmooth.isOn) ? 1 : 0);
trackingPresenter.ChangeSmooth(toggleSmooth.isOn);
}
public void OnChangeCoverUp()
{
PlayerPrefs.SetInt(PlayerPrefsKey.COVER_UP,
(toggleCoverUp.isOn) ? 1 : 0);
trackingPresenter.ChangeCoverUp(toggleCoverUp.isOn);
}
/// <summary>
/// IPの値をセットする
/// </summary>
/// <param name="text"></param>
public void SetIP(string text)
{
inputIP.text = text;
}
/// <summary>
/// Portの値をセットする
/// </summary>
/// <param name="text"></param>
public void SetPort(string text)
{
inputPort.text = text;
}
/// <summary>
/// FPSの値をセットする
/// </summary>
/// <param name="text"></param>
public void SetFpsIndex(int index)
{
fpsIndex = index;
textFpsButton.text = fpsList[fpsIndex].ToString();
}
/// <summary>
/// AdjustAbnormalPositionのフラグセット
/// </summary>
/// <param name="value"></param>
public void SetAdjustAbnormalPosition(int value)
{
toggleAdjustAbnormalPosition.isOn = (value == 1) ? true : false;
}
/// <summary>
/// Smoothのフラグセット
/// </summary>
/// <param name="value"></param>
public void SetSmooth(int value)
{
toggleSmooth.isOn = (value == 1) ? true : false;
}
/// <summary>
/// CoverUpのフラグセット
/// </summary>
/// <param name="value"></param>
public void SetCoverUp(int value)
{
toggleCoverUp.isOn = (value == 1) ? true : false;
}
}
|
using Bhbk.Lib.Identity.Grants;
using Bhbk.Lib.Identity.Models.Alert;
using Bhbk.Lib.Identity.Services;
using System;
using System.Threading.Tasks;
namespace Bhbk.Lib.Identity.Services
{
public interface IAlertService
{
AlertServiceRepository Endpoints { get; }
IOAuth2JwtGrant Grant { get; set; }
ValueTask<bool> Dequeue_EmailV1(Guid emailID);
ValueTask<bool> Dequeue_TextV1(Guid textID);
ValueTask<bool> Enqueue_EmailV1(EmailV1 model);
ValueTask<bool> Enqueue_TextV1(TextV1 model);
}
}
|
using Microsoft.EntityFrameworkCore;
using TvMaze.Core.Constants;
using TvMaze.Core.Entity;
namespace TvMaze.Infrastructure.Data.DbMapping
{
public static class CastMap
{
public static ModelBuilder MapCasts(this ModelBuilder modelBuilder)
{
var entity = modelBuilder.Entity<Cast>();
// Key
entity.HasKey(k => k.Id);
// Index
entity.HasIndex(i => new { i.ShowId, i.Name })
.IsUnique();
// Relations
entity.HasOne(p => p.Show)
.WithMany(o => o.Casts)
.HasForeignKey(f => f.ShowId);
// Length
entity.Property(p => p.Name).HasMaxLength(PropertyConstants.DEFAULT_LENGTH);
return modelBuilder;
}
}
}
|
@page
@model MyRolesDataModel
@{
ViewData["Title"] = "My Roles & Permissions";
ViewData["ActivePage"] = ManageNavPages.MyRoles;
}
<h4>@ViewData["Title"]</h4>
<div class="row">
<div class="col-md-6">
<div class="card text-center">
<div class="card-body">
<p class="card-text">
@if (Model.Roles.Any())
{
@: Your account may have 1 or more permissions (AKA Roles). Below are what is assigned to your account:
}
else
{
@: You do not currently have any roles. Please speak to an administratior or raise a support ticket.
}
</p>
<h6 class="card-title">You have <span class="badge badge-dark">@Model.Roles.Count</span> Roles/Permissions </h6>
</div>
<ul class="list-group list-group-flush">
@foreach (var role in Model.Roles)
{
<li class="list-group-item">@role</li>
}
</ul>
</div>
</div>
</div>
@section Scripts {
<partial name="_ValidationScriptsPartial" />
}
|
using UnityEngine;
using UnityEditor;
namespace SOA
{
[CustomEditor(typeof(Vector3EventAsset))]
public class Vector3EventAssetEditor : EventAssetEditor<Vector3> { }
} |
using System;
using Il2CppDummyDll;
// Token: 0x02000441 RID: 1089
[Token(Token = "0x2000441")]
public enum RoleTeamTypes
{
// Token: 0x04001742 RID: 5954
[Token(Token = "0x4001742")]
Crewmate,
// Token: 0x04001743 RID: 5955
[Token(Token = "0x4001743")]
Impostor
}
|
// Copyright 2017-2020 Elringus (Artyom Sovetnikov). All Rights Reserved.
using System;
using UnityEngine;
using UnityEngine.Events;
namespace Naninovel
{
/// <summary>
/// Hosts events routed by <see cref="GenericActor{TBehaviour}"/>.
/// </summary>
public class CharacterActorBehaviour : GenericActorBehaviour
{
[System.Serializable]
private class LookDirectionChangedEvent : UnityEvent<CharacterLookDirection> { }
[System.Serializable]
private class IsSpeakingChangedEvent : UnityEvent<bool> { }
/// <summary>
/// Invoked when look direction of the character is changed.
/// </summary>
public event Action<CharacterLookDirection> OnLookDirectionChanged;
/// <summary>
/// Invoked when the character becomes or cease to be the author of the last printed text message.
/// </summary>
public event Action<bool> OnIsSpeakingChanged;
public bool TransformByLookDirection => transformByLookDirection;
public float LookDeltaAngle => lookDeltaAngle;
[Tooltip("Invoked when look direction of the character is changed.")]
[SerializeField] private LookDirectionChangedEvent onLookDirectionChanged = default;
[Tooltip("Invoked when the character becomes or cease to be the author of the last printed text message.")]
[SerializeField] private IsSpeakingChangedEvent onIsSpeakingChanged = default;
[Tooltip("Whether to react to look direction changes by rotating the object's transform.")]
[SerializeField] private bool transformByLookDirection = true;
[Tooltip("When `" + nameof(transformByLookDirection) + "` is enabled, controls the rotation angle.")]
[SerializeField] private float lookDeltaAngle = 30;
public void InvokeLookDirectionChangedEvent (CharacterLookDirection value)
{
OnLookDirectionChanged?.Invoke(value);
onLookDirectionChanged?.Invoke(value);
}
public void InvokeIsSpeakingChangedEvent (bool value)
{
OnIsSpeakingChanged?.Invoke(value);
onIsSpeakingChanged?.Invoke(value);
}
}
}
|
#if DEBUG
using FaceOff.Shared;
using Foundation;
using Newtonsoft.Json;
namespace FaceOff.iOS
{
public partial class AppDelegate
{
public AppDelegate() => Xamarin.Calabash.Start();
[Export(BackdoorMethodConstants.GetPicturePageTitle + ":")]
public NSString GetPicturePageTitle(NSString noValue)
{
var mainNavigationPage = (Xamarin.Forms.NavigationPage)Xamarin.Forms.Application.Current.MainPage;
return Serialize(mainNavigationPage.CurrentPage.Title);
}
[Export(BackdoorMethodConstants.SubmitImageForPhoto1 + ":")]
public async void SubmitImageForPhoto1(NSString serializedInput)
{
var playerEmotionModel = Deserialize<PlayerEmotionModel>(serializedInput);
await UITestBackdoorService.SubmitImageForPhoto1(playerEmotionModel.PlayerName, playerEmotionModel.Emotion).ConfigureAwait(false);
}
[Export(BackdoorMethodConstants.SubmitImageForPhoto2 + ":")]
public async void SubmitImageForPhoto2(NSString serializedInput)
{
var playerEmotionModel = Deserialize<PlayerEmotionModel>(serializedInput);
await UITestBackdoorService.SubmitImageForPhoto2(playerEmotionModel.PlayerName, playerEmotionModel.Emotion).ConfigureAwait(false);
}
static NSString Serialize<T>(T data) => new NSString(JsonConvert.SerializeObject(data));
static T Deserialize<T>(NSString data) => JsonConvert.DeserializeObject<T>(data.ToString()) ?? throw new JsonException();
}
}
#endif
|
//=================================================================================================
// Copyright 2013-2017 Dirk Lemstra <https://magick.codeplex.com/>
//
// Licensed under the ImageMagick License (the "License"); you may not use this file except in
// compliance with the License. You may obtain a copy of the License at
//
// http://www.imagemagick.org/script/license.php
//
// 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 ImageMagick;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Magick.NET.Tests
{
[TestClass]
public class ExifDescriptionAttributeTests
{
[TestMethod]
public void Test_ExifTag()
{
var exifProfile = new ExifProfile();
exifProfile.SetValue(ExifTag.ResolutionUnit, (ushort)1);
ExifValue value = exifProfile.GetValue(ExifTag.ResolutionUnit);
Assert.AreEqual("None", value.ToString());
exifProfile.SetValue(ExifTag.ResolutionUnit, (ushort)2);
value = exifProfile.GetValue(ExifTag.ResolutionUnit);
Assert.AreEqual("Inches", value.ToString());
exifProfile.SetValue(ExifTag.ResolutionUnit, (ushort)3);
value = exifProfile.GetValue(ExifTag.ResolutionUnit);
Assert.AreEqual("Centimeter", value.ToString());
exifProfile.SetValue(ExifTag.ResolutionUnit, (ushort)4);
value = exifProfile.GetValue(ExifTag.ResolutionUnit);
Assert.AreEqual("4", value.ToString());
exifProfile.SetValue(ExifTag.ImageWidth, 123);
value = exifProfile.GetValue(ExifTag.ImageWidth);
Assert.AreEqual("123", value.ToString());
}
}
}
|
using System;
using System.Collections.Generic;
namespace SnapMD.VirtualCare.ApiModels.Scheduling.Coverage
{
/// <summary>
/// Availability blocks coverage time frame with user ids.
/// </summary>
public class CoverageTimeFrame
{
/// <summary>
/// Time from.
/// </summary>
public DateTimeOffset From { get; set; }
/// <summary>
/// Time to.
/// </summary>
public DateTimeOffset To { get; set; }
/// <summary>
/// Clinician user ids for time frame.
/// </summary>
public List<int> Clinicians { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Simplic.Cloud.API.DataPort
{
public class TransformationResultQueueItemResponse
{
public Guid TransformationQueueId { get; set; }
public Guid OrganizationId { get; set; }
}
public class TransformationResultResponse
{
public Guid Guid { get; set; }
public Guid OrganizationId { get; set; }
public byte[] OriginalContent { get; set; }
public byte[] ProcessedContent { get; set; }
public int Status { get; set; }
public DateTime UploadTime { get; set; }
public DateTime ProcessedTime { get; set; }
public Guid TransformerId { get; set; }
public string ResultMessage { get; set; }
}
}
|
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using LeakyBucket.Owin.Identifiers;
namespace LeakyBucket.Owin.Store
{
public class DefaultRequestStore : IRequestStore
{
private readonly int _maxNumberOfRequests;
private readonly object _syncObject = new object();
private readonly IDictionary<IClientIdentifier, Queue<DateTime>> _requests =
new ConcurrentDictionary<IClientIdentifier, Queue<DateTime>>();
public DefaultRequestStore(int maxNumberOfRequests)
{
_maxNumberOfRequests = maxNumberOfRequests;
}
public int NumberOfRequestsFor(IClientIdentifier identifier)
{
lock (_syncObject)
{
return _requests.ContainsKey(identifier)
? _requests[identifier].Count
: 0;
}
}
public void AddRequest(IClientIdentifier identifier, DateTime dateTime)
{
lock (_syncObject)
{
if (!_requests.ContainsKey(identifier))
_requests.Add(identifier, new Queue<DateTime>(_maxNumberOfRequests));
if (_requests[identifier].Count == _maxNumberOfRequests)
_requests[identifier].Dequeue();
_requests[identifier].Enqueue(dateTime);
}
}
public void DeleteRequestsOlderThan(IClientIdentifier identifier, DateTime expiryDate)
{
lock (_syncObject)
{
if (_requests.ContainsKey(identifier))
{
while (HasExpired(identifier, expiryDate))
{
_requests[identifier].Dequeue();
}
}
DeleteEmptyRequestsData(identifier);
}
}
private void DeleteEmptyRequestsData(IClientIdentifier identifier)
{
if (_requests.ContainsKey(identifier) && _requests[identifier].Count == 0)
_requests.Remove(identifier);
}
private bool HasExpired(IClientIdentifier identifier, DateTime expiryDate)
{
return _requests[identifier].Count > 0 && _requests[identifier].Peek() < expiryDate;
}
}
} |
using System.IO;
using System.Reflection;
using LVK.Core;
namespace LVK.Configuration.StandardConfigurators
{
internal class EnvironmentVariablesConfigurator : IConfigurationConfigurator
{
public void Configure(IConfigurationBuilder configurationBuilder)
{
Assembly assembly = Assembly.GetEntryAssembly() ?? Assembly.GetExecutingAssembly();
var entryAssemblyLocation = assembly.NotNull().Location.NotNull();
var entryAssemblyFilename = Path.GetFileNameWithoutExtension(entryAssemblyLocation);
configurationBuilder.AddEnvironmentVariables($"{entryAssemblyFilename.ToUpper()}_");
}
}
} |
using Autofac;
using ModernSlavery.Core.Interfaces;
using ModernSlavery.Core.SharedKernel;
using Moq;
namespace ModernSlavery.Tests.Common.TestHelpers
{
public static class SetupHelpers
{
//TODO: Possible seperate this method for WebUI and Webjobs?
public static void SetupMockLogRecordGlobals(ContainerBuilder builder = null)
{
// Used by WebUI
var badSicLog = new Mock<IAuditLogger>().Object;
var manualChangeLog = new Mock<IAuditLogger>().Object;
var registrationLog = new Mock<IAuditLogger>().Object;
var submissionLog = new Mock<IAuditLogger>().Object;
var searchLog = new Mock<IAuditLogger>().Object;
var emailSendLog = new Mock<IAuditLogger>().Object;
if (builder != null)
{
builder.RegisterInstance(Mock.Of<IFileRepository>()).SingleInstance();
builder.RegisterInstance(badSicLog).Keyed<IAuditLogger>(Filenames.BadSicLog).SingleInstance();
builder.RegisterInstance(manualChangeLog).Keyed<IAuditLogger>(Filenames.ManualChangeLog)
.SingleInstance();
builder.RegisterInstance(registrationLog).Keyed<IAuditLogger>(Filenames.RegistrationLog)
.SingleInstance();
builder.RegisterInstance(submissionLog).Keyed<IAuditLogger>(Filenames.SubmissionLog)
.SingleInstance();
builder.RegisterInstance(searchLog).Keyed<IAuditLogger>(Filenames.SearchLog).SingleInstance();
builder.RegisterInstance(emailSendLog).Keyed<IAuditLogger>(Filenames.EmailSendLog).SingleInstance();
builder.RegisterInstance(Mock.Of<IUserLogger>()).SingleInstance();
builder.RegisterInstance(Mock.Of<IRegistrationLogger>()).SingleInstance();
}
}
}
} |
//Generated by LateBindingApi.CodeGenerator
using LateBindingApi.Core;
namespace LateBindingApi.Excel.Enums
{
[SupportByLibrary("XL10","XL11","XL12","XL14","XL9")]
public enum XlConsolidationFunction
{
[SupportByLibrary("XL10","XL11","XL12","XL14","XL9")]
xlAverage = -4106,
[SupportByLibrary("XL10","XL11","XL12","XL14","XL9")]
xlCount = -4112,
[SupportByLibrary("XL10","XL11","XL12","XL14","XL9")]
xlCountNums = -4113,
[SupportByLibrary("XL10","XL11","XL12","XL14","XL9")]
xlMax = -4136,
[SupportByLibrary("XL10","XL11","XL12","XL14","XL9")]
xlMin = -4139,
[SupportByLibrary("XL10","XL11","XL12","XL14","XL9")]
xlProduct = -4149,
[SupportByLibrary("XL10","XL11","XL12","XL14","XL9")]
xlStDev = -4155,
[SupportByLibrary("XL10","XL11","XL12","XL14","XL9")]
xlStDevP = -4156,
[SupportByLibrary("XL10","XL11","XL12","XL14","XL9")]
xlSum = -4157,
[SupportByLibrary("XL10","XL11","XL12","XL14","XL9")]
xlVar = -4164,
[SupportByLibrary("XL10","XL11","XL12","XL14","XL9")]
xlVarP = -4165,
[SupportByLibrary("XL10","XL11","XL12","XL14","XL9")]
xlUnknown = 1000
}
}
|
namespace SixtenLabs.SpawnOfVulkan
{
public enum Format : long
{
FormatUndefined = 0,
FormatR4g4UnormPack8 = 1,
FormatR4g4b4a4UnormPack16 = 2,
FormatB4g4r4a4UnormPack16 = 3,
FormatR5g6b5UnormPack16 = 4,
FormatB5g6r5UnormPack16 = 5,
FormatR5g5b5a1UnormPack16 = 6,
FormatB5g5r5a1UnormPack16 = 7,
FormatA1r5g5b5UnormPack16 = 8,
FormatR8Unorm = 9,
FormatR8Snorm = 10,
FormatR8Uscaled = 11,
FormatR8Sscaled = 12,
FormatR8Uint = 13,
FormatR8Sint = 14,
FormatR8Srgb = 15,
FormatR8g8Unorm = 16,
FormatR8g8Snorm = 17,
FormatR8g8Uscaled = 18,
FormatR8g8Sscaled = 19,
FormatR8g8Uint = 20,
FormatR8g8Sint = 21,
FormatR8g8Srgb = 22,
FormatR8g8b8Unorm = 23,
FormatR8g8b8Snorm = 24,
FormatR8g8b8Uscaled = 25,
FormatR8g8b8Sscaled = 26,
FormatR8g8b8Uint = 27,
FormatR8g8b8Sint = 28,
FormatR8g8b8Srgb = 29,
FormatB8g8r8Unorm = 30,
FormatB8g8r8Snorm = 31,
FormatB8g8r8Uscaled = 32,
FormatB8g8r8Sscaled = 33,
FormatB8g8r8Uint = 34,
FormatB8g8r8Sint = 35,
FormatB8g8r8Srgb = 36,
FormatR8g8b8a8Unorm = 37,
FormatR8g8b8a8Snorm = 38,
FormatR8g8b8a8Uscaled = 39,
FormatR8g8b8a8Sscaled = 40,
FormatR8g8b8a8Uint = 41,
FormatR8g8b8a8Sint = 42,
FormatR8g8b8a8Srgb = 43,
FormatB8g8r8a8Unorm = 44,
FormatB8g8r8a8Snorm = 45,
FormatB8g8r8a8Uscaled = 46,
FormatB8g8r8a8Sscaled = 47,
FormatB8g8r8a8Uint = 48,
FormatB8g8r8a8Sint = 49,
FormatB8g8r8a8Srgb = 50,
FormatA8b8g8r8UnormPack32 = 51,
FormatA8b8g8r8SnormPack32 = 52,
FormatA8b8g8r8UscaledPack32 = 53,
FormatA8b8g8r8SscaledPack32 = 54,
FormatA8b8g8r8UintPack32 = 55,
FormatA8b8g8r8SintPack32 = 56,
FormatA8b8g8r8SrgbPack32 = 57,
FormatA2r10g10b10UnormPack32 = 58,
FormatA2r10g10b10SnormPack32 = 59,
FormatA2r10g10b10UscaledPack32 = 60,
FormatA2r10g10b10SscaledPack32 = 61,
FormatA2r10g10b10UintPack32 = 62,
FormatA2r10g10b10SintPack32 = 63,
FormatA2b10g10r10UnormPack32 = 64,
FormatA2b10g10r10SnormPack32 = 65,
FormatA2b10g10r10UscaledPack32 = 66,
FormatA2b10g10r10SscaledPack32 = 67,
FormatA2b10g10r10UintPack32 = 68,
FormatA2b10g10r10SintPack32 = 69,
FormatR16Unorm = 70,
FormatR16Snorm = 71,
FormatR16Uscaled = 72,
FormatR16Sscaled = 73,
FormatR16Uint = 74,
FormatR16Sint = 75,
FormatR16Sfloat = 76,
FormatR16g16Unorm = 77,
FormatR16g16Snorm = 78,
FormatR16g16Uscaled = 79,
FormatR16g16Sscaled = 80,
FormatR16g16Uint = 81,
FormatR16g16Sint = 82,
FormatR16g16Sfloat = 83,
FormatR16g16b16Unorm = 84,
FormatR16g16b16Snorm = 85,
FormatR16g16b16Uscaled = 86,
FormatR16g16b16Sscaled = 87,
FormatR16g16b16Uint = 88,
FormatR16g16b16Sint = 89,
FormatR16g16b16Sfloat = 90,
FormatR16g16b16a16Unorm = 91,
FormatR16g16b16a16Snorm = 92,
FormatR16g16b16a16Uscaled = 93,
FormatR16g16b16a16Sscaled = 94,
FormatR16g16b16a16Uint = 95,
FormatR16g16b16a16Sint = 96,
FormatR16g16b16a16Sfloat = 97,
FormatR32Uint = 98,
FormatR32Sint = 99,
FormatR32Sfloat = 100,
FormatR32g32Uint = 101,
FormatR32g32Sint = 102,
FormatR32g32Sfloat = 103,
FormatR32g32b32Uint = 104,
FormatR32g32b32Sint = 105,
FormatR32g32b32Sfloat = 106,
FormatR32g32b32a32Uint = 107,
FormatR32g32b32a32Sint = 108,
FormatR32g32b32a32Sfloat = 109,
FormatR64Uint = 110,
FormatR64Sint = 111,
FormatR64Sfloat = 112,
FormatR64g64Uint = 113,
FormatR64g64Sint = 114,
FormatR64g64Sfloat = 115,
FormatR64g64b64Uint = 116,
FormatR64g64b64Sint = 117,
FormatR64g64b64Sfloat = 118,
FormatR64g64b64a64Uint = 119,
FormatR64g64b64a64Sint = 120,
FormatR64g64b64a64Sfloat = 121,
FormatB10g11r11UfloatPack32 = 122,
FormatE5b9g9r9UfloatPack32 = 123,
FormatD16Unorm = 124,
FormatX8D24UnormPack32 = 125,
FormatD32Sfloat = 126,
FormatS8Uint = 127,
FormatD16UnormS8Uint = 128,
FormatD24UnormS8Uint = 129,
FormatD32SfloatS8Uint = 130,
FormatBc1RgbUnormBlock = 131,
FormatBc1RgbSrgbBlock = 132,
FormatBc1RgbaUnormBlock = 133,
FormatBc1RgbaSrgbBlock = 134,
FormatBc2UnormBlock = 135,
FormatBc2SrgbBlock = 136,
FormatBc3UnormBlock = 137,
FormatBc3SrgbBlock = 138,
FormatBc4UnormBlock = 139,
FormatBc4SnormBlock = 140,
FormatBc5UnormBlock = 141,
FormatBc5SnormBlock = 142,
FormatBc6hUfloatBlock = 143,
FormatBc6hSfloatBlock = 144,
FormatBc7UnormBlock = 145,
FormatBc7SrgbBlock = 146,
FormatEtc2R8g8b8UnormBlock = 147,
FormatEtc2R8g8b8SrgbBlock = 148,
FormatEtc2R8g8b8a1UnormBlock = 149,
FormatEtc2R8g8b8a1SrgbBlock = 150,
FormatEtc2R8g8b8a8UnormBlock = 151,
FormatEtc2R8g8b8a8SrgbBlock = 152,
FormatEacR11UnormBlock = 153,
FormatEacR11SnormBlock = 154,
FormatEacR11g11UnormBlock = 155,
FormatEacR11g11SnormBlock = 156,
FormatAstc4X4UnormBlock = 157,
FormatAstc4X4SrgbBlock = 158,
FormatAstc5X4UnormBlock = 159,
FormatAstc5X4SrgbBlock = 160,
FormatAstc5X5UnormBlock = 161,
FormatAstc5X5SrgbBlock = 162,
FormatAstc6X5UnormBlock = 163,
FormatAstc6X5SrgbBlock = 164,
FormatAstc6X6UnormBlock = 165,
FormatAstc6X6SrgbBlock = 166,
FormatAstc8X5UnormBlock = 167,
FormatAstc8X5SrgbBlock = 168,
FormatAstc8X6UnormBlock = 169,
FormatAstc8X6SrgbBlock = 170,
FormatAstc8X8UnormBlock = 171,
FormatAstc8X8SrgbBlock = 172,
FormatAstc10X5UnormBlock = 173,
FormatAstc10X5SrgbBlock = 174,
FormatAstc10X6UnormBlock = 175,
FormatAstc10X6SrgbBlock = 176,
FormatAstc10X8UnormBlock = 177,
FormatAstc10X8SrgbBlock = 178,
FormatAstc10X10UnormBlock = 179,
FormatAstc10X10SrgbBlock = 180,
FormatAstc12X10UnormBlock = 181,
FormatAstc12X10SrgbBlock = 182,
FormatAstc12X12UnormBlock = 183,
FormatAstc12X12SrgbBlock = 184,
FormatPvrtc12BppUnormBlockImg = 10000054000,
FormatPvrtc14BppUnormBlockImg = 10000054001,
FormatPvrtc22BppUnormBlockImg = 10000054002,
FormatPvrtc24BppUnormBlockImg = 10000054003,
FormatPvrtc12BppSrgbBlockImg = 10000054004,
FormatPvrtc14BppSrgbBlockImg = 10000054005,
FormatPvrtc22BppSrgbBlockImg = 10000054006,
FormatPvrtc24BppSrgbBlockImg = 10000054007
}
} |
namespace WithinUsingsFolder_NoUsings
{
internal class WithinUsingsFolder_NoUsingsClass
{
void FooBar()
{
System.Console.WriteLine("hey");
}
}
}
|
using Microsoft.EntityFrameworkCore.Migrations;
namespace PROG2230_Byounguk_Min.Migrations
{
public partial class Initial : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "TransactionRecords",
columns: table => new
{
TransactionRecordId = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
TickerSymbol = table.Column<string>(type: "nvarchar(max)", nullable: false),
CompanyName = table.Column<string>(type: "nvarchar(max)", nullable: false),
Quantity = table.Column<int>(type: "int", nullable: false),
SharePrice = table.Column<double>(type: "float", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_TransactionRecords", x => x.TransactionRecordId);
});
migrationBuilder.InsertData(
table: "TransactionRecords",
columns: new[] { "TransactionRecordId", "CompanyName", "Quantity", "SharePrice", "TickerSymbol" },
values: new object[] { 1, "Microsoft", 100, 123.45, "MSFT" });
migrationBuilder.InsertData(
table: "TransactionRecords",
columns: new[] { "TransactionRecordId", "CompanyName", "Quantity", "SharePrice", "TickerSymbol" },
values: new object[] { 2, "Google", 100, 2701.7600000000002, "GOOG" });
migrationBuilder.InsertData(
table: "TransactionRecords",
columns: new[] { "TransactionRecordId", "CompanyName", "Quantity", "SharePrice", "TickerSymbol" },
values: new object[] { 3, "Walmart", 200, 140.97999999999999, "WMT" });
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "TransactionRecords");
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraFollow : MonoBehaviour
{
[SerializeField] private Transform target;
private float smoothSpeed = 0.2f;
[SerializeField] private Vector3 offset = new Vector3(0, 0, -1);
private bool follow = false;
public bool Follow
{
get { return follow; }
set { follow = value; }
}
private void Update()
{
if (follow)
transform.position = Vector3.Lerp(transform.position, target.position + offset, smoothSpeed);
}
}
|
using System.Collections.Generic;
namespace AsmResolver.PE.Imports
{
/// <summary>
/// Represents a single module that was imported into a portable executable as part of the imports data directory.
/// Each instance represents one entry in the imports directory.
/// </summary>
public interface IImportedModule
{
/// <summary>
/// Gets or sets the name of the module that was imported.
/// </summary>
string? Name
{
get;
set;
}
/// <summary>
/// Gets or sets the time stamp that the module was loaded into memory.
/// </summary>
/// <remarks>
/// This field is always 0 if the PE was read from the disk.
/// </remarks>
uint TimeDateStamp
{
get;
set;
}
/// <summary>
/// Gets or sets the index of the first member that is a forwarder.
/// </summary>
uint ForwarderChain
{
get;
set;
}
/// <summary>
/// Gets a collection of members from the module that were imported.
/// </summary>
IList<ImportedSymbol> Symbols
{
get;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.CompilerServices;
namespace Toast
{
public abstract class Component
{
public Entity Entity { get; set; }
}
public class TagComponent : Component
{
public string Tag
{
get => GetTag_Native(Entity.ID);
set => SetTag_Native(Entity.ID, value);
}
[MethodImpl(MethodImplOptions.InternalCall)]
public static extern string GetTag_Native(ulong entityID);
[MethodImpl(MethodImplOptions.InternalCall)]
public static extern void SetTag_Native(ulong entityID, string tag);
}
public class TransformComponent : Component
{
public Matrix4 Transform
{
get
{
Matrix4 result;
GetTransform_Native(Entity.ID, out result);
return result;
}
set
{
SetTransform_Native(Entity.ID, ref value);
}
}
public Vector3 Translation
{
get
{
GetTranslation_Native(Entity.ID, out Vector3 result);
return result;
}
set
{
SetTranslation_Native(Entity.ID, ref value);
}
}
public Vector3 Rotation
{
get
{
GetRotation_Native(Entity.ID, out Vector3 result);
return result;
}
set
{
SetRotation_Native(Entity.ID, ref value);
}
}
public Vector3 Scale
{
get
{
GetScale_Native(Entity.ID, out Vector3 result);
return result;
}
set
{
SetScale_Native(Entity.ID, ref value);
}
}
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern void GetTransform_Native(ulong entityID, out Matrix4 outTranslation);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern void SetTransform_Native(ulong entityID, ref Matrix4 inTranslation);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern void GetTranslation_Native(ulong entityID, out Vector3 outTranslation);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern void SetTranslation_Native(ulong entityID, ref Vector3 inTranslation);
[MethodImpl(MethodImplOptions.InternalCall)]
public static extern void GetRotation_Native(ulong entityID, out Vector3 outRotation);
[MethodImpl(MethodImplOptions.InternalCall)]
public static extern void SetRotation_Native(ulong entityID, ref Vector3 inRotation);
[MethodImpl(MethodImplOptions.InternalCall)]
public static extern void GetScale_Native(ulong entityID, out Vector3 outScale);
[MethodImpl(MethodImplOptions.InternalCall)]
public static extern void SetScale_Native(ulong entityID, ref Vector3 inScale);
}
public class CameraComponent : Component
{
public Camera Camera
{
get
{
Camera result = new Camera(GetCamera_Native(Entity.ID));
return result;
}
set
{
IntPtr ptr = value == null ? IntPtr.Zero : value.mUnmanagedInstance;
SetCamera_Native(Entity.ID, ptr);
}
}
public float FarClip
{
get
{
return GetFarClip_Native(Entity.ID);
}
set
{
SetFarClip_Native(Entity.ID, value);
}
}
public float NearClip
{
get
{
return GetNearClip_Native(Entity.ID);
}
set
{
SetNearClip_Native(Entity.ID, value);
}
}
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern IntPtr GetCamera_Native(ulong entityID);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern void SetCamera_Native(ulong entityID, IntPtr unmanagedInstance);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern void SetFarClip_Native(ulong entityID, float farClip);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern float GetFarClip_Native(ulong entityID);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern void SetNearClip_Native(ulong entityID, float nearClip);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern float GetNearClip_Native(ulong entityID);
}
public class PlanetComponent : Component
{
public Mesh Mesh
{
get
{
Mesh result = new Mesh(GetMesh_Native(Entity.ID));
return result;
}
set
{
IntPtr ptr = value == null ? IntPtr.Zero : value.mUnmanagedInstance;
SetMesh_Native(Entity.ID, ptr);
}
}
public float Radius
{
get
{
GetRadius_Native(Entity.ID, out float result);
return result;
}
set
{
}
}
public int Subdivisions
{
get
{
GetSubdivisions_Native(Entity.ID, out int result);
return result;
}
set
{
}
}
public double[] DistanceLUT
{
get
{
return GetDistanceLUT_Native(Entity.ID);
}
set
{
}
}
public double[] FaceLevelDotLUT
{
get
{
return GetFaceLevelDotLUT_Native(Entity.ID);
}
set
{
}
}
public void RegeneratePlanet(Vector3 cameraPos, Matrix4 cameraTransform)
{
RegeneratePlanet_Native(Entity.ID, cameraPos, cameraTransform);
}
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern IntPtr GetMesh_Native(ulong entityID);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern void SetMesh_Native(ulong entityID, IntPtr unmanagedInstance);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern void RegeneratePlanet_Native(ulong entityID, Vector3 cameraPos, Matrix4 cameraForward);
[MethodImpl(MethodImplOptions.InternalCall)]
public static extern void GetRadius_Native(ulong entityID, out float inScale);
[MethodImpl(MethodImplOptions.InternalCall)]
public static extern void GetSubdivisions_Native(ulong entityID, out int inScale);
[MethodImpl(MethodImplOptions.InternalCall)]
public static extern double[] GetDistanceLUT_Native(ulong entityID);
[MethodImpl(MethodImplOptions.InternalCall)]
public static extern double[] GetFaceLevelDotLUT_Native(ulong entityID);
}
public class MeshComponent : Component
{
public Mesh Mesh
{
get
{
Mesh result = new Mesh(GetMesh_Native(Entity.ID));
return result;
}
set
{
IntPtr ptr = value == null ? IntPtr.Zero : value.mUnmanagedInstance;
SetMesh_Native(Entity.ID, ptr);
}
}
public void RegeneratePlanet(Vector3 cameraPos, Matrix4 cameraTransform)
{
RegeneratePlanet_Native(Entity.ID, cameraPos, cameraTransform);
}
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern IntPtr GetMesh_Native(ulong entityID);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern void SetMesh_Native(ulong entityID, IntPtr unmanagedInstance);
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern void RegeneratePlanet_Native(ulong entityID, Vector3 cameraPos, Matrix4 cameraForward);
}
}
|
/*
* Copyright(c) Trickyrat All Rights Reserved.
* Licensed under the MIT LICENSE.
*/
using System;
namespace Start_App.Application.Common.Interfaces
{
public interface IDateTime
{
DateTime Now { get; }
}
}
|
using Group3.Semester3.DesktopClient.Services;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Text;
namespace Group3.Semester3.DesktopClient.Model
{
public class RegisterWindowParams
{
public ApiService ApiService { get; set; }
}
//public class RegisterWindowModel
//{
// public event PropertyChangedEventHandler PropertyChanged;
// private void NotifyPropertyChanged([CallerMemberName] string propertyName = "")
// {
// PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
// }
// public bool NameRequiredPromptShown
// {
// get => nameRequiredPromptShownValue;
// set
// {
// if (value != nameRequiredPromptShownValue)
// {
// nameRequiredPromptShownValue = value;
// NotifyPropertyChanged();
// }
// }
// }
// public bool PasswordRequiredPromptShown
// {
// get => passwordRequiredPromptShownValue;
// set
// {
// if (value != passwordRequiredPromptShownValue)
// {
// passwordRequiredPromptShownValue = value;
// NotifyPropertyChanged();
// }
// }
// }
// public bool PasswordRepeatRequiredPromptShown
// {
// get => passwordRepeatRequiredPromptShownValue;
// set
// {
// if (value != passwordRepeatRequiredPromptShownValue)
// {
// passwordRepeatRequiredPromptShownValue = value;
// NotifyPropertyChanged();
// }
// }
// }
// public bool EmailRequiredPromptShown
// {
// get => emailRequiredPromptShownValue;
// set
// {
// if (value != emailRequiredPromptShownValue)
// {
// emailRequiredPromptShownValue = value;
// NotifyPropertyChanged();
// }
// }
// }
// private bool passwordRequiredPromptShownValue;
// private bool passwordRepeatRequiredPromptShownValue;
// private bool emailRequiredPromptShownValue;
// private bool nameRequiredPromptShownValue;
//}
class LoginWindowModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged([CallerMemberName] string propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public bool PasswordRequiredPromptShown
{
get
{
return passwordRequiredPromptShownValue;
}
set
{
if (value != passwordRequiredPromptShownValue)
{
passwordRequiredPromptShownValue = value;
NotifyPropertyChanged();
}
}
}
public bool EmailRequiredPromptShown
{
get
{
return this.emailRequiredPromptShownValue;
}
set
{
if (value != this.emailRequiredPromptShownValue)
{
this.emailRequiredPromptShownValue = value;
NotifyPropertyChanged();
}
}
}
private bool passwordRequiredPromptShownValue;
private bool emailRequiredPromptShownValue;
}
}
|
/**
*/
using System;
using System.Collections.Generic;
using System.IO;
namespace AIngle.ipc
{
public class LocalTransceiver : Transceiver
{
private readonly Responder responder;
public LocalTransceiver(Responder responder)
{
if (responder == null) throw new ArgumentNullException("responder");
this.responder = responder;
}
public override string RemoteName
{
get { return "local"; }
}
public override IList<MemoryStream> Transceive(IList<MemoryStream> request)
{
return responder.Respond(request);
}
public override IList<MemoryStream> ReadBuffers()
{
throw new NotSupportedException();
}
public override void WriteBuffers(IList<MemoryStream> getBytes)
{
throw new NotSupportedException();
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class SceneChangeManager : Singleton<SceneChangeManager>
{
[SerializeField] GameObject loadingPanel;
[SerializeField] Image loadingBar;
private void Start()
{
SceneManager.activeSceneChanged += OnLoadFirstLvl;
}
public void LoadLevel(int i)
{
if (i == 1)
{
StartCoroutine(LoadAsync(i));
}
else if (i == 2)
{
StartCoroutine(LoadAsync(i));
InitManagers();
}
else if (i == 3)
{
SceneManager.LoadScene("Nivel3");
InitManagers();
}
}
public void LoadMenu()
{
SceneManager.LoadScene("MainMenu");
}
public void SetLoadingPanelActive(bool active)
{
loadingPanel?.SetActive(active);
}
public void SetLoadingBarFillAmount(float value)
{
loadingBar.fillAmount = value;
}
IEnumerator LoadAsync(int i)
{
AsyncOperation op;
if (i == 1)
{
op = SceneManager.LoadSceneAsync("Nivel1");
}
else if (i == 2)
{
op = SceneManager.LoadSceneAsync("Nivel2");
}
else
{
op = SceneManager.LoadSceneAsync("Nivel3");
}
SetLoadingPanelActive(true);
while (!op.isDone)
{
float progress = Mathf.Clamp01(op.progress / 0.9f);
SetLoadingBarFillAmount(progress);
yield return null;
}
}
private void OnLoadFirstLvl(Scene current, Scene next)
{
if (next.name == "Nivel1")
{
InitManagers();
}
else if (next.name == "MainMenu")
{
OnLoadMenu();
}
SetLoadingPanelActive(false);
}
private static void InitManagers()
{
GameManager.Instance.Init();
InputManager.Instance.Init();
WeaponPrefabsLists.Instance.Init();
WaveManager.Instance.Init();
WeaponManager.Instance._player.Init();
}
private void OnLoadMenu()
{
Destroy(FindObjectOfType<WaveManager>().gameObject);
Destroy(FindObjectOfType<WeaponPrefabsLists>().gameObject);
//Destroy(FindObjectOfType<InputManager>().gameObject);
InputManager.Instance.ResetInit();
GameManager.Instance.ResetInit();
WeaponManager.Instance._player.Unsubscribe();
//Destroy(FindObjectOfType<GameManager>().gameObject);
Destroy(FindObjectOfType<WeaponManager>().gameObject);
Destroy(FindObjectOfType<EnemiesManager>().gameObject);
Destroy(FindObjectOfType<CanvasDDOL>().gameObject);
}
public void ExitGame()
{
Application.Quit();
}
}
|
using System.Threading.Tasks;
using Westmoor.DowntimePlanner.Requests;
namespace Westmoor.DowntimePlanner.Repositories
{
public interface IApiKeyWriteRepository
{
Task CreateAsync(CreateApiKeyRequest request);
Task UpdateAsync(string key, UpdateApiKeyRequest request);
Task DeleteAsync(string idp, string key);
}
}
|
namespace Windows.UI.Xaml.Controls;
public interface ICommandBarElement
{
bool IsCompact { get; set; }
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using PA.Business.Interfaces;
using PA.Core.DataModel.Entities;
using PA.Core.Infrastructure.ResultObjects;
using PA.Data.Interfaces;
namespace PA.Business.Logic
{
public class ProductService : IProductService
{
private readonly IProductRepository _productRepository;
public ProductService(IProductRepository productRepository)
{
_productRepository = productRepository;
}
public DataResult<List<Product>> GetProducts()
{
try
{
var products = _productRepository.QueryProducts().ToList();
return new DataResult<List<Product>>
{
Data = products,
IsSuccess = true,
Message = "Retrieved Products"
};
}
catch (Exception ex)
{
return new DataResult<List<Product>>
{
Message = ex.Message,
IsSuccess = false,
Data = null
};
}
}
}
}
|
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using Exceptional.Analyzer.Helpers;
using Exceptional.Analyzer.Models;
using Exceptional.Analyzer.Models.Docs;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
namespace Exceptional.Analyzer.Rules
{
/// <summary>
/// Searching for uncaught and undocumented throw statements
/// </summary>
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class ThrowStatementAnalyzer : DiagnosticAnalyzer
{
/// <summary>
/// Diagnostic id
/// </summary>
public const string DiagnosticId = "EX1001";
private static readonly string Title = Resources.EX1001_Title;
private static readonly string MessageFormat = Resources.EX1001_Message;
private static readonly string Description = Resources.EX1001_Description;
private static readonly Category Category = Category.Documentation;
private static readonly DiagnosticDescriptor Rule = new(
DiagnosticId,
Title,
MessageFormat,
Category.DisplayName,
DiagnosticSeverity.Warning,
true,
Description,
Category.GetHelpLinkUri(DiagnosticId)
);
/// <inheritdoc />
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule);
/// <inheritdoc />
public override void Initialize(AnalysisContext context)
{
context.EnableConcurrentExecution();
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
context.RegisterSymbolAction(AnalyzeSymbol, SymbolKind.Method);
}
private static void AnalyzeSymbol(SymbolAnalysisContext context)
{
IEnumerable<SyntaxNode> syntaxNodes = context.Symbol
.DeclaringSyntaxReferences
.Select(syntaxReference => syntaxReference.GetSyntax(context.CancellationToken));
DocumentationComment symbolDocumentation = XmlDoc.GetDocumentationComment(context);
foreach (SyntaxNode syntaxNode in syntaxNodes)
{
if (!(syntaxNode is MethodDeclarationSyntax methodDeclarationSyntax))
{
continue;
}
SemanticModel semanticModel = context.Compilation.GetSemanticModel(syntaxNode.SyntaxTree);
ThrowStatementSyntax[] throwStatements = FindStatementSyntax
.FindThrowStatements(methodDeclarationSyntax.Body.Statements)
.ToArray();
foreach (ThrowStatementSyntax throwStatement in throwStatements)
{
AnalyzeThrowStatement(context, throwStatement, semanticModel, symbolDocumentation);
}
}
}
private static void AnalyzeThrowStatement(SymbolAnalysisContext context,
ThrowStatementSyntax throwStatement,
SemanticModel semanticModel,
DocumentationComment symbolDocumentation)
{
ThrowStatementAnalysisData analysisData = ThrowStatementAnalysisData.Create(throwStatement, semanticModel);
bool isCaught = IsExceptionCaught(analysisData, semanticModel);
bool isDocumented = IsExceptionDocumented(context, analysisData, symbolDocumentation);
if (isCaught || isDocumented)
{
return;
}
Diagnostic diagnostic = Diagnostic.Create(Rule, throwStatement.GetLocation(), analysisData.ThrownType);
context.ReportDiagnostic(diagnostic);
}
private static bool IsExceptionCaught(ThrowStatementAnalysisData analysisData,
SemanticModel semanticModel)
{
SyntaxNode currentParent = analysisData.ThrowStatement.Parent;
while (currentParent != null)
{
if (currentParent is TryStatementSyntax tryStatement)
{
bool thrownTypeIsCaught = tryStatement.Catches
.Where(catchClause => catchClause != analysisData.RethrowOf)
.Select(catchClause => semanticModel.GetTypeInfo(catchClause.Declaration.Type).Type)
.Any(caughtType =>
SymbolEqualityComparer.IncludeNullability.Equals(caughtType, analysisData.ThrownType));
if (thrownTypeIsCaught)
{
return true;
}
}
currentParent = currentParent.Parent;
}
return false;
}
private static bool IsExceptionDocumented(SymbolAnalysisContext context,
ThrowStatementAnalysisData analysisData,
DocumentationComment documentationComment)
{
if (documentationComment.Exceptions == null)
{
return false;
}
IEnumerable<ITypeSymbol> thrownBaseTypes = GetAllTypesOf(analysisData.ThrownType);
return documentationComment.Exceptions
.Where(exceptionDocumentationComment => exceptionDocumentationComment?.Type != null)
.Select(exceptionDocumentationComment => exceptionDocumentationComment.Type?.Substring(2))
.Select(documentedExceptionTypeName =>
context.Compilation.GetTypeByMetadataName(documentedExceptionTypeName))
.Any(documentedExceptionType => thrownBaseTypes.Contains(documentedExceptionType));
}
private static ImmutableArray<ITypeSymbol> GetAllTypesOf(ITypeSymbol? superset)
{
IList<ITypeSymbol> result = new List<ITypeSymbol>();
ITypeSymbol? type = superset;
while (type != null)
{
result.Add(type);
type = type.BaseType;
}
return result.ToImmutableArray();
}
}
}
|
using System.Collections.Generic;
using EasyAbp.Abp.SettingUi.Dto;
using Volo.Abp.Application;
using Volo.Abp.Modularity;
using Volo.Abp.VirtualFileSystem;
using Volo.Abp.Authorization;
using Volo.Abp.Json.SystemTextJson;
namespace EasyAbp.Abp.SettingUi
{
[DependsOn(
typeof(AbpSettingUiDomainSharedModule),
typeof(AbpDddApplicationContractsModule),
typeof(AbpAuthorizationModule)
)]
public class AbpSettingUiApplicationContractsModule : AbpModule
{
public override void ConfigureServices(ServiceConfigurationContext context)
{
Configure<AbpSystemTextJsonSerializerOptions>(options =>
{
// System.Text.Json seems cannot deserialize the Dictionary<string, object> type properly,
// So we let JSON.NET do this
options.UnsupportedTypes.AddIfNotContains(typeof(List<SettingGroup>));
});
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.SceneManagement;
public class OpeningTransition : MonoBehaviour {
public string nextLevel;
// Use this for initialization
void Start () {
Color fade_color = FadeManager.Instance.fadeImage.color;
FadeManager.Instance.fadeImage.color = new Color(fade_color.r,
fade_color.g,
fade_color.b,
1.0f);
Transition();
}
void SwapScene()
{
SceneSwapper.Instance.SwapScene(nextLevel);
}
void FadeEnd()
{
Animation openingAnimation = GetComponent<Animation>();
Animator openingController = GetComponent<Animator>();
AnimationEvent animationEvent = new AnimationEvent();
animationEvent.functionName = "SwapScene";
animationEvent.time = openingAnimation.clip.length;
openingAnimation.clip.AddEvent(animationEvent);
openingController.SetBool("playing", true);
}
void Transition()
{
FadeManager.Instance.Fade(false, 1.5f, FadeEnd);
}
// Update is called once per frame
void Update () {
if (Input.GetButtonDown("Cancel"))
{
#if UNITY_EDITOR
UnityEditor.EditorApplication.isPlaying = false;
#else
Application.Quit();
#endif
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu]
[System.Serializable]
public class TimelineElements : ScriptableObject
{
[SerializeField]
public List<TimelineElement> elements =new List<TimelineElement>();
public void AddElement(TimelineElement element){ elements.Add(element); }
public void RemoveElement(TimelineElement element){ elements.Add(element); }
public void ClearElements() { elements.Clear(); }
public List<TimelineElement> GetElements(int chapterId, TimelineType tlp)
{
List<TimelineElement> response = new List<TimelineElement>();
foreach (var item in elements)
{
if (item.chapterId==chapterId && tlp.Equals(item.type))
{
response.Add(item);
}
}
return response;
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Caching;
namespace Jusfr.Caching {
public class HttpRuntimeCacheProvider : CacheProvider, IHttpRuntimeCacheProvider, IRegion {
private static readonly Object _nullEntry = new Object();
private const String _prefix = "HRCP_";
public virtual String Region { get; private set; }
public HttpRuntimeCacheProvider() {
}
public HttpRuntimeCacheProvider(String region) {
Region = region;
}
private Boolean InnerTryGet(String key, out object entry) {
entry = HttpRuntime.Cache.Get(key);
return entry != null;
}
public override bool TryGet<T>(string key, out T entry) {
String cacheKey = BuildCacheKey(key);
Object cacheEntry;
Boolean exist = InnerTryGet(cacheKey, out cacheEntry);
if (exist) {
if (cacheEntry != null) {
if (!(cacheEntry is T)) {
throw new InvalidOperationException(String.Format("缓存项`[{0}]`类型错误, {1} or {2} ?",
key, cacheEntry.GetType().FullName, typeof(T).FullName));
}
entry = (T)cacheEntry;
}
else {
entry = (T)((Object)null);
}
}
else {
entry = default(T);
}
return exist;
}
protected override String BuildCacheKey(String key) {
//Region 为空将被当作 String.Empty 处理
return Region == null
? String.Concat(_prefix, key)
: String.Concat(_prefix, Region, "_", key);
}
private Object BuildCacheEntry<T>(T value) {
Object entry = value;
if (value == null) {
entry = _nullEntry;
}
return entry;
}
public T GetOrCreate<T>(String key, Func<T> function, TimeSpan slidingExpiration) {
T value;
if (TryGet<T>(key, out value)) {
return value;
}
value = function();
Overwrite(key, value, slidingExpiration);
return value;
}
public T GetOrCreate<T>(String key, Func<T> function, DateTime absoluteExpiration) {
T value;
if (TryGet<T>(key, out value)) {
return value;
}
value = function();
Overwrite(key, value, absoluteExpiration);
return value;
}
public override void Overwrite<T>(String key, T value) {
HttpRuntime.Cache.Insert(BuildCacheKey(key), BuildCacheEntry<T>(value));
}
//slidingExpiration 时间内无访问则过期
public void Overwrite<T>(String key, T value, TimeSpan slidingExpiration) {
HttpRuntime.Cache.Insert(BuildCacheKey(key), BuildCacheEntry<T>(value), null,
Cache.NoAbsoluteExpiration, slidingExpiration);
}
//absoluteExpiration 时过期
public void Overwrite<T>(String key, T value, DateTime absoluteExpiration) {
HttpRuntime.Cache.Insert(BuildCacheKey(key), BuildCacheEntry<T>(value), null,
absoluteExpiration, Cache.NoSlidingExpiration);
}
public override void Expire(String key) {
HttpRuntime.Cache.Remove(BuildCacheKey(key));
}
internal Boolean Hit(DictionaryEntry entry) {
return (entry.Key is String) && ((String)entry.Key).StartsWith(BuildCacheKey(String.Empty));
}
}
}
|
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
namespace Collectively.Api.Tests.EndToEnd.Framework
{
public interface IHttpClient
{
Task<IEnumerable<T>> GetCollectionAsync<T>(string endpoint);
Task<T> GetAsync<T>(string endpoint);
Task<HttpResponseMessage> GetAsync(string endpoint);
Task<Stream> GetStreamAsync(string endpoint);
Task<HttpResponseMessage> PostAsync(string endpoint, object data);
Task<T> PostAsync<T>(string endpoint, object data);
Task<HttpResponseMessage> PutAsync(string endpoint, object data);
Task<HttpResponseMessage> DeleteAsync(string endpoint);
void SetHeader(string name, string value);
}
} |
using EFDM.Abstractions.Audit;
using System.Collections.Generic;
namespace EFDM.Core.Audit {
public class AuditEvent : IAuditEvent {
public string ContextId { get; set; }
public List<IEventEntry> Entries { get; set; }
public int Result { get; set; }
public bool Success { get; set; }
public string ErrorMessage { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace p1_2.Models
{
public class CheckoutView
{
public int CheckoutViewId { get; set; }
public CustomerAddress CustomerAddress { get; set; }
public List<ShoppingCart> ShoppingCarts { get; set; }
}
}
|
using System;
using Utility.Storage.StorageHelper.Common;
namespace Utility.Storage.StorageHelper
{
static class StorageParametersExtension
{
public static DynamicParameters ToDapperParameters(this Func<Parameters, Parameters> getter)
{
if (getter == null) return null;
var parameters = new Parameters();
return (getter(parameters) ?? parameters).Result;
}
}
}
|
using GeneralStockMarket.Entities.Concrete;
using Microsoft.EntityFrameworkCore;
namespace GeneralStockMarket.Dal.Concrete.EntityFrameworkCore.Contexts
{
public class GeneralStockMarketDbContext : DbContext
{
public GeneralStockMarketDbContext(DbContextOptions<GeneralStockMarketDbContext> options) : base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.ApplyConfiguration(new Mapping.DepositRequestMap());
modelBuilder.ApplyConfiguration(new Mapping.MarketItemMap());
modelBuilder.ApplyConfiguration(new Mapping.NewTypeRequestMap());
modelBuilder.ApplyConfiguration(new Mapping.ProductDepositRequestMap());
modelBuilder.ApplyConfiguration(new Mapping.ProductItemMap());
modelBuilder.ApplyConfiguration(new Mapping.ProductMap());
modelBuilder.ApplyConfiguration(new Mapping.TransactionMap());
modelBuilder.ApplyConfiguration(new Mapping.WalletMap());
base.OnModelCreating(modelBuilder);
}
public DbSet<LimitOptionRequest> LimitOptionRequests { get; set; }
public DbSet<DepositRequest> DepositRequests { get; set; }
public DbSet<MarketItem> MarketItems { get; set; }
public DbSet<NewTypeRequest> NewTypeRequests { get; set; }
public DbSet<Product> Products { get; set; }
public DbSet<ProductDepositRequest> ProductDepositRequests { get; set; }
public DbSet<ProductItem> ProductItems { get; set; }
public DbSet<Transaction> Transactions { get; set; }
public DbSet<Wallet> Wallets { get; set; }
}
}
|
using GestaoFluxoFinanceiro.Negocio.Models;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace GestaoFluxoFinanceiro.Negocio.Interfaces
{
public interface IMovimentoProfissionalRepository : IRepository<MovimentoProfissional>
{
Task<MovimentoProfissional> ObterMovimentoPorProfissional(Guid ProfissionalId);
Task<MovimentoProfissional> ObterMovimentoPorId(Guid MovimentoId);
Task<MovimentoProfissional> ObterMovimentoProfissionalCompetencia(Guid ProfissionalId, string competencia);
Task<IEnumerable<MovimentoProfissional>> ObterMovimentos();
Task<IEnumerable<MovimentoProfissional>> ObterMovimentosReceitaCompetencia(string competencia);
Task<Caixa> BuscarCompetenciaCaixa();
}
}
|
using FSNEP.Core.Domain;
namespace FSNEP.BLL.Interfaces
{
public interface ITimeRecordBLL : IRecordBLL<TimeRecord>
{
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.