content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2
values |
|---|---|---|---|---|---|---|---|---|
using System.Collections.Generic;
namespace Task4
{
public class ParsingTreeNode
{
public string Value;
public List<ParsingTreeNode> Childrens = new List<ParsingTreeNode>();
}
}
| 15.666667 | 71 | 0.755319 | [
"MIT"
] | KvanTTT/BMSTU-Education | CompilerConstruction/Task4/ParsingTreeNode.cs | 190 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.ML.Runtime;
using Microsoft.ML.Runtime.CommandLine;
using Microsoft.ML.Runtime.Data;
using Microsoft.ML.Runtime.EntryPoints;
using Microsoft.ML.Runtime.Internal.Utilities;
using Microsoft.ML.Runtime.Model;
using Microsoft.ML.Transforms;
using System;
using System.Text;
[assembly: LoadableClass(typeof(LabelIndicatorTransform), typeof(LabelIndicatorTransform.Arguments), typeof(SignatureDataTransform),
LabelIndicatorTransform.UserName, LabelIndicatorTransform.LoadName, "LabelIndicator")]
[assembly: LoadableClass(typeof(LabelIndicatorTransform), null, typeof(SignatureLoadDataTransform), LabelIndicatorTransform.UserName,
LabelIndicatorTransform.LoaderSignature)]
[assembly: LoadableClass(typeof(void), typeof(LabelIndicatorTransform), null, typeof(SignatureEntryPointModule), LabelIndicatorTransform.LoadName)]
namespace Microsoft.ML.Transforms
{
/// <summary>
/// Remaps multiclass labels to binary T,F labels, primarily for use with OVA.
/// </summary>
public sealed class LabelIndicatorTransform : OneToOneTransformBase
{
internal const string Summary = "Remaps labels from multiclass to binary, for OVA.";
internal const string UserName = "Label Indicator Transform";
public const string LoaderSignature = "LabelIndicatorTransform";
public const string LoadName = LoaderSignature;
private readonly int[] _classIndex;
private static VersionInfo GetVersionInfo()
{
return new VersionInfo(
modelSignature: "LBINDTRN",
verWrittenCur: 0x00010001, // Initial
verReadableCur: 0x00010001,
verWeCanReadBack: 0x00010001,
loaderSignature: LoaderSignature,
loaderAssemblyName: typeof(LabelIndicatorTransform).Assembly.FullName);
}
public sealed class Column : OneToOneColumn
{
[Argument(ArgumentType.AtMostOnce, HelpText = "The positive example class for binary classification.", ShortName = "index")]
public int? ClassIndex;
public static Column Parse(string str)
{
Contracts.AssertNonEmpty(str);
var res = new Column();
if (res.TryParse(str))
return res;
return null;
}
public bool TryUnparse(StringBuilder sb)
{
Contracts.AssertValue(sb);
return TryUnparseCore(sb);
}
}
public sealed class Arguments : TransformInputBase
{
[Argument(ArgumentType.Multiple, HelpText = "New column definition(s) (optional form: name:src)", ShortName = "col", SortOrder = 1)]
public Column[] Column;
[Argument(ArgumentType.AtMostOnce, HelpText = "Label of the positive class.", ShortName = "index")]
public int ClassIndex;
}
public static LabelIndicatorTransform Create(IHostEnvironment env,
ModelLoadContext ctx, IDataView input)
{
Contracts.CheckValue(env, nameof(env));
IHost h = env.Register(LoaderSignature);
h.CheckValue(ctx, nameof(ctx));
h.CheckValue(input, nameof(input));
return h.Apply("Loading Model",
ch => new LabelIndicatorTransform(h, ctx, input));
}
public static LabelIndicatorTransform Create(IHostEnvironment env,
Arguments args, IDataView input)
{
Contracts.CheckValue(env, nameof(env));
IHost h = env.Register(LoaderSignature);
h.CheckValue(args, nameof(args));
h.CheckValue(input, nameof(input));
return h.Apply("Loading Model",
ch => new LabelIndicatorTransform(h, args, input));
}
public override void Save(ModelSaveContext ctx)
{
Host.CheckValue(ctx, nameof(ctx));
ctx.CheckAtModel();
ctx.SetVersionInfo(GetVersionInfo());
SaveBase(ctx);
ctx.Writer.WriteIntStream(_classIndex);
}
private static string TestIsMulticlassLabel(ColumnType type)
{
if (type.KeyCount > 0 || type == NumberType.R4 || type == NumberType.R8)
return null;
return $"Label column type is not supported for binary remapping: {type}. Supported types: key, float, double.";
}
/// <summary>
/// Convenience constructor for public facing API.
/// </summary>
/// <param name="env">Host Environment.</param>
/// <param name="input">Input <see cref="IDataView"/>. This is the output from previous transform or loader.</param>
/// <param name="classIndex">Label of the positive class.</param>
/// <param name="name">Name of the output column.</param>
/// <param name="source">Name of the input column. If this is null '<paramref name="name"/>' will be used.</param>
public LabelIndicatorTransform(IHostEnvironment env,
IDataView input,
int classIndex,
string name,
string source = null)
: this(env, new Arguments() { Column = new[] { new Column() { Source = source ?? name, Name = name } }, ClassIndex = classIndex }, input)
{
}
public LabelIndicatorTransform(IHostEnvironment env, Arguments args, IDataView input)
: base(env, LoadName, Contracts.CheckRef(args, nameof(args)).Column,
input, TestIsMulticlassLabel)
{
Host.AssertNonEmpty(Infos);
Host.Assert(Infos.Length == Utils.Size(args.Column));
_classIndex = new int[Infos.Length];
for (int iinfo = 0; iinfo < Infos.Length; ++iinfo)
_classIndex[iinfo] = args.Column[iinfo].ClassIndex ?? args.ClassIndex;
Metadata.Seal();
}
private LabelIndicatorTransform(IHost host, ModelLoadContext ctx, IDataView input)
: base(host, ctx, input, TestIsMulticlassLabel)
{
Host.AssertValue(ctx);
Host.AssertNonEmpty(Infos);
_classIndex = new int[Infos.Length];
for (int iinfo = 0; iinfo < Infos.Length; ++iinfo)
_classIndex[iinfo] = ctx.Reader.ReadInt32();
Metadata.Seal();
}
protected override ColumnType GetColumnTypeCore(int iinfo)
{
Host.Assert(0 <= iinfo && iinfo < Infos.Length);
return BoolType.Instance;
}
protected override Delegate GetGetterCore(IChannel ch, IRow input,
int iinfo, out Action disposer)
{
Host.AssertValue(ch);
ch.AssertValue(input);
ch.Assert(0 <= iinfo && iinfo < Infos.Length);
disposer = null;
var info = Infos[iinfo];
return GetGetter(ch, input, iinfo);
}
private ValueGetter<bool> GetGetter(IChannel ch, IRow input, int iinfo)
{
Host.AssertValue(ch);
ch.AssertValue(input);
ch.Assert(0 <= iinfo && iinfo < Infos.Length);
var info = Infos[iinfo];
ch.Assert(TestIsMulticlassLabel(info.TypeSrc) == null);
if (info.TypeSrc.KeyCount > 0)
{
var srcGetter = input.GetGetter<uint>(info.Source);
var src = default(uint);
uint cls = (uint)(_classIndex[iinfo] + 1);
return
(ref bool dst) =>
{
srcGetter(ref src);
dst = src == cls;
};
}
if (info.TypeSrc == NumberType.R4)
{
var srcGetter = input.GetGetter<float>(info.Source);
var src = default(float);
return
(ref bool dst) =>
{
srcGetter(ref src);
dst = src == _classIndex[iinfo];
};
}
if (info.TypeSrc == NumberType.R8)
{
var srcGetter = input.GetGetter<double>(info.Source);
var src = default(double);
return
(ref bool dst) =>
{
srcGetter(ref src);
dst = src == _classIndex[iinfo];
};
}
throw Host.ExceptNotSupp($"Label column type is not supported for binary remapping: {info.TypeSrc}. Supported types: key, float, double.");
}
[TlcModule.EntryPoint(Name = "Transforms.LabelIndicator", Desc = "Label remapper used by OVA", UserName = "LabelIndicator",
ShortName = "LabelIndictator")]
public static CommonOutputs.TransformOutput LabelIndicator(IHostEnvironment env, Arguments input)
{
Contracts.CheckValue(env, nameof(env));
var host = env.Register("LabelIndictator");
host.CheckValue(input, nameof(input));
EntryPointUtils.CheckInputArgs(host, input);
var xf = Create(host, input, input.Data);
return new CommonOutputs.TransformOutput { Model = new TransformModel(env, xf, input.Data), OutputData = xf };
}
}
}
| 39.726141 | 151 | 0.585126 | [
"MIT"
] | Caraul/machinelearning | src/Microsoft.ML.Data/Transforms/LabelIndicatorTransform.cs | 9,574 | C# |
using System;
using System.Linq;
using System.Threading.Tasks;
using Template10.Samples.TilesSample.ViewModels;
using Windows.UI.StartScreen;
using Windows.UI.Notifications;
using NotificationsExtensions.Tiles;
using NotificationsExtensions.Toasts;
namespace Template10.Samples.TilesSample.Services.TileService
{
class TileService
{
internal async Task<bool> IsPinned(DetailPageViewModel detailPageViewModel)
{
var tileId = detailPageViewModel.ToString();
return (await SecondaryTile.FindAllAsync()).Any(x => x.TileId.Equals(tileId));
}
internal async Task<bool> PinAsync(DetailPageViewModel detailPageViewModel)
{
var name = "Tiles sample";
var title = "Template 10";
var body = detailPageViewModel.Value;
var image = "https://raw.githubusercontent.com/Windows-XAML/Template10/master/Assets/Template10.png";
var bindingContent = new TileBindingContentAdaptive()
{
PeekImage = new TilePeekImage()
{
Source = new TileImageSource(image)
},
Children =
{
new TileText()
{
Text = title,
Style = TileTextStyle.Body
},
new TileText()
{
Text = body,
Wrap = true,
Style = TileTextStyle.CaptionSubtle
}
}
};
var binding = new TileBinding()
{
Branding = TileBranding.NameAndLogo,
DisplayName = name,
Content = bindingContent
};
var content = new TileContent()
{
Visual = new TileVisual()
{
TileMedium = binding,
TileWide = binding,
TileLarge = binding
}
};
var xml = content.GetXml();
// show tile
var tileId = detailPageViewModel.ToString();
if (!await IsPinned(detailPageViewModel))
{
// initial pin
var logo = new Uri("ms-appx:///Assets/Logo.png");
var secondaryTile = new SecondaryTile(tileId)
{
Arguments = detailPageViewModel.Value,
DisplayName = name,
VisualElements =
{
Square44x44Logo = logo,
Square150x150Logo = logo,
Wide310x150Logo = logo,
Square310x310Logo = logo,
ShowNameOnSquare150x150Logo = true,
},
};
if (!await secondaryTile.RequestCreateAsync())
{
System.Diagnostics.Debugger.Break();
return false;
}
}
// add notifications
var tileNotification = new TileNotification(xml);
var tileUpdater = TileUpdateManager.CreateTileUpdaterForSecondaryTile(tileId);
tileUpdater.Update(tileNotification);
// show toast
ShowToast(detailPageViewModel);
// result
return true;
}
void ShowToast(DetailPageViewModel detailPageViewModel)
{
var data = detailPageViewModel.Value;
var image = "https://raw.githubusercontent.com/Windows-XAML/Template10/master/Assets/Template10.png";
var content = new ToastContent()
{
Launch = data,
Visual = new ToastVisual()
{
TitleText = new ToastText()
{
Text = "Secondary tile pinned"
},
BodyTextLine1 = new ToastText()
{
Text = detailPageViewModel.Value
},
AppLogoOverride = new ToastAppLogo()
{
Crop = ToastImageCrop.Circle,
Source = new ToastImageSource(image)
}
},
Audio = new ToastAudio()
{
Src = new Uri("ms-winsoundevent:Notification.IM")
}
};
var notification = new ToastNotification(content.GetXml());
var notifier = ToastNotificationManager.CreateToastNotifier();
notifier.Show(notification);
}
internal async Task<bool> UnPinAsync(DetailPageViewModel detailPageViewModel)
{
if (!await IsPinned(detailPageViewModel))
return true;
try
{
var tileId = detailPageViewModel.ToString();
var tile = new SecondaryTile(tileId);
return await tile.RequestDeleteAsync();
}
catch (Exception)
{
System.Diagnostics.Debugger.Break();
return false;
}
}
}
}
| 31.946429 | 113 | 0.47438 | [
"Apache-2.0"
] | ArtjomP/Template10 | Samples/Tiles/Services/TileService/TileService.cs | 5,369 | C# |
using System;
using UserTasks.Core.SharedKernel;
namespace UserTasks.Core.Interfaces
{
/// <summary>
/// This interface is implemented by entities which must be audited.
/// Related properties automatically set when saving/updating <see cref="BaseEntity"/> objects.
/// </summary>
public interface IAuditedEntity
{
string CreatedBy { get; set; }
string UpdatedBy { get; set; }
DateTime CreatedDate { get; set; }
DateTime UpdatedDate { get; set; }
}
}
| 28.5 | 99 | 0.65692 | [
"MIT"
] | nasraldin/UserTasks | UserTasks.Core/Interfaces/IAuditedEntity.cs | 515 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Xml.Linq;
using UnityEngine;
namespace Unity.VisualScripting
{
public static class XmlDocumentation
{
class Data
{
public Dictionary<Assembly, Dictionary<string, XmlDocumentationTags>> documentations;
public Dictionary<Type, XmlDocumentationTags> typeDocumentations;
public Dictionary<MemberInfo, XmlDocumentationTags> memberDocumentations;
public Dictionary<object, XmlDocumentationTags> enumDocumentations;
public void Clear()
{
documentations.Clear();
typeDocumentations.Clear();
memberDocumentations.Clear();
enumDocumentations.Clear();
}
}
private static Lazy<Data> LazyData = new Lazy<Data>(Init);
private static readonly object @lock = new object();
public static event Action loadComplete;
public static bool loaded { get; private set; }
private static string[] fallbackDirectories;
internal static void Initialize()
{
BackgroundWorker.Schedule(BackgroundWork);
}
private static Data Init()
{
return new Data
{
documentations = new Dictionary<Assembly, Dictionary<string, XmlDocumentationTags>>(),
typeDocumentations = new Dictionary<Type, XmlDocumentationTags>(),
memberDocumentations = new Dictionary<MemberInfo, XmlDocumentationTags>(),
enumDocumentations = new Dictionary<object, XmlDocumentationTags>(),
};
}
public static void BackgroundWork()
{
var preloadedAssemblies = new List<Assembly>();
preloadedAssemblies.AddRange(Codebase.settingsAssemblies);
preloadedAssemblies.AddRange(Codebase.ludiqEditorAssemblies);
for (var i = 0; i < preloadedAssemblies.Count; i++)
{
var assembly = preloadedAssemblies[i];
ProgressUtility.DisplayProgressBar($"Documentation ({assembly.GetName().Name})...", null, (float)i / Codebase.settingsAssemblies.Count);
var documentation = GetDocumentationUncached(assembly);
lock (@lock)
{
if (!LazyData.Value.documentations.ContainsKey(assembly))
{
LazyData.Value.documentations.Add(assembly, documentation);
}
}
}
UnityAPI.Async(() =>
{
loaded = true;
loadComplete?.Invoke();
});
}
public static void ClearCache()
{
if (!LazyData.IsValueCreated)
return;
lock (@lock)
{
LazyData.Value.Clear();
}
}
private static Dictionary<string, XmlDocumentationTags> Documentation(Assembly assembly)
{
lock (@lock)
{
if (!loaded)
{
return null;
}
var valueDocumentations = LazyData.Value.documentations;
if (!valueDocumentations.ContainsKey(assembly))
{
valueDocumentations.Add(assembly, GetDocumentationUncached(assembly));
}
return valueDocumentations[assembly];
}
}
private static Dictionary<string, XmlDocumentationTags> GetDocumentationUncached(Assembly assembly)
{
var assemblyPath = assembly.Location;
var documentationPath = Path.ChangeExtension(assemblyPath, ".xml");
#if UNITY_EDITOR_OSX || UNITY_EDITOR_LINUX
documentationPath = "/" + documentationPath;
#endif
if (fallbackDirectories == null)
{
fallbackDirectories = new[]
{
BoltCore.Paths.dotNetDocumentation,
BoltCore.Paths.assemblyDocumentations
};
}
if (!File.Exists(documentationPath))
{
foreach (var fallbackDirectory in fallbackDirectories)
{
if (Directory.Exists(fallbackDirectory))
{
var fallbackPath = Path.Combine(fallbackDirectory, Path.GetFileName(documentationPath));
if (File.Exists(fallbackPath))
{
documentationPath = fallbackPath;
break;
}
}
}
}
if (!File.Exists(documentationPath))
{
return null;
}
XDocument document;
try
{
document = XDocument.Load(documentationPath);
}
catch (Exception ex)
{
Debug.LogWarning("Failed to load XML documentation:\n" + ex);
return null;
}
var ns = document.Root.Name.Namespace;
var dictionary = new Dictionary<string, XmlDocumentationTags>();
foreach (var memberElement in document.Element(ns + "doc").Element(ns + "members").Elements(ns + "member"))
{
var nameAttribute = memberElement.Attribute("name");
if (nameAttribute != null)
{
if (dictionary.ContainsKey(nameAttribute.Value))
{
// Unity sometimes has duplicate member documentation in their XMLs.
// Safely skip.
continue;
}
dictionary.Add(nameAttribute.Value, new XmlDocumentationTags(memberElement));
}
}
return dictionary;
}
public static XmlDocumentationTags Documentation(this MemberInfo memberInfo)
{
if (memberInfo is Type)
{
return ((Type)memberInfo).Documentation();
}
else if (memberInfo is MethodInfo)
{
return ((MethodInfo)memberInfo).Documentation();
}
else if (memberInfo is FieldInfo)
{
return ((FieldInfo)memberInfo).Documentation();
}
else if (memberInfo is PropertyInfo)
{
return ((PropertyInfo)memberInfo).Documentation();
}
else if (memberInfo is ConstructorInfo)
{
return ((ConstructorInfo)memberInfo).Documentation();
}
return null;
}
public static string ParameterSummary(this MethodBase methodBase, ParameterInfo parameterInfo)
{
return methodBase.Documentation()?.ParameterSummary(parameterInfo);
}
public static string Summary(this MemberInfo memberInfo)
{
return memberInfo.Documentation()?.summary;
}
public static string Summary(this Enum @enum)
{
return @enum.Documentation()?.summary;
}
public static XmlDocumentationTags Documentation(this Enum @enum)
{
lock (@lock)
{
if (!loaded)
{
return null;
}
var xmlDocumentationTagsMap = LazyData.Value.enumDocumentations;
if (!xmlDocumentationTagsMap.ContainsKey(@enum))
{
xmlDocumentationTagsMap.Add(@enum, GetDocumentationFromNameInherited(@enum.GetType(), 'F', @enum.ToString(), null));
}
return xmlDocumentationTagsMap[@enum];
}
}
private static XmlDocumentationTags Documentation(this MethodInfo methodInfo)
{
lock (@lock)
{
if (!loaded)
{
return null;
}
var xmlDocumentationTagsMap = LazyData.Value.memberDocumentations;
if (!xmlDocumentationTagsMap.ContainsKey(methodInfo))
{
var methodDocumentation = GetDocumentationFromNameInherited(methodInfo.DeclaringType, 'M', methodInfo.Name, methodInfo.GetParameters());
methodDocumentation?.CompleteWithMethodBase(methodInfo, methodInfo.ReturnType);
xmlDocumentationTagsMap.Add(methodInfo, methodDocumentation);
}
return xmlDocumentationTagsMap[methodInfo];
}
}
private static XmlDocumentationTags Documentation(this FieldInfo fieldInfo)
{
lock (@lock)
{
if (!loaded)
{
return null;
}
var xmlDocumentationTagsMap = LazyData.Value.memberDocumentations;
if (!xmlDocumentationTagsMap.ContainsKey(fieldInfo))
{
xmlDocumentationTagsMap.Add(fieldInfo, GetDocumentationFromNameInherited(fieldInfo.DeclaringType, 'F', fieldInfo.Name, null));
}
return xmlDocumentationTagsMap[fieldInfo];
}
}
private static XmlDocumentationTags Documentation(this PropertyInfo propertyInfo)
{
lock (@lock)
{
if (!loaded)
{
return null;
}
var xmlDocumentationTagsMap = LazyData.Value.memberDocumentations;
if (!xmlDocumentationTagsMap.ContainsKey(propertyInfo))
{
xmlDocumentationTagsMap.Add(propertyInfo, GetDocumentationFromNameInherited(propertyInfo.DeclaringType, 'P', propertyInfo.Name, null));
}
return xmlDocumentationTagsMap[propertyInfo];
}
}
private static XmlDocumentationTags Documentation(this ConstructorInfo constructorInfo)
{
lock (@lock)
{
if (!loaded)
{
return null;
}
var xmlDocumentationTagsMap = LazyData.Value.memberDocumentations;
if (!xmlDocumentationTagsMap.ContainsKey(constructorInfo))
{
var constructorDocumentation = GetDocumentationFromNameInherited(constructorInfo.DeclaringType, 'M', "#ctor", constructorInfo.GetParameters());
constructorDocumentation?.CompleteWithMethodBase(constructorInfo, constructorInfo.DeclaringType);
xmlDocumentationTagsMap.Add(constructorInfo, constructorDocumentation);
}
return xmlDocumentationTagsMap[constructorInfo];
}
}
private static XmlDocumentationTags Documentation(this Type type)
{
lock (@lock)
{
if (!loaded)
{
return null;
}
var xmlDocumentationTagsMap = LazyData.Value.typeDocumentations;
if (!xmlDocumentationTagsMap.ContainsKey(type))
{
xmlDocumentationTagsMap.Add(type, GetDocumentationFromNameInherited(type, 'T', null, null));
}
return xmlDocumentationTagsMap[type];
}
}
private static XmlDocumentationTags GetDocumentationFromNameInherited(Type type, char prefix, string memberName, IEnumerable<ParameterInfo> parameterTypes)
{
var documentation = GetDocumentationFromName(type, prefix, memberName, parameterTypes);
if (documentation != null && documentation.inherit)
{
foreach (var implementedType in type.BaseTypeAndInterfaces())
{
var implementedDocumentation = GetDocumentationFromNameInherited(implementedType, prefix, memberName, parameterTypes);
if (implementedDocumentation != null)
{
return implementedDocumentation;
}
}
return null;
}
return documentation;
}
private static XmlDocumentationTags GetDocumentationFromName(Type type, char prefix, string memberName, IEnumerable<ParameterInfo> parameterTypes)
{
var documentation = Documentation(type.Assembly);
if (documentation == null)
{
return null;
}
if (type.IsGenericType)
{
type = type.GetGenericTypeDefinition();
}
var fullName = $"{prefix}:{type.Namespace}{(type.Namespace != null ? "." : "")}{type.Name.Replace('+', '.')}";
if (!string.IsNullOrEmpty(memberName))
{
fullName += "." + memberName;
if (parameterTypes != null && parameterTypes.Any())
{
fullName += "(" + string.Join(",", parameterTypes.Select(p => p.ParameterType.ToString() + (p.IsOut || p.ParameterType.IsByRef ? "@" : "")).ToArray()) + ")";
}
}
if (documentation.ContainsKey(fullName))
{
return documentation[fullName];
}
return null;
}
}
}
| 33.409756 | 177 | 0.531975 | [
"Apache-2.0"
] | ASlugin/Homework-2sem | SCP-087/Library/PackageCache/com.unity.visualscripting@1.7.6/Editor/VisualScripting.Core/Documentation/XmlDocumentation.cs | 13,698 | C# |
using SharpenedMinecraft.Types.Blocks;
using System;
using System.Collections.Generic;
using System.Text;
namespace SharpenedMinecraft.Types.Items
{
public class Sea_pickleItem : ItemStack
{
public override string Id => "minecraft:sea_pickle";
public override Int32 ProtocolId => 74;
public override void OnUse(World world, Vector3 Pos, Player player)
{
world.SetBlock(Pos, new Sea_pickleBlock(), player);
}
}
}
| 22.5 | 75 | 0.660606 | [
"MIT"
] | SharpenedMinecraft/SM1 | Main/Types/Items/Sea_pickleItem.cs | 495 | C# |
using SOLID_._1.SRP.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SOLID_._1.SRP.Good_Example
{
public class GoodInsertEmployee
{
public GoodLogger goodLogger;
public GoodInsertEmployee()
{
goodLogger = new GoodLogger();
}
string log;
public void CreateEmployee(Employee employee)
{
StringBuilder stringBuilder = new StringBuilder();
try
{
stringBuilder.Append(employee.Id.ToString());
stringBuilder.Append(employee.FirstName);
stringBuilder.Append(employee.LastName);
stringBuilder.Append(employee.HireDate.ToString());
log = goodLogger.BuildLog(stringBuilder.ToString());
goodLogger.LogFile(@"C:\Log.txt", log);
}
catch (Exception ex)
{
log = goodLogger.BuildLog(ex.Message);
goodLogger.LogFile(@"C:\Log.txt", log);
}
}
}
}
| 25.911111 | 69 | 0.54717 | [
"MIT"
] | CeyhunAslan/SOLID | SOLID/SOLID_/1.Single Responsibility Principle/Good Example/GoodInsertEmployee.cs | 1,168 | C# |
using System;
using System.ComponentModel.DataAnnotations;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
namespace OnlinePremios.Mvc.Areas.Identity.Pages.Account.Manage
{
public class DeletePersonalDataModel : PageModel
{
private readonly UserManager<IdentityUser> _userManager;
private readonly SignInManager<IdentityUser> _signInManager;
private readonly ILogger<DeletePersonalDataModel> _logger;
public DeletePersonalDataModel(
UserManager<IdentityUser> userManager,
SignInManager<IdentityUser> signInManager,
ILogger<DeletePersonalDataModel> logger)
{
_userManager = userManager;
_signInManager = signInManager;
_logger = logger;
}
[BindProperty]
public InputModel Input { get; set; }
public class InputModel
{
[Required]
[DataType(DataType.Password)]
public string Password { get; set; }
}
public bool RequirePassword { get; set; }
public async Task<IActionResult> OnGet()
{
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
}
RequirePassword = await _userManager.HasPasswordAsync(user);
return Page();
}
public async Task<IActionResult> OnPostAsync()
{
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
}
RequirePassword = await _userManager.HasPasswordAsync(user);
if (RequirePassword)
{
if (!await _userManager.CheckPasswordAsync(user, Input.Password))
{
ModelState.AddModelError(string.Empty, "Incorrect password.");
return Page();
}
}
var result = await _userManager.DeleteAsync(user);
var userId = await _userManager.GetUserIdAsync(user);
if (!result.Succeeded)
{
throw new InvalidOperationException($"Unexpected error occurred deleting user with ID '{userId}'.");
}
await _signInManager.SignOutAsync();
_logger.LogInformation("User with ID '{UserId}' deleted themselves.", userId);
return Redirect("~/");
}
}
}
| 32.607143 | 116 | 0.596568 | [
"MIT"
] | carlosItDevelop/OnlinePremios | src/OnlinePremio.Mvc/Areas/Identity/Pages/Account/Manage/DeletePersonalData.cshtml.cs | 2,741 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using XNALib;
namespace QTD
{
public class InfoPanel
{
static readonly Rectangle DrawRect = new Rectangle(800, 100, 400, 512);
static readonly Texture2D BG = Common.White1px50Trans;
List<StringBuilder> Texts = new List<StringBuilder>(50);
static readonly SpriteFont Font = Common.str2Font("InfoPanel");
float TextSpacingY;
public InfoPanel()
{
TextSpacingY = Font.MeasureString(Common.MeasureString).Y;
}
public void SetText(List<StringBuilder> texts)
{
Texts.Clear();
Texts.AddRange(texts);
}
public void ClearText()
{
Texts.Clear();
}
public void Draw()
{
if (Texts.Count > 0)
{
// BG
Engine.Instance.SpriteBatch.Draw(BG, DrawRect, Color.Gray);
// Texts
float locY = DrawRect.Y + 20;
foreach (StringBuilder text in Texts)
{
Engine.Instance.SpriteBatch.DrawString(Font, text, new Vector2(DrawRect.X + 10, locY), Color.White);
locY += TextSpacingY;
}
}
}
}
} | 27.407407 | 120 | 0.564189 | [
"MIT"
] | SquirtingElephant/QTD | QTD/QTD/InfoPanel.cs | 1,482 | C# |
namespace Cogito.MassTransit.Scheduling.Periodic
{
public class PT12H :
P
{
}
}
| 8.153846 | 49 | 0.575472 | [
"MIT"
] | alethic/Cogito.MassTransit | Cogito.MassTransit/Scheduling/Periodic/PT12H.cs | 108 | C# |
/*
* Created by SharpDevelop.
* User: Dan
* Date: 29/10/2009
* Time: 12:07 AM
*
* To change this template use Tools | Options | Coding | Edit Standard Headers.
*/
using System;
namespace Thorm
{
/// <summary>
/// Maps data types to 'Thorm-safe' types
/// </summary>
public static class DataTypeMapping
{
/// <summary>
/// Cast the given object to the required type.
/// </summary>
/// <param name="type">The type to cast to</param>
/// <param name="obj">The object to cast</param>
/// <returns>The object, in the required type.</returns>
public static object CastObjectTo(Type type, object obj)
{
object ret = obj;
// Use this for nullable types
if (type.IsGenericType) type = type.GetGenericArguments()[0];
string objstr = obj.ToString();
if (type == typeof(int)) ret = int.Parse(objstr);
else if (type == typeof(decimal)) ret = decimal.Parse(objstr);
else if (type == typeof(DateTime)) ret = DateTime.Parse(objstr);
else if (type == typeof(string)) ret = objstr;
return ret;
}
}
}
| 26.55 | 80 | 0.638418 | [
"BSD-3-Clause"
] | LogicAndTrick/thor | Thorm/Static/DataTypeMapping.cs | 1,064 | C# |
using System;
using System.Globalization;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Data;
namespace PrismaGUI.Converters
{
internal class RegexStringConverter : IValueConverter
{
public object? Convert(object? value, Type targetType, object parameter, CultureInfo _)
{
return value is Regex regex ? regex.ToString() : DependencyProperty.UnsetValue;
}
public object? ConvertBack(object? value, Type targetType, object parameter, CultureInfo _)
{
string? pattern = value?.ToString();
if (string.IsNullOrWhiteSpace(pattern))
{
return DependencyProperty.UnsetValue;
}
try
{
// Give 2.5 seconds as maximum to prevent blocking the UI forever.
return new Regex(pattern, RegexOptions.None, TimeSpan.FromMilliseconds(2500));
}
catch (ArgumentException)
{
return DependencyProperty.UnsetValue;
}
}
}
}
| 29.513514 | 99 | 0.606227 | [
"MIT"
] | mainframe98/Prisma | PrismaGUI/Converters/RegexStringConverter.cs | 1,094 | C# |
/**
* Autogenerated by Thrift Compiler (0.11.0)
*
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
* @generated
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.IO;
using Thrift;
using Thrift.Collections;
using System.Runtime.Serialization;
using Thrift.Protocol;
using Thrift.Transport;
namespace STB_Modeling_Techniques.DEISProject.ODEDataModel.ThriftContract
{
#if !SILVERLIGHT
[Serializable]
#endif
public partial class TDDIActivity : TBase
{
private string _Gid;
private bool _IsCitation;
private bool _IsAbstract;
private TDDIAbstractSACMElement _CitedElement;
private TDDIAbstractSACMElement _AbstractForm;
private TDDIAbstractLangString _Name;
private TDDIDescription _Description;
private List<TDDIImplementationConstraintRef> _ImplementationConstraint;
private List<TDDINoteRef> _Note;
private List<TDDITaggedValueRef> _TaggedValue;
private List<TDDIPropertyRef> _Property;
private string _StartTime;
private string _EndTime;
public string Gid
{
get
{
return _Gid;
}
set
{
__isset.Gid = true;
this._Gid = value;
}
}
public bool IsCitation
{
get
{
return _IsCitation;
}
set
{
__isset.IsCitation = true;
this._IsCitation = value;
}
}
public bool IsAbstract
{
get
{
return _IsAbstract;
}
set
{
__isset.IsAbstract = true;
this._IsAbstract = value;
}
}
public TDDIAbstractSACMElement CitedElement
{
get
{
return _CitedElement;
}
set
{
__isset.CitedElement = true;
this._CitedElement = value;
}
}
public TDDIAbstractSACMElement AbstractForm
{
get
{
return _AbstractForm;
}
set
{
__isset.AbstractForm = true;
this._AbstractForm = value;
}
}
public TDDIAbstractLangString Name
{
get
{
return _Name;
}
set
{
__isset.Name = true;
this._Name = value;
}
}
public TDDIDescription Description
{
get
{
return _Description;
}
set
{
__isset.Description = true;
this._Description = value;
}
}
public List<TDDIImplementationConstraintRef> ImplementationConstraint
{
get
{
return _ImplementationConstraint;
}
set
{
__isset.ImplementationConstraint = true;
this._ImplementationConstraint = value;
}
}
public List<TDDINoteRef> Note
{
get
{
return _Note;
}
set
{
__isset.Note = true;
this._Note = value;
}
}
public List<TDDITaggedValueRef> TaggedValue
{
get
{
return _TaggedValue;
}
set
{
__isset.TaggedValue = true;
this._TaggedValue = value;
}
}
public List<TDDIPropertyRef> Property
{
get
{
return _Property;
}
set
{
__isset.Property = true;
this._Property = value;
}
}
public string StartTime
{
get
{
return _StartTime;
}
set
{
__isset.StartTime = true;
this._StartTime = value;
}
}
public string EndTime
{
get
{
return _EndTime;
}
set
{
__isset.EndTime = true;
this._EndTime = value;
}
}
public Isset __isset;
#if !SILVERLIGHT
[Serializable]
#endif
public struct Isset {
public bool Gid;
public bool IsCitation;
public bool IsAbstract;
public bool CitedElement;
public bool AbstractForm;
public bool Name;
public bool Description;
public bool ImplementationConstraint;
public bool Note;
public bool TaggedValue;
public bool Property;
public bool StartTime;
public bool EndTime;
}
public TDDIActivity() {
this._Gid = "";
this.__isset.Gid = true;
this._IsCitation = false;
this.__isset.IsCitation = true;
this._IsAbstract = false;
this.__isset.IsAbstract = true;
this._ImplementationConstraint = new List<TDDIImplementationConstraintRef>();
this.__isset.ImplementationConstraint = true;
this._Note = new List<TDDINoteRef>();
this.__isset.Note = true;
this._TaggedValue = new List<TDDITaggedValueRef>();
this.__isset.TaggedValue = true;
this._Property = new List<TDDIPropertyRef>();
this.__isset.Property = true;
this._StartTime = "";
this.__isset.StartTime = true;
this._EndTime = "";
this.__isset.EndTime = true;
}
public void Read (TProtocol iprot)
{
iprot.IncrementRecursionDepth();
try
{
TField field;
iprot.ReadStructBegin();
while (true)
{
field = iprot.ReadFieldBegin();
if (field.Type == TType.Stop) {
break;
}
switch (field.ID)
{
case 1:
if (field.Type == TType.String) {
Gid = iprot.ReadString();
} else {
TProtocolUtil.Skip(iprot, field.Type);
}
break;
case 2:
if (field.Type == TType.Bool) {
IsCitation = iprot.ReadBool();
} else {
TProtocolUtil.Skip(iprot, field.Type);
}
break;
case 3:
if (field.Type == TType.Bool) {
IsAbstract = iprot.ReadBool();
} else {
TProtocolUtil.Skip(iprot, field.Type);
}
break;
case 4:
if (field.Type == TType.Struct) {
CitedElement = new TDDIAbstractSACMElement();
CitedElement.Read(iprot);
} else {
TProtocolUtil.Skip(iprot, field.Type);
}
break;
case 5:
if (field.Type == TType.Struct) {
AbstractForm = new TDDIAbstractSACMElement();
AbstractForm.Read(iprot);
} else {
TProtocolUtil.Skip(iprot, field.Type);
}
break;
case 6:
if (field.Type == TType.Struct) {
Name = new TDDIAbstractLangString();
Name.Read(iprot);
} else {
TProtocolUtil.Skip(iprot, field.Type);
}
break;
case 7:
if (field.Type == TType.Struct) {
Description = new TDDIDescription();
Description.Read(iprot);
} else {
TProtocolUtil.Skip(iprot, field.Type);
}
break;
case 8:
if (field.Type == TType.List) {
{
ImplementationConstraint = new List<TDDIImplementationConstraintRef>();
TList _list1284 = iprot.ReadListBegin();
for( int _i1285 = 0; _i1285 < _list1284.Count; ++_i1285)
{
TDDIImplementationConstraintRef _elem1286;
_elem1286 = new TDDIImplementationConstraintRef();
_elem1286.Read(iprot);
ImplementationConstraint.Add(_elem1286);
}
iprot.ReadListEnd();
}
} else {
TProtocolUtil.Skip(iprot, field.Type);
}
break;
case 9:
if (field.Type == TType.List) {
{
Note = new List<TDDINoteRef>();
TList _list1287 = iprot.ReadListBegin();
for( int _i1288 = 0; _i1288 < _list1287.Count; ++_i1288)
{
TDDINoteRef _elem1289;
_elem1289 = new TDDINoteRef();
_elem1289.Read(iprot);
Note.Add(_elem1289);
}
iprot.ReadListEnd();
}
} else {
TProtocolUtil.Skip(iprot, field.Type);
}
break;
case 10:
if (field.Type == TType.List) {
{
TaggedValue = new List<TDDITaggedValueRef>();
TList _list1290 = iprot.ReadListBegin();
for( int _i1291 = 0; _i1291 < _list1290.Count; ++_i1291)
{
TDDITaggedValueRef _elem1292;
_elem1292 = new TDDITaggedValueRef();
_elem1292.Read(iprot);
TaggedValue.Add(_elem1292);
}
iprot.ReadListEnd();
}
} else {
TProtocolUtil.Skip(iprot, field.Type);
}
break;
case 11:
if (field.Type == TType.List) {
{
Property = new List<TDDIPropertyRef>();
TList _list1293 = iprot.ReadListBegin();
for( int _i1294 = 0; _i1294 < _list1293.Count; ++_i1294)
{
TDDIPropertyRef _elem1295;
_elem1295 = new TDDIPropertyRef();
_elem1295.Read(iprot);
Property.Add(_elem1295);
}
iprot.ReadListEnd();
}
} else {
TProtocolUtil.Skip(iprot, field.Type);
}
break;
case 12:
if (field.Type == TType.String) {
StartTime = iprot.ReadString();
} else {
TProtocolUtil.Skip(iprot, field.Type);
}
break;
case 13:
if (field.Type == TType.String) {
EndTime = iprot.ReadString();
} else {
TProtocolUtil.Skip(iprot, field.Type);
}
break;
default:
TProtocolUtil.Skip(iprot, field.Type);
break;
}
iprot.ReadFieldEnd();
}
iprot.ReadStructEnd();
}
finally
{
iprot.DecrementRecursionDepth();
}
}
public void Write(TProtocol oprot) {
oprot.IncrementRecursionDepth();
try
{
TStruct struc = new TStruct("TDDIActivity");
oprot.WriteStructBegin(struc);
TField field = new TField();
if (Gid != null && __isset.Gid) {
field.Name = "Gid";
field.Type = TType.String;
field.ID = 1;
oprot.WriteFieldBegin(field);
oprot.WriteString(Gid);
oprot.WriteFieldEnd();
}
if (__isset.IsCitation) {
field.Name = "IsCitation";
field.Type = TType.Bool;
field.ID = 2;
oprot.WriteFieldBegin(field);
oprot.WriteBool(IsCitation);
oprot.WriteFieldEnd();
}
if (__isset.IsAbstract) {
field.Name = "IsAbstract";
field.Type = TType.Bool;
field.ID = 3;
oprot.WriteFieldBegin(field);
oprot.WriteBool(IsAbstract);
oprot.WriteFieldEnd();
}
if (CitedElement != null && __isset.CitedElement) {
field.Name = "CitedElement";
field.Type = TType.Struct;
field.ID = 4;
oprot.WriteFieldBegin(field);
CitedElement.Write(oprot);
oprot.WriteFieldEnd();
}
if (AbstractForm != null && __isset.AbstractForm) {
field.Name = "AbstractForm";
field.Type = TType.Struct;
field.ID = 5;
oprot.WriteFieldBegin(field);
AbstractForm.Write(oprot);
oprot.WriteFieldEnd();
}
if (Name != null && __isset.Name) {
field.Name = "Name";
field.Type = TType.Struct;
field.ID = 6;
oprot.WriteFieldBegin(field);
Name.Write(oprot);
oprot.WriteFieldEnd();
}
if (Description != null && __isset.Description) {
field.Name = "Description";
field.Type = TType.Struct;
field.ID = 7;
oprot.WriteFieldBegin(field);
Description.Write(oprot);
oprot.WriteFieldEnd();
}
if (ImplementationConstraint != null && __isset.ImplementationConstraint) {
field.Name = "ImplementationConstraint";
field.Type = TType.List;
field.ID = 8;
oprot.WriteFieldBegin(field);
{
oprot.WriteListBegin(new TList(TType.Struct, ImplementationConstraint.Count));
foreach (TDDIImplementationConstraintRef _iter1296 in ImplementationConstraint)
{
_iter1296.Write(oprot);
}
oprot.WriteListEnd();
}
oprot.WriteFieldEnd();
}
if (Note != null && __isset.Note) {
field.Name = "Note";
field.Type = TType.List;
field.ID = 9;
oprot.WriteFieldBegin(field);
{
oprot.WriteListBegin(new TList(TType.Struct, Note.Count));
foreach (TDDINoteRef _iter1297 in Note)
{
_iter1297.Write(oprot);
}
oprot.WriteListEnd();
}
oprot.WriteFieldEnd();
}
if (TaggedValue != null && __isset.TaggedValue) {
field.Name = "TaggedValue";
field.Type = TType.List;
field.ID = 10;
oprot.WriteFieldBegin(field);
{
oprot.WriteListBegin(new TList(TType.Struct, TaggedValue.Count));
foreach (TDDITaggedValueRef _iter1298 in TaggedValue)
{
_iter1298.Write(oprot);
}
oprot.WriteListEnd();
}
oprot.WriteFieldEnd();
}
if (Property != null && __isset.Property) {
field.Name = "Property";
field.Type = TType.List;
field.ID = 11;
oprot.WriteFieldBegin(field);
{
oprot.WriteListBegin(new TList(TType.Struct, Property.Count));
foreach (TDDIPropertyRef _iter1299 in Property)
{
_iter1299.Write(oprot);
}
oprot.WriteListEnd();
}
oprot.WriteFieldEnd();
}
if (StartTime != null && __isset.StartTime) {
field.Name = "StartTime";
field.Type = TType.String;
field.ID = 12;
oprot.WriteFieldBegin(field);
oprot.WriteString(StartTime);
oprot.WriteFieldEnd();
}
if (EndTime != null && __isset.EndTime) {
field.Name = "EndTime";
field.Type = TType.String;
field.ID = 13;
oprot.WriteFieldBegin(field);
oprot.WriteString(EndTime);
oprot.WriteFieldEnd();
}
oprot.WriteFieldStop();
oprot.WriteStructEnd();
}
finally
{
oprot.DecrementRecursionDepth();
}
}
public override string ToString() {
StringBuilder __sb = new StringBuilder("TDDIActivity(");
bool __first = true;
if (Gid != null && __isset.Gid) {
if(!__first) { __sb.Append(", "); }
__first = false;
__sb.Append("Gid: ");
__sb.Append(Gid);
}
if (__isset.IsCitation) {
if(!__first) { __sb.Append(", "); }
__first = false;
__sb.Append("IsCitation: ");
__sb.Append(IsCitation);
}
if (__isset.IsAbstract) {
if(!__first) { __sb.Append(", "); }
__first = false;
__sb.Append("IsAbstract: ");
__sb.Append(IsAbstract);
}
if (CitedElement != null && __isset.CitedElement) {
if(!__first) { __sb.Append(", "); }
__first = false;
__sb.Append("CitedElement: ");
__sb.Append(CitedElement);
}
if (AbstractForm != null && __isset.AbstractForm) {
if(!__first) { __sb.Append(", "); }
__first = false;
__sb.Append("AbstractForm: ");
__sb.Append(AbstractForm);
}
if (Name != null && __isset.Name) {
if(!__first) { __sb.Append(", "); }
__first = false;
__sb.Append("Name: ");
__sb.Append(Name);
}
if (Description != null && __isset.Description) {
if(!__first) { __sb.Append(", "); }
__first = false;
__sb.Append("Description: ");
__sb.Append(Description);
}
if (ImplementationConstraint != null && __isset.ImplementationConstraint) {
if(!__first) { __sb.Append(", "); }
__first = false;
__sb.Append("ImplementationConstraint: ");
__sb.Append(ImplementationConstraint);
}
if (Note != null && __isset.Note) {
if(!__first) { __sb.Append(", "); }
__first = false;
__sb.Append("Note: ");
__sb.Append(Note);
}
if (TaggedValue != null && __isset.TaggedValue) {
if(!__first) { __sb.Append(", "); }
__first = false;
__sb.Append("TaggedValue: ");
__sb.Append(TaggedValue);
}
if (Property != null && __isset.Property) {
if(!__first) { __sb.Append(", "); }
__first = false;
__sb.Append("Property: ");
__sb.Append(Property);
}
if (StartTime != null && __isset.StartTime) {
if(!__first) { __sb.Append(", "); }
__first = false;
__sb.Append("StartTime: ");
__sb.Append(StartTime);
}
if (EndTime != null && __isset.EndTime) {
if(!__first) { __sb.Append(", "); }
__first = false;
__sb.Append("EndTime: ");
__sb.Append(EndTime);
}
__sb.Append(")");
return __sb.ToString();
}
}
}
| 27.709924 | 91 | 0.504628 | [
"MIT"
] | DEIS-Project-EU/DDI-Scripting-Tools | ODE_Tooladapter/ThriftContract/ODEThriftContract/gen_Thrift_ODE/csharp/STB_Modeling_Techniques/DEISProject/ODEDataModel/ThriftContract/TDDIActivity.cs | 18,150 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using ChainedRam.Core.Generation;
using UnityEngine;
[Obsolete("Use: ShowupOnScreenGenerator")]
public class MoveToGenerator : TimedGenerator
{
public GameObject Movable;
public Transform Destenation;
[ContextMenuItem("Sync", "SyncSpeed")]
public float Speed;
protected bool IsMoving;
private const float DistanceDalta = 0.01f;
protected override void OnGenerate(GenerateEventArgs e)
{
IsMoving = true;
}
protected override void FixedUpdate()
{
base.FixedUpdate();
if (!IsMoving)
{
return;
}
Movable.transform.position = Vector3.MoveTowards(Movable.transform.position, Destenation.position, Speed * Time.fixedDeltaTime);
IsMoving = Vector3.Distance(Movable.transform.position, Destenation.position) > DistanceDalta;
}
protected override float GetSyncedWaitTime()
{
return Vector3.Distance(Movable.transform.position, Destenation.position) / Speed;
}
private void SyncSpeed()
{
Speed = Vector3.Distance(Movable.transform.position, Destenation.position) / WaitTime;
}
}
| 24 | 136 | 0.685458 | [
"MIT"
] | KLD/Mahatha | Assets/Scripts/Core/Generation/MoveToGenerator.cs | 1,226 | C# |
//
// PropertyInfoTest.cs - NUnit Test Cases for PropertyInfo
//
// Author:
// Gert Driesen (drieseng@users.sourceforge.net)
//
// (C) 2004-2007 Gert Driesen
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Threading;
#if !MONOTOUCH
using System.Reflection.Emit;
#endif
using System.IO;
using NUnit.Framework;
namespace MonoTests.System.Reflection
{
[TestFixture]
public class PropertyInfoTest
{
[Test]
public void GetAccessorsTest ()
{
Type type = typeof (TestClass);
PropertyInfo property = type.GetProperty ("ReadOnlyProperty");
MethodInfo [] methods = property.GetAccessors (true);
Assert.AreEqual (1, methods.Length, "#A1");
Assert.IsNotNull (methods [0], "#A2");
Assert.AreEqual ("get_ReadOnlyProperty", methods [0].Name, "#A3");
methods = property.GetAccessors (false);
Assert.AreEqual (1, methods.Length, "#B1");
Assert.IsNotNull (methods [0], "#B2");
Assert.AreEqual ("get_ReadOnlyProperty", methods [0].Name, "#B3");
property = typeof (Base).GetProperty ("P");
methods = property.GetAccessors (true);
Assert.AreEqual (2, methods.Length, "#C1");
Assert.IsNotNull (methods [0], "#C2");
Assert.IsNotNull (methods [1], "#C3");
Assert.IsTrue (HasMethod (methods, "get_P"), "#C4");
Assert.IsTrue (HasMethod (methods, "set_P"), "#C5");
methods = property.GetAccessors (false);
Assert.AreEqual (2, methods.Length, "#D1");
Assert.IsNotNull (methods [0], "#D2");
Assert.IsNotNull (methods [1], "#D3");
Assert.IsTrue (HasMethod (methods, "get_P"), "#D4");
Assert.IsTrue (HasMethod (methods, "set_P"), "#D5");
methods = property.GetAccessors ();
Assert.AreEqual (2, methods.Length, "#E1");
Assert.IsNotNull (methods [0], "#E2");
Assert.IsNotNull (methods [1], "#E3");
Assert.IsTrue (HasMethod (methods, "get_P"), "#E4");
Assert.IsTrue (HasMethod (methods, "set_P"), "#E5");
property = typeof (TestClass).GetProperty ("Private",
BindingFlags.NonPublic | BindingFlags.Instance);
methods = property.GetAccessors (true);
Assert.AreEqual (2, methods.Length, "#F1");
Assert.IsNotNull (methods [0], "#F2");
Assert.IsNotNull (methods [1], "#F3");
Assert.IsTrue (HasMethod (methods, "get_Private"), "#F4");
Assert.IsTrue (HasMethod (methods, "set_Private"), "#F5");
methods = property.GetAccessors (false);
Assert.AreEqual (0, methods.Length, "#G");
methods = property.GetAccessors ();
Assert.AreEqual (0, methods.Length, "#H");
property = typeof (TestClass).GetProperty ("PrivateSetter");
methods = property.GetAccessors (true);
Assert.AreEqual (2, methods.Length, "#H1");
Assert.IsNotNull (methods [0], "#H2");
Assert.IsNotNull (methods [1], "#H3");
Assert.IsTrue (HasMethod (methods, "get_PrivateSetter"), "#H4");
Assert.IsTrue (HasMethod (methods, "set_PrivateSetter"), "#H5");
methods = property.GetAccessors (false);
Assert.AreEqual (1, methods.Length, "#I1");
Assert.IsNotNull (methods [0], "#I2");
Assert.AreEqual ("get_PrivateSetter", methods [0].Name, "#I3");
methods = property.GetAccessors ();
Assert.AreEqual (1, methods.Length, "#J1");
Assert.IsNotNull (methods [0], "#J2");
Assert.AreEqual ("get_PrivateSetter", methods [0].Name, "#J3");
}
[Test]
public void GetCustomAttributes ()
{
object [] attrs;
PropertyInfo p = typeof (Base).GetProperty ("P");
attrs = p.GetCustomAttributes (false);
Assert.AreEqual (1, attrs.Length, "#A1");
Assert.AreEqual (typeof (ThisAttribute), attrs [0].GetType (), "#A2");
attrs = p.GetCustomAttributes (true);
Assert.AreEqual (1, attrs.Length, "#A3");
Assert.AreEqual (typeof (ThisAttribute), attrs [0].GetType (), "#A4");
p = typeof (Base).GetProperty ("T");
attrs = p.GetCustomAttributes (false);
Assert.AreEqual (2, attrs.Length, "#B1");
Assert.IsTrue (HasAttribute (attrs, typeof (ThisAttribute)), "#B2");
Assert.IsTrue (HasAttribute (attrs, typeof (ComVisibleAttribute)), "#B3");
attrs = p.GetCustomAttributes (true);
Assert.AreEqual (2, attrs.Length, "#B41");
Assert.IsTrue (HasAttribute (attrs, typeof (ThisAttribute)), "#B5");
Assert.IsTrue (HasAttribute (attrs, typeof (ComVisibleAttribute)), "#B6");
p = typeof (Base).GetProperty ("Z");
attrs = p.GetCustomAttributes (false);
Assert.AreEqual (0, attrs.Length, "#C1");
attrs = p.GetCustomAttributes (true);
Assert.AreEqual (0, attrs.Length, "#C2");
}
[Test]
public void GetCustomAttributes_Inherited ()
{
object [] attrs;
PropertyInfo p = typeof (Derived).GetProperty ("P");
attrs = p.GetCustomAttributes (false);
Assert.AreEqual (0, attrs.Length, "#A1");
attrs = p.GetCustomAttributes (true);
Assert.AreEqual (0, attrs.Length, "#A3");
p = typeof (Derived).GetProperty ("T");
attrs = p.GetCustomAttributes (false);
Assert.AreEqual (2, attrs.Length, "#B1");
Assert.IsTrue (HasAttribute (attrs, typeof (ThisAttribute)), "#B2");
Assert.IsTrue (HasAttribute (attrs, typeof (ComVisibleAttribute)), "#B3");
attrs = p.GetCustomAttributes (true);
Assert.AreEqual (2, attrs.Length, "#B41");
Assert.IsTrue (HasAttribute (attrs, typeof (ThisAttribute)), "#B5");
Assert.IsTrue (HasAttribute (attrs, typeof (ComVisibleAttribute)), "#B6");
p = typeof (Derived).GetProperty ("Z");
attrs = p.GetCustomAttributes (false);
Assert.AreEqual (0, attrs.Length, "#C1");
attrs = p.GetCustomAttributes (true);
Assert.AreEqual (0, attrs.Length, "#C2");
}
[Test]
public void IsDefined_AttributeType_Null ()
{
Type derived = typeof (Derived);
PropertyInfo pi = derived.GetProperty ("P");
try {
pi.IsDefined ((Type) null, false);
Assert.Fail ("#1");
} catch (ArgumentNullException ex) {
Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
Assert.IsNull (ex.InnerException, "#3");
Assert.IsNotNull (ex.Message, "#4");
Assert.IsNotNull (ex.ParamName, "#5");
Assert.AreEqual ("attributeType", ex.ParamName, "#6");
}
}
[Test]
public void AccessorsReflectedType ()
{
PropertyInfo pi = typeof (Derived).GetProperty ("T");
Assert.AreEqual (typeof (Derived), pi.GetGetMethod ().ReflectedType);
Assert.AreEqual (typeof (Derived), pi.GetSetMethod ().ReflectedType);
}
[Test] // bug #399985
public void SetValue_Enum ()
{
TestClass t = new TestClass ();
PropertyInfo pi = t.GetType ().GetProperty ("Targets");
pi.SetValue (t, AttributeTargets.Field, null);
Assert.AreEqual (AttributeTargets.Field, t.Targets, "#1");
pi.SetValue (t, (int) AttributeTargets.Interface, null);
Assert.AreEqual (AttributeTargets.Interface, t.Targets, "#2");
}
public class ThisAttribute : Attribute
{
}
class Base
{
[ThisAttribute]
public virtual string P {
get { return null; }
set { }
}
[ThisAttribute]
[ComVisible (false)]
public virtual string T {
get { return null; }
set { }
}
public virtual string Z {
get { return null; }
set { }
}
}
class Derived : Base
{
public override string P {
get { return null; }
set { }
}
}
static void RunTest (Type t, bool use_getter) {
var p = t.GetProperty ("Item");
var idx = p.GetIndexParameters ();
var m_args = t.GetMethod (use_getter ? "get_Item" : "set_Item").GetParameters ();
Assert.AreEqual (2, idx.Length, "#1");
Assert.AreEqual (typeof (double), idx [0].ParameterType, "#2");
Assert.AreEqual (p, idx [0].Member, "#3");
Assert.AreEqual ("a", idx [0].Name, "#4");
Assert.AreEqual (0, idx [0].Position, "#5");
Assert.AreEqual (m_args [0].MetadataToken, idx [0].MetadataToken, "#6");
Assert.AreEqual (ParameterAttributes.None, idx [0].Attributes, "#7");
Assert.AreEqual (typeof (string), idx [1].ParameterType, "#8");
Assert.AreEqual (p, idx [1].Member, "#9");
Assert.AreEqual ("b", idx [1].Name, "#10");
Assert.AreEqual (1, idx [1].Position, "#11");
Assert.AreEqual (m_args [1].MetadataToken, idx [1].MetadataToken, "#12");
Assert.AreEqual (ParameterAttributes.None, idx [1].Attributes, "#13");
var idx2 = p.GetIndexParameters ();
//No interning exposed
Assert.AreNotSame (idx, idx2, "#14");
Assert.AreNotSame (idx [0], idx2 [1], "#15");
}
[Test]
public void GetIndexParameterReturnsObjectsBoundToTheProperty ()
{
RunTest (typeof (TestA), false);
RunTest (typeof (TestB), true);
}
public class TestA {
public int this[double a, string b] {
set {}
}
}
public class TestB {
public int this[double a, string b] {
get { return 1; }
set {}
}
}
[Test]
public void GetIndexParameterReturnedObjectsCustomAttributes () {
var pa = typeof (TestC).GetProperty ("Item").GetIndexParameters () [0];
Assert.IsTrue (pa.IsDefined (typeof (ParamArrayAttribute), false), "#1");
var pb = typeof (TestD).GetProperty ("Item").GetIndexParameters () [0];
Assert.IsTrue (pb.IsDefined (typeof (ParamArrayAttribute), false), "#2");
Assert.AreEqual (1, Attribute.GetCustomAttributes (pa).Length, "#3");
Assert.AreEqual (1, Attribute.GetCustomAttributes (pb).Length, "#4");
Assert.AreEqual (0, pa.GetOptionalCustomModifiers ().Length, "#5");
Assert.AreEqual (0, pb.GetRequiredCustomModifiers ().Length, "#6");
}
public class TestC {
public int this[params double[] a] {
get { return 99; }
}
}
public class TestD {
public int this[params double[] a] {
set { }
}
}
static string CreateTempAssembly ()
{
FileStream f = null;
string path;
Random rnd;
int num = 0;
rnd = new Random ();
do {
num = rnd.Next ();
num++;
path = Path.Combine (Path.GetTempPath (), "tmp" + num.ToString ("x") + ".dll");
try {
f = new FileStream (path, FileMode.CreateNew);
} catch { }
} while (f == null);
f.Close ();
return "tmp" + num.ToString ("x") + ".dll";
}
public class TestE {
public int PropE {
get { return 99; }
}
}
#if !MONOTOUCH
[Test]
public void ConstantValue () {
/*This test looks scary because we can't generate a default value with C# */
var assemblyName = new AssemblyName ();
assemblyName.Name = "MonoTests.System.Reflection.Emit.PropertyInfoTest";
string an = CreateTempAssembly ();
var assembly = Thread.GetDomain ().DefineDynamicAssembly (assemblyName, AssemblyBuilderAccess.RunAndSave, Path.GetTempPath ());
var module = assembly.DefineDynamicModule ("module1", an);
var tb = module.DefineType ("Test", TypeAttributes.Public);
var prop = tb.DefineProperty ("Prop", PropertyAttributes.HasDefault, typeof (string), new Type [0]);
var getter = tb.DefineMethod ("get_Prop", MethodAttributes.Public, typeof (string), new Type [0]);
var ilgen = getter.GetILGenerator ();
ilgen.Emit (OpCodes.Ldnull);
ilgen.Emit (OpCodes.Ret);
var setter = tb.DefineMethod ("set_Prop", MethodAttributes.Public, null, new Type [1] { typeof (string) });
setter.GetILGenerator ().Emit (OpCodes.Ret);
prop.SetConstant ("test");
prop.SetGetMethod (getter);
prop.SetSetMethod (setter);
tb.CreateType ();
File.Delete (Path.Combine (Path.GetTempPath (), an));
assembly.Save (an);
var asm = Assembly.LoadFrom (Path.Combine (Path.GetTempPath (), an));
var t = asm.GetType ("Test");
var p = t.GetProperty ("Prop");
Assert.AreEqual ("test", p.GetConstantValue (), "#1");
File.Delete (Path.Combine (Path.GetTempPath (), an));
var pa = typeof (TestE).GetProperty ("PropE");
try {
pa.GetConstantValue ();
Assert.Fail ("#2");
} catch (InvalidOperationException) {
}
}
#endif
public class A<T>
{
public string Property {
get { return typeof (T).FullName; }
}
}
public int? nullable_field;
public int? NullableProperty {
get { return nullable_field; }
set { nullable_field = value; }
}
[Test]
public void NullableTests ()
{
PropertyInfoTest t = new PropertyInfoTest ();
PropertyInfo pi = typeof(PropertyInfoTest).GetProperty("NullableProperty");
pi.SetValue (t, 100, null);
Assert.AreEqual (100, pi.GetValue (t, null));
pi.SetValue (t, null, null);
Assert.AreEqual (null, pi.GetValue (t, null));
}
[Test]
public void Bug77160 ()
{
object instance = new A<string> ();
Type type = instance.GetType ();
PropertyInfo property = type.GetProperty ("Property");
Assert.AreEqual (typeof (string).FullName, property.GetValue (instance, null));
}
[Test]
public void ToStringTest ()
{
var pa = typeof (TestC).GetProperty ("Item");
Assert.AreEqual ("Int32 Item [Double[]]", pa.ToString ());
}
static bool HasAttribute (object [] attrs, Type attributeType)
{
foreach (object attr in attrs)
if (attr.GetType () == attributeType)
return true;
return false;
}
static bool HasMethod (MethodInfo [] methods, string name)
{
foreach (MethodInfo method in methods)
if (method.Name == name)
return true;
return false;
}
private class TestClass
{
private AttributeTargets _targets = AttributeTargets.Assembly;
public AttributeTargets Targets {
get { return _targets; }
set { _targets = value; }
}
public string ReadOnlyProperty {
get { return string.Empty; }
}
private string Private {
get { return null; }
set { }
}
public string PrivateSetter {
get { return null; }
private set { }
}
}
[Test] // bug #633671
public void DeclaringTypeOfPropertyFromInheritedTypePointsToBase ()
{
var inherit1 = typeof(InheritsFromClassWithNullableDateTime);
var siblingProperty = inherit1.GetProperty("Property1");
Assert.AreEqual (typeof (ClassWithNullableDateTime), siblingProperty.DeclaringType, "#1");
Assert.AreEqual (typeof (InheritsFromClassWithNullableDateTime), siblingProperty.ReflectedType, "#2");
//The check is done twice since the bug is related to getting those 2 properties multiple times.
Assert.AreEqual (typeof (ClassWithNullableDateTime), siblingProperty.DeclaringType, "#3");
Assert.AreEqual (typeof (InheritsFromClassWithNullableDateTime), siblingProperty.ReflectedType, "#4");
}
public class ClassWithNullableDateTime
{
public DateTime? Property1 { get; set; }
}
public class InheritsFromClassWithNullableDateTime : ClassWithNullableDateTime
{
}
public static int ThrowingProperty {
get {
throw new ObjectDisposedException("TestClass");
}
}
[Test]
public void GetException () {
var prop = typeof(PropertyInfoTest).GetProperty("ThrowingProperty");
try {
prop.GetValue (null, null);
Assert.Fail ();
} catch (TargetInvocationException ex) {
Assert.IsTrue (ex.InnerException is ObjectDisposedException);
}
}
public class DefaultValueTest
{
public string this[int val, string param = "test"]
{
get{ return val + param; }
}
}
[Test]
public void PropertyWithDefaultValue ()
{
var parameters = typeof (DefaultValueTest).GetProperty ("Item").GetIndexParameters ();
var defaultParam = parameters[parameters.Length - 1];
Assert.AreEqual ("param", defaultParam.Name, "#1");
Assert.AreEqual ("test", defaultParam.DefaultValue, "#2");
}
}
}
| 29.829982 | 130 | 0.66636 | [
"Apache-2.0"
] | BitExodus/test01 | mcs/class/corlib/Test/System.Reflection/PropertyInfoTest.cs | 16,317 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ElevatorDesign
{
interface ILift
{
void SelectFloor(Floor floor);
void OpenDoor();
void CloseDoor();
}
}
| 16.8125 | 38 | 0.67658 | [
"Apache-2.0"
] | sameer58250/ElevatorDesign | ElevatorDesign/ILift.cs | 271 | C# |
/* Copyright 2010-2014 MongoDB Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace MongoDB.Bson
{
/// <summary>
/// An interface for custom mappers that map an object to a BsonValue.
/// </summary>
public interface ICustomBsonTypeMapper
{
/// <summary>
/// Tries to map an object to a BsonValue.
/// </summary>
/// <param name="value">An object.</param>
/// <param name="bsonValue">The BsonValue.</param>
/// <returns>True if the mapping was successfull.</returns>
bool TryMapToBsonValue(object value, out BsonValue bsonValue);
}
}
| 35.0625 | 74 | 0.686275 | [
"MIT"
] | 21thCenturyBoy/LandlordsProject | Landlords_Client01/Landlords_Client01/Unity/Assets/ThirdParty/MongoDB/MongoDB.Bson/ObjectModel/ICustomBsonTypeMapper.cs | 1,124 | C# |
using Raiding.Factories;
using Raiding.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Raiding.Core
{
public class Engine : IEngine
{
private readonly FactoryHero factoryHero;
private ICollection<BaseHero> heroes;
public Engine()
{
this.factoryHero = new FactoryHero();
this.heroes = new List<BaseHero>();
}
public void Run()
{
int needValidHeroes = int.Parse(Console.ReadLine());
int counterValidHeroes = 0;
while (counterValidHeroes != needValidHeroes)
{
string heroName = Console.ReadLine();
string heroType = Console.ReadLine();
BaseHero baseHero = this.factoryHero.CreateHero(heroName, heroType);
if (baseHero != null)
{
this.heroes.Add(baseHero);
counterValidHeroes++;
}
}
int BossHp = int.Parse(Console.ReadLine());
double heroesPower = this.heroes.Sum(h => h.Power);
foreach (BaseHero hero in heroes)
{
Console.WriteLine(hero.CastAbility());
}
if (heroesPower >= BossHp && BossHp > 0)
{
Console.WriteLine("Victory!");
}
else if (heroesPower < BossHp)
{
Console.WriteLine("Defeat...");
}
}
}
}
| 26.586207 | 84 | 0.51297 | [
"MIT"
] | martinsivanov/CSharp-Advanced-September-2020 | C # OOP/Homeworks/08 - Polymorphism - Exercise/03. Raiding/Core/Engine.cs | 1,544 | C# |
using System;
using System.Threading;
using EndGate.Server.Collision;
using EndGate.Server;
namespace EndGate.Server
{
/// <summary>
/// Provides collision, game, and server logic code.
/// </summary>
public abstract class Game : IUpdateable, IDisposable
{
private GameTime _gameTime;
/// <summary>
/// The game configuration. Used to modify the update and push intervals.
/// </summary>
public GameConfiguration Configuration;
/// <summary>
/// A collision manager which is used to actively detect collisions between monitored <see cref="Collidable"/>'s.
/// </summary>
public CollisionManager CollisionManager;
internal static long GameIDs = 0;
internal long ID = 0;
/// <summary>
/// Initiates a new game object.
/// </summary>
public Game()
{
_gameTime = new GameTime();
ID = Interlocked.Increment(ref GameIDs);
CollisionManager = new CollisionManager();
Configuration = new GameConfiguration(GameRunner.Instance.Register(this));
}
internal void PrepareUpdate()
{
_gameTime.Update();
CollisionManager.Update(_gameTime);
Update(_gameTime);
}
internal void PreparePush()
{
Push();
}
/// <summary>
/// Triggered on a regular interval defined by the <see cref="GameConfiguration"/>. Should be overridden to run game logic.
/// </summary>
/// <param name="gameTime">The global game time object. Used to represent total time running and used to track update interval elapsed speeds.</param>
public virtual void Update(GameTime gameTime)
{
}
/// <summary>
/// Triggered on a regular interval defined by the <see cref="GameConfiguration"/>. Should be overridden to push data over the wire to connected clients.
/// </summary>
public virtual void Push()
{
}
/// <summary>
/// Disposes the game and stops the update and push intervals.
/// </summary>
public virtual void Dispose()
{
GameRunner.Instance.Unregister(this);
}
}
}
| 30.328947 | 162 | 0.588286 | [
"MIT"
] | NTaylorMullen/EndGate.Server | EndGate.Server/EndGate.Server.Core/Game/Game.cs | 2,307 | C# |
/**
/// ScrimpNet.Core Library
/// Copyright © 2005-2011
///
/// This module is Copyright © 2005-2011 Steve Powell
/// All rights reserved.
///
/// This library is free software; you can redistribute it and/or
/// modify it under the terms of the Microsoft Public License (Ms-PL)
///
/// This library is distributed in the hope that it will be
/// useful, but WITHOUT ANY WARRANTY; without even the implied
/// warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
/// PURPOSE. See theMicrosoft Public License (Ms-PL) License for more
/// details.
///
/// You should have received a copy of the Microsoft Public License (Ms-PL)
/// License along with this library; if not you may
/// find it here: http://www.opensource.org/licenses/ms-pl.html
///
/// Steve Powell, spowell@scrimpnet.com
**/
using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using ScrimpNet.Cryptography;
using System.Security.Cryptography;
using ScrimpNet;
using ScrimpNet.Text;
namespace CoreTests
{
/// <summary>
/// Summary description for CryptographyTests
/// </summary>
[TestClass]
public class CryptographyTests
{
public CryptographyTests()
{
//
// TODO: Add constructor logic here
//
}
private TestContext testContextInstance;
/// <summary>
///Gets or sets the test context which provides
///information about and functionality for the current test run.
///</summary>
public TestContext TestContext
{
get
{
return testContextInstance;
}
set
{
testContextInstance = value;
}
}
// #region Additional test attributes
// //
// // You can use the following additional attributes as you write your tests:
// //
// // Use ClassInitialize to run code before running the first test in the class
// // [ClassInitialize()]
// // public static void MyClassInitialize(TestContext testContext) { }
// //
// // Use ClassCleanup to run code after all tests in a class have run
// // [ClassCleanup()]
// // public static void MyClassCleanup() { }
// //
// // Use TestInitialize to run code before running each test
// // [TestInitialize()]
// // public void MyTestInitialize() { }
// //
// // Use TestCleanup to run code after each test has run
// // [TestCleanup()]
// // public void MyTestCleanup() { }
// //
// #endregion
// [TestMethod]
// public void EncryptByteArray_HappyPath()
// {
// //-------------------------------------------------------
// // arrange
// //-------------------------------------------------------
// string sourceString = "0123456789";
// //-------------------------------------------------------
// // act
// //-------------------------------------------------------
// string encryptedResult = CryptoUtils.Encryptor.Encrypt(sourceString);
// string decryptedResult = CryptoUtils.Encryptor.Decrypt(encryptedResult);
// //-------------------------------------------------------
// // assert
// //-------------------------------------------------------
// Assert.AreEqual(sourceString,decryptedResult);
// }
// [TestMethod]
// public void EncryptByPasswordBase64_HappyPath()
// {
// //-------------------------------------------------------
// // arrange
// //-------------------------------------------------------
// string sourceString = "0123456789";
// string password = "password";
// //-------------------------------------------------------
// // act
// //-------------------------------------------------------
// string encryptedResult = CryptoUtils.Encryptor.Encrypt(sourceString, password, StringFormat.Base64);
// string decryptedResult = CryptoUtils.Encryptor.Decrypt(encryptedResult, password, StringFormat.Base64);
// //-------------------------------------------------------
// // assert
// //-------------------------------------------------------
// Assert.AreEqual(sourceString, decryptedResult);
// }
// [TestMethod]
// public void EncryptByPasswordDefault_HappyPath()
// {
// //-------------------------------------------------------
// // arrange
// //-------------------------------------------------------
// string sourceString = "0123456789";
// string password = "password";
// //-------------------------------------------------------
// // act
// //-------------------------------------------------------
// string encryptedResult = CryptoUtils.Encryptor.Encrypt(sourceString, password);
// string decryptedResult = CryptoUtils.Encryptor.Decrypt(encryptedResult, password);
// //-------------------------------------------------------
// // assert
// //-------------------------------------------------------
// Assert.AreEqual(sourceString, decryptedResult);
// }
// [TestMethod]
// public void KeyFile_Serialization()
// {
// string s = KeyFile.GenerateKeyFileString_Base64Unencrypted(new TimeSpan(365*2,0,0,0,0));
// byte[] bytes = Convert.FromBase64String(s);
// KeyFile kf = Serialize.From.Binary<KeyFile>(bytes);
// }
}
}
| 36.64375 | 117 | 0.463244 | [
"MIT"
] | catcat0921/lindexi_gd | ScrimpNet.Library.Suite Solution/__TestProjects/ScrimpNet.Core Tests/Cryptography/CryptographyTests.cs | 5,867 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Buffers;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Text;
using Internal.Runtime.CompilerServices;
namespace System
{
// The String class represents a static string of characters. Many of
// the string methods perform some type of transformation on the current
// instance and return the result as a new string. As with arrays, character
// positions (indices) are zero-based.
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public sealed partial class String : IComparable, IEnumerable, IConvertible, IEnumerable<char>, IComparable<string?>, IEquatable<string?>, ICloneable
{
//
// These fields map directly onto the fields in an EE StringObject. See object.h for the layout.
//
[NonSerialized]
private readonly int _stringLength;
// For empty strings, _firstChar will be '\0', since strings are both null-terminated and length-prefixed.
// The field is also read-only, however String uses .ctors that C# doesn't recognise as .ctors,
// so trying to mark the field as 'readonly' causes the compiler to complain.
[NonSerialized]
private char _firstChar;
/*
* CONSTRUCTORS
*
* Defining a new constructor for string-like types (like String) requires changes both
* to the managed code below and to the native VM code. See the comment at the top of
* src/vm/ecall.cpp for instructions on how to add new overloads.
*/
[MethodImpl(MethodImplOptions.InternalCall)]
[DynamicDependency("Ctor(System.Char[])")]
public extern String(char[]? value);
private
#if !CORECLR
static
#endif
string Ctor(char[]? value)
{
if (value == null || value.Length == 0)
return Empty;
string result = FastAllocateString(value.Length);
Buffer.Memmove(
elementCount: (uint)result.Length, // derefing Length now allows JIT to prove 'result' not null below
destination: ref result._firstChar,
source: ref MemoryMarshal.GetArrayDataReference(value));
return result;
}
[MethodImpl(MethodImplOptions.InternalCall)]
[DynamicDependency("Ctor(System.Char[],System.Int32,System.Int32)")]
public extern String(char[] value, int startIndex, int length);
private
#if !CORECLR
static
#endif
string Ctor(char[] value, int startIndex, int length)
{
if (value == null)
throw new ArgumentNullException(nameof(value));
if (startIndex < 0)
throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_StartIndex);
if (length < 0)
throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_NegativeLength);
if (startIndex > value.Length - length)
throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index);
if (length == 0)
return Empty;
string result = FastAllocateString(length);
Buffer.Memmove(
elementCount: (uint)result.Length, // derefing Length now allows JIT to prove 'result' not null below
destination: ref result._firstChar,
source: ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(value), startIndex));
return result;
}
[CLSCompliant(false)]
[MethodImpl(MethodImplOptions.InternalCall)]
[DynamicDependency("Ctor(System.Char*)")]
public extern unsafe String(char* value);
private
#if !CORECLR
static
#endif
unsafe string Ctor(char* ptr)
{
if (ptr == null)
return Empty;
int count = wcslen(ptr);
if (count == 0)
return Empty;
string result = FastAllocateString(count);
Buffer.Memmove(
elementCount: (uint)result.Length, // derefing Length now allows JIT to prove 'result' not null below
destination: ref result._firstChar,
source: ref *ptr);
return result;
}
[CLSCompliant(false)]
[MethodImpl(MethodImplOptions.InternalCall)]
[DynamicDependency("Ctor(System.Char*,System.Int32,System.Int32)")]
public extern unsafe String(char* value, int startIndex, int length);
private
#if !CORECLR
static
#endif
unsafe string Ctor(char* ptr, int startIndex, int length)
{
if (length < 0)
throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_NegativeLength);
if (startIndex < 0)
throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_StartIndex);
char* pStart = ptr + startIndex;
// overflow check
if (pStart < ptr)
throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_PartialWCHAR);
if (length == 0)
return Empty;
if (ptr == null)
throw new ArgumentOutOfRangeException(nameof(ptr), SR.ArgumentOutOfRange_PartialWCHAR);
string result = FastAllocateString(length);
Buffer.Memmove(
elementCount: (uint)result.Length, // derefing Length now allows JIT to prove 'result' not null below
destination: ref result._firstChar,
source: ref *pStart);
return result;
}
[CLSCompliant(false)]
[MethodImpl(MethodImplOptions.InternalCall)]
[DynamicDependency("Ctor(System.SByte*)")]
public extern unsafe String(sbyte* value);
private
#if !CORECLR
static
#endif
unsafe string Ctor(sbyte* value)
{
byte* pb = (byte*)value;
if (pb == null)
return Empty;
int numBytes = strlen((byte*)value);
return CreateStringForSByteConstructor(pb, numBytes);
}
[CLSCompliant(false)]
[MethodImpl(MethodImplOptions.InternalCall)]
[DynamicDependency("Ctor(System.SByte*,System.Int32,System.Int32)")]
public extern unsafe String(sbyte* value, int startIndex, int length);
private
#if !CORECLR
static
#endif
unsafe string Ctor(sbyte* value, int startIndex, int length)
{
if (startIndex < 0)
throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_StartIndex);
if (length < 0)
throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_NegativeLength);
if (value == null)
{
if (length == 0)
return Empty;
throw new ArgumentNullException(nameof(value));
}
byte* pStart = (byte*)(value + startIndex);
// overflow check
if (pStart < value)
throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_PartialWCHAR);
return CreateStringForSByteConstructor(pStart, length);
}
// Encoder for String..ctor(sbyte*) and String..ctor(sbyte*, int, int)
private static unsafe string CreateStringForSByteConstructor(byte* pb, int numBytes)
{
Debug.Assert(numBytes >= 0);
Debug.Assert(pb <= (pb + numBytes));
if (numBytes == 0)
return Empty;
#if TARGET_WINDOWS
int numCharsRequired = Interop.Kernel32.MultiByteToWideChar(Interop.Kernel32.CP_ACP, Interop.Kernel32.MB_PRECOMPOSED, pb, numBytes, (char*)null, 0);
if (numCharsRequired == 0)
throw new ArgumentException(SR.Arg_InvalidANSIString);
string newString = FastAllocateString(numCharsRequired);
fixed (char* pFirstChar = &newString._firstChar)
{
numCharsRequired = Interop.Kernel32.MultiByteToWideChar(Interop.Kernel32.CP_ACP, Interop.Kernel32.MB_PRECOMPOSED, pb, numBytes, pFirstChar, numCharsRequired);
}
if (numCharsRequired == 0)
throw new ArgumentException(SR.Arg_InvalidANSIString);
return newString;
#else
return Encoding.UTF8.GetString(pb, numBytes);
#endif
}
[CLSCompliant(false)]
[MethodImpl(MethodImplOptions.InternalCall)]
[DynamicDependency("Ctor(System.SByte*,System.Int32,System.Int32,System.Text.Encoding)")]
public extern unsafe String(sbyte* value, int startIndex, int length, Encoding enc);
private
#if !CORECLR
static
#endif
unsafe string Ctor(sbyte* value, int startIndex, int length, Encoding? enc)
{
if (enc == null)
return new string(value, startIndex, length);
if (length < 0)
throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_NeedNonNegNum);
if (startIndex < 0)
throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_StartIndex);
if (value == null)
{
if (length == 0)
return Empty;
throw new ArgumentNullException(nameof(value));
}
byte* pStart = (byte*)(value + startIndex);
// overflow check
if (pStart < value)
throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_PartialWCHAR);
return enc.GetString(new ReadOnlySpan<byte>(pStart, length));
}
[MethodImpl(MethodImplOptions.InternalCall)]
[DynamicDependency("Ctor(System.Char,System.Int32)")]
public extern String(char c, int count);
private
#if !CORECLR
static
#endif
string Ctor(char c, int count)
{
if (count <= 0)
{
if (count == 0)
return Empty;
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NegativeCount);
}
string result = FastAllocateString(count);
if (c != '\0') // Fast path null char string
{
unsafe
{
fixed (char* dest = &result._firstChar)
{
uint cc = (uint)((c << 16) | c);
uint* dmem = (uint*)dest;
if (count >= 4)
{
count -= 4;
do
{
dmem[0] = cc;
dmem[1] = cc;
dmem += 2;
count -= 4;
} while (count >= 0);
}
if ((count & 2) != 0)
{
*dmem = cc;
dmem++;
}
if ((count & 1) != 0)
((char*)dmem)[0] = c;
}
}
}
return result;
}
[MethodImpl(MethodImplOptions.InternalCall)]
[DynamicDependency("Ctor(System.ReadOnlySpan{System.Char})")]
public extern String(ReadOnlySpan<char> value);
private
#if !CORECLR
static
#endif
unsafe string Ctor(ReadOnlySpan<char> value)
{
if (value.Length == 0)
return Empty;
string result = FastAllocateString(value.Length);
Buffer.Memmove(ref result._firstChar, ref MemoryMarshal.GetReference(value), (uint)value.Length);
return result;
}
public static string Create<TState>(int length, TState state, SpanAction<char, TState> action)
{
if (action == null)
throw new ArgumentNullException(nameof(action));
if (length <= 0)
{
if (length == 0)
return Empty;
throw new ArgumentOutOfRangeException(nameof(length));
}
string result = FastAllocateString(length);
action(new Span<char>(ref result.GetRawStringData(), length), state);
return result;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static implicit operator ReadOnlySpan<char>(string? value) =>
value != null ? new ReadOnlySpan<char>(ref value.GetRawStringData(), value.Length) : default;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal bool TryGetSpan(int startIndex, int count, out ReadOnlySpan<char> slice)
{
#if TARGET_64BIT
// See comment in Span<T>.Slice for how this works.
if ((ulong)(uint)startIndex + (ulong)(uint)count > (ulong)(uint)Length)
{
slice = default;
return false;
}
#else
if ((uint)startIndex > (uint)Length || (uint)count > (uint)(Length - startIndex))
{
slice = default;
return false;
}
#endif
slice = new ReadOnlySpan<char>(ref Unsafe.Add(ref _firstChar, startIndex), count);
return true;
}
public object Clone()
{
return this;
}
public static unsafe string Copy(string str)
{
if (str == null)
throw new ArgumentNullException(nameof(str));
string result = FastAllocateString(str.Length);
Buffer.Memmove(
elementCount: (uint)result.Length, // derefing Length now allows JIT to prove 'result' not null below
destination: ref result._firstChar,
source: ref str._firstChar);
return result;
}
// Converts a substring of this string to an array of characters. Copies the
// characters of this string beginning at position sourceIndex and ending at
// sourceIndex + count - 1 to the character array buffer, beginning
// at destinationIndex.
//
public unsafe void CopyTo(int sourceIndex, char[] destination, int destinationIndex, int count)
{
if (destination == null)
throw new ArgumentNullException(nameof(destination));
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NegativeCount);
if (sourceIndex < 0)
throw new ArgumentOutOfRangeException(nameof(sourceIndex), SR.ArgumentOutOfRange_Index);
if (count > Length - sourceIndex)
throw new ArgumentOutOfRangeException(nameof(sourceIndex), SR.ArgumentOutOfRange_IndexCount);
if (destinationIndex > destination.Length - count || destinationIndex < 0)
throw new ArgumentOutOfRangeException(nameof(destinationIndex), SR.ArgumentOutOfRange_IndexCount);
Buffer.Memmove(
destination: ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(destination), destinationIndex),
source: ref Unsafe.Add(ref _firstChar, sourceIndex),
elementCount: (uint)count);
}
// Returns the entire string as an array of characters.
public char[] ToCharArray()
{
if (Length == 0)
return Array.Empty<char>();
char[] chars = new char[Length];
Buffer.Memmove(
destination: ref MemoryMarshal.GetArrayDataReference(chars),
source: ref _firstChar,
elementCount: (uint)Length);
return chars;
}
// Returns a substring of this string as an array of characters.
//
public char[] ToCharArray(int startIndex, int length)
{
// Range check everything.
if (startIndex < 0 || startIndex > Length || startIndex > Length - length)
throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index);
if (length <= 0)
{
if (length == 0)
return Array.Empty<char>();
throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_Index);
}
char[] chars = new char[length];
Buffer.Memmove(
destination: ref MemoryMarshal.GetArrayDataReference(chars),
source: ref Unsafe.Add(ref _firstChar, startIndex),
elementCount: (uint)length);
return chars;
}
[NonVersionable]
public static bool IsNullOrEmpty([NotNullWhen(false)] string? value)
{
// Using 0u >= (uint)value.Length rather than
// value.Length == 0 as it will elide the bounds check to
// the first char: value[0] if that is performed following the test
// for the same test cost.
// Ternary operator returning true/false prevents redundant asm generation:
// https://github.com/dotnet/runtime/issues/4207
return (value == null || 0u >= (uint)value.Length) ? true : false;
}
public static bool IsNullOrWhiteSpace([NotNullWhen(false)] string? value)
{
if (value == null) return true;
for (int i = 0; i < value.Length; i++)
{
if (!char.IsWhiteSpace(value[i])) return false;
}
return true;
}
/// <summary>
/// Returns a reference to the first element of the String. If the string is null, an access will throw a NullReferenceException.
/// </summary>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
[NonVersionable]
public ref readonly char GetPinnableReference() => ref _firstChar;
internal ref char GetRawStringData() => ref _firstChar;
// Helper for encodings so they can talk to our buffer directly
// stringLength must be the exact size we'll expect
internal static unsafe string CreateStringFromEncoding(
byte* bytes, int byteLength, Encoding encoding)
{
Debug.Assert(bytes != null);
Debug.Assert(byteLength >= 0);
// Get our string length
int stringLength = encoding.GetCharCount(bytes, byteLength);
Debug.Assert(stringLength >= 0, "stringLength >= 0");
// They gave us an empty string if they needed one
// 0 bytelength might be possible if there's something in an encoder
if (stringLength == 0)
return Empty;
string s = FastAllocateString(stringLength);
fixed (char* pTempChars = &s._firstChar)
{
int doubleCheck = encoding.GetChars(bytes, byteLength, pTempChars, stringLength);
Debug.Assert(stringLength == doubleCheck,
"Expected encoding.GetChars to return same length as encoding.GetCharCount");
}
return s;
}
// This is only intended to be used by char.ToString.
// It is necessary to put the code in this class instead of Char, since _firstChar is a private member.
// Making _firstChar internal would be dangerous since it would make it much easier to break String's immutability.
internal static string CreateFromChar(char c)
{
string result = FastAllocateString(1);
result._firstChar = c;
return result;
}
internal static string CreateFromChar(char c1, char c2)
{
string result = FastAllocateString(2);
result._firstChar = c1;
Unsafe.Add(ref result._firstChar, 1) = c2;
return result;
}
internal static unsafe void wstrcpy(char* dmem, char* smem, int charCount)
{
Buffer.Memmove((byte*)dmem, (byte*)smem, ((uint)charCount) * 2);
}
// Returns this string.
public override string ToString()
{
return this;
}
// Returns this string.
public string ToString(IFormatProvider? provider)
{
return this;
}
public CharEnumerator GetEnumerator()
{
return new CharEnumerator(this);
}
IEnumerator<char> IEnumerable<char>.GetEnumerator()
{
return new CharEnumerator(this);
}
IEnumerator IEnumerable.GetEnumerator()
{
return new CharEnumerator(this);
}
/// <summary>
/// Returns an enumeration of <see cref="Rune"/> from this string.
/// </summary>
/// <remarks>
/// Invalid sequences will be represented in the enumeration by <see cref="Rune.ReplacementChar"/>.
/// </remarks>
public StringRuneEnumerator EnumerateRunes()
{
return new StringRuneEnumerator(this);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static unsafe int wcslen(char* ptr)
{
// IndexOf processes memory in aligned chunks, and thus it won't crash even if it accesses memory beyond the null terminator.
int length = SpanHelpers.IndexOf(ref *ptr, '\0', int.MaxValue);
if (length < 0)
{
ThrowMustBeNullTerminatedString();
}
return length;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static unsafe int strlen(byte* ptr)
{
// IndexOf processes memory in aligned chunks, and thus it won't crash even if it accesses memory beyond the null terminator.
int length = SpanHelpers.IndexOf(ref *ptr, (byte)'\0', int.MaxValue);
if (length < 0)
{
ThrowMustBeNullTerminatedString();
}
return length;
}
[DoesNotReturn]
private static void ThrowMustBeNullTerminatedString()
{
throw new ArgumentException(SR.Arg_MustBeNullTerminatedString);
}
//
// IConvertible implementation
//
public TypeCode GetTypeCode()
{
return TypeCode.String;
}
bool IConvertible.ToBoolean(IFormatProvider? provider)
{
return Convert.ToBoolean(this, provider);
}
char IConvertible.ToChar(IFormatProvider? provider)
{
return Convert.ToChar(this, provider);
}
sbyte IConvertible.ToSByte(IFormatProvider? provider)
{
return Convert.ToSByte(this, provider);
}
byte IConvertible.ToByte(IFormatProvider? provider)
{
return Convert.ToByte(this, provider);
}
short IConvertible.ToInt16(IFormatProvider? provider)
{
return Convert.ToInt16(this, provider);
}
ushort IConvertible.ToUInt16(IFormatProvider? provider)
{
return Convert.ToUInt16(this, provider);
}
int IConvertible.ToInt32(IFormatProvider? provider)
{
return Convert.ToInt32(this, provider);
}
uint IConvertible.ToUInt32(IFormatProvider? provider)
{
return Convert.ToUInt32(this, provider);
}
long IConvertible.ToInt64(IFormatProvider? provider)
{
return Convert.ToInt64(this, provider);
}
ulong IConvertible.ToUInt64(IFormatProvider? provider)
{
return Convert.ToUInt64(this, provider);
}
float IConvertible.ToSingle(IFormatProvider? provider)
{
return Convert.ToSingle(this, provider);
}
double IConvertible.ToDouble(IFormatProvider? provider)
{
return Convert.ToDouble(this, provider);
}
decimal IConvertible.ToDecimal(IFormatProvider? provider)
{
return Convert.ToDecimal(this, provider);
}
DateTime IConvertible.ToDateTime(IFormatProvider? provider)
{
return Convert.ToDateTime(this, provider);
}
object IConvertible.ToType(Type type, IFormatProvider? provider)
{
return Convert.DefaultToType((IConvertible)this, type, provider);
}
// Normalization Methods
// These just wrap calls to Normalization class
public bool IsNormalized()
{
return IsNormalized(NormalizationForm.FormC);
}
public bool IsNormalized(NormalizationForm normalizationForm)
{
if (this.IsAscii())
{
// If its ASCII && one of the 4 main forms, then its already normalized
if (normalizationForm == NormalizationForm.FormC ||
normalizationForm == NormalizationForm.FormKC ||
normalizationForm == NormalizationForm.FormD ||
normalizationForm == NormalizationForm.FormKD)
return true;
}
return Normalization.IsNormalized(this, normalizationForm);
}
public string Normalize()
{
return Normalize(NormalizationForm.FormC);
}
public string Normalize(NormalizationForm normalizationForm)
{
if (this.IsAscii())
{
// If its ASCII && one of the 4 main forms, then its already normalized
if (normalizationForm == NormalizationForm.FormC ||
normalizationForm == NormalizationForm.FormKC ||
normalizationForm == NormalizationForm.FormD ||
normalizationForm == NormalizationForm.FormKD)
return this;
}
return Normalization.Normalize(this, normalizationForm);
}
private unsafe bool IsAscii()
{
fixed (char* str = &_firstChar)
{
return ASCIIUtility.GetIndexOfFirstNonAsciiChar(str, (uint)Length) == (uint)Length;
}
}
}
}
| 34.909677 | 174 | 0.576714 | [
"MIT"
] | 71221-maker/runtime | src/libraries/System.Private.CoreLib/src/System/String.cs | 27,055 | C# |
using Sketch2Code.AI;
using Sketch2Code.Core.Entities;
using Sketch2Code.Core.Services.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Sketch2Code.Core.Helpers;
using System.IO;
using System.Drawing;
using System.Configuration;
using Microsoft.WindowsAzure.Storage.Blob;
using Microsoft.WindowsAzure.Storage;
using Newtonsoft.Json;
using Sketch2Code.Core.BoxGeometry;
using Microsoft.Extensions.Logging;
using Sketch2Code.AI.Entities;
using Microsoft.Azure.CognitiveServices.Vision.ComputerVision.Models;
namespace Sketch2Code.Core
{
public class ObjectDetectionAppService : IObjectDetectionAppService
{
ObjectDetector _detectorClient;
CloudBlobClient _cloudBlobClient;
int predicted_index = 0;
public ObjectDetectionAppService(ObjectDetector detectorClient, ILogger logger)
{
_detectorClient = detectorClient;
_detectorClient.Initialize();
var account = CloudStorageAccount.Parse(ConfigurationManager.AppSettings["AzureWebJobsStorage"]);
_cloudBlobClient = account.CreateCloudBlobClient();
}
public ObjectDetectionAppService() : this(new ObjectDetector(),
new LoggerFactory().CreateLogger<ObjectDetectionAppService>())
{
}
public ObjectDetectionAppService(ILogger logger) : this(new ObjectDetector(), logger)
{
}
public async Task<IList<PredictedObject>> GetPredictionAsync(byte[] data)
{
throw new NotImplementedException();
}
private static void removePredictionsUnderProbabilityThreshold(List<PredictionModel> predictions)
{
var Probability = Convert.ToInt32(ConfigurationManager.AppSettings["Probability"]);
predictions.RemoveAll(p => p.Probability < (Probability / 100D));
}
private void assignPredictedText(PredictedObject predictedObject, List<Line> textLines)
{
predictedObject.Text = new List<string>();
foreach (var textLine in textLines)
{
//if areas are 100% overlapping assign every textline
Overlap ovl = new Overlap();
Entities.BoundingBox b = new Entities.BoundingBox();
// Bounding box of a recognized region, line, or word, depending on the parent object.
// It's an arrary of eight numbers represent the four points (x-coordinate, y-coordinate
// from the left-top corner of the image) of the detected rectangle from the left-top corner
// in the clockwise direction.
var xPoints = textLine.BoundingBox.Where((value, index) => index % 2 == 0).ToArray();
var yPoints = textLine.BoundingBox.Where((value, index) => index % 2 != 0).ToArray();
var min_x = xPoints.Min();
var min_y = yPoints.Min();
var max_x = xPoints.Max();
var max_y = yPoints.Max();
b.Left = min_x;
b.Top = min_y;
b.Width = max_x - min_x;
b.Height = max_y - min_y;
//If boxes overlaps more than 50% we decide they are the same thing
if (ovl.OverlapArea(predictedObject.BoundingBox, b) > 0.5)
{
for(int j = 0; j < textLine.Words.Count; j++)
{
predictedObject.Text.Add(textLine.Words[j].Text);
}
}
}
}
private void removeUnusableImages(List<PredictedObject> list)
{
//Remove images with size over 4mb
list.RemoveAll(img => img.SlicedImage.Length >= 4 * 1024 * 1024);
//Exclude images outside of this range 40x40 - 3200x3200
list.RemoveAll(p => p.BoundingBox.Height > 3200 || p.BoundingBox.Height < 40);
list.RemoveAll(p => p.BoundingBox.Width > 3200 || p.BoundingBox.Width < 40);
}
private PredictedObject buildPredictedObject(PredictionModel p, Image image, byte[] data)
{
PredictedObject predictedObject = new PredictedObject();
predictedObject.BoundingBox.Top = p.BoundingBox.Top * image.Height;
predictedObject.BoundingBox.Height = p.BoundingBox.Height * image.Height;
predictedObject.BoundingBox.Left = p.BoundingBox.Left * image.Width;
predictedObject.BoundingBox.Width = p.BoundingBox.Width * image.Width;
predictedObject.BoundingBox.TopNorm = p.BoundingBox.Top;
predictedObject.BoundingBox.LeftNorm = p.BoundingBox.Left;
predictedObject.BoundingBox.MaxHeight = image.Height;
predictedObject.BoundingBox.MaxWidth = image.Width;
predictedObject.ClassName = p.TagName;
predictedObject.Probability = p.Probability;
predictedObject.SlicedImage = data.SliceImage(predictedObject.BoundingBox.Left,
predictedObject.BoundingBox.Top, predictedObject.BoundingBox.Width, predictedObject.BoundingBox.Height);
predictedObject.Name = ($"slice_{predictedObject.ClassName}_{predicted_index}");
predictedObject.FileName = ($"slices/{predictedObject.Name}.png");
predicted_index++;
return predictedObject;
}
private Image buildAndVerifyImage(byte[] data)
{
double imageWidth = 0;
double imageHeight = 0;
Image img;
using (var ms = new MemoryStream(data))
{
img = Image.FromStream(ms);
imageWidth = img.Width;
imageHeight = img.Height;
if ((imageWidth == 0) || (imageHeight == 0))
{
throw new InvalidOperationException("Invalid image dimensions");
}
}
return img;
}
public async Task SaveResults(IList<PredictedObject> predictedObjects, string id)
{
if (_cloudBlobClient == null) throw new InvalidOperationException("blobClient is null");
var slices_container = $"{id}/slices";
for (int i = 0; i < predictedObjects.Count; i++)
{
PredictedObject result = (PredictedObject)predictedObjects[i];
await this.SaveResults(result.SlicedImage, slices_container, $"{result.Name}.png");
}
}
public async Task SaveResults(byte[] file, string container, string fileName)
{
CloudBlobContainer theContainer = null;
if (_cloudBlobClient == null) throw new InvalidOperationException("blobClient is null");
var segments = container.Split(@"/".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
var rootContainerPath = segments.First();
var relativePath = String.Join(@"/", segments.Except(new string[] { rootContainerPath }));
theContainer = _cloudBlobClient.GetContainerReference($"{rootContainerPath}");
await theContainer.CreateIfNotExistsAsync();
var permission = new BlobContainerPermissions();
permission.PublicAccess = BlobContainerPublicAccessType.Blob;
await theContainer.SetPermissionsAsync(permission);
if (relativePath != rootContainerPath)
{
fileName = Path.Combine(relativePath, fileName);
}
var blob = theContainer.GetBlockBlobReference(fileName);
await blob.UploadFromByteArrayAsync(file, 0, file.Length);
}
public async Task SaveHtmlResults(string html, string container, string fileName)
{
CloudBlobContainer theContainer = null;
if (_cloudBlobClient == null) throw new InvalidOperationException("blobClient is null");
var segments = container.Split(@"/".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
var rootContainerPath = segments.First();
var relativePath = String.Join(@"/", segments.Except(new string[] { rootContainerPath }));
theContainer = _cloudBlobClient.GetContainerReference($"{rootContainerPath}");
await theContainer.CreateIfNotExistsAsync();
var permission = new BlobContainerPermissions();
permission.PublicAccess = BlobContainerPublicAccessType.Blob;
await theContainer.SetPermissionsAsync(permission);
if (relativePath != rootContainerPath)
{
fileName = Path.Combine(relativePath, fileName);
}
var blob = theContainer.GetBlockBlobReference(fileName);
await blob.UploadTextAsync(html);
}
public async Task<PredictionDetail> GetPredictionAsync(string folderId)
{
if (String.IsNullOrWhiteSpace(folderId))
throw new ArgumentNullException("folderId");
var blobContainer = _cloudBlobClient.GetContainerReference(folderId);
bool exists = await blobContainer.ExistsAsync();
if (!exists)
throw new DirectoryNotFoundException($"Container {folderId} does not exist");
var groupsBlob = blobContainer.GetBlockBlobReference("groups.json");
var detail = new PredictionDetail();
detail.OriginalImage = await this.GetFile(folderId, "original.png");
detail.PredictionImage = await this.GetFile(folderId, "predicted.png");
detail.PredictedObjects = await this.GetFile<IList<PredictedObject>>(folderId, "results.json");
var groupBox = await this.GetFile<GroupBox>(folderId, "groups.json");
detail.GroupBox = new List<GroupBox> { groupBox };
return detail;
}
public async Task<IList<CloudBlobContainer>> GetPredictionsAsync()
{
return await Task.Run(() => _cloudBlobClient.ListContainers().Where(l => l.Name != "azure-webjobs-hosts")
.OrderByDescending(c => c.Properties.LastModified).ToList());
}
public async Task<byte[]> GetFile(string container, string file)
{
var blobcontainer = _cloudBlobClient.GetContainerReference(container);
if (!await blobcontainer.ExistsAsync())
{
throw new ApplicationException($"container {container} does not exist");
}
var blob = blobcontainer.GetBlobReference(file);
if (!await blob.ExistsAsync())
{
throw new ApplicationException($"file {file} does not exist in container {container}");
}
using (var ms = new MemoryStream())
{
await blob.DownloadToStreamAsync(ms);
return ms.ToArray();
}
}
public async Task<T> GetFile<T>(string container, string file)
{
var data = await this.GetFile(container, file);
if (data == null) return default(T);
return JsonConvert.DeserializeObject<T>(Encoding.UTF8.GetString(data));
}
public async Task<GroupBox> CreateGroupBoxAsync(IList<PredictedObject> predictedObjects)
{
var result = await Task.Run(() =>
{
//Project each prediction into its bounding box
foreach (var p in predictedObjects)
p.BoundingBox.PredictedObject = p;
var list = predictedObjects.Select(p => p.BoundingBox).ToList();
//Execute BoxGeometry methods
BoxGeometry.Geometry g = new BoxGeometry.Geometry();
g.RemoveOverlapping(list);
BoxGeometry.GroupBox root = g.BuildGroups(list);
return root;
});
return result;
}
}
}
| 40.721088 | 117 | 0.615352 | [
"MIT"
] | Bhaskers-Blu-Org2/AISchoolTutorials | sketch2code/Sketch2Code.Core/Services/ObjectDetectionAppService.cs | 11,974 | C# |
namespace Bog.Domain.Common
{
using System;
using Bog.Domain.Entities.Contracts;
public interface ITrackableEntity
{
#region Public Properties
/// <summary>
/// Gets or sets the created at.
/// </summary>
DateTime CreatedAt { get; set; }
/// <summary>
/// Gets or sets the created by.
/// </summary>
IAccount CreatedBy { get; set; }
/// <summary>
/// Gets or sets the modified at.
/// </summary>
DateTime ModifiedAt { get; set; }
/// <summary>
/// Gets or sets the last modified by.
/// </summary>
IAccount ModifiedBy { get; set; }
#endregion
}
} | 22.242424 | 50 | 0.506812 | [
"MIT"
] | BankOfGiving/Bog.net | Bog.Domain.Entities/Contracts/ITrackableEntity.cs | 736 | C# |
namespace VRFI
{
public class VRFI_InputBlock
{
public enum InputAlias
{
あいうえお,
かきくけこ,
さしすせそ,
たちつてと,
なにぬねの,
はひふへほ,
まみむめも,
やゆよ,
らりるれろ,
わをんー
}
public enum KeyTemplates
{
Japanese_Normal,
Japanese_dakuten,
Japanese_handakuten,
Japanese_komozi
}
public static string[,] DefaultCharacterBlock = {
{ "あ", "い", "う", "え", "お" },
{ "か", "き", "く", "け", "こ" },
{ "さ", "し", "す", "せ", "そ" },
{ "た", "ち", "つ", "て", "と" },
{ "な", "に", "ぬ", "ね", "の" },
{ "は", "ひ", "ふ", "へ", "ほ" },
{ "ま", "み", "む", "め", "も" },
{ "や", "(" , "ゆ", ")" , "よ" },
{ "ら", "り", "る", "れ", "ろ" },
{ "わ", "を", "ん", "ー", " " },
};
public static string[,] DakutenCharacterBlock = {
{ "あ゛", "い゛", "う゛", "え゛", "お゛" },
{ "が" , "ぎ" , "ぐ" , "げ" , "ご" },
{ "ざ" , "じ" , "ず" , "ぜ" , "ぞ" },
{ "だ" , "ぢ" , "づ" , "で" , "ど" },
{ "な゛", "に゛", "ぬ゛", "ね゛", "の゛" },
{ "ば" , "び" , "ぶ" , "べ" , "ぼ" },
{ "ま゛", "み゛", "む゛", "め゛", "も゛" },
{ "や゛", "「" , "ゆ゛", "」" , "よ゛" },
{ "ら゛", "り゛", "る゛", "れ゛", "ろ゛" },
{ "わ゛", "を゛", "ん゛", "~" , " " },
};
public static string[,] HandakutenCharacterBlock = {
{ "あ", "い", "う", "え", "お" },
{ "か", "き", "く", "け", "こ" },
{ "さ", "し", "す", "せ", "そ" },
{ "た", "ち", "つ", "て", "と" },
{ "な", "に", "ぬ", "ね", "の" },
{ "ぱ", "ぴ", "ぷ", "ぺ", "ぽ" },
{ "ま", "み", "む", "め", "も" },
{ "や", "[" , "ゆ", "]" , "よ" },
{ "ら", "り", "る", "れ", "ろ" },
{ "わ", "を", "ん", "-", " " },
};
public static string[,] KomoziCharacterBlock = {
{ "ぁ", "ぃ", "ぅ", "ぇ", "ぉ" },
{ "か", "き", "く", "け", "こ" },
{ "さ", "し", "す", "せ", "そ" },
{ "た", "ち", "っ", "て", "と" },
{ "な", "に", "ぬ", "ね", "の" },
{ "ぱ", "ぴ", "ぷ", "ぺ", "ぽ" },
{ "ま", "み", "む", "め", "も" },
{ "ゃ", "[" , "ゅ", "]" , "ょ" },
{ "ら", "り", "る", "れ", "ろ" },
{ "ゎ", "を", "ん", "-", " " },
};
}
}
| 31 | 60 | 0.216129 | [
"MIT"
] | donafudo/VRFlickInput | Assets/VRFlickInput/Scripts/VRFI_InputBlock.cs | 3,008 | C# |
// <copyright file="SumDataLong.cs" company="OpenTelemetry Authors">
// Copyright 2018, OpenTelemetry Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
using System;
using System.Diagnostics;
namespace OpenTelemetry.Stats.Aggregations
{
[DebuggerDisplay("{ToString(),nq}")]
public sealed class SumDataLong : AggregationData, ISumDataLong
{
internal SumDataLong(long sum)
{
this.Sum = sum;
}
public long Sum { get; }
public static ISumDataLong Create(long sum)
{
return new SumDataLong(sum);
}
public override T Match<T>(
Func<ISumDataDouble, T> p0,
Func<ISumDataLong, T> p1,
Func<ICountData, T> p2,
Func<IMeanData, T> p3,
Func<IDistributionData, T> p4,
Func<ILastValueDataDouble, T> p5,
Func<ILastValueDataLong, T> p6,
Func<IAggregationData, T> defaultFunction)
{
return p1.Invoke(this);
}
/// <inheritdoc/>
public override string ToString()
{
return nameof(SumDataLong)
+ "{"
+ nameof(this.Sum) + "=" + this.Sum
+ "}";
}
/// <inheritdoc/>
public override bool Equals(object o)
{
if (o == this)
{
return true;
}
if (o is SumDataLong that)
{
return this.Sum == that.Sum;
}
return false;
}
/// <inheritdoc/>
public override int GetHashCode()
{
long h = 1;
h *= 1000003;
h ^= (this.Sum >> 32) ^ this.Sum;
return (int)h;
}
}
}
| 27.821429 | 75 | 0.542576 | [
"Apache-2.0"
] | alexvaluyskiy/opentelemetry-dotnet | src/OpenTelemetry/Stats/Aggregations/SumDataLong.cs | 2,339 | C# |
using System;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("AWSSDK.ElasticFileSystem")]
#if BCL35
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - Amazon Elastic File System. Amazon Elastic File System (Amazon EFS) is a file storage service for Amazon Elastic Compute Cloud (Amazon EC2) instances.")]
#elif BCL45
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (4.5) - Amazon Elastic File System. Amazon Elastic File System (Amazon EFS) is a file storage service for Amazon Elastic Compute Cloud (Amazon EC2) instances.")]
#elif PCL
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (PCL) - Amazon Elastic File System. Amazon Elastic File System (Amazon EFS) is a file storage service for Amazon Elastic Compute Cloud (Amazon EC2) instances.")]
#elif UNITY
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (Unity) - Amazon Elastic File System. Amazon Elastic File System (Amazon EFS) is a file storage service for Amazon Elastic Compute Cloud (Amazon EC2) instances.")]
#elif CORECLR
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (CoreCLR)- Amazon Elastic File System. Amazon Elastic File System (Amazon EFS) is a file storage service for Amazon Elastic Compute Cloud (Amazon EC2) instances.")]
#else
#error Unknown platform constant - unable to set correct AssemblyDescription
#endif
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyProduct("Amazon Web Services SDK for .NET")]
[assembly: AssemblyCompany("Amazon.com, Inc")]
[assembly: AssemblyCopyright("Copyright 2009-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("3.3")]
[assembly: AssemblyFileVersion("3.3.0.9")]
#if WINDOWS_PHONE || UNITY
[assembly: System.CLSCompliant(false)]
# else
[assembly: System.CLSCompliant(true)]
#endif
#if BCL
[assembly: System.Security.AllowPartiallyTrustedCallers]
#endif | 49.719298 | 233 | 0.767466 | [
"Apache-2.0"
] | miltador-forks/aws-sdk-net | sdk/src/Services/ElasticFileSystem/Properties/AssemblyInfo.cs | 2,834 | C# |
using System;
namespace UnityScriptLab.Input.Value.Provider {
/// <summary>
/// Combines two InputValues into one.
/// </summary>
public class Combinator<In1, In2, Out> : ValueProvider<Out> {
In1 currentValue1;
In2 currentValue2;
Func<In1, In2, Out> combine;
public Combinator(InputValue<In1> input1, InputValue<In2> input2, Func<In1, In2, Out> combine) {
input1.Updated += v => currentValue1 = v;
input2.Updated += v => currentValue2 = v;
this.combine = combine;
}
public Out GetValue(InputSystem input) {
return combine(currentValue1, currentValue2);
}
}
}
| 27.130435 | 100 | 0.661859 | [
"MIT"
] | DerTraveler/unityscriptlab-input | UnityScriptLab/Input/Value/Provider/Combinator.cs | 624 | C# |
using System.ComponentModel.DataAnnotations;
namespace ThisProject.Models
{
public class ExternalLoginConfirmationViewModel
{
[Required]
[Display(Name = "User name")]
public string UserName { get; set; }
}
public class ManageUserViewModel
{
[Required]
[DataType(DataType.Password)]
[Display(Name = "Current password")]
public string OldPassword { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "New password")]
public string NewPassword { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm new password")]
[Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}
public class LoginViewModel
{
[Required]
[Display(Name = "User name")]
public string UserName { get; set; }
[Required]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[Display(Name = "Remember me?")]
public bool RememberMe { get; set; }
}
public class RegisterViewModel
{
[Required]
[Display(Name = "User name")]
public string UserName { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}
}
| 30.6875 | 110 | 0.604379 | [
"Unlicense"
] | rugbyjohnny/OffOn | ThisProject/ThisProject/Models/AccountViewModels.cs | 1,966 | C# |
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using System.Collections.Generic;
namespace MonsterGame
{
// TODO : Work on Shuriken
// Finish AI
// Get damage
// Add R
// Add Game over/ win screen
// Add Menu
// Add animations
// Add Audio
public class MonsterGame : Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
Player player;
UITop ui;
Floor floor;
Enemy enemy;
public const int screenWidth = 1280, screenHeight = 720;
public MonsterGame()
{
graphics = new GraphicsDeviceManager(this);
graphics.PreferredBackBufferWidth = screenWidth;
graphics.PreferredBackBufferHeight = screenHeight;
graphics.ApplyChanges();
Content.RootDirectory = "Content";
}
protected override void Initialize()
{
base.Initialize();
}
protected override void LoadContent()
{
spriteBatch = new SpriteBatch(GraphicsDevice);
ResourceLoader.LoadResources(Content);
player = new Player();
floor = new Floor();
ui = new UITop(player);
enemy = new Enemy(player);
}
protected override void Update(GameTime gameTime)
{
if (Keyboard.GetState().IsKeyDown(Keys.Escape))
Exit();
player.Update(gameTime);
floor.Update(gameTime);
ui.Update(gameTime);
enemy.Update(gameTime);
if (player.IsGrounded == false) floor.CheckGrounded(player);
base.Update(gameTime);
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
spriteBatch.Begin();
floor.Draw(spriteBatch);
player.Draw(spriteBatch);
ui.Draw(spriteBatch);
enemy.Draw(spriteBatch);
spriteBatch.End();
base.Draw(gameTime);
}
}
}
| 27.164557 | 72 | 0.565704 | [
"MIT"
] | FrancoCuevas444/MonsterGame | LD33 Version/MonsterGame.cs | 2,148 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CTT_TextGen : MonoBehaviour
{
Texture2D texture;
int[,] noise;
public int size = 200;
public bool ready = false;
// Start is called before the first frame update
void Awake()
{
noise = new int[size, size];
for (int x = 0; x < size; x++)
for (int y = 0; y < size; y++)
noise[x, y] = (int)Mathf.Round(Random.value);
}
void Start()
{
texture = new Texture2D((int)size, (int)size, TextureFormat.ARGB32, false);
texture.filterMode = FilterMode.Point;
//GetComponent<Renderer>().material.mainTexture = texture;
generateTexture(size);
ready = true;
}
public float freq = 0.02f;
public int noiseScale = 1;
// LM component, K
public float la = 0.2f; // left oblique contrast
public float lb = 0.2f; // right oblique contrast
float theta_a = 0.25f * Mathf.PI; // / 2.0f; //-1.0f * Mathf.PI / 2.0f; // orientation of left oblique, -45 deg clockwise from vertical
float theta_b = -0.25f * Mathf.PI; //; // orientation of right oblique, 45 deg clockwise from vertical
float theta_c = 0.25f * Mathf.PI;
float theta_d = -0.25f * Mathf.PI;
public float phi_a = 0.5f; // spatial phase of left oblique
public float phi_b = -0.5f; // spatial phase of right oblique
public float phi_c = 0.5f;
public float phi_d = 0.5f;
public float mc = 0.2f; //modulation depths of the left and right obliques respective- ly
public float md = 0.2f; //modulation depths of the left and right obliques respective - ly
public float l0 = 0.5f; // mean luminance of the monitor
public float n = 0.1f; // contrast of noise texture
private void OnValidate()
{
if (ready)
{
generateTexture(size);
}
}
// want period to be 200
// natural period is 2 pi
// 0.005 == 1/200 (*2pi)
void generateTexture(int size)
{
float min = 10.0f;
float max = -10.0f;
int centre = size / 2;
float _phi_a = Mathf.PI * phi_a; // spatial phase of left oblique
float _phi_b = Mathf.PI * phi_b; // spatial phase of right oblique
float _phi_c = Mathf.PI * phi_c;
float _phi_d = Mathf.PI * phi_d;
for (int y = 0; y < size; y++)
{
for (int x = 0; x < size; x++)
{
float k = (la * Mathf.Cos(2.0f * Mathf.PI * freq * ((Mathf.Cos(theta_a) * x) - (Mathf.Sin(theta_a) * y)) - phi_a))
+ (lb * Mathf.Cos(2.0f * Mathf.PI * freq * ((Mathf.Cos(theta_b) * x) - (Mathf.Sin(theta_b) * y)) - phi_b));
float m = (mc * Mathf.Cos(2.0f * Mathf.PI * freq * ((Mathf.Cos(theta_c) * x) - (Mathf.Sin(theta_c) * y)) - phi_c))
+ (md * Mathf.Cos(2.0f * Mathf.PI * freq * ((Mathf.Cos(theta_d) * x) - (Mathf.Sin(theta_d) * y)) - phi_d));
float r = noise[x / noiseScale, y / noiseScale]; //.Round(Random.value);
float l = l0 * (1.0f + k + (n * r) + (n * r * m));
float a = 1.0f;
int distance = (int) Mathf.Sqrt(((x - centre) * (x - centre)) + ((y - centre) * (y - centre)));
if (distance >= centre)
a = 0.0f;
texture.SetPixel(x, y, new Color(l, l, l, a));
if (l > max)
max = l;
if (l < min)
min = l;
}
}
//Debug.Log(max + " " + min);
texture.Apply();
}
// Update is called once per frame
void Update()
{
}
public Texture2D getTexture()
{
return texture;
}
}
| 28.477612 | 140 | 0.527254 | [
"MIT"
] | paultennent/canttouchthis | Assets/Scripts/CTT_TextGen.cs | 3,818 | C# |
namespace AcFunDanmu.Enums
{
public static class Command
{
public const string REGISTER = "Basic.Register";
public const string UNREGISTER = "Basic.Unregister";
public const string KEEP_ALIVE = "Basic.KeepAlive";
public const string PING = "Basic.Ping";
public const string CLIENT_CONFIG_GET = "Basic.ClientConfigGet";
public const string MESSAGE_SESSION = "Message.Session";
public const string MESSAGE_PULL_OLD = "Message.PullOld";
public const string GROUP_USER_GROUP_LIST = "Group.UserGroupList";
public const string GLOBAL_COMMAND = "Global.ZtLiveInteractive.CsCmd";
public const string PUSH_MESSAGE = "Push.ZtLiveInteractive.Message";
}
public static class GlobalCommand
{
public const string ENTER_ROOM = "ZtLiveCsEnterRoom";
public const string ENTER_ROOM_ACK = "ZtLiveCsEnterRoomAck";
public const string HEARTBEAT = "ZtLiveCsHeartbeat";
public const string HEARTBEAT_ACK = "ZtLiveCsHeartbeatAck";
public const string USER_EXIT = "ZtLiveCsUserExit";
public const string USER_EXIT_ACK = "ZtLiveCsUserExitAck";
}
public static class PushMessage
{
public const string ACTION_SIGNAL = "ZtLiveScActionSignal";
public const string STATE_SIGNAL = "ZtLiveScStateSignal";
public const string NOTIFY_SIGNAL = "ZtLiveScNotifySignal";
public const string STATUS_CHANGED = "ZtLiveScStatusChanged";
public const string TICKET_INVALID = "ZtLiveScTicketInvalid";
public static class ActionSignal
{
public const string COMMENT = "CommonActionSignalComment";
public const string LIKE = "CommonActionSignalLike";
public const string ENTER_ROOM = "CommonActionSignalUserEnterRoom";
public const string FOLLOW = "CommonActionSignalUserFollowAuthor";
public const string THROW_BANANA = "AcfunActionSignalThrowBanana";
public const string GIFT = "CommonActionSignalGift";
public const string RICH_TEXT = "CommonActionSignalRichText";
}
public static class StateSignal
{
public const string ACFUN_DISPLAY_INFO = "AcfunStateSignalDisplayInfo";
public const string DISPLAY_INFO = "CommonStateSignalDisplayInfo";
public const string TOP_USRES = "CommonStateSignalTopUsers";
public const string RECENT_COMMENT = "CommonStateSignalRecentComment";
public const string CHAT_CALL = "CommonStateSignalChatCall";
public const string CHAT_ACCEPT = "CommonStateSignalChatAccept";
public const string CHAT_READY = "CommonStateSignalChatReady";
public const string CHAT_END = "CommonStateSignalChatEnd";
public const string CURRENT_RED_PACK_LIST = "CommonStateSignalCurrentRedpackList";
public const string AUTHOR_CHAT_CALL = "CommonStateSignalAuthorChatCall";
public const string AUTHOR_CHAT_ACCEPT = "CommonStateSignalAuthorChatAccept";
public const string AUTHOR_CHAT_READY = "CommonStateSignalAuthorChatReady";
public const string AUTHOR_CHAT_END = "CommonStateSignalAuthorChatEnd";
public const string AUTHOR_CHAT_CHANGE_SOUND_CONFIG = "CommonStateSignalAuthorChatChangeSoundConfig";
}
public static class NotifySignal
{
public const string KICKED_OUT = "CommonNotifySignalKickedOut";
public const string VIOLATION_ALERT = "CommonNotifySignalViolationAlert";
public const string LIVE_MANAGER_STATE = "CommonNotifySignalLiveManagerState";
}
}
}
| 48.605263 | 113 | 0.704656 | [
"MIT"
] | megatontech/AcFunDanmaku | AcFunDanmu/Enums.cs | 3,696 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Nucleo.Demos.MvpSamples.PresenterLoadingSamples {
public partial class ConventionMatching {
/// <summary>
/// lblMessage control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblMessage;
}
}
| 32.16 | 84 | 0.49005 | [
"MIT"
] | brianmains/Nucleo.NET | mvp_src/Backup/Demos.WebForms.Mvp/Demos/MvpSamples/PresenterLoadingSamples/ConventionMatching.aspx.designer.cs | 806 | C# |
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
using DSynth.Engine.TokenHandlers;
using Xunit;
namespace DSynth.Engine.Tests.UnitTests
{
public class MacAddressHandlerTests
{
private const string _unitTestProviderName = "UnitTestProviderName";
[Fact]
public void ShouldGetReplacementValue()
{
string token = "{{MacAddress:MacAddress}}";
TokenDescriptor descriptor = new TokenDescriptor(token);
ITokenHandler handler = TokenHandlerFactory.GetHandler(descriptor, _unitTestProviderName, null);
string result = handler.GetReplacementValue();
string[] macAddressSegments = result.Split(":");
Assert.True(macAddressSegments.Length == 6);
}
}
} | 40.074074 | 108 | 0.554529 | [
"MIT"
] | microsoft/DSynth | src/DSynth.Engine.Tests/UnitTests/TokenHandlers/MacAddressHandlerTests.cs | 1,082 | C# |
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using EasyAbp.NotificationService.Notifications;
using Volo.Abp.DependencyInjection;
using Volo.Abp.TextTemplating;
namespace EasyAbp.NotificationService.Provider.Mailing.UserWelcomeNotifications
{
public class UserWelcomeNotificationFactory : NotificationFactory<UserWelcomeNotificationDataModel, CreateEmailNotificationEto>, ITransientDependency
{
private readonly ITemplateRenderer _templateRenderer;
public UserWelcomeNotificationFactory(ITemplateRenderer templateRenderer)
{
_templateRenderer = templateRenderer;
}
public override async Task<CreateEmailNotificationEto> CreateAsync(UserWelcomeNotificationDataModel model, IEnumerable<Guid> userIds)
{
var subject = await _templateRenderer.RenderAsync("UserWelcomeEmailSubject", model);
var body = await _templateRenderer.RenderAsync("UserWelcomeEmailBody", model);
return new CreateEmailNotificationEto(userIds, subject, body);
}
}
} | 39.714286 | 153 | 0.752698 | [
"MIT"
] | wagnerhsu/sample-EasyAbp-NotificationService | providers/Mailing/EasyAbp.NotificationService.Provider.Mailing.Test/EasyAbp/NotificationService/Provider/Mailing/UserWelcomeNotifications/UserWelcomeNotificationFactory.cs | 1,114 | C# |
using BlogEngine.Core.Data.Models;
using Newtonsoft.Json;
using NuGet;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
namespace BlogEngine.Core.Packaging
{
/// <summary>
/// Online gallery
/// </summary>
public static class Gallery
{
/// <summary>
/// Load gallery packages
/// </summary>
/// <param name="packages">Packages to load</param>
public static void Load(List<Package> packages)
{
try
{
var packs = GetNugetPackages().ToList();
var extras = GetPackageExtras();
foreach (var pkg in packs)
{
if (pkg.IsLatestVersion)
{
var jp = new Package
{
Id = pkg.Id,
Authors = pkg.Authors == null ? "unknown" : string.Join(", ", pkg.Authors),
Description = pkg.Description.Length > 140 ? string.Format("{0}...", pkg.Description.Substring(0, 140)) : pkg.Description,
DownloadCount = pkg.DownloadCount,
LastUpdated = pkg.Published != null ? pkg.Published.Value.ToString("yyyy-MM-dd HH:mm") : "", // format for sort order to work with strings
Title = string.IsNullOrEmpty(pkg.Title) ? pkg.Id : pkg.Title,
OnlineVersion = pkg.Version.ToString(),
Website = pkg.ProjectUrl == null ? null : pkg.ProjectUrl.ToString(),
Tags = pkg.Tags,
IconUrl = pkg.IconUrl == null ? null : pkg.IconUrl.ToString()
};
if (!string.IsNullOrEmpty(jp.IconUrl) && !jp.IconUrl.StartsWith("http:"))
jp.IconUrl = Constants.GalleryUrl + jp.IconUrl;
if (string.IsNullOrEmpty(jp.IconUrl))
jp.IconUrl = DefaultThumbnail("");
if (extras != null && extras.Any())
{
var extra = extras.FirstOrDefault(e => e.Id.ToLower() == pkg.Id.ToLower() + "." + pkg.Version);
if (extra != null)
{
jp.Extra = extra;
jp.DownloadCount = extra.DownloadCount;
jp.Rating = extra.Rating;
jp.PackageType = extra.PkgType.ToString();
}
}
packages.Add(jp);
}
}
}
catch (Exception ex)
{
Utils.Log("BlogEngine.Core.Packaging.Load", ex);
}
}
/// <summary>
/// Gets extra filds from remote gallery if gallery supports it
/// </summary>
/// <param name="id">Package ID</param>
/// <returns>Object with extra package fields</returns>
public static PackageExtra GetPackageExtra(string id)
{
try
{
var url = BlogConfig.GalleryFeedUrl.Replace("/nuget", "/api/extras/" + id);
WebClient wc = new WebClient();
string json = wc.DownloadString(url);
return JsonConvert.DeserializeObject<PackageExtra>(json);
}
catch (Exception)
{
return null;
}
}
/// <summary>
/// BlogEngine.Gallery implements Nuget.Server
/// and adds fields like download counts, reviews, ratings etc.
/// </summary>
/// <returns>List of extra fields if exist</returns>
public static IEnumerable<PackageExtra> GetPackageExtras()
{
try
{
var url = BlogConfig.GalleryFeedUrl.Replace("/nuget", "/api/extras");
WebClient wc = new WebClient();
string json = wc.DownloadString(url);
return JsonConvert.DeserializeObject<List<PackageExtra>>(json);
}
catch (Exception)
{
return null;
}
}
/// <summary>
/// Rate package
/// </summary>
/// <param name="id">Pacakge ID</param>
/// <param name="review">Review</param>
/// <returns>Empty if success, message otherwise</returns>
public static string RatePackage(string id, Review review)
{
try
{
var url = BlogConfig.GalleryFeedUrl.Replace("/nuget", "/api/review?pkgId=" + id);
WebClient wc = new WebClient();
var data = JsonConvert.SerializeObject(review);
wc.Headers.Add("content-type", "application/json");
var result = wc.UploadString(url, "PUT", data);
// sanitize result replacing garbage returned by service
if (result == "\"\"") result = string.Empty;
result = result.Replace("\"", "").Replace("\\", "");
Blog.CurrentInstance.Cache.Remove(Constants.CacheKey);
return result;
}
catch (Exception ex)
{
Utils.Log("Error rating package", ex);
return ex.Message;
}
}
#region Private methods
static IEnumerable<IPackage> GetNugetPackages()
{
var rep = PackageRepositoryFactory.Default.CreateRepository(BlogConfig.GalleryFeedUrl);
return rep.GetPackages();
}
static string DefaultThumbnail(string packageType)
{
switch (packageType)
{
case "Theme":
return $"{Utils.ApplicationRelativeWebRoot}Content/images/blog/Theme.png";
case "Extension":
return $"{Utils.ApplicationRelativeWebRoot}Content/images/blog/ext.png";
case "Widget":
return $"{Utils.ApplicationRelativeWebRoot}Content/images/blog/Widget.png";
}
return $"{Utils.ApplicationRelativeWebRoot}Content/images/blog/pkg.png";
}
#endregion
}
} | 37.822485 | 166 | 0.484981 | [
"Unlicense"
] | Solotzy/Analysis-of-BlogEngine.NET | BlogEngine/BlogEngine.Core/Services/Packaging/Gallery.cs | 6,394 | C# |
using UnityEngine;
using UnityEngine.UI;
public class ForgotPassword : StartMenuPage
{
public GameObject SignInPage;
public InputField email;
public void GoToSignInButtonEvent()
{
this.SignInPage.SetActive(true);
}
public void ValidateButtonEvent()
{
this._api.resetMyPassword(this.email.text, this.ResetResult);
}
public int ResetResult(int k, string l)
{
return k;
}
} | 19.217391 | 69 | 0.667421 | [
"MIT"
] | PlayArShop/mobile-application | Assets/Mainmenu/Scripts/Startmenu/ForgotPassword.cs | 442 | C# |
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using NEventStore;
using NEventStore.PollingClient;
using SimpleIdServer.OpenBankingApi.Domains;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using System.Transactions;
using static NEventStore.PollingClient.PollingClient2;
namespace SimpleIdServer.OpenBankingApi
{
public class EventStoreJob : IJob
{
private readonly IStoreEvents _storeEvents;
private readonly OpenBankingApiOptions _options;
private readonly IServiceProvider _serviceProvider;
private readonly ILogger<EventStoreJob> _logger;
private PollingClient2 _client;
public EventStoreJob(
IStoreEvents storeEvents,
IServiceProvider serviceProvider,
IOptions<OpenBankingApiOptions> options,
ILogger<EventStoreJob> logger)
{
_storeEvents = storeEvents;
_serviceProvider = serviceProvider;
_options = options.Value;
_logger = logger;
}
public void Start()
{
_client = new PollingClient2(_storeEvents.Advanced, Handle, _options.WaitInterval);
_client.StartFrom();
}
public void Stop()
{
if (_client != null)
{
_client.Dispose();
}
}
private HandlingResult Handle(ICommit commit)
{
try
{
using (var transaction = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
{
foreach (var evt in commit.Events)
{
var domainEvt = evt.Body as DomainEvent;
var genericType = domainEvt.GetType();
var messageBrokerType = typeof(IEventHandler<>).MakeGenericType(genericType);
var lst = (IEnumerable<object>)_serviceProvider.GetService(typeof(IEnumerable<>).MakeGenericType(messageBrokerType));
foreach (var r in lst)
{
var task = (Task)messageBrokerType.GetMethod("Handle").Invoke(r, new object[] { domainEvt, CancellationToken.None });
task.Wait();
}
}
transaction.Complete();
}
}
catch(Exception ex)
{
_logger.LogError(ex.ToString());
return HandlingResult.Retry;
}
return HandlingResult.MoveToNext;
}
}
}
| 33.160494 | 145 | 0.570365 | [
"Apache-2.0"
] | LaTranche31/SimpleIdServer | src/OpenBankingApi/SimpleIdServer.OpenBankingApi/EventStoreJob.cs | 2,688 | C# |
using System.Collections.Generic;
using Essensoft.Paylink.Alipay.Response;
namespace Essensoft.Paylink.Alipay.Request
{
/// <summary>
/// alipay.open.public.group.batchquery
/// </summary>
public class AlipayOpenPublicGroupBatchqueryRequest : IAlipayRequest<AlipayOpenPublicGroupBatchqueryResponse>
{
#region IAlipayRequest Members
private bool needEncrypt = false;
private string apiVersion = "1.0";
private string terminalType;
private string terminalInfo;
private string prodCode;
private string notifyUrl;
private string returnUrl;
private AlipayObject bizModel;
public void SetNeedEncrypt(bool needEncrypt)
{
this.needEncrypt = needEncrypt;
}
public bool GetNeedEncrypt()
{
return needEncrypt;
}
public void SetNotifyUrl(string notifyUrl)
{
this.notifyUrl = notifyUrl;
}
public string GetNotifyUrl()
{
return notifyUrl;
}
public void SetReturnUrl(string returnUrl)
{
this.returnUrl = returnUrl;
}
public string GetReturnUrl()
{
return returnUrl;
}
public void SetTerminalType(string terminalType)
{
this.terminalType = terminalType;
}
public string GetTerminalType()
{
return terminalType;
}
public void SetTerminalInfo(string terminalInfo)
{
this.terminalInfo = terminalInfo;
}
public string GetTerminalInfo()
{
return terminalInfo;
}
public void SetProdCode(string prodCode)
{
this.prodCode = prodCode;
}
public string GetProdCode()
{
return prodCode;
}
public string GetApiName()
{
return "alipay.open.public.group.batchquery";
}
public void SetApiVersion(string apiVersion)
{
this.apiVersion = apiVersion;
}
public string GetApiVersion()
{
return apiVersion;
}
public IDictionary<string, string> GetParameters()
{
var parameters = new AlipayDictionary();
return parameters;
}
public AlipayObject GetBizModel()
{
return bizModel;
}
public void SetBizModel(AlipayObject bizModel)
{
this.bizModel = bizModel;
}
#endregion
}
}
| 22.568966 | 113 | 0.558442 | [
"MIT"
] | fory77/paylink | src/Essensoft.Paylink.Alipay/Request/AlipayOpenPublicGroupBatchqueryRequest.cs | 2,620 | C# |
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.Aws.WafV2.Outputs
{
[OutputType]
public sealed class WebAclRuleStatementNotStatementStatementNotStatementStatementByteMatchStatement
{
/// <summary>
/// Part of a web request that you want AWS WAF to inspect. See Field to Match below for details.
/// </summary>
public readonly Outputs.WebAclRuleStatementNotStatementStatementNotStatementStatementByteMatchStatementFieldToMatch? FieldToMatch;
/// <summary>
/// Area within the portion of a web request that you want AWS WAF to search for `search_string`. Valid values include the following: `EXACTLY`, `STARTS_WITH`, `ENDS_WITH`, `CONTAINS`, `CONTAINS_WORD`. See the AWS [documentation](https://docs.aws.amazon.com/waf/latest/APIReference/API_ByteMatchStatement.html) for more information.
/// </summary>
public readonly string PositionalConstraint;
/// <summary>
/// String value that you want AWS WAF to search for. AWS WAF searches only in the part of web requests that you designate for inspection in `field_to_match`. The maximum length of the value is 50 bytes.
/// </summary>
public readonly string SearchString;
/// <summary>
/// Text transformations eliminate some of the unusual formatting that attackers use in web requests in an effort to bypass detection. See Text Transformation below for details.
/// </summary>
public readonly ImmutableArray<Outputs.WebAclRuleStatementNotStatementStatementNotStatementStatementByteMatchStatementTextTransformation> TextTransformations;
[OutputConstructor]
private WebAclRuleStatementNotStatementStatementNotStatementStatementByteMatchStatement(
Outputs.WebAclRuleStatementNotStatementStatementNotStatementStatementByteMatchStatementFieldToMatch? fieldToMatch,
string positionalConstraint,
string searchString,
ImmutableArray<Outputs.WebAclRuleStatementNotStatementStatementNotStatementStatementByteMatchStatementTextTransformation> textTransformations)
{
FieldToMatch = fieldToMatch;
PositionalConstraint = positionalConstraint;
SearchString = searchString;
TextTransformations = textTransformations;
}
}
}
| 52.32 | 340 | 0.739297 | [
"ECL-2.0",
"Apache-2.0"
] | chivandikwa/pulumi-aws | sdk/dotnet/WafV2/Outputs/WebAclRuleStatementNotStatementStatementNotStatementStatementByteMatchStatement.cs | 2,616 | C# |
using System;
using GNet.IO;
using GNet.PInvoke;
namespace GNet.Profiler.MacroSystem_ORIG
{
public class KeyTap : Step
{
public KeyTap(ScanCode scanCode)
{
Inputs = new InputWrapper[] { InputSimulator.KeyWrapper(scanCode), InputSimulator.KeyWrapper(scanCode, true) };
toString = "KeyTap(" + scanCode.ToString() + ")";
}
public KeyTap(char key)
{
Inputs = new InputWrapper[] { InputSimulator.KeyWrapper(key), InputSimulator.KeyWrapper(key, true) };
toString = "KeyTap(" + key + ")";
}
}
}
| 27.043478 | 124 | 0.575563 | [
"MIT"
] | HaKDMoDz/GNet | src/Profiler/MacroSystem_ORIG/KeyTap.cs | 624 | C# |
#if !NETSTANDARD13
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the iam-2010-05-08.normal.json service model.
*/
using Amazon.Runtime;
namespace Amazon.IdentityManagement.Model
{
/// <summary>
/// Paginator for the ListSigningCertificates operation
///</summary>
public interface IListSigningCertificatesPaginator
{
/// <summary>
/// Enumerable containing all full responses for the operation
/// </summary>
IPaginatedEnumerable<ListSigningCertificatesResponse> Responses { get; }
/// <summary>
/// Enumerable containing all of the Certificates
/// </summary>
IPaginatedEnumerable<SigningCertificate> Certificates { get; }
}
}
#endif | 32.925 | 101 | 0.697798 | [
"Apache-2.0"
] | PureKrome/aws-sdk-net | sdk/src/Services/IdentityManagement/Generated/Model/_bcl45+netstandard/IListSigningCertificatesPaginator.cs | 1,317 | C# |
using System.Reflection;
using System.Runtime.InteropServices;
// Allgemeine Informationen über eine Assembly werden über die folgenden
// Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern,
// die einer Assembly zugeordnet sind.
[assembly: AssemblyTitle("uprove_samlcommunication")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("uprove_samlcommunication")]
[assembly: AssemblyCopyright("Copyright © 2018")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Durch Festlegen von ComVisible auf "false" werden die Typen in dieser Assembly unsichtbar
// für COM-Komponenten. Wenn Sie auf einen Typ in dieser Assembly von
// COM aus zugreifen müssen, sollten Sie das ComVisible-Attribut für diesen Typ auf "True" festlegen.
[assembly: ComVisible(false)]
// Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird
[assembly: Guid("1a99ea2f-ccb0-48e7-bd64-bb2ca935bc50")]
// Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten:
//
// Hauptversion
// Nebenversion
// Buildnummer
// Revision
//
// Sie können alle Werte angeben oder die standardmäßigen Build- und Revisionsnummern
// übernehmen, indem Sie "*" eingeben:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config")] | 43.166667 | 106 | 0.763835 | [
"Apache-2.0",
"MIT"
] | fablei/uprove_samlcommunication | uprove_samlcommunication/Properties/AssemblyInfo.cs | 1,571 | C# |
#region license
// Copyright (c) 2007-2010 Mauricio Scheffer
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
namespace SolrNetLight.Commands.Parameters {
/// <summary>
/// Commit/optimize options
/// </summary>
public class CommitOptions {
/// <summary>
/// Block until a new searcher is opened and registered as the main query searcher, making the changes visible.
/// Default is true
/// </summary>
public bool? WaitSearcher { get; set; }
/// <summary>
/// Block until index changes are flushed to disk
/// Default is true
/// </summary>
public bool? WaitFlush { get; set; }
/// <summary>
/// Optimizes down to at most this number of segments
/// Default is 1
/// </summary>
/// <remarks>Requires Solr 1.3</remarks>
public int? MaxSegments { get; set; }
/// <summary>
/// Merge segments with deletes away
/// </summary>
/// <remarks>Requires Solr 1.4</remarks>
public bool? ExpungeDeletes { get; set; }
}
} | 34.255319 | 120 | 0.634783 | [
"Apache-2.0"
] | SolrNetLight/SolrNetLight | SolrNetLight/Commands/Parameters/CommitOptions.cs | 1,612 | C# |
using System.Net.Mime;
using umbraco.BusinessLogic;
namespace OurUmbraco.Our.Businesslogic
{
public class ProjectContributor
{
public int ProjectId { get; set; }
public int MemberId { get; set; }
public ProjectContributor(int projectId, int memberId)
{
ProjectId = projectId;
MemberId = memberId;
}
public void Add()
{
using (var sqlHelper = Application.SqlHelper)
{
var exists = sqlHelper.ExecuteScalar<int>(
"SELECT 1 FROM projectContributors WHERE projectId = @projectId and memberId = @memberId;",
sqlHelper.CreateParameter("@projectId", ProjectId),
sqlHelper.CreateParameter("@memberId", MemberId)) > 0;
if (exists == false)
{
sqlHelper.ExecuteNonQuery(
"INSERT INTO projectContributors(projectId,memberId) values(@projectId,@memberId);",
sqlHelper.CreateParameter("@projectId", ProjectId),
sqlHelper.CreateParameter("@memberId", MemberId));
}
}
}
public void Delete()
{
using (var sqlHelper = Application.SqlHelper)
{
sqlHelper.ExecuteNonQuery(
"DELETE FROM projectContributors WHERE projectId = @projectId and memberId = @memberId;",
sqlHelper.CreateParameter("@projectId", ProjectId),
sqlHelper.CreateParameter("@memberId", MemberId));
}
}
}
}
| 35.638298 | 121 | 0.532537 | [
"MIT"
] | AaronSadlerUK/OurUmbraco | OurUmbraco/Our/Businesslogic/ProjectContributor.cs | 1,677 | C# |
//-----------------------------------------------------------------------
// <copyright file="SqliteJournalSpec.cs" company="Akka.NET Project">
// Copyright (C) 2009-2020 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2020 .NET Foundation <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using Akka.Configuration;
using Akka.Persistence.TCK.Journal;
using Akka.Util.Internal;
using Xunit.Abstractions;
namespace Akka.Persistence.Sqlite.Tests
{
public class SqliteJournalSpec : JournalSpec
{
private static AtomicCounter counter = new AtomicCounter(0);
public SqliteJournalSpec(ITestOutputHelper output)
: base(CreateSpecConfig("Filename=file:memdb-journal-" + counter.IncrementAndGet() + ".db;Mode=Memory;Cache=Shared"), "SqliteJournalSpec", output)
{
SqlitePersistence.Get(Sys);
Initialize();
}
// TODO: hack. Replace when https://github.com/akkadotnet/akka.net/issues/3811
protected override bool SupportsSerialization => false;
private static Config CreateSpecConfig(string connectionString)
{
return ConfigurationFactory.ParseString(@"
akka.persistence {
publish-plugin-commands = on
journal {
plugin = ""akka.persistence.journal.sqlite""
sqlite {
class = ""Akka.Persistence.Sqlite.Journal.SqliteJournal, Akka.Persistence.Sqlite""
plugin-dispatcher = ""akka.actor.default-dispatcher""
table-name = event_journal
metadata-table-name = journal_metadata
auto-initialize = on
connection-string = """ + connectionString + @"""
}
}
}");
}
}
}
| 40.38 | 158 | 0.535414 | [
"Apache-2.0"
] | Bogdan-Rotund/akka.net | src/contrib/persistence/Akka.Persistence.Sqlite.Tests/SqliteJournalSpec.cs | 2,021 | C# |
using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Markup;
[assembly: AssemblyTitle("Hillinworks.TiledImage.Controls")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Hillinworks")]
[assembly: AssemblyProduct("Hillinworks.TiledImage.Controls")]
[assembly: AssemblyCopyright("Copyright © 2018")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None,
ResourceDictionaryLocation.SourceAssembly
)]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: XmlnsDefinition("http://schemas.hillinworks.com/tiled-image", "Hillinworks.TiledImage.Controls")]
[assembly: XmlnsDefinition("http://schemas.hillinworks.com/tiled-image", "Hillinworks.TiledImage.Controls.Overlays")] | 34.074074 | 117 | 0.786957 | [
"MIT"
] | hillinworks/TiledImageView | Hillinworks.TiledImage.Controls/Properties/AssemblyInfo.cs | 923 | C# |
using System.Linq;
using NUnit.Framework;
namespace Fettle.Tests.Core
{
class Multiple_mutants_per_syntax_node : Contexts.Default
{
public Multiple_mutants_per_syntax_node()
{
Given_a_partially_tested_app_in_which_multiple_mutants_survive_for_a_syntax_node();
Given_source_file_filters("**/PartiallyTestedNumberComparison.cs");
When_mutation_testing_the_app();
}
[Test]
public void Then_only_one_surviving_mutant_is_returned_per_syntax_node()
{
Assert.That(MutationTestResult.SurvivingMutants.Count(sm => sm.SourceLine == 7), Is.EqualTo(1));
}
}
} | 31.272727 | 109 | 0.670058 | [
"MIT"
] | AlexanderWinter/fettle | src/Tests/Core/Multiple_mutants_per_syntax_node.cs | 690 | C# |
using System;
namespace REST.API.DataContracts.Requests
{
public class UserCreationRequest
{
public DateTime Date { get; set; }
public User User { get; set; }
}
}
| 16.166667 | 42 | 0.628866 | [
"MIT"
] | bohdan-skrypka/architecture-setup-rest-api-template | REST/REST.API.DataContracts/Requests/UserCreationRequest.cs | 196 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the clouddirectory-2017-01-11.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.CloudDirectory.Model
{
/// <summary>
/// This is the response object from the ListPublishedSchemaArns operation.
/// </summary>
public partial class ListPublishedSchemaArnsResponse : AmazonWebServiceResponse
{
private string _nextToken;
private List<string> _schemaArns = new List<string>();
/// <summary>
/// Gets and sets the property NextToken.
/// <para>
/// The pagination token.
/// </para>
/// </summary>
public string NextToken
{
get { return this._nextToken; }
set { this._nextToken = value; }
}
// Check to see if NextToken property is set
internal bool IsSetNextToken()
{
return this._nextToken != null;
}
/// <summary>
/// Gets and sets the property SchemaArns.
/// <para>
/// The ARNs of published schemas.
/// </para>
/// </summary>
public List<string> SchemaArns
{
get { return this._schemaArns; }
set { this._schemaArns = value; }
}
// Check to see if SchemaArns property is set
internal bool IsSetSchemaArns()
{
return this._schemaArns != null && this._schemaArns.Count > 0;
}
}
} | 29.342105 | 112 | 0.623767 | [
"Apache-2.0"
] | ChristopherButtars/aws-sdk-net | sdk/src/Services/CloudDirectory/Generated/Model/ListPublishedSchemaArnsResponse.cs | 2,230 | C# |
/* Copyright © 2019 Lee Kelleher.
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
using System;
using Umbraco.Core;
using Umbraco.Core.Models.PublishedContent;
using Umbraco.Core.PropertyEditors;
namespace Umbraco.Community.Contentment.DataEditors
{
public sealed class RenderMacroValueConverter : PropertyValueConverterBase
{
public override bool IsConverter(IPublishedPropertyType propertyType) => propertyType.EditorAlias.InvariantEquals(RenderMacroDataEditor.DataEditorAlias);
public override PropertyCacheLevel GetPropertyCacheLevel(IPublishedPropertyType propertyType) => PropertyCacheLevel.None;
public override Type GetPropertyValueType(IPublishedPropertyType propertyType) => typeof(object);
public override bool? IsValue(object value, PropertyValueLevel level) => false;
}
}
| 41.375 | 161 | 0.780463 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | arknu/umbraco-contentment | src/Umbraco.Community.Contentment/DataEditors/RenderMacro/RenderMacroValueConverter.cs | 996 | C# |
using Extreme.Net;
using OpenBullet.Models;
using RuriLib;
using RuriLib.ViewModels;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net;
using System.Text;
using System.Windows;
namespace OpenBullet.ViewModels
{
public class ConfigManagerViewModel : ViewModelBase
{
private List<ConfigViewModel> cachedConfigs = new List<ConfigViewModel>();
private ObservableCollection<ConfigViewModel> configsList;
public ObservableCollection<ConfigViewModel> ConfigsList {
get {
return
SearchString == "" ?
configsList :
new ObservableCollection<ConfigViewModel>(configsList.Where(c => c.Name.ToLower().Contains(SearchString.ToLower())));
}
set { configsList = value; OnPropertyChanged("ConfigsList"); OnPropertyChanged("Total"); } }
public int Total { get { return ConfigsList.Count; } }
public string SavedConfig { get; set; }
public Config moreInfoConfig;
public Config MoreInfoConfig { get { return moreInfoConfig; } set { moreInfoConfig = value; OnPropertyChanged("MoreInfoConfig"); } }
public string CurrentConfigName { get { return Globals.mainWindow.ConfigsPage.CurrentConfig.Name; } }
private string searchString = "";
public string SearchString { get { return searchString; } set { searchString = value; OnPropertyChanged("SearchString"); OnPropertyChanged("ConfigsList"); OnPropertyChanged("Total"); } }
public ConfigManagerViewModel()
{
configsList = new ObservableCollection<ConfigViewModel>();
RefreshList(true);
}
public bool NameTaken(string name)
{
return ConfigsList.Any(x => x.Name == name);
}
public void RefreshCurrent()
{
OnPropertyChanged("CurrentConfigName");
}
public void RefreshList(bool pullSources)
{
// Scan the directory and the sources for configs
if (pullSources)
{
ConfigsList = new ObservableCollection<ConfigViewModel>(
GetConfigsFromSources()
.Concat(GetConfigsFromDisk(true))
);
}
else
{
ConfigsList = new ObservableCollection<ConfigViewModel>(
cachedConfigs
.Concat(GetConfigsFromDisk(true))
);
}
OnPropertyChanged("Total");
}
public List<ConfigViewModel> GetConfigsFromDisk(bool sort = false)
{
List<ConfigViewModel> models = new List<ConfigViewModel>();
// Load the configs in the root folder
foreach(var file in Directory.EnumerateFiles(Globals.configFolder).Where(file => file.EndsWith(".loli")))
{
try { models.Add(new ConfigViewModel(file, "Default", IOManager.LoadConfig(file))); }
catch { Globals.LogError(Components.ConfigManager, "Could not load file: " + file); }
}
// Load the configs in the subfolders
foreach(var categoryFolder in Directory.EnumerateDirectories(Globals.configFolder))
{
foreach(var file in Directory.EnumerateFiles(categoryFolder).Where(file => file.EndsWith(".loli")))
{
try { models.Add(new ConfigViewModel(file, Path.GetFileName(categoryFolder), IOManager.LoadConfig(file))); }
catch { Globals.LogError(Components.ConfigManager, "Could not load file: " + file); }
}
}
if (sort) { models.Sort((m1, m2) => m1.Config.Settings.LastModified.CompareTo(m2.Config.Settings.LastModified)); }
return models;
}
public List<ConfigViewModel> GetConfigsFromSources()
{
var list = new List<ConfigViewModel>();
cachedConfigs = new List<ConfigViewModel>();
foreach(var source in Globals.obSettings.Sources.Sources)
{
WebClient wc = new WebClient();
switch (source.Auth)
{
case Source.AuthMode.ApiKey:
wc.Headers.Add(HttpRequestHeader.Authorization, source.ApiKey);
break;
case Source.AuthMode.UserPass:
var header = BlockFunction.Base64Encode($"{source.Username}:{source.Password}");
wc.Headers.Add(HttpRequestHeader.Authorization, $"Basic {header}");
break;
default:
break;
}
byte[] file = new byte[] { };
try
{
file = wc.DownloadData(source.ApiUrl);
}
catch (Exception ex)
{
MessageBox.Show($"Could not contact API {source.ApiUrl}\r\nReason: {ex.Message}");
continue;
}
var status = wc.ResponseHeaders["Result"];
if (status != null && status == "Error")
{
MessageBox.Show($"Error from API {source.ApiUrl}\r\nThe server says: {Encoding.ASCII.GetString(file)}");
continue;
}
try
{
using (var zip = new ZipArchive(new MemoryStream(file), ZipArchiveMode.Read))
{
foreach (var entry in zip.Entries)
{
using (var stream = entry.Open())
{
using (TextReader tr = new StreamReader(stream))
{
var text = tr.ReadToEnd();
var cfg = IOManager.DeserializeConfig(text);
list.Add(new ConfigViewModel("", "Remote", cfg, true));
cachedConfigs.Add(new ConfigViewModel("", "Remote", cfg, true));
}
}
}
}
}
catch { }
}
return list;
}
}
} | 38.245614 | 194 | 0.526147 | [
"MIT"
] | ALEHACKsp/openbullet-Cracked.to- | OpenBullet/ViewModels/ConfigManagerViewModel.cs | 6,542 | C# |
// Copyright 2016-2019, Pulumi Corporation
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi
{
/// <summary>
/// Useful static utility methods for both creating and working with <see cref="Output{T}"/>s.
/// </summary>
public static partial class Output
{
public static Output<T> Create<T>(T value)
=> Create(Task.FromResult(value));
public static Output<T> Create<T>(Task<T> value)
=> Output<T>.Create(value);
public static Output<T> CreateSecret<T>(T value)
=> CreateSecret(Task.FromResult(value));
public static Output<T> CreateSecret<T>(Task<T> value)
=> Output<T>.CreateSecret(value);
/// <summary>
/// Returns a new <see cref="Output{T}"/> which is a copy of the existing output but marked as
/// a non-secret. The original output is not modified in any way.
/// </summary>
public static Output<T> Unsecret<T>(Output<T> output)
=> output.WithIsSecret(Task.FromResult(false));
/// <summary>
/// Retrieves the secretness status of the given output.
/// </summary>
public static async Task<bool> IsSecretAsync<T>(Output<T> output)
{
var dataTask = await output.DataTask.ConfigureAwait(false);
return dataTask.IsSecret;
}
/// <summary>
/// Combines all the <see cref="Input{T}"/> values in <paramref name="inputs"/>
/// into a single <see cref="Output{T}"/> with an <see cref="ImmutableArray{T}"/>
/// containing all their underlying values. If any of the <see cref="Input{T}"/>s are not
/// known, the final result will be not known. Similarly, if any of the <see
/// cref="Input{T}"/>s are secrets, then the final result will be a secret.
/// </summary>
public static Output<ImmutableArray<T>> All<T>(params Input<T>[] inputs)
=> Output<T>.All(ImmutableArray.CreateRange(inputs));
/// <summary>
/// <see cref="All{T}(Input{T}[])"/> for more details.
/// </summary>
public static Output<ImmutableArray<T>> All<T>(IEnumerable<Input<T>> inputs)
=> Output<T>.All(ImmutableArray.CreateRange(inputs));
/// <summary>
/// Combines all the <see cref="Output{T}"/> values in <paramref name="outputs"/>
/// into a single <see cref="Output{T}"/> with an <see cref="ImmutableArray{T}"/>
/// containing all their underlying values. If any of the <see cref="Output{T}"/>s are not
/// known, the final result will be not known. Similarly, if any of the <see
/// cref="Output{T}"/>s are secrets, then the final result will be a secret.
/// </summary>
public static Output<ImmutableArray<T>> All<T>(params Output<T>[] outputs)
=> All(outputs.AsEnumerable());
/// <summary>
/// <see cref="All{T}(Output{T}[])"/> for more details.
/// </summary>
public static Output<ImmutableArray<T>> All<T>(IEnumerable<Output<T>> outputs)
=> Output<T>.All(ImmutableArray.CreateRange(outputs.Select(o => (Input<T>)o)));
/// <summary>
/// Takes in a <see cref="FormattableString"/> with potential <see cref="Input{T}"/>s or
/// <see cref="Output{T}"/> in the 'placeholder holes'. Conceptually, this method unwraps
/// all the underlying values in the holes, combines them appropriately with the <see
/// cref="FormattableString.Format"/> string, and produces an <see cref="Output{T}"/>
/// containing the final result.
/// <para/>
/// If any of the <see cref="Input{T}"/>s or <see cref="Output{T}"/>s are not known, the
/// final result will be not known. Similarly, if any of the <see cref="Input{T}"/>s or
/// <see cref="Output{T}"/>s are secrets, then the final result will be a secret.
/// </summary>
public static Output<string> Format(FormattableString formattableString)
{
var arguments = formattableString.GetArguments();
var inputs = new Input<object?>[arguments.Length];
for (var i = 0; i < arguments.Length; i++)
{
var arg = arguments[i];
inputs[i] = arg.ToObjectOutput();
}
return All(inputs).Apply(objs =>
string.Format(formattableString.Format, objs.ToArray()));
}
internal static Output<ImmutableArray<T>> Concat<T>(Output<ImmutableArray<T>> values1, Output<ImmutableArray<T>> values2)
=> Tuple(values1, values2).Apply(a => a.Item1.AddRange(a.Item2));
}
/// <summary>
/// Internal interface to allow our code to operate on outputs in an untyped manner. Necessary
/// as there is no reasonable way to write algorithms over heterogeneous instantiations of
/// generic types.
/// </summary>
internal interface IOutput
{
Task<ImmutableHashSet<Resource>> GetResourcesAsync();
/// <summary>
/// Returns an <see cref="Output{T}"/> equivalent to this, except with our
/// <see cref="OutputData{X}.Value"/> casted to an object.
/// </summary>
Task<OutputData<object?>> GetDataAsync();
}
/// <summary>
/// <see cref="Output{T}"/>s are a key part of how Pulumi tracks dependencies between <see
/// cref="Resource"/>s. Because the values of outputs are not available until resources are
/// created, these are represented using the special <see cref="Output{T}"/>s type, which
/// internally represents two things:
/// <list type="number">
/// <item>An eventually available value of the output</item>
/// <item>The dependency on the source(s) of the output value</item>
/// </list>
/// In fact, <see cref="Output{T}"/>s is quite similar to <see cref="Task{TResult}"/>.
/// Additionally, they carry along dependency information.
/// <para/>
/// The output properties of all resource objects in Pulumi have type <see cref="Output{T}"/>.
/// </summary>
public sealed class Output<T> : IOutput
{
internal Task<OutputData<T>> DataTask { get; private set; }
internal Output(Task<OutputData<T>> dataTask)
=> DataTask = dataTask;
internal async Task<T> GetValueAsync()
{
var data = await DataTask.ConfigureAwait(false);
return data.Value;
}
async Task<ImmutableHashSet<Resource>> IOutput.GetResourcesAsync()
{
var data = await DataTask.ConfigureAwait(false);
return data.Resources;
}
async Task<OutputData<object?>> IOutput.GetDataAsync()
=> await DataTask.ConfigureAwait(false);
public static Output<T> Create(Task<T> value)
=> Create(value, isSecret: false);
internal static Output<T> CreateSecret(Task<T> value)
=> Create(value, isSecret: true);
internal Output<T> WithIsSecret(Task<bool> isSecret)
{
async Task<OutputData<T>> GetData()
{
var data = await this.DataTask.ConfigureAwait(false);
return new OutputData<T>(data.Resources, data.Value, data.IsKnown, await isSecret.ConfigureAwait(false));
}
return new Output<T>(GetData());
}
private static Output<T> Create(Task<T> value, bool isSecret)
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
var tcs = new TaskCompletionSource<OutputData<T>>();
value.Assign(tcs, t => OutputData.Create(ImmutableHashSet<Resource>.Empty, t, isKnown: true, isSecret: isSecret));
return new Output<T>(tcs.Task);
}
/// <summary>
/// <see cref="Apply{U}(Func{T, Output{U}})"/> for more details.
/// </summary>
public Output<U> Apply<U>(Func<T, U> func)
=> Apply(t => Output.Create(func(t)));
/// <summary>
/// <see cref="Apply{U}(Func{T, Output{U}})"/> for more details.
/// </summary>
public Output<U> Apply<U>(Func<T, Task<U>> func)
=> Apply(t => Output.Create(func(t)));
/// <summary>
/// <see cref="Apply{U}(Func{T, Output{U}})"/> for more details.
/// </summary>
public Output<U> Apply<U>(Func<T, Input<U>?> func)
=> Apply(t => func(t).ToOutput());
/// <summary>
/// Transforms the data of this <see cref="Output{T}"/> with the provided <paramref
/// name="func"/>. The result remains an <see cref="Output{T}"/> so that dependent resources
/// can be properly tracked.
/// <para/>
/// <paramref name="func"/> is not allowed to make resources.
/// <para/>
/// <paramref name="func"/> can return other <see cref="Output{T}"/>s. This can be handy if
/// you have an <c>Output<SomeType></c> and you want to get a transitive dependency of
/// it. i.e.:
///
/// <code>
/// Output<SomeType> d1 = ...;
/// Output<OtherType> d2 = d1.Apply(v => v.OtherOutput); // getting an output off of 'v'.
/// </code>
///
/// In this example, taking a dependency on d2 means a resource will depend on all the resources
/// of d1. It will <b>not</b> depend on the resources of v.x.y.OtherDep.
/// <para/>
/// Importantly, the Resources that d2 feels like it will depend on are the same resources
/// as d1. If you need have multiple <see cref="Output{T}"/>s and a single <see
/// cref="Output{T}"/> is needed that combines both set of resources, then <see
/// cref="Output.All{T}(Input{T}[])"/> or <see cref="Output.Tuple{X, Y, Z}(Input{X}, Input{Y}, Input{Z})"/>
/// should be used instead.
/// <para/>
/// This function will only be called execution of a <c>pulumi up</c> request. It will not
/// run during <c>pulumi preview</c> (as the values of resources are of course not known
/// then).
/// </summary>
public Output<U> Apply<U>(Func<T, Output<U>?> func)
=> new Output<U>(ApplyHelperAsync(DataTask, func));
private static async Task<OutputData<U>> ApplyHelperAsync<U>(
Task<OutputData<T>> dataTask, Func<T, Output<U>?> func)
{
var data = await dataTask.ConfigureAwait(false);
var resources = data.Resources;
// During previews only perform the apply if the engine was able to
// give us an actual value for this Output.
if (!data.IsKnown && Deployment.Instance.IsDryRun)
{
return new OutputData<U>(resources, default!, isKnown: false, data.IsSecret);
}
var inner = func(data.Value);
if (inner == null)
{
return OutputData.Create(resources, default(U)!, data.IsKnown, data.IsSecret);
}
var innerData = await inner.DataTask.ConfigureAwait(false);
return OutputData.Create(
data.Resources.Union(innerData.Resources), innerData.Value,
data.IsKnown && innerData.IsKnown, data.IsSecret || innerData.IsSecret);
}
internal static Output<ImmutableArray<T>> All(ImmutableArray<Input<T>> inputs)
=> new Output<ImmutableArray<T>>(AllHelperAsync(inputs));
private static async Task<OutputData<ImmutableArray<T>>> AllHelperAsync(ImmutableArray<Input<T>> inputs)
{
var resources = ImmutableHashSet.CreateBuilder<Resource>();
var values = ImmutableArray.CreateBuilder<T>(inputs.Length);
var isKnown = true;
var isSecret = false;
foreach (var input in inputs)
{
var output = (Output<T>)input;
var data = await output.DataTask.ConfigureAwait(false);
values.Add(data.Value);
resources.UnionWith(data.Resources);
(isKnown, isSecret) = OutputData.Combine(data, isKnown, isSecret);
}
return OutputData.Create(resources.ToImmutable(), values.MoveToImmutable(), isKnown, isSecret);
}
internal static Output<(T1, T2, T3, T4, T5, T6, T7, T8)> Tuple<T1, T2, T3, T4, T5, T6, T7, T8>(
Input<T1> item1, Input<T2> item2, Input<T3> item3, Input<T4> item4,
Input<T5> item5, Input<T6> item6, Input<T7> item7, Input<T8> item8)
=> new Output<(T1, T2, T3, T4, T5, T6, T7, T8)>(
TupleHelperAsync(item1, item2, item3, item4, item5, item6, item7, item8));
private static async Task<OutputData<(T1, T2, T3, T4, T5, T6, T7, T8)>> TupleHelperAsync<T1, T2, T3, T4, T5, T6, T7, T8>(
Input<T1> item1, Input<T2> item2, Input<T3> item3, Input<T4> item4,
Input<T5> item5, Input<T6> item6, Input<T7> item7, Input<T8> item8)
{
var resources = ImmutableHashSet.CreateBuilder<Resource>();
(T1, T2, T3, T4, T5, T6, T7, T8) tuple = default;
var isKnown = true;
var isSecret = false;
Update(await GetData(item1).ConfigureAwait(false), ref tuple.Item1);
Update(await GetData(item2).ConfigureAwait(false), ref tuple.Item2);
Update(await GetData(item3).ConfigureAwait(false), ref tuple.Item3);
Update(await GetData(item4).ConfigureAwait(false), ref tuple.Item4);
Update(await GetData(item5).ConfigureAwait(false), ref tuple.Item5);
Update(await GetData(item6).ConfigureAwait(false), ref tuple.Item6);
Update(await GetData(item7).ConfigureAwait(false), ref tuple.Item7);
Update(await GetData(item8).ConfigureAwait(false), ref tuple.Item8);
return OutputData.Create(resources.ToImmutable(), tuple, isKnown, isSecret);
static async Task<OutputData<X>> GetData<X>(Input<X> input)
{
var output = (Output<X>)input;
return await output.DataTask.ConfigureAwait(false);
}
void Update<X>(OutputData<X> data, ref X location)
{
resources.UnionWith(data.Resources);
location = data.Value;
(isKnown, isSecret) = OutputData.Combine(data, isKnown, isSecret);
}
}
}
}
| 44.93865 | 129 | 0.587986 | [
"Apache-2.0"
] | ankitdobhal/pulumi | sdk/dotnet/Pulumi/Core/Output.cs | 14,650 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the datapipeline-2012-10-29.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Amazon.DataPipeline.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.DataPipeline.Model.Internal.MarshallTransformations
{
/// <summary>
/// RemoveTags Request Marshaller
/// </summary>
public class RemoveTagsRequestMarshaller : IMarshaller<IRequest, RemoveTagsRequest> , IMarshaller<IRequest,AmazonWebServiceRequest>
{
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public IRequest Marshall(AmazonWebServiceRequest input)
{
return this.Marshall((RemoveTagsRequest)input);
}
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="publicRequest"></param>
/// <returns></returns>
public IRequest Marshall(RemoveTagsRequest publicRequest)
{
IRequest request = new DefaultRequest(publicRequest, "Amazon.DataPipeline");
string target = "DataPipeline.RemoveTags";
request.Headers["X-Amz-Target"] = target;
request.Headers["Content-Type"] = "application/x-amz-json-1.1";
request.HttpMethod = "POST";
string uriResourcePath = "/";
request.ResourcePath = uriResourcePath;
using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture))
{
JsonWriter writer = new JsonWriter(stringWriter);
writer.WriteObjectStart();
var context = new JsonMarshallerContext(request, writer);
if(publicRequest.IsSetPipelineId())
{
context.Writer.WritePropertyName("pipelineId");
context.Writer.Write(publicRequest.PipelineId);
}
if(publicRequest.IsSetTagKeys())
{
context.Writer.WritePropertyName("tagKeys");
context.Writer.WriteArrayStart();
foreach(var publicRequestTagKeysListValue in publicRequest.TagKeys)
{
context.Writer.Write(publicRequestTagKeysListValue);
}
context.Writer.WriteArrayEnd();
}
writer.WriteObjectEnd();
string snippet = stringWriter.ToString();
request.Content = System.Text.Encoding.UTF8.GetBytes(snippet);
}
return request;
}
private static RemoveTagsRequestMarshaller _instance = new RemoveTagsRequestMarshaller();
internal static RemoveTagsRequestMarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static RemoveTagsRequestMarshaller Instance
{
get
{
return _instance;
}
}
}
} | 35.156522 | 135 | 0.61118 | [
"Apache-2.0"
] | DalavanCloud/aws-sdk-net | sdk/src/Services/DataPipeline/Generated/Model/Internal/MarshallTransformations/RemoveTagsRequestMarshaller.cs | 4,043 | C# |
// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Windows.Forms;
using ICSharpCode.Core;
using ICSharpCode.NRefactory.Ast;
using ICSharpCode.NRefactory.PrettyPrinter;
using ICSharpCode.SharpDevelop.Refactoring;
namespace SharpRefactoring.Forms
{
/// <summary>
/// Description of ExtractMethodForm.
/// </summary>
public partial class ExtractMethodForm : Form
{
Func<IOutputAstVisitor> generator;
MethodDeclaration declaration;
BlockStatement body;
bool cancelUnload = false;
public ExtractMethodForm(MethodDeclaration declaration, Func<IOutputAstVisitor> generator)
{
//
// The InitializeComponent() call is required for Windows Forms designer support.
//
InitializeComponent();
SetTranslation(this);
this.declaration = declaration;
this.generator = generator;
IOutputAstVisitor visitor = this.generator.Invoke();
body = declaration.Body;
declaration.Body = new BlockStatement();
declaration.AcceptVisitor(visitor, null);
this.txtName.Text = this.declaration.Name;
this.txtPreview.Text = visitor.Text;
this.txtName.SelectAll();
}
void SetTranslation(Control c)
{
c.Text = StringParser.Parse(c.Text);
foreach (Control ctrl in c.Controls)
SetTranslation(ctrl);
}
void btnOKClick(object sender, EventArgs e)
{
if (FindReferencesAndRenameHelper.CheckName(this.txtName.Text, string.Empty)) {
this.Text = this.txtName.Text;
this.DialogResult = DialogResult.OK;
this.declaration.Body = body;
cancelUnload = false;
} else
cancelUnload = true;
}
void btnCancelClick(object sender, EventArgs e)
{
this.DialogResult = DialogResult.Cancel;
}
void txtNameTextChanged(object sender, EventArgs e)
{
declaration.Name = this.txtName.Text;
IOutputAstVisitor visitor = this.generator.Invoke();
declaration.AcceptVisitor(visitor, null);
this.txtPreview.Text = visitor.Text;
}
void ExtractMethodFormFormClosing(object sender, FormClosingEventArgs e)
{
e.Cancel = cancelUnload;
}
}
}
| 32.204082 | 93 | 0.743346 | [
"MIT"
] | galich/SharpDevelop | src/AddIns/Misc/SharpRefactoring/Project/Src/Forms/ExtractMethodForm.cs | 3,158 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CPP
{
class Program
{
static void Main(string[] args)
{
}
}
}
| 14.125 | 39 | 0.632743 | [
"MIT"
] | dragobaltov/Programming-Basics-And-Fundamentals | CPP/CPP/Program.cs | 228 | C# |
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata.Conventions;
using Microsoft.EntityFrameworkCore.Metadata.Conventions.Infrastructure;
using Microsoft.Extensions.DependencyInjection;
namespace System.Data.SQLiteEFCore
{
/// <summary>
/// <para>
/// A builder for building conventions for SQLite.
/// </para>
/// <para>
/// The service lifetime is <see cref="ServiceLifetime.Scoped" /> and multiple registrations
/// are allowed. This means that each <see cref="DbContext" /> instance will use its own
/// set of instances of this service.
/// The implementations may depend on other services registered with any lifetime.
/// The implementations do not need to be thread-safe.
/// </para>
/// </summary>
public class SqliteConventionSetBuilder : RelationalConventionSetBuilder
{
/// <summary>
/// Creates a new <see cref="SqliteConventionSetBuilder" /> instance.
/// </summary>
/// <param name="dependencies"> The core dependencies for this service. </param>
/// <param name="relationalDependencies"> The relational dependencies for this service. </param>
public SqliteConventionSetBuilder(
[NotNull] ProviderConventionSetBuilderDependencies dependencies,
[NotNull] RelationalConventionSetBuilderDependencies relationalDependencies)
: base(dependencies, relationalDependencies)
{
}
/// <summary>
/// <para>
/// Call this method to build a <see cref="ConventionSet" /> for SQLite when using
/// the <see cref="ModelBuilder" /> outside of <see cref="DbContext.OnModelCreating" />.
/// </para>
/// <para>
/// Note that it is unusual to use this method.
/// Consider using <see cref="DbContext" /> in the normal way instead.
/// </para>
/// </summary>
/// <returns> The convention set. </returns>
public static ConventionSet Build()
{
using var serviceScope = CreateServiceScope();
using var context = serviceScope.ServiceProvider.GetService<DbContext>();
return ConventionSet.CreateConventionSet(context);
}
/// <summary>
/// <para>
/// Call this method to build a <see cref="ModelBuilder" /> for SQLite outside of <see cref="DbContext.OnModelCreating" />.
/// </para>
/// <para>
/// Note that it is unusual to use this method.
/// Consider using <see cref="DbContext" /> in the normal way instead.
/// </para>
/// </summary>
/// <returns> The convention set. </returns>
public static ModelBuilder CreateModelBuilder()
{
using var serviceScope = CreateServiceScope();
using var context = serviceScope.ServiceProvider.GetService<DbContext>();
return new ModelBuilder(ConventionSet.CreateConventionSet(context), context.GetService<ModelDependencies>());
}
private static IServiceScope CreateServiceScope()
{
var serviceProvider = new ServiceCollection()
.AddEntityFrameworkSqlite()
.AddDbContext<DbContext>(
(p, o) =>
o.UseSqlite("Filename=_.db")
.UseInternalServiceProvider(p))
.BuildServiceProvider();
return serviceProvider.GetRequiredService<IServiceScopeFactory>().CreateScope();
}
}
}
| 45.144578 | 139 | 0.601815 | [
"MIT"
] | erikzhouxin/NSqliteCipher | src/Entity/SqliteConventionSetBuilder.cs | 3,747 | C# |
/*
* Copyright (c) 2018 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
namespace TencentCloud.Ms.V20180408.Models
{
using Newtonsoft.Json;
using System.Collections.Generic;
using TencentCloud.Common;
public class BindInfo : AbstractModel
{
/// <summary>
/// app的icon的url
/// </summary>
[JsonProperty("AppIconUrl")]
public string AppIconUrl{ get; set; }
/// <summary>
/// app的名称
/// </summary>
[JsonProperty("AppName")]
public string AppName{ get; set; }
/// <summary>
/// app的包名
/// </summary>
[JsonProperty("AppPkgName")]
public string AppPkgName{ get; set; }
/// <summary>
/// For internal usage only. DO NOT USE IT.
/// </summary>
internal override void ToMap(Dictionary<string, string> map, string prefix)
{
this.SetParamSimple(map, prefix + "AppIconUrl", this.AppIconUrl);
this.SetParamSimple(map, prefix + "AppName", this.AppName);
this.SetParamSimple(map, prefix + "AppPkgName", this.AppPkgName);
}
}
}
| 29.844828 | 83 | 0.623339 | [
"Apache-2.0"
] | ImEdisonJiang/tencentcloud-sdk-dotnet | TencentCloud/Ms/V20180408/Models/BindInfo.cs | 1,747 | C# |
using CodeGen.Web.Models;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
namespace CodeGen.Web.Utility
{
public class RepoAdoNetGenerator
{
public static string SingleName(string tableName)
{
// if finish on ies replace with y
if (tableName.Substring(tableName.Length - 3) == "ies")
tableName = tableName.Substring(0, tableName.Length - 3) + "y";
else
// if finish on xes replace with es
if (tableName.Substring(tableName.Length - 3) == "xes" ||
tableName.Substring(tableName.Length - 3) == "oes" ||
tableName.Substring(tableName.Length - 3) == "ses"
)
tableName = tableName.Substring(0, tableName.Length - 2);
else
// if finish on 's' replace it
if (tableName.Substring(tableName.Length - 1) == "s" &&
tableName.Substring(tableName.Length - 2) != "is")
tableName = tableName.Substring(0, tableName.Length - 1);
return tableName;
}
}
}
| 32.611111 | 79 | 0.565588 | [
"MIT"
] | VladoJuric/CodeGen.Net.Ang2 | CodeGen.Web/Utility/RepoAdoNetGenerator.cs | 1,176 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Serilog;
using Serilog.Events;
namespace Events.API
{
public class Program
{
public static int Main(string[] args)
{
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Override("Microsoft", LogEventLevel.Information)
.Enrich.FromLogContext()
.WriteTo.Console()
.CreateLogger();
try
{
Log.Information("Starting web host");
CreateHostBuilder(args).Build().Run();
return 0;
}
catch (Exception ex)
{
Log.Fatal(ex, "Host terminated unexpectedly");
return 1;
}
finally
{
Log.CloseAndFlush();
}
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseSerilog((context, services, configuration) =>
{
configuration.ReadFrom.Configuration(context.Configuration)
.ReadFrom.Services(services)
.Enrich.FromLogContext()
.WriteTo.Console()
.WriteTo.File("log.txt");
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
| 30.103448 | 79 | 0.510882 | [
"MIT"
] | Streaming-Cuba/events-backend | Events.API/Program.cs | 1,746 | C# |
// Copyright 2007-2016 Chris Patterson, Dru Sellers, Travis Smith, et. al.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
namespace MassTransit.Saga
{
using System.Threading.Tasks;
using GreenPipes;
/// <summary>
/// A saga repository is used by the service bus to dispatch messages to sagas
/// </summary>
/// <typeparam name="TSaga"></typeparam>
public interface ISagaRepository<TSaga> :
IProbeSite
where TSaga : class, ISaga
{
/// <summary>
/// Send the message to the saga repository where the context.CorrelationId has the CorrelationId
/// of the saga instance.
/// </summary>
/// <typeparam name="T">The message type</typeparam>
/// <param name="context">The message consume context</param>
/// <param name="policy">The saga policy for the message</param>
/// <param name="next">The saga consume pipe</param>
/// <returns></returns>
Task Send<T>(ConsumeContext<T> context, ISagaPolicy<TSaga, T> policy, IPipe<SagaConsumeContext<TSaga, T>> next)
where T : class;
/// <summary>
/// Send the message to the saga repository where the query is used to find matching saga instances,
/// which are invoked concurrently.
/// </summary>
/// <typeparam name="T">The message type</typeparam>
/// <param name="context">The saga query consume context</param>
/// <param name="policy">The saga policy for the message</param>
/// <param name="next">The saga consume pipe</param>
/// <returns></returns>
Task SendQuery<T>(SagaQueryConsumeContext<TSaga, T> context, ISagaPolicy<TSaga, T> policy, IPipe<SagaConsumeContext<TSaga, T>> next)
where T : class;
}
} | 46.156863 | 141 | 0.640187 | [
"ECL-2.0",
"Apache-2.0"
] | AOrlov/MassTransit | src/MassTransit/Saga/ISagaRepository.cs | 2,354 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNative.Network.V20170301.Outputs
{
/// <summary>
/// Authentication certificates of an application gateway.
/// </summary>
[OutputType]
public sealed class ApplicationGatewayAuthenticationCertificateResponse
{
/// <summary>
/// Certificate public data.
/// </summary>
public readonly string? Data;
/// <summary>
/// A unique read-only string that changes whenever the resource is updated.
/// </summary>
public readonly string? Etag;
/// <summary>
/// Resource ID.
/// </summary>
public readonly string? Id;
/// <summary>
/// Name of the resource that is unique within a resource group. This name can be used to access the resource.
/// </summary>
public readonly string? Name;
/// <summary>
/// Provisioning state of the authentication certificate resource. Possible values are: 'Updating', 'Deleting', and 'Failed'.
/// </summary>
public readonly string? ProvisioningState;
[OutputConstructor]
private ApplicationGatewayAuthenticationCertificateResponse(
string? data,
string? etag,
string? id,
string? name,
string? provisioningState)
{
Data = data;
Etag = etag;
Id = id;
Name = name;
ProvisioningState = provisioningState;
}
}
}
| 30 | 133 | 0.603333 | [
"Apache-2.0"
] | polivbr/pulumi-azure-native | sdk/dotnet/Network/V20170301/Outputs/ApplicationGatewayAuthenticationCertificateResponse.cs | 1,800 | C# |
using System.IO;
using CP77.CR2W.Reflection;
using FastMember;
using static CP77.CR2W.Types.Enums;
namespace CP77.CR2W.Types
{
[REDMeta]
public class rendRenderMultilayerMaskBlobHeader : CVariable
{
[Ordinal(0)] [RED("atlasHeight")] public CUInt32 AtlasHeight { get; set; }
[Ordinal(1)] [RED("atlasWidth")] public CUInt32 AtlasWidth { get; set; }
[Ordinal(2)] [RED("flags")] public CUInt32 Flags { get; set; }
[Ordinal(3)] [RED("maskHeight")] public CUInt32 MaskHeight { get; set; }
[Ordinal(4)] [RED("maskHeightLow")] public CUInt32 MaskHeightLow { get; set; }
[Ordinal(5)] [RED("maskTileSize")] public CUInt32 MaskTileSize { get; set; }
[Ordinal(6)] [RED("maskWidth")] public CUInt32 MaskWidth { get; set; }
[Ordinal(7)] [RED("maskWidthLow")] public CUInt32 MaskWidthLow { get; set; }
[Ordinal(8)] [RED("numLayers")] public CUInt32 NumLayers { get; set; }
[Ordinal(9)] [RED("version")] public CUInt32 Version { get; set; }
public rendRenderMultilayerMaskBlobHeader(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name) { }
}
}
| 44.4 | 121 | 0.679279 | [
"MIT"
] | Eingin/CP77Tools | CP77.CR2W/Types/cp77/rendRenderMultilayerMaskBlobHeader.cs | 1,086 | C# |
// -------------------------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// -------------------------------------------------------------------------------------------------
using System;
using System.Diagnostics;
using EnsureThat;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Primitives;
using Microsoft.Health.Core;
using Microsoft.Health.Fhir.Core.Features.Context;
using Microsoft.Health.Fhir.Core.Features.Operations;
using Microsoft.Health.Fhir.Core.Features.Operations.Reindex;
using Microsoft.Health.Fhir.Core.Features.Operations.Reindex.Models;
using Microsoft.Health.Fhir.CosmosDb.Features.Storage;
namespace Microsoft.Health.Fhir.CosmosDb.Features.Operations.Reindex
{
public class ReindexJobCosmosThrottleController : IReindexJobThrottleController
{
private int? _provisionedRUThroughput;
private DateTimeOffset? _intervalStart = null;
private double _rUsConsumedDuringInterval = 0.0;
private ushort _delayFactor = 0;
private double? _targetRUs = null;
private uint _targetBatchSize = 100;
private uint _jobConfiguredBatchSize = 100;
private bool _initialized = false;
private readonly IFhirRequestContextAccessor _fhirRequestContextAccessor;
private readonly ILogger<ReindexJobCosmosThrottleController> _logger;
public ReindexJobCosmosThrottleController(
IFhirRequestContextAccessor fhirRequestContextAccessor,
ILogger<ReindexJobCosmosThrottleController> logger)
{
EnsureArg.IsNotNull(fhirRequestContextAccessor, nameof(fhirRequestContextAccessor));
EnsureArg.IsNotNull(logger, nameof(logger));
_fhirRequestContextAccessor = fhirRequestContextAccessor;
_logger = logger;
}
public ReindexJobRecord ReindexJobRecord { get; set; } = null;
public void Initialize(ReindexJobRecord reindexJobRecord, int? provisionedDatastoreCapacity)
{
EnsureArg.IsNotNull(reindexJobRecord, nameof(reindexJobRecord));
ReindexJobRecord = reindexJobRecord;
_provisionedRUThroughput = provisionedDatastoreCapacity;
_jobConfiguredBatchSize = reindexJobRecord.MaximumNumberOfResourcesPerQuery;
if (ReindexJobRecord.TargetDataStoreUsagePercentage.HasValue
&& ReindexJobRecord.TargetDataStoreUsagePercentage.Value > 0
&& _provisionedRUThroughput.HasValue
&& _provisionedRUThroughput > 0)
{
_targetRUs = _provisionedRUThroughput.Value * (ReindexJobRecord.TargetDataStoreUsagePercentage.Value / 100.0);
_logger.LogInformation($"Reindex throttling initialized, target RUs: {_targetRUs}");
_delayFactor = 0;
_rUsConsumedDuringInterval = 0.0;
_initialized = true;
_targetBatchSize = reindexJobRecord.MaximumNumberOfResourcesPerQuery;
}
}
public int GetThrottleBasedDelay()
{
if (!_initialized)
{
// not initialized
return 0;
}
return ReindexJobRecord.QueryDelayIntervalInMilliseconds * _delayFactor;
}
public uint GetThrottleBatchSize()
{
if (!_initialized)
{
// not initialized
return _jobConfiguredBatchSize;
}
return _targetBatchSize;
}
/// <summary>
/// Captures the currently recorded database consumption
/// </summary>
/// <returns>Returns an average database resource consumtion per second</returns>
public double UpdateDatastoreUsage()
{
double averageRUsConsumed = 0.0;
if (_initialized)
{
var requestContext = _fhirRequestContextAccessor.FhirRequestContext;
Debug.Assert(
requestContext.Method.Equals(OperationsConstants.Reindex, StringComparison.OrdinalIgnoreCase),
"We should not be here with FhirRequestContext that is not reindex!");
if (!_intervalStart.HasValue)
{
_intervalStart = Clock.UtcNow;
}
double responseRequestCharge = 0.0;
if (requestContext.ResponseHeaders.TryGetValue(CosmosDbHeaders.RequestCharge, out StringValues existingHeaderValue))
{
if (double.TryParse(existingHeaderValue.ToString(), out double headerRequestCharge))
{
responseRequestCharge += headerRequestCharge;
}
}
if (responseRequestCharge > _targetRUs)
{
double batchPercent = _targetRUs.Value / responseRequestCharge;
_targetBatchSize = (uint)(_targetBatchSize * batchPercent);
_targetBatchSize = _targetBatchSize >= 10 ? _targetBatchSize : 10;
_logger.LogInformation($"Reindex query for one batch was larger than target RUs, current query cost: {responseRequestCharge}. Reduced batch size to: {_targetBatchSize}");
}
else
{
_targetBatchSize = _jobConfiguredBatchSize;
}
_rUsConsumedDuringInterval += responseRequestCharge;
// calculate average RU consumption per second
averageRUsConsumed = _rUsConsumedDuringInterval / (Clock.UtcNow - _intervalStart).Value.TotalSeconds;
// we want to sum all the consumed RUs over a period of time
// that is about 5x the current delay between queries
// then we average that RU consumption per second
// and compare it against the target
if ((Clock.UtcNow - _intervalStart).Value.TotalMilliseconds >=
(5 * (ReindexJobRecord.QueryDelayIntervalInMilliseconds + GetThrottleBasedDelay())))
{
if (averageRUsConsumed > _targetRUs)
{
_delayFactor += 1;
_logger.LogInformation($"Reindex RU consumption high, delay factor increase to: {_delayFactor}");
}
else if (averageRUsConsumed < (_targetRUs * 0.75)
&& _delayFactor > 0)
{
_delayFactor -= 1;
}
_intervalStart = Clock.UtcNow;
_rUsConsumedDuringInterval = 0.0;
}
// clear out the value in the FhirRequestContext
requestContext.ResponseHeaders.Remove(CosmosDbHeaders.RequestCharge);
}
return averageRUsConsumed;
}
}
}
| 42.652695 | 191 | 0.598063 | [
"MIT"
] | cmelo05/fhir-server | src/Microsoft.Health.Fhir.CosmosDb/Features/Operations/Reindex/ReindexJobCosmosThrottleController.cs | 7,125 | C# |
/*
TShock, a server mod for Terraria
Copyright (C) 2011-2016 Nyx Studios (fka. The TShock Team)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using MySql.Data.MySqlClient;
namespace TShockAPI.DB
{
public class TileManager
{
private IDbConnection database;
public List<TileBan> TileBans = new List<TileBan>();
public TileManager(IDbConnection db)
{
database = db;
var table = new SqlTable("TileBans",
new SqlColumn("TileId", MySqlDbType.Int32) { Primary = true },
new SqlColumn("AllowedGroups", MySqlDbType.Text)
);
var creator = new SqlTableCreator(db,
db.GetSqlType() == SqlType.Sqlite
? (IQueryBuilder)new SqliteQueryCreator()
: new MysqlQueryCreator());
creator.EnsureTableStructure(table);
UpdateBans();
}
public void UpdateBans()
{
TileBans.Clear();
using (var reader = database.QueryReader("SELECT * FROM TileBans"))
{
while (reader != null && reader.Read())
{
TileBan ban = new TileBan((short)reader.Get<Int32>("TileId"));
ban.SetAllowedGroups(reader.Get<string>("AllowedGroups"));
TileBans.Add(ban);
}
}
}
public void AddNewBan(short id = 0)
{
try
{
database.Query("INSERT INTO TileBans (TileId, AllowedGroups) VALUES (@0, @1);",
id, "");
if (!TileIsBanned(id, null))
TileBans.Add(new TileBan(id));
}
catch (Exception ex)
{
TShock.Log.Error(ex.ToString());
}
}
public void RemoveBan(short id)
{
if (!TileIsBanned(id, null))
return;
try
{
database.Query("DELETE FROM TileBans WHERE TileId=@0;", id);
TileBans.Remove(new TileBan(id));
}
catch (Exception ex)
{
TShock.Log.Error(ex.ToString());
}
}
public bool TileIsBanned(short id)
{
if (TileBans.Contains(new TileBan(id)))
{
return true;
}
return false;
}
public bool TileIsBanned(short id, TSPlayer ply)
{
if (TileBans.Contains(new TileBan(id)))
{
TileBan b = GetBanById(id);
return !b.HasPermissionToPlaceTile(ply);
}
return false;
}
public bool AllowGroup(short id, string name)
{
string groupsNew = "";
TileBan b = GetBanById(id);
if (b != null)
{
try
{
groupsNew = String.Join(",", b.AllowedGroups);
if (groupsNew.Length > 0)
groupsNew += ",";
groupsNew += name;
b.SetAllowedGroups(groupsNew);
int q = database.Query("UPDATE TileBans SET AllowedGroups=@0 WHERE TileId=@1", groupsNew,
id);
return q > 0;
}
catch (Exception ex)
{
TShock.Log.Error(ex.ToString());
}
}
return false;
}
public bool RemoveGroup(short id, string group)
{
TileBan b = GetBanById(id);
if (b != null)
{
try
{
b.RemoveGroup(group);
string groups = string.Join(",", b.AllowedGroups);
int q = database.Query("UPDATE TileBans SET AllowedGroups=@0 WHERE TileId=@1", groups,
id);
if (q > 0)
return true;
}
catch (Exception ex)
{
TShock.Log.Error(ex.ToString());
}
}
return false;
}
public TileBan GetBanById(short id)
{
foreach (TileBan b in TileBans)
{
if (b.ID == id)
{
return b;
}
}
return null;
}
}
public class TileBan : IEquatable<TileBan>
{
public short ID { get; set; }
public List<string> AllowedGroups { get; set; }
public TileBan(short id)
: this()
{
ID = id;
AllowedGroups = new List<string>();
}
public TileBan()
{
ID = 0;
AllowedGroups = new List<string>();
}
public bool Equals(TileBan other)
{
return ID == other.ID;
}
public bool HasPermissionToPlaceTile(TSPlayer ply)
{
if (ply == null)
return false;
if (ply.HasPermission(Permissions.canusebannedtiles))
return true;
var cur = ply.Group;
var traversed = new List<Group>();
while (cur != null)
{
if (AllowedGroups.Contains(cur.Name))
{
return true;
}
if (traversed.Contains(cur))
{
throw new InvalidOperationException("Infinite group parenting ({0})".SFormat(cur.Name));
}
traversed.Add(cur);
cur = cur.Parent;
}
return false;
// could add in the other permissions in this class instead of a giant if switch.
}
public void SetAllowedGroups(String groups)
{
// prevent null pointer exceptions
if (!string.IsNullOrEmpty(groups))
{
List<String> groupArr = groups.Split(',').ToList();
for (int i = 0; i < groupArr.Count; i++)
{
groupArr[i] = groupArr[i].Trim();
//Console.WriteLine(groupArr[i]);
}
AllowedGroups = groupArr;
}
}
public bool RemoveGroup(string groupName)
{
return AllowedGroups.Remove(groupName);
}
public override string ToString()
{
return ID + (AllowedGroups.Count > 0 ? " (" + String.Join(",", AllowedGroups) + ")" : "");
}
}
} | 22.596838 | 95 | 0.608536 | [
"MIT"
] | BloodARG/tModLoaderTShock | TShock-general-devel/TShockAPI/DB/TileManager.cs | 5,467 | C# |
using System.Collections.Generic;
using System.Collections.ObjectModel;
namespace WebFrontEnd.Areas.HelpPage.ModelDescriptions
{
public class EnumTypeModelDescription : ModelDescription
{
public EnumTypeModelDescription()
{
Values = new Collection<EnumValueDescription>();
}
public Collection<EnumValueDescription> Values { get; private set; }
}
} | 27 | 76 | 0.708642 | [
"MIT"
] | ashkan-saeedi-mazdeh/GuessTheNumber-sample | WebFrontEnd/Areas/HelpPage/ModelDescriptions/EnumTypeModelDescription.cs | 405 | C# |
using MDPlayer.Properties;
namespace MDPlayer.form
{
partial class frmC352
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(frmC352));
this.pbScreen = new System.Windows.Forms.PictureBox();
((System.ComponentModel.ISupportInitialize)(this.pbScreen)).BeginInit();
this.SuspendLayout();
//
// pbScreen
//
this.pbScreen.Image = global::MDPlayer.Properties.Resources.planeC352;
this.pbScreen.Location = new System.Drawing.Point(0, 0);
this.pbScreen.Name = "pbScreen";
this.pbScreen.Size = new System.Drawing.Size(524, 264);
this.pbScreen.TabIndex = 1;
this.pbScreen.TabStop = false;
this.pbScreen.MouseClick += new System.Windows.Forms.MouseEventHandler(this.pbScreen_MouseClick);
//
// frmC352
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.SystemColors.ControlDarkDark;
this.ClientSize = new System.Drawing.Size(524, 264);
this.Controls.Add(this.pbScreen);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MaximizeBox = false;
this.Name = "frmC352";
this.Text = "C352";
this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.frmC352_FormClosed);
this.Load += new System.EventHandler(this.frmC352_Load);
this.Resize += new System.EventHandler(this.frmC352_Resize);
((System.ComponentModel.ISupportInitialize)(this.pbScreen)).EndInit();
this.ResumeLayout(false);
}
#endregion
public System.Windows.Forms.PictureBox pbScreen;
}
} | 40.513889 | 139 | 0.604731 | [
"MIT"
] | HoppingTappy/MDPlayer | MDPlayer/MDPlayer/form/KB/PCM/frmC352.Designer.cs | 2,919 | C# |
// <copyright file="FriendContext.cs" company="MUnique">
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
// </copyright>
namespace MUnique.OpenMU.Persistence.EntityFramework
{
using Microsoft.EntityFrameworkCore;
using MUnique.OpenMU.Persistence.EntityFramework.Model;
/// <summary>
/// Context to load instances of <see cref="Friend"/>s.
/// </summary>
public class FriendContext : DbContext
{
/// <summary>
/// Configures the model.
/// </summary>
/// <param name="modelBuilder">The model builder.</param>
internal static void ConfigureModel(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Friend>().ToTable("Friend", "friend");
modelBuilder.Entity<Friend>(e =>
{
e.HasAlternateKey(f => new { f.CharacterId, f.FriendId });
});
}
/// <inheritdoc/>
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
base.OnConfiguring(optionsBuilder);
this.Configure(optionsBuilder);
}
/// <inheritdoc/>
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
ConfigureModel(modelBuilder);
modelBuilder.Entity<CharacterName>().HasKey(f => f.Id);
}
}
}
| 32.604651 | 101 | 0.614123 | [
"MIT"
] | RuriRyan/OpenMU | src/Persistence/EntityFramework/FriendContext.cs | 1,404 | C# |
using System.IO;
namespace TURAG.Feldbus.Types
{
/// <summary>
/// Models the data part of a packet sent from device to host, excluding
/// address and checksum, which are removed from the raw data beforehand.
/// Received data can be accessed using the various Read- functions of the
/// BinaryReader base class.
/// </summary>
public class BusResponse : BinaryReader
{
/// <summary>
/// Creates a new instance.
/// </summary>
/// <param name="size">Initial capacitance for the underlying MemoryStream object.</param>
public BusResponse(int size = 0) : base(new MemoryStream(size))
{
}
internal long Capacity { get => ((MemoryStream)BaseStream).Capacity; }
internal void Fill(byte[] data)
{
((MemoryStream)BaseStream).Write(data, 0, data.Length);
((MemoryStream)BaseStream).Seek(0, SeekOrigin.Begin);
}
}
}
| 31.032258 | 98 | 0.613306 | [
"Apache-2.0"
] | turag-ev/TURAG-Feldbus-csharp | TURAG.Feldbus-csharp/Types/BusResponse.cs | 964 | C# |
namespace BulletMLLib
{
public class TimesNode : BulletMLNode
{
public TimesNode() : base(ENodeName.times)
{
}
}
}
| 11.363636 | 44 | 0.68 | [
"MIT"
] | Formedras/BulletMLLib_dmanning | BulletMLLib/BulletMLLib.SharedProject/Nodes/TimesNode.cs | 125 | C# |
using Grpc.Core;
using Microsoft.Extensions.Logging;
using System.Threading.Tasks;
namespace Spear.Tests.Grpc
{
public class GreeterService : Greeter.GreeterBase
{
private readonly ILogger<GreeterService> _logger;
public GreeterService(ILogger<GreeterService> logger)
{
_logger = logger;
}
public override Task<HelloReply> SayHello(HelloRequest request, ServerCallContext context)
{
return Task.FromResult(new HelloReply
{
Message = "Hello " + request.Name
});
}
}
}
| 25.041667 | 98 | 0.620632 | [
"Apache-2.0"
] | clever903/spear | test/Spear.Tests.Grpc/Services/GreeterService.cs | 601 | C# |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// File System.Configuration.ExeConfigurationFileMap.cs
// Automatically generated contract file.
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;
// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108
namespace System.Configuration
{
sealed public partial class ExeConfigurationFileMap : ConfigurationFileMap
{
#region Methods and constructors
public override Object Clone ()
{
return default(Object);
}
public ExeConfigurationFileMap ()
{
}
#if NETFRAMEWORK_4_0
public ExeConfigurationFileMap (string machineConfigFileName)
{
}
#endif
#endregion
#region Properties and indexers
public string ExeConfigFilename
{
get
{
return default(string);
}
set
{
}
}
public string LocalUserConfigFilename
{
get
{
return default(string);
}
set
{
}
}
public string RoamingUserConfigFilename
{
get
{
return default(string);
}
set
{
}
}
#endregion
}
}
| 29.62766 | 463 | 0.715619 | [
"MIT"
] | Acidburn0zzz/CodeContracts | Microsoft.Research/Contracts/System.Configuration/System.Configuration.ExeConfigurationFileMap.cs | 2,785 | C# |
using ProjetoModeloDDD.Domain.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjetoModeloDDD.Domain.Interfaces
{
public interface IClienteRepository : IRepositoryBase<Cliente>
{
}
}
| 20.428571 | 66 | 0.79021 | [
"MIT"
] | rafaelraah/Projeto_ModeloDDD | ProjetoModeloDDD/ProjetoModeloDDD.Domain/Interfaces/IClienteRepository.cs | 288 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp.CodeRefactorings.LambdaSimplifier;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings.LambdaSimplifier
{
public class LambdaSimplifierTests : AbstractCSharpCodeActionTest
{
protected override object CreateCodeRefactoringProvider(Workspace workspace)
{
return new LambdaSimplifierCodeRefactoringProvider();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsLambdaSimplifier)]
public async Task TestFixAll1()
{
await TestAsync(
@"using System; class C { void Foo() { Bar(s [||]=> Quux(s)); } void Bar(Func<int,string> f); string Quux(int i); }",
@"using System; class C { void Foo() { Bar(Quux); } void Bar(Func<int,string> f); string Quux(int i); }",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsLambdaSimplifier)]
public async Task TestFixCoContravariance1()
{
await TestAsync(
@"using System; class C { void Foo() { Bar(s [||]=> Quux(s)); } void Bar(Func<object,string> f); string Quux(object o); }",
@"using System; class C { void Foo() { Bar(Quux); } void Bar(Func<object,string> f); string Quux(object o); }",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsLambdaSimplifier)]
public async Task TestFixCoContravariance2()
{
await TestAsync(
@"using System; class C { void Foo() { Bar(s [||]=> Quux(s)); } void Bar(Func<string, object> f); string Quux(object o); }",
@"using System; class C { void Foo() { Bar(Quux); } void Bar(Func<string, object> f); string Quux(object o); }",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsLambdaSimplifier)]
public async Task TestFixCoContravariance3()
{
await TestMissingAsync(
@"using System; class C { void Foo() { Bar(s [||]=> Quux(s)); } void Bar(Func<string, string> f); object Quux(object o); }");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsLambdaSimplifier)]
public async Task TestFixCoContravariance4()
{
await TestMissingAsync(
@"using System; class C { void Foo() { Bar(s [||]=> Quux(s)); } void Bar(Func<object, object> f); string Quux(string o); }");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsLambdaSimplifier)]
public async Task TestFixCoContravariance5()
{
await TestMissingAsync(
@"using System; class C { void Foo() { Bar(s [||]=> Quux(s)); } void Bar(Func<object, string> f); object Quux(string o); }");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsLambdaSimplifier)]
public async Task TestFixAll2()
{
await TestAsync(
@"using System; class C { void Foo() { Bar((s1, s2) [||]=> Quux(s1, s2)); } void Bar(Func<int,bool,string> f); string Quux(int i, bool b); }",
@"using System; class C { void Foo() { Bar(Quux); } void Bar(Func<int,bool,string> f); string Quux(int i, bool b); }",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsLambdaSimplifier)]
public async Task TestFixAll3()
{
await TestAsync(
@"using System; class C { void Foo() { Bar((s1, s2) [||]=> { return Quux(s1, s2); }); } void Bar(Func<int,bool,string> f); string Quux(int i, bool b); }",
@"using System; class C { void Foo() { Bar(Quux); } void Bar(Func<int,bool,string> f); string Quux(int i, bool b); }",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsLambdaSimplifier)]
public async Task TestFixAll4()
{
await TestAsync(
@"using System; class C { void Foo() { Bar((s1, s2) [||]=> { return this.Quux(s1, s2); }); } void Bar(Func<int,bool,string> f); string Quux(int i, bool b); }",
@"using System; class C { void Foo() { Bar(this.Quux); } void Bar(Func<int,bool,string> f); string Quux(int i, bool b); }",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsLambdaSimplifier)]
public async Task TestFixOneOrAll()
{
await TestAsync(
@"using System; class C { void Foo() { Bar(s [||]=> Quux(s)); Bar(s => Quux(s)); } void Bar(Func<int,string> f); string Quux(int i); }",
@"using System; class C { void Foo() { Bar(Quux); Bar(s => Quux(s)); } void Bar(Func<int,string> f); string Quux(int i); }",
index: 0);
await TestAsync(
@"using System; class C { void Foo() { Bar(s [||]=> Quux(s)); Bar(s => Quux(s)); } void Bar(Func<int,string> f); string Quux(int i); }",
@"using System; class C { void Foo() { Bar(Quux); Bar(Quux); } void Bar(Func<int,string> f); string Quux(int i); }",
index: 1);
}
[WorkItem(542562)]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsLambdaSimplifier)]
public async Task TestMissingOnAmbiguity1()
{
await TestMissingAsync(
@"
using System;
class A
{
static void Foo<T>(T x) where T : class { }
static void Bar(Action<int> x) { }
static void Bar(Action<string> x) { }
static void Main()
{
Bar(x => [||]Foo(x));
}
}");
}
[WorkItem(627092)]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsLambdaSimplifier)]
public async Task TestMissingOnLambdaWithDynamic_1()
{
await TestMissingAsync(
@"using System;
class Program
{
static void Main()
{
C<string>.InvokeFoo();
}
}
class C<T>
{
public static void InvokeFoo()
{
Action<dynamic, string> foo = (x, y) => [||]C<T>.Foo(x, y); // Simplify lambda expression
foo(1, "");
}
static void Foo(object x, object y)
{
Console.WriteLine(""Foo(object x, object y)"");
}
static void Foo(object x, T y)
{
Console.WriteLine(""Foo(object x, T y)"");
}
}");
}
[WorkItem(627092)]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsLambdaSimplifier)]
public async Task TestMissingOnLambdaWithDynamic_2()
{
await TestMissingAsync(
@"using System;
class Program
{
static void Main()
{
C<string>.InvokeFoo();
}
}
class Casd<T>
{
public static void InvokeFoo()
{
Action<dynamic> foo = x => [||]Casd<T>.Foo(x); // Simplify lambda expression
foo(1, "");
}
private static void Foo(dynamic x)
{
throw new NotImplementedException();
}
static void Foo(object x, object y)
{
Console.WriteLine(""Foo(object x, object y)"");
}
static void Foo(object x, T y)
{
Console.WriteLine(""Foo(object x, T y)"");
}
}");
}
[WorkItem(544625)]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsLambdaSimplifier)]
public async Task ParenthesizeIfParseChanges()
{
var code = @"
using System;
class C
{
static void M()
{
C x = new C();
int y = 1;
Bar(() [||]=> { return Console.ReadLine(); } < x, y > (1 + 2));
}
static void Bar(object a, object b) { }
public static bool operator <(Func<string> y, C x) { return true; }
public static bool operator >(Func<string> y, C x) { return true; }
}";
var expected = @"
using System;
class C
{
static void M()
{
C x = new C();
int y = 1;
Bar((Console.ReadLine) < x, y > (1 + 2));
}
static void Bar(object a, object b) { }
public static bool operator <(Func<string> y, C x) { return true; }
public static bool operator >(Func<string> y, C x) { return true; }
}";
await TestAsync(code, expected, compareTokens: false);
}
[WorkItem(545856)]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsLambdaSimplifier)]
public async Task TestWarningOnSideEffects()
{
await TestAsync(
@"using System ; class C { void Main ( ) { Func < string > a = ( ) [||]=> new C ( ) . ToString ( ) ; } } ",
@"using System ; class C { void Main ( ) { Func < string > a = {|Warning:new C ()|} . ToString ; } } ");
}
[WorkItem(545994)]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsLambdaSimplifier)]
public async Task TestNonReturnBlockSyntax()
{
await TestAsync(
@"using System ; class Program { static void Main ( ) { Action a = [||]( ) => { Console . WriteLine ( ) ; } ; } } ",
@"using System ; class Program { static void Main ( ) { Action a = Console . WriteLine ; } } ");
}
}
}
| 34.814672 | 160 | 0.584784 | [
"Apache-2.0"
] | TronsGuitar/roslyn | src/EditorFeatures/CSharpTest/CodeActions/LambdaSimplifier/LambdaSimplifierTests.cs | 9,017 | C# |
using System;
namespace Glued
{
public static partial class CaseExtensions
{
public static Action<Action<T>> Case<T>(this T t, Func<T, bool> guard, Action<T> action)
{
return next => { if (guard(t)) action(t); else next(t); };
}
public static Action<Action<T>> Case<T>(this Action<Action<T>> source, Func<T, bool> guard, Action<T> action)
{
return next => source(t => { if (guard(t)) action(t); else next(t); });
}
public static void Else<T>(this Action<Action<T>> source, Action<T> action)
{
source(action);
}
}
} | 28.954545 | 117 | 0.549451 | [
"MIT"
] | corker/Glued | src/Glued/CaseExtensions.Action.cs | 637 | C# |
using Avalonia;
using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Markup.Xaml;
using DS3BehaviorToolGUI.ViewModels;
using DS3BehaviorToolGUI.Views;
namespace DS3BehaviorToolGUI
{
public class App : Application
{
public override void Initialize()
{
AvaloniaXamlLoader.Load(this);
}
public override void OnFrameworkInitializationCompleted()
{
if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
{
desktop.MainWindow = new MainWindow
{
};
}
base.OnFrameworkInitializationCompleted();
}
}
}
| 23.896552 | 87 | 0.62482 | [
"MIT"
] | The12thAvenger/DS3BehaviorToolGUI | BindingCrashCourse/App.axaml.cs | 693 | C# |
namespace TarbikMap.Storage
{
using System;
using System.Collections.Generic;
using System.Linq;
internal class Game
{
public Game(DateTime validUntil, GameConfiguration configuration, IList<Player> players)
{
this.ValidUntil = validUntil;
this.Configuration = configuration;
this.Players = players;
}
public DateTime ValidUntil { get; private set; }
public GameConfiguration Configuration { get; private set; }
public string? CurrentConfigurationError { get; set; }
public IList<GameTask?>? Tasks { get; set; }
public IList<Player> Players { get; private set; }
public bool Starting { get; set; }
public bool Started { get; set; }
public string? NextGameId { get; set; }
public DateTime? CurrentTaskAnsweringStart { get; set; }
public DateTime? CurrentTaskCompletingStart { get; set; }
public string? LoadedTypeLabel { get; set; }
public string? LoadedAreaLabel { get; set; }
public int StateCounter { get; set; }
public int TasksCompleted
{
get
{
return this.Players.Count == 0 ? 0 : this.Players.Select(p => p.TasksCompleted).Min();
}
}
public int TasksAnswered
{
get
{
return this.Players.Count == 0 ? 0 : this.Players.Select(p => p.Answers.Count).Min();
}
}
}
}
| 25.813559 | 102 | 0.570584 | [
"MIT"
] | milan11/tarbikmap | TarbikMap/Storage/Game.cs | 1,523 | C# |
using Autofac;
using AutoMapper.Autofac.Shared.Entities;
using AutoMapper.Contrib.Autofac.DependencyInjection;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace AutoMapper.Autofac.WebApi
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers()
.AddNewtonsoftJson();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment()) app.UseDeveloperExceptionPage();
app.UseHttpsRedirection();
app.UseRouting();
app.UseEndpoints(endpoints => endpoints.MapControllers());
}
public void ConfigureContainer(ContainerBuilder builder)
{
builder.AddAutoMapper(typeof(Customer).Assembly);
}
}
} | 28.657143 | 80 | 0.656032 | [
"MIT"
] | Morreed/AutoMapper.Contrib.Autofac.DependencyInjection | samples/AutoMapper.Autofac.WebApi/Startup.cs | 1,003 | C# |
// Copyright (c) Six Labors.
// Licensed under the Apache License, Version 2.0.
using SixLabors.ImageSharp.Processing.Processors.Convolution;
namespace SixLabors.ImageSharp.Processing
{
/// <summary>
/// Defines Gaussian blurring extensions to apply on an <see cref="Image"/>
/// using Mutate/Clone.
/// </summary>
public static class GaussianBlurExtensions
{
/// <summary>
/// Applies a Gaussian blur to the image.
/// </summary>
/// <param name="source">The image this method extends.</param>
/// <returns>The <see cref="IImageProcessingContext"/> to allow chaining of operations.</returns>
public static IImageProcessingContext GaussianBlur(this IImageProcessingContext source)
=> source.ApplyProcessor(new GaussianBlurProcessor());
/// <summary>
/// Applies a Gaussian blur to the image.
/// </summary>
/// <param name="source">The image this method extends.</param>
/// <param name="sigma">The 'sigma' value representing the weight of the blur.</param>
/// <returns>The <see cref="IImageProcessingContext"/> to allow chaining of operations.</returns>
public static IImageProcessingContext GaussianBlur(this IImageProcessingContext source, float sigma)
=> source.ApplyProcessor(new GaussianBlurProcessor(sigma));
/// <summary>
/// Applies a Gaussian blur to the image.
/// </summary>
/// <param name="source">The image this method extends.</param>
/// <param name="sigma">The 'sigma' value representing the weight of the blur.</param>
/// <param name="rectangle">
/// The <see cref="Rectangle"/> structure that specifies the portion of the image object to alter.
/// </param>
/// <returns>The <see cref="IImageProcessingContext"/> to allow chaining of operations.</returns>
public static IImageProcessingContext GaussianBlur(this IImageProcessingContext source, float sigma, Rectangle rectangle)
=> source.ApplyProcessor(new GaussianBlurProcessor(sigma), rectangle);
/// <summary>
/// Applies a Gaussian blur to the image.
/// </summary>
/// <param name="source">The image this method extends.</param>
/// <param name="sigma">The 'sigma' value representing the weight of the blur.</param>
/// <param name="rectangle">
/// The <see cref="Rectangle"/> structure that specifies the portion of the image object to alter.
/// </param>
/// <param name="borderWrapModeX">
/// The <see cref="BorderWrappingMode"/> to use when mapping the pixels outside of the border, in X direction.
/// </param>
/// <param name="borderWrapModeY">
/// The <see cref="BorderWrappingMode"/> to use when mapping the pixels outside of the border, in Y direction.
/// </param>
/// <returns>The <see cref="IImageProcessingContext"/> to allow chaining of operations.</returns>
public static IImageProcessingContext GaussianBlur(this IImageProcessingContext source, float sigma, Rectangle rectangle, BorderWrappingMode borderWrapModeX, BorderWrappingMode borderWrapModeY)
{
var processor = new GaussianBlurProcessor(sigma, borderWrapModeX, borderWrapModeY);
return source.ApplyProcessor(processor, rectangle);
}
}
}
| 52.461538 | 201 | 0.659531 | [
"Apache-2.0"
] | AlexanderSemenyak/ImageSharp | src/ImageSharp/Processing/Extensions/Convolution/GaussianBlurExtensions.cs | 3,412 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
namespace DynamicBatteryStorage
{
/// <summary>
/// This Vessel Module calculates vessel energy production and consumption, and chooses a part to act as a 'battery buffer' at high time warp speeds
///
/// </summary>
public class VesselDataManager : VesselModule
{
#region Accessors
public VesselElectricalData ElectricalData { get { return electricalData; } }
public VesselThermalData HeatData { get { return heatData; } }
public bool Ready { get { return dataReady; } }
#endregion
#region PrivateVariables
bool dataReady = false;
bool vesselLoaded = false;
VesselElectricalData electricalData;
VesselThermalData heatData;
#endregion
protected override void OnStart()
{
base.OnStart();
// These events need to trigger a refresh
//GameEvents.onVesselDestroy.Add(new EventData<Vessel>.OnEvent(RefreshVesselData));
GameEvents.onVesselGoOnRails.Add(new EventData<Vessel>.OnEvent(RefreshVesselData));
GameEvents.onVesselWasModified.Add(new EventData<Vessel>.OnEvent(RefreshVesselData));
}
void OnDestroy()
{
// Clean up events when the item is destroyed
//GameEvents.onVesselDestroy.Remove(RefreshVesselData);
GameEvents.onVesselGoOnRails.Remove(RefreshVesselData);
GameEvents.onVesselWasModified.Remove(RefreshVesselData);
}
void FixedUpdate()
{
if (HighLogic.LoadedSceneIsFlight && !dataReady)
{
if (!vesselLoaded && FlightGlobals.ActiveVessel == vessel)
{
RefreshVesselData();
vesselLoaded = true;
}
if (vesselLoaded && FlightGlobals.ActiveVessel != vessel)
{
vesselLoaded = false;
}
}
}
/// <summary>
/// Referesh the data, given a Vessel event
/// </summary>
protected void RefreshVesselData(Vessel eventVessel)
{
if (Settings.DebugMode)
Utils.Log(String.Format("[{0}]: Refreshing VesselData from Vessel event", this.GetType().Name));
RefreshVesselData();
}
/// <summary>
/// Referesh the data, given a ConfigNode event
/// </summary>
protected void RefreshVesselData(ConfigNode node)
{
if (Settings.DebugMode)
Utils.Log(String.Format("[{0}]: Refreshing VesselData from save node event", this.GetType().Name));
RefreshVesselData();
}
/// <summary>
/// Referesh the data classes
/// </summary>
protected void RefreshVesselData()
{
if (vessel == null || vessel.Parts == null)
return;
electricalData = new VesselElectricalData(vessel.Parts);
heatData = new VesselThermalData(vessel.Parts);
dataReady = true;
if (Settings.DebugMode)
{
Utils.Log(String.Format("Dumping electrical database: \n{0}", electricalData.ToString()));
Utils.Log(String.Format("Dumping thermal database: \n{0}", heatData.ToString()));
}
}
}
}
| 27.321429 | 150 | 0.65817 | [
"MIT",
"Unlicense"
] | Grimmas/DynamicBatteryStorage | Source/DynamicBatteryStorage/Data/VesselDataManager.cs | 3,060 | C# |
using Autodesk.Navisworks.Api;
using Autodesk.Navisworks.Api.Clash;
using System;
using System.Collections.Generic;
using TUM.CMS.VplControl.Core;
namespace ENGyn.Nodes.Clash
{
public class CompactAllTests : Node
{
public CompactAllTests(VplControl hostCanvas)
: base(hostCanvas)
{
AddInputPortToNode("Any", typeof(object));
AddOutputPortToNode("ClashTests", typeof(object));
//Help
this.BottomComment.Text = "Compact all clashes, run it disconnected or put any input to order the execution after any other node";
this.ShowHelpOnMouseOver = true;
}
public override void Calculate()
{
var input = InputPorts[0].Data;
var RESULT = CompactAllClashTest(input);
OutputPorts[0].Data = RESULT;
}
public override Node Clone()
{
return new CompactAllTests(HostCanvas)
{
Top = Top,
Left = Left
};
}
public List<object> CompactAllClashTest(object input)
{
Document doc = Autodesk.Navisworks.Api.Application.ActiveDocument;
var clashes = doc.GetClash();
var output = new List<object>();
if (input != null)
{
clashes.TestsData.TestsCompactAllTests();
}
foreach (var item in clashes.TestsData.Tests)
{
output.Add(clashes.TestsData.CreateReference(item));
}
return output;
}
}
public class CompactTest : Node
{
public CompactTest(VplControl hostCanvas)
: base(hostCanvas)
{
AddInputPortToNode("ClashTest", typeof(object));
AddOutputPortToNode("ClashTests", typeof(object));
}
public override void Calculate()
{
var input = InputPorts[0].Data;
var RESULT = CompactClashTest(input);
OutputPorts[0].Data = RESULT;
}
/// <summary>
/// Compacts single Clashtest list of ClashesTest
/// </summary>
/// <param name="input"></param>
public IEnumerable<object> CompactClashes(object input)
{
var doc = Autodesk.Navisworks.Api.Application.ActiveDocument;
if (input != null)
{
var t = input.GetType();
if (t == typeof(SavedItemReference))
{
var ClashFromReference = doc.ResolveReference(input as SavedItemReference) as ClashTest;
var clashes = doc.GetClash();
clashes.TestsData.TestsCompactTest(ClashFromReference);
yield return input;
}
if (MainTools.IsList(input))
{
var listData = input as List<object>;
if (listData[0].GetType() == typeof(Autodesk.Navisworks.Api.Clash.ClashTest))
{
foreach (var ct in input as List<object>)
{
var ClashFromReference = doc.ResolveReference(ct as SavedItemReference) as ClashTest;
var clashes = doc.GetClash();
clashes.TestsData.TestsCompactTest(ClashFromReference);
yield return ct;
}
}
}
}
}
void wait(int x)
{
DateTime t = DateTime.Now;
DateTime tf = DateTime.Now.AddSeconds(x);
while (t < tf)
{
t = DateTime.Now;
}
}
public List<object> CompactClashTest(object input)
{
var output = new List<object>();
var doc = Autodesk.Navisworks.Api.Application.ActiveDocument;
if (input != null)
{
var t = input.GetType();
if (t == typeof(SavedItemReference))
{
var ClashFromReference = doc.ResolveReference(input as SavedItemReference) as ClashTest;
var clashes = doc.GetClash();
wait(1);
clashes.TestsData.TestsCompactTest(ClashFromReference);
output.Add(input);
}
if (MainTools.IsList(input))
{
var listData = input as List<object>;
if (listData[0].GetType() == typeof(SavedItemReference))
{
foreach (var ct in input as List<object>)
{
var ClashFromReference = doc.ResolveReference(ct as SavedItemReference) as ClashTest;
var clashes = doc.GetClash();
clashes.TestsData.TestsCompactTest(ClashFromReference);
wait(1);
output.Add(ct);
}
}
}
}
return output;
}
public override Node Clone()
{
return new CompactTest(HostCanvas)
{
Top = Top,
Left = Left
};
}
}
} | 28.150259 | 142 | 0.484263 | [
"MIT"
] | ENGworks-DEV/ENGyn | src/ENGyn-Nodes/Clash/CompactTest.cs | 5,435 | C# |
using UnityEngine;
//A giant enumerator that we'll be using for a bunch of direction values that we'll be using.
//We don't even use all of them a lot but even so it's useful to have solely for readability
public enum Direction {
North, East, South, West
}
public enum DirectionChange {
None, TurnRight, TurnLeft, TurnAround
}
public static class DirectionExtensions {
//A whole load of other value arrays that keep track of which way is where.
//These are sorted out in the "Get[Blank]" functions located below
//It uses the direction
static Quaternion[] rotations = {
Quaternion.identity,
Quaternion.Euler(0f, 90f, 0f),
Quaternion.Euler(0f, 180f, 0f),
Quaternion.Euler(0f, 270f, 0f)
};
static Vector3[] halfVectors = {
Vector3.forward * 0.5f,
Vector3.right * 0.5f,
Vector3.back * 0.5f,
Vector3.left * 0.5f
};
public static Quaternion GetRotation (this Direction direction) {
return rotations[(int)direction];
}
public static DirectionChange GetDirectionChangeTo (
this Direction current, Direction next
) {
if (current == next) {
return DirectionChange.None;
}
else if (current + 1 == next || current - 3 == next) {
return DirectionChange.TurnRight;
}
else if (current - 1 == next || current + 3 == next) {
return DirectionChange.TurnLeft;
}
return DirectionChange.TurnAround;
}
public static float GetAngle (this Direction direction) {
return (float)direction * 90f;
}
public static Vector3 GetHalfVector (this Direction direction) {
return halfVectors[(int)direction];
}
} | 27.928571 | 93 | 0.710997 | [
"MIT"
] | NodeReplacer/Tower-Defense-Game | Assets/Scripts/Direction.cs | 1,566 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
namespace Nanosoft
{
/**
* Класс управляющий окном списка квестов
*/
public class QuestWindow: WindowBehaviour
{
/**
* Ссылка на панель списока квестов
*/
public GameObject questList;
/**
* Ссылка на префаб элементов
*/
public GameObject questItemPrefab;
/**
* Ссылка на панельку с пояснением что квестов нет
*/
public GameObject noQuestInfo;
/**
* Ссылка на панельку с журналом квеста
*/
public GameObject questLog;
/**
* Ссылка на префаб элемента журнала квеста
*/
public GameObject questLogPrefab;
/**
* Ссылка на менеджер квестов
*/
protected QuestManager questManager;
/**
* Максимальное число квестов
*/
public int capacity = 10;
/**
* Актуальное число квестов в списке
*/
private int questCount = 0;
/**
* Ссылки на элементы
*/
private GameObject[] questItems;
/**
* Максимальное число записей в журнале квеста
*/
public int logCapacity = 10;
/**
* Актуальное число записей в журнале квеста
*/
private int logCount = 0;
/**
* Сслыка на элементы журнала квеста
*/
private GameObject[] logItems;
/**
* Инициализация
*/
public void Init(QuestManager qm)
{
questManager = qm;
InitQuestList();
InitQuestLog();
Refresh();
}
/**
* Инициализация списка квестов (элементов окна)
*/
protected void InitQuestList()
{
questCount = 0;
questItems = new GameObject[capacity];
Transform t = questList.transform;
for(int i = 0; i < capacity; i++)
{
GameObject obj = Instantiate(questItemPrefab, t);
obj.SetActive(false);
questItems[i] = obj;
}
}
/**
* Инициализация журнала квеста
*/
protected void InitQuestLog()
{
logCount = 0;
logItems = new GameObject[logCapacity];
Transform t = questLog.transform;
for(int i = 0; i < logCapacity; i++)
{
GameObject obj = Instantiate(questLogPrefab, t);
obj.SetActive(false);
logItems[i] = obj;
}
}
/**
* Обновить список квестов
*/
public void Refresh()
{
if ( questManager.GetActiveQuests() > 0 )
{
noQuestInfo.SetActive(false);
RefreshQuestList();
questList.SetActive(true);
}
else
{
questList.SetActive(false);
noQuestInfo.SetActive(true);
ClearQuestLog();
}
}
protected void RefreshQuestList()
{
int i = 0;
foreach(Quest quest in questManager.quests)
{
if ( i >= capacity ) break;
if ( quest == null || !quest.active ) continue;
var obj = questItems[i];
obj.transform.Find("Text").GetComponent<Text>().text = quest.questTitle;
var btnClick = obj.GetComponent<Button>().onClick;
btnClick.RemoveAllListeners();
btnClick.AddListener( quest.ShowQuestLog );
obj.SetActive(true);
i++;
}
for(int j = i; j < questCount; j++)
{
questItems[j].SetActive(false);
}
questCount = i;
if ( questCount > 0 )
{
// TODO something...
questItems[0].GetComponent<Button>().onClick.Invoke();
}
else
{
ClearQuestLog();
}
}
/**
* Отобразить журнал квеста
*
* Данная функция вызывается при нажатии соответствующей кнопки в журнале
* заданий
*/
public void ShowQuestLog(Quest quest)
{
int i = 0;
foreach(string msg in quest.questLog)
{
if ( i >= logCapacity || msg == null ) break;
var obj = logItems[i];
obj.GetComponent<Text>().text = msg;
obj.SetActive(true);
i++;
}
for(int j = i; j < logCount; j++)
{
logItems[j].SetActive(false);
}
logCount = i;
}
/**
* Очистить журнал квеста
*/
public void ClearQuestLog()
{
for(int j = 0; j < logCount; j++)
{
logItems[j].SetActive(false);
}
logCount = 0;
}
} // class QuestWindow
} // namespace Nanosoft
| 17.37037 | 75 | 0.642058 | [
"MIT"
] | zolotov-av/unity | Test Unity Project/Assets/Nanosets/Scripts/QuestWindow.cs | 4,350 | C# |
using System.Collections.Generic;
using System.Threading.Tasks;
using Gandalan.IDAS.Client.Contracts.Contracts;
using Gandalan.IDAS.WebApi.Client.Settings;
using Gandalan.IDAS.WebApi.DTO;
namespace Gandalan.IDAS.WebApi.Client.BusinessRoutinen
{
public class ContractWebRoutinen : WebRoutinenBase
{
public ContractWebRoutinen(IWebApiConfig settings) : base(settings)
{
}
public ContractDTO[] GetAll()
{
if (Login())
{
return Get<ContractDTO[]>("Contracts");
}
return null;
}
public ContractDTO SaveContract(ContractDTO dto)
{
if (Login())
{
return Put<ContractDTO>("Contracts", dto);
}
return null;
}
public string DeleteContract(ContractDTO dto)
{
if (Login())
{
return Delete<string>("Contracts/" + dto.ContractGuid);
}
return null;
}
public async Task<ContractDTO[]> GetAllAsync()
{
return await Task.Run(() => GetAll());
}
public async Task SaveContractAsync(ContractDTO dto)
{
await Task.Run(() => SaveContract(dto));
}
public async Task DeleteContractAsync(ContractDTO dto)
{
await Task.Run(() => DeleteContract(dto));
}
}
}
| 24.525424 | 75 | 0.539737 | [
"MIT"
] | Saibamen/idas-client-libs | Gandalan.IDAS.WebApi.Client/BusinessRoutinen/ContractWebRoutinen.cs | 1,449 | C# |
namespace UnionFind;
/// <summary>
/// 使用加权 quick-union 算法的并查集。
/// </summary>
public class WeightedQuickUnionUf : QuickUnionUf
{
/// <summary>
/// 记录各个树大小的数组。
/// </summary>
/// <value>记录各个树大小的数组。</value>
protected int[] Size;
/// <summary>
/// 记录 parent 数组的访问次数的计数器。
/// </summary>
/// <value>parent 数组的访问次数。</value>
public int ArrayParentVisitCount { get; private set; }
/// <summary>
/// 记录 size 数组的访问次数的计数器。
/// </summary>
/// <value>size 数组的访问次数。</value>
public int ArraySizeVisitCount { get; private set; }
/// <summary>
/// 建立使用加权 quick-union 的并查集。
/// </summary>
/// <param name="n">并查集的大小。</param>
public WeightedQuickUnionUf(int n) : base(n)
{
Size = new int[n];
for (var i = 0; i < n; i++)
{
Size[i] = 1;
}
ArrayParentVisitCount = 0;
ArraySizeVisitCount = 0;
}
/// <summary>
/// 清零数组访问计数。
/// </summary>
public override void ResetArrayCount()
{
ArrayParentVisitCount = 0;
ArraySizeVisitCount = 0;
}
/// <summary>
/// 获取 size 数组。
/// </summary>
/// <returns>返回 size 数组。</returns>
public int[] GetSize()
{
return Size;
}
/// <summary>
/// 寻找一个结点所在的连通分量。
/// </summary>
/// <param name="p">需要寻找的结点。</param>
/// <returns>该结点所属的连通分量。</returns>
public override int Find(int p)
{
Validate(p);
while (p != Parent[p])
{
p = Parent[p];
ArrayParentVisitCount += 2;
}
ArrayParentVisitCount++;
return p;
}
/// <summary>
/// 将两个结点所属的连通分量合并。
/// </summary>
/// <param name="p">需要合并的结点。</param>
/// <param name="q">需要合并的另一个结点。</param>
public override void Union(int p, int q)
{
var rootP = Find(p);
var rootQ = Find(q);
if (rootP == rootQ)
{
return;
}
if (Size[rootP] < Size[rootQ])
{
Parent[rootP] = rootQ;
Size[rootQ] += Size[rootP];
}
else
{
Parent[rootQ] = rootP;
Size[rootP] += Size[rootQ];
}
ArrayParentVisitCount++;
ArraySizeVisitCount += 4;
TotalCount--;
}
} | 22.359223 | 58 | 0.497178 | [
"MIT"
] | Higurashi-kagome/Algorithms-4th-Edition-in-Csharp | 1 Fundamental/1.5/UnionFind/WeightedQuickUnionUF.cs | 2,667 | C# |
// <auto-generated />
namespace RiskTracker.Migrations
{
using System.CodeDom.Compiler;
using System.Data.Entity.Migrations;
using System.Data.Entity.Migrations.Infrastructure;
using System.Resources;
[GeneratedCode("EntityFramework.Migrations", "6.1.1-30610")]
public sealed partial class addsuspendedflagtoorgs : IMigrationMetadata
{
private readonly ResourceManager Resources = new ResourceManager(typeof(addsuspendedflagtoorgs));
string IMigrationMetadata.Id
{
get { return "201510061332028_add-suspended-flag-to-orgs"; }
}
string IMigrationMetadata.Source
{
get { return null; }
}
string IMigrationMetadata.Target
{
get { return Resources.GetString("Target"); }
}
}
}
| 28.433333 | 105 | 0.631887 | [
"MIT"
] | Inside-Outcomes/Risk-Tracker | RiskMapsCore/Migrations/201510061332028_add-suspended-flag-to-orgs.Designer.cs | 853 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the ds-2015-04-16.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.DirectoryService.Model
{
/// <summary>
/// Contains information for the <a>ConnectDirectory</a> operation when an AD Connector
/// directory is being created.
/// </summary>
public partial class DirectoryConnectSettings
{
private List<string> _customerDnsIps = new List<string>();
private string _customerUserName;
private List<string> _subnetIds = new List<string>();
private string _vpcId;
/// <summary>
/// Gets and sets the property CustomerDnsIps.
/// <para>
/// A list of one or more IP addresses of DNS servers or domain controllers in the on-premises
/// directory.
/// </para>
/// </summary>
[AWSProperty(Required=true)]
public List<string> CustomerDnsIps
{
get { return this._customerDnsIps; }
set { this._customerDnsIps = value; }
}
// Check to see if CustomerDnsIps property is set
internal bool IsSetCustomerDnsIps()
{
return this._customerDnsIps != null && this._customerDnsIps.Count > 0;
}
/// <summary>
/// Gets and sets the property CustomerUserName.
/// <para>
/// The user name of an account in the on-premises directory that is used to connect to
/// the directory. This account must have the following permissions:
/// </para>
/// <ul> <li>
/// <para>
/// Read users and groups
/// </para>
/// </li> <li>
/// <para>
/// Create computer objects
/// </para>
/// </li> <li>
/// <para>
/// Join computers to the domain
/// </para>
/// </li> </ul>
/// </summary>
[AWSProperty(Required=true, Min=1)]
public string CustomerUserName
{
get { return this._customerUserName; }
set { this._customerUserName = value; }
}
// Check to see if CustomerUserName property is set
internal bool IsSetCustomerUserName()
{
return this._customerUserName != null;
}
/// <summary>
/// Gets and sets the property SubnetIds.
/// <para>
/// A list of subnet identifiers in the VPC in which the AD Connector is created.
/// </para>
/// </summary>
[AWSProperty(Required=true)]
public List<string> SubnetIds
{
get { return this._subnetIds; }
set { this._subnetIds = value; }
}
// Check to see if SubnetIds property is set
internal bool IsSetSubnetIds()
{
return this._subnetIds != null && this._subnetIds.Count > 0;
}
/// <summary>
/// Gets and sets the property VpcId.
/// <para>
/// The identifier of the VPC in which the AD Connector is created.
/// </para>
/// </summary>
[AWSProperty(Required=true)]
public string VpcId
{
get { return this._vpcId; }
set { this._vpcId = value; }
}
// Check to see if VpcId property is set
internal bool IsSetVpcId()
{
return this._vpcId != null;
}
}
} | 31.08209 | 102 | 0.577431 | [
"Apache-2.0"
] | ChristopherButtars/aws-sdk-net | sdk/src/Services/DirectoryService/Generated/Model/DirectoryConnectSettings.cs | 4,165 | C# |
using System;
using System.Drawing;
using System.Diagnostics;
using System.ComponentModel;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using UIKit;
using GLKit;
using Metal;
using MapKit;
using ModelIO;
using SceneKit;
using Security;
using AudioUnit;
using CoreVideo;
using CoreMedia;
using QuickLook;
using Foundation;
using CoreMotion;
using ObjCRuntime;
using AddressBook;
using CoreGraphics;
using CoreLocation;
using AVFoundation;
using NewsstandKit;
using CoreAnimation;
using CoreFoundation;
namespace BraintreeVenmo
{
[Preserve(AllMembers = true)]
public static class BraintreeVenmoLinker
{
/// <summary>
/// PayPalUtils and PayPalDataCollector are in use internally by BrainTreePayPal.
/// BUT from public APIs, Xamarin.iOS couldn't know that.
/// This code is to tell Xamarin.iOS that we need those both frameworks.
/// </summary>
public static void Init() {
new BTVenmoDriver();
new BraintreeCard.BTCard();
}
}
partial class BTVenmoDriver
{
internal BTVenmoDriver() {}
static BTVenmoDriver() {
global::ApiDefinition.Messaging.void_objc_msgSend(class_ptr, Selector.GetHandle("load"));
}
}
}
namespace ApiDefinition
{
partial class Messaging
{
[DllImport(LIBOBJC_DYLIB, EntryPoint = "objc_msgSend")]
public extern static void void_objc_msgSend(IntPtr receiver, IntPtr selector);
}
}
| 23.25 | 101 | 0.727823 | [
"MIT"
] | GravitonStudios/braintree-ios-binding | GravitonStudios.BraintreeVenmo.iOS/Extras.cs | 1,490 | C# |
using Microsoft.AspNetCore.Identity;
namespace MyShoppingStore.Models
{
public class AppUser: IdentityUser
{
public string Occupation { get; set; }
}
}
| 17.4 | 46 | 0.689655 | [
"MIT"
] | jdizon0721/ComITProjectPresentation | MyShoppingStoreApp/MyShoppingStore/Models/AppUser.cs | 176 | C# |
using System.IO;
using System.Reflection;
using System.Text;
namespace HotChocolate.Benchmark.Tests
{
public class ResourceHelper
{
private const string _resourcePath =
"HotChocolate.Benchmark.Tests.Resources";
private Assembly _assembly;
public ResourceHelper()
{
_assembly = GetType().Assembly;
}
public string GetResourceString(string fileName)
{
Stream stream = GetResourceStream(fileName);
if (stream != null)
{
using (var reader = new StreamReader(stream, Encoding.UTF8))
{
return reader.ReadToEnd();
}
}
throw new FileNotFoundException(
"Could not find the specified resource file",
fileName);
}
private Stream GetResourceStream(string fileName)
{
return _assembly.GetManifestResourceStream(
$"{_resourcePath}.{fileName}");
}
}
}
| 26.35 | 76 | 0.551233 | [
"MIT"
] | Dolfik1/hotchocolate | benchmarks/Benchmark.Tests/ResourceHelper.cs | 1,056 | C# |
using System.IO;
using System.Runtime.Serialization;
using GameEstate.Red.Formats.Red.CR2W.Reflection;
using FastMember;
using static GameEstate.Red.Formats.Red.Records.Enums;
namespace GameEstate.Red.Formats.Red.Types
{
[DataContract(Namespace = "")]
[REDMeta]
public class CJournalCreatureVitalSpotGroup : CJournalContainer
{
public CJournalCreatureVitalSpotGroup(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name){ }
public static new CVariable Create(CR2WFile cr2w, CVariable parent, string name) => new CJournalCreatureVitalSpotGroup(cr2w, parent, name);
public override void Read(BinaryReader file, uint size) => base.Read(file, size);
public override void Write(BinaryWriter file) => base.Write(file);
}
} | 33.695652 | 142 | 0.76 | [
"MIT"
] | bclnet/GameEstate | src/Estates/Red/GameEstate.Red.Format/Red/W3/RTTIConvert/CJournalCreatureVitalSpotGroup.cs | 775 | C# |
using Microsoft.SharePoint.Client;
using PnP.Framework.Diagnostics;
using PnP.Framework.Provisioning.Model;
using PnP.Framework.Provisioning.ObjectHandlers;
namespace PnP.Framework.Provisioning.Extensibility
{
/// <summary>
/// Defines an interface which allows to plugin custom Provisioning Extensibility Handlers to the template extraction/provisioning pipeline
/// </summary>
public interface IProvisioningExtensibilityHandler : IProvisioningExtensibilityTokenProvider
{
/// <summary>
/// Execute custom actions during provisioning of a template
/// </summary>
/// <param name="ctx">The target ClientContext</param>
/// <param name="template">The current Provisioning Template</param>
/// <param name="applyingInformation">The Provisioning Template application information object</param>
/// <param name="tokenParser">Token parser instance</param>
/// <param name="scope">The PnPMonitoredScope of the current step in the pipeline</param>
/// <param name="configurationData">The configuration data, if any, for the handler</param>
void Provision(ClientContext ctx, ProvisioningTemplate template, ProvisioningTemplateApplyingInformation applyingInformation, TokenParser tokenParser, PnPMonitoredScope scope, string configurationData);
/// <summary>
/// Execute custom actions during extraction of a template
/// </summary>
/// <param name="ctx">The target ClientContext</param>
/// <param name="template">The current Provisioning Template</param>
/// <param name="creationInformation">The Provisioning Template creation information object</param>
/// <param name="scope">The PnPMonitoredScope of the current step in the pipeline</param>
/// <param name="configurationData">The configuration data, if any, for the handler</param>
/// <returns>The Provisioning Template eventually enriched by the handler during extraction</returns>
ProvisioningTemplate Extract(ClientContext ctx, ProvisioningTemplate template, ProvisioningTemplateCreationInformation creationInformation, PnPMonitoredScope scope, string configurationData);
}
}
| 61.527778 | 210 | 0.73544 | [
"MIT"
] | Arturiby/pnpframework | src/lib/PnP.Framework/Provisioning/Extensibility/IProvisioningExtensibilityHandler.cs | 2,217 | C# |
// <auto-generated />
using System;
using GrpcDemo.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Volo.Abp.EntityFrameworkCore;
namespace GrpcDemo.Migrations
{
[DbContext(typeof(GrpcDemoMigrationsDbContext))]
partial class GrpcDemoMigrationsDbContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.UseIdentityColumns()
.HasAnnotation("_Abp_DatabaseProvider", EfCoreDatabaseProvider.SqlServer)
.HasAnnotation("Relational:MaxIdentifierLength", 128)
.HasAnnotation("ProductVersion", "5.0.0");
modelBuilder.Entity("Volo.Abp.AuditLogging.AuditLog", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<string>("ApplicationName")
.HasMaxLength(96)
.HasColumnType("nvarchar(96)")
.HasColumnName("ApplicationName");
b.Property<string>("BrowserInfo")
.HasMaxLength(512)
.HasColumnType("nvarchar(512)")
.HasColumnName("BrowserInfo");
b.Property<string>("ClientId")
.HasMaxLength(64)
.HasColumnType("nvarchar(64)")
.HasColumnName("ClientId");
b.Property<string>("ClientIpAddress")
.HasMaxLength(64)
.HasColumnType("nvarchar(64)")
.HasColumnName("ClientIpAddress");
b.Property<string>("ClientName")
.HasMaxLength(128)
.HasColumnType("nvarchar(128)")
.HasColumnName("ClientName");
b.Property<string>("Comments")
.HasMaxLength(256)
.HasColumnType("nvarchar(256)")
.HasColumnName("Comments");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasMaxLength(40)
.HasColumnType("nvarchar(40)")
.HasColumnName("ConcurrencyStamp");
b.Property<string>("CorrelationId")
.HasMaxLength(64)
.HasColumnType("nvarchar(64)")
.HasColumnName("CorrelationId");
b.Property<string>("Exceptions")
.HasMaxLength(4000)
.HasColumnType("nvarchar(4000)")
.HasColumnName("Exceptions");
b.Property<int>("ExecutionDuration")
.HasColumnType("int")
.HasColumnName("ExecutionDuration");
b.Property<DateTime>("ExecutionTime")
.HasColumnType("datetime2");
b.Property<string>("ExtraProperties")
.HasColumnType("nvarchar(max)")
.HasColumnName("ExtraProperties");
b.Property<string>("HttpMethod")
.HasMaxLength(16)
.HasColumnType("nvarchar(16)")
.HasColumnName("HttpMethod");
b.Property<int?>("HttpStatusCode")
.HasColumnType("int")
.HasColumnName("HttpStatusCode");
b.Property<Guid?>("ImpersonatorTenantId")
.HasColumnType("uniqueidentifier")
.HasColumnName("ImpersonatorTenantId");
b.Property<Guid?>("ImpersonatorUserId")
.HasColumnType("uniqueidentifier")
.HasColumnName("ImpersonatorUserId");
b.Property<Guid?>("TenantId")
.HasColumnType("uniqueidentifier")
.HasColumnName("TenantId");
b.Property<string>("TenantName")
.HasColumnType("nvarchar(max)");
b.Property<string>("Url")
.HasMaxLength(256)
.HasColumnType("nvarchar(256)")
.HasColumnName("Url");
b.Property<Guid?>("UserId")
.HasColumnType("uniqueidentifier")
.HasColumnName("UserId");
b.Property<string>("UserName")
.HasMaxLength(256)
.HasColumnType("nvarchar(256)")
.HasColumnName("UserName");
b.HasKey("Id");
b.HasIndex("TenantId", "ExecutionTime");
b.HasIndex("TenantId", "UserId", "ExecutionTime");
b.ToTable("AbpAuditLogs");
});
modelBuilder.Entity("Volo.Abp.AuditLogging.AuditLogAction", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<Guid>("AuditLogId")
.HasColumnType("uniqueidentifier")
.HasColumnName("AuditLogId");
b.Property<int>("ExecutionDuration")
.HasColumnType("int")
.HasColumnName("ExecutionDuration");
b.Property<DateTime>("ExecutionTime")
.HasColumnType("datetime2")
.HasColumnName("ExecutionTime");
b.Property<string>("ExtraProperties")
.HasColumnType("nvarchar(max)")
.HasColumnName("ExtraProperties");
b.Property<string>("MethodName")
.HasMaxLength(128)
.HasColumnType("nvarchar(128)")
.HasColumnName("MethodName");
b.Property<string>("Parameters")
.HasMaxLength(2000)
.HasColumnType("nvarchar(2000)")
.HasColumnName("Parameters");
b.Property<string>("ServiceName")
.HasMaxLength(256)
.HasColumnType("nvarchar(256)")
.HasColumnName("ServiceName");
b.Property<Guid?>("TenantId")
.HasColumnType("uniqueidentifier")
.HasColumnName("TenantId");
b.HasKey("Id");
b.HasIndex("AuditLogId");
b.HasIndex("TenantId", "ServiceName", "MethodName", "ExecutionTime");
b.ToTable("AbpAuditLogActions");
});
modelBuilder.Entity("Volo.Abp.AuditLogging.EntityChange", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<Guid>("AuditLogId")
.HasColumnType("uniqueidentifier")
.HasColumnName("AuditLogId");
b.Property<DateTime>("ChangeTime")
.HasColumnType("datetime2")
.HasColumnName("ChangeTime");
b.Property<byte>("ChangeType")
.HasColumnType("tinyint")
.HasColumnName("ChangeType");
b.Property<string>("EntityId")
.IsRequired()
.HasMaxLength(128)
.HasColumnType("nvarchar(128)")
.HasColumnName("EntityId");
b.Property<Guid?>("EntityTenantId")
.HasColumnType("uniqueidentifier");
b.Property<string>("EntityTypeFullName")
.IsRequired()
.HasMaxLength(128)
.HasColumnType("nvarchar(128)")
.HasColumnName("EntityTypeFullName");
b.Property<string>("ExtraProperties")
.HasColumnType("nvarchar(max)")
.HasColumnName("ExtraProperties");
b.Property<Guid?>("TenantId")
.HasColumnType("uniqueidentifier")
.HasColumnName("TenantId");
b.HasKey("Id");
b.HasIndex("AuditLogId");
b.HasIndex("TenantId", "EntityTypeFullName", "EntityId");
b.ToTable("AbpEntityChanges");
});
modelBuilder.Entity("Volo.Abp.AuditLogging.EntityPropertyChange", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<Guid>("EntityChangeId")
.HasColumnType("uniqueidentifier");
b.Property<string>("NewValue")
.HasMaxLength(512)
.HasColumnType("nvarchar(512)")
.HasColumnName("NewValue");
b.Property<string>("OriginalValue")
.HasMaxLength(512)
.HasColumnType("nvarchar(512)")
.HasColumnName("OriginalValue");
b.Property<string>("PropertyName")
.IsRequired()
.HasMaxLength(128)
.HasColumnType("nvarchar(128)")
.HasColumnName("PropertyName");
b.Property<string>("PropertyTypeFullName")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("nvarchar(64)")
.HasColumnName("PropertyTypeFullName");
b.Property<Guid?>("TenantId")
.HasColumnType("uniqueidentifier")
.HasColumnName("TenantId");
b.HasKey("Id");
b.HasIndex("EntityChangeId");
b.ToTable("AbpEntityPropertyChanges");
});
modelBuilder.Entity("Volo.Abp.BackgroundJobs.BackgroundJobRecord", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasMaxLength(40)
.HasColumnType("nvarchar(40)")
.HasColumnName("ConcurrencyStamp");
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2")
.HasColumnName("CreationTime");
b.Property<string>("ExtraProperties")
.HasColumnType("nvarchar(max)")
.HasColumnName("ExtraProperties");
b.Property<bool>("IsAbandoned")
.ValueGeneratedOnAdd()
.HasColumnType("bit")
.HasDefaultValue(false);
b.Property<string>("JobArgs")
.IsRequired()
.HasMaxLength(1048576)
.HasColumnType("nvarchar(max)");
b.Property<string>("JobName")
.IsRequired()
.HasMaxLength(128)
.HasColumnType("nvarchar(128)");
b.Property<DateTime?>("LastTryTime")
.HasColumnType("datetime2");
b.Property<DateTime>("NextTryTime")
.HasColumnType("datetime2");
b.Property<byte>("Priority")
.ValueGeneratedOnAdd()
.HasColumnType("tinyint")
.HasDefaultValue((byte)15);
b.Property<short>("TryCount")
.ValueGeneratedOnAdd()
.HasColumnType("smallint")
.HasDefaultValue((short)0);
b.HasKey("Id");
b.HasIndex("IsAbandoned", "NextTryTime");
b.ToTable("AbpBackgroundJobs");
});
modelBuilder.Entity("Volo.Abp.FeatureManagement.FeatureValue", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(128)
.HasColumnType("nvarchar(128)");
b.Property<string>("ProviderKey")
.HasMaxLength(64)
.HasColumnType("nvarchar(64)");
b.Property<string>("ProviderName")
.HasMaxLength(64)
.HasColumnType("nvarchar(64)");
b.Property<string>("Value")
.IsRequired()
.HasMaxLength(128)
.HasColumnType("nvarchar(128)");
b.HasKey("Id");
b.HasIndex("Name", "ProviderName", "ProviderKey");
b.ToTable("AbpFeatureValues");
});
modelBuilder.Entity("Volo.Abp.Identity.IdentityClaimType", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasMaxLength(40)
.HasColumnType("nvarchar(40)")
.HasColumnName("ConcurrencyStamp");
b.Property<string>("Description")
.HasMaxLength(256)
.HasColumnType("nvarchar(256)");
b.Property<string>("ExtraProperties")
.HasColumnType("nvarchar(max)")
.HasColumnName("ExtraProperties");
b.Property<bool>("IsStatic")
.HasColumnType("bit");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(256)
.HasColumnType("nvarchar(256)");
b.Property<string>("Regex")
.HasMaxLength(512)
.HasColumnType("nvarchar(512)");
b.Property<string>("RegexDescription")
.HasMaxLength(128)
.HasColumnType("nvarchar(128)");
b.Property<bool>("Required")
.HasColumnType("bit");
b.Property<int>("ValueType")
.HasColumnType("int");
b.HasKey("Id");
b.ToTable("AbpClaimTypes");
});
modelBuilder.Entity("Volo.Abp.Identity.IdentityLinkUser", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<Guid?>("SourceTenantId")
.HasColumnType("uniqueidentifier");
b.Property<Guid>("SourceUserId")
.HasColumnType("uniqueidentifier");
b.Property<Guid?>("TargetTenantId")
.HasColumnType("uniqueidentifier");
b.Property<Guid>("TargetUserId")
.HasColumnType("uniqueidentifier");
b.HasKey("Id");
b.HasIndex("SourceUserId", "SourceTenantId", "TargetUserId", "TargetTenantId")
.IsUnique()
.HasFilter("[SourceTenantId] IS NOT NULL AND [TargetTenantId] IS NOT NULL");
b.ToTable("AbpLinkUsers");
});
modelBuilder.Entity("Volo.Abp.Identity.IdentityRole", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasMaxLength(40)
.HasColumnType("nvarchar(40)")
.HasColumnName("ConcurrencyStamp");
b.Property<string>("ExtraProperties")
.HasColumnType("nvarchar(max)")
.HasColumnName("ExtraProperties");
b.Property<bool>("IsDefault")
.HasColumnType("bit")
.HasColumnName("IsDefault");
b.Property<bool>("IsPublic")
.HasColumnType("bit")
.HasColumnName("IsPublic");
b.Property<bool>("IsStatic")
.HasColumnType("bit")
.HasColumnName("IsStatic");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(256)
.HasColumnType("nvarchar(256)");
b.Property<string>("NormalizedName")
.IsRequired()
.HasMaxLength(256)
.HasColumnType("nvarchar(256)");
b.Property<Guid?>("TenantId")
.HasColumnType("uniqueidentifier")
.HasColumnName("TenantId");
b.HasKey("Id");
b.HasIndex("NormalizedName");
b.ToTable("AbpRoles");
});
modelBuilder.Entity("Volo.Abp.Identity.IdentityRoleClaim", b =>
{
b.Property<Guid>("Id")
.HasColumnType("uniqueidentifier");
b.Property<string>("ClaimType")
.IsRequired()
.HasMaxLength(256)
.HasColumnType("nvarchar(256)");
b.Property<string>("ClaimValue")
.HasMaxLength(1024)
.HasColumnType("nvarchar(1024)");
b.Property<Guid>("RoleId")
.HasColumnType("uniqueidentifier");
b.Property<Guid?>("TenantId")
.HasColumnType("uniqueidentifier")
.HasColumnName("TenantId");
b.HasKey("Id");
b.HasIndex("RoleId");
b.ToTable("AbpRoleClaims");
});
modelBuilder.Entity("Volo.Abp.Identity.IdentitySecurityLog", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<string>("Action")
.HasMaxLength(96)
.HasColumnType("nvarchar(96)");
b.Property<string>("ApplicationName")
.HasMaxLength(96)
.HasColumnType("nvarchar(96)");
b.Property<string>("BrowserInfo")
.HasMaxLength(512)
.HasColumnType("nvarchar(512)");
b.Property<string>("ClientId")
.HasMaxLength(64)
.HasColumnType("nvarchar(64)");
b.Property<string>("ClientIpAddress")
.HasMaxLength(64)
.HasColumnType("nvarchar(64)");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasMaxLength(40)
.HasColumnType("nvarchar(40)")
.HasColumnName("ConcurrencyStamp");
b.Property<string>("CorrelationId")
.HasMaxLength(64)
.HasColumnType("nvarchar(64)");
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<string>("ExtraProperties")
.HasColumnType("nvarchar(max)")
.HasColumnName("ExtraProperties");
b.Property<string>("Identity")
.HasMaxLength(96)
.HasColumnType("nvarchar(96)");
b.Property<Guid?>("TenantId")
.HasColumnType("uniqueidentifier")
.HasColumnName("TenantId");
b.Property<string>("TenantName")
.HasMaxLength(64)
.HasColumnType("nvarchar(64)");
b.Property<Guid?>("UserId")
.HasColumnType("uniqueidentifier");
b.Property<string>("UserName")
.HasMaxLength(256)
.HasColumnType("nvarchar(256)");
b.HasKey("Id");
b.HasIndex("TenantId", "Action");
b.HasIndex("TenantId", "ApplicationName");
b.HasIndex("TenantId", "Identity");
b.HasIndex("TenantId", "UserId");
b.ToTable("AbpSecurityLogs");
});
modelBuilder.Entity("Volo.Abp.Identity.IdentityUser", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<int>("AccessFailedCount")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasDefaultValue(0)
.HasColumnName("AccessFailedCount");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasMaxLength(40)
.HasColumnType("nvarchar(40)")
.HasColumnName("ConcurrencyStamp");
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2")
.HasColumnName("CreationTime");
b.Property<Guid?>("CreatorId")
.HasColumnType("uniqueidentifier")
.HasColumnName("CreatorId");
b.Property<Guid?>("DeleterId")
.HasColumnType("uniqueidentifier")
.HasColumnName("DeleterId");
b.Property<DateTime?>("DeletionTime")
.HasColumnType("datetime2")
.HasColumnName("DeletionTime");
b.Property<string>("Email")
.IsRequired()
.HasMaxLength(256)
.HasColumnType("nvarchar(256)")
.HasColumnName("Email");
b.Property<bool>("EmailConfirmed")
.ValueGeneratedOnAdd()
.HasColumnType("bit")
.HasDefaultValue(false)
.HasColumnName("EmailConfirmed");
b.Property<string>("ExtraProperties")
.HasColumnType("nvarchar(max)")
.HasColumnName("ExtraProperties");
b.Property<bool>("IsDeleted")
.ValueGeneratedOnAdd()
.HasColumnType("bit")
.HasDefaultValue(false)
.HasColumnName("IsDeleted");
b.Property<bool>("IsExternal")
.ValueGeneratedOnAdd()
.HasColumnType("bit")
.HasDefaultValue(false)
.HasColumnName("IsExternal");
b.Property<DateTime?>("LastModificationTime")
.HasColumnType("datetime2")
.HasColumnName("LastModificationTime");
b.Property<Guid?>("LastModifierId")
.HasColumnType("uniqueidentifier")
.HasColumnName("LastModifierId");
b.Property<bool>("LockoutEnabled")
.ValueGeneratedOnAdd()
.HasColumnType("bit")
.HasDefaultValue(false)
.HasColumnName("LockoutEnabled");
b.Property<DateTimeOffset?>("LockoutEnd")
.HasColumnType("datetimeoffset");
b.Property<string>("Name")
.HasMaxLength(64)
.HasColumnType("nvarchar(64)")
.HasColumnName("Name");
b.Property<string>("NormalizedEmail")
.IsRequired()
.HasMaxLength(256)
.HasColumnType("nvarchar(256)")
.HasColumnName("NormalizedEmail");
b.Property<string>("NormalizedUserName")
.IsRequired()
.HasMaxLength(256)
.HasColumnType("nvarchar(256)")
.HasColumnName("NormalizedUserName");
b.Property<string>("PasswordHash")
.HasMaxLength(256)
.HasColumnType("nvarchar(256)")
.HasColumnName("PasswordHash");
b.Property<string>("PhoneNumber")
.HasMaxLength(16)
.HasColumnType("nvarchar(16)")
.HasColumnName("PhoneNumber");
b.Property<bool>("PhoneNumberConfirmed")
.ValueGeneratedOnAdd()
.HasColumnType("bit")
.HasDefaultValue(false)
.HasColumnName("PhoneNumberConfirmed");
b.Property<string>("SecurityStamp")
.IsRequired()
.HasMaxLength(256)
.HasColumnType("nvarchar(256)")
.HasColumnName("SecurityStamp");
b.Property<string>("Surname")
.HasMaxLength(64)
.HasColumnType("nvarchar(64)")
.HasColumnName("Surname");
b.Property<Guid?>("TenantId")
.HasColumnType("uniqueidentifier")
.HasColumnName("TenantId");
b.Property<bool>("TwoFactorEnabled")
.ValueGeneratedOnAdd()
.HasColumnType("bit")
.HasDefaultValue(false)
.HasColumnName("TwoFactorEnabled");
b.Property<string>("UserName")
.IsRequired()
.HasMaxLength(256)
.HasColumnType("nvarchar(256)")
.HasColumnName("UserName");
b.HasKey("Id");
b.HasIndex("Email");
b.HasIndex("NormalizedEmail");
b.HasIndex("NormalizedUserName");
b.HasIndex("UserName");
b.ToTable("AbpUsers");
});
modelBuilder.Entity("Volo.Abp.Identity.IdentityUserClaim", b =>
{
b.Property<Guid>("Id")
.HasColumnType("uniqueidentifier");
b.Property<string>("ClaimType")
.IsRequired()
.HasMaxLength(256)
.HasColumnType("nvarchar(256)");
b.Property<string>("ClaimValue")
.HasMaxLength(1024)
.HasColumnType("nvarchar(1024)");
b.Property<Guid?>("TenantId")
.HasColumnType("uniqueidentifier")
.HasColumnName("TenantId");
b.Property<Guid>("UserId")
.HasColumnType("uniqueidentifier");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("AbpUserClaims");
});
modelBuilder.Entity("Volo.Abp.Identity.IdentityUserLogin", b =>
{
b.Property<Guid>("UserId")
.HasColumnType("uniqueidentifier");
b.Property<string>("LoginProvider")
.HasMaxLength(64)
.HasColumnType("nvarchar(64)");
b.Property<string>("ProviderDisplayName")
.HasMaxLength(128)
.HasColumnType("nvarchar(128)");
b.Property<string>("ProviderKey")
.IsRequired()
.HasMaxLength(196)
.HasColumnType("nvarchar(196)");
b.Property<Guid?>("TenantId")
.HasColumnType("uniqueidentifier")
.HasColumnName("TenantId");
b.HasKey("UserId", "LoginProvider");
b.HasIndex("LoginProvider", "ProviderKey");
b.ToTable("AbpUserLogins");
});
modelBuilder.Entity("Volo.Abp.Identity.IdentityUserOrganizationUnit", b =>
{
b.Property<Guid>("OrganizationUnitId")
.HasColumnType("uniqueidentifier");
b.Property<Guid>("UserId")
.HasColumnType("uniqueidentifier");
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2")
.HasColumnName("CreationTime");
b.Property<Guid?>("CreatorId")
.HasColumnType("uniqueidentifier")
.HasColumnName("CreatorId");
b.Property<Guid?>("TenantId")
.HasColumnType("uniqueidentifier")
.HasColumnName("TenantId");
b.HasKey("OrganizationUnitId", "UserId");
b.HasIndex("UserId", "OrganizationUnitId");
b.ToTable("AbpUserOrganizationUnits");
});
modelBuilder.Entity("Volo.Abp.Identity.IdentityUserRole", b =>
{
b.Property<Guid>("UserId")
.HasColumnType("uniqueidentifier");
b.Property<Guid>("RoleId")
.HasColumnType("uniqueidentifier");
b.Property<Guid?>("TenantId")
.HasColumnType("uniqueidentifier")
.HasColumnName("TenantId");
b.HasKey("UserId", "RoleId");
b.HasIndex("RoleId", "UserId");
b.ToTable("AbpUserRoles");
});
modelBuilder.Entity("Volo.Abp.Identity.IdentityUserToken", b =>
{
b.Property<Guid>("UserId")
.HasColumnType("uniqueidentifier");
b.Property<string>("LoginProvider")
.HasMaxLength(64)
.HasColumnType("nvarchar(64)");
b.Property<string>("Name")
.HasMaxLength(128)
.HasColumnType("nvarchar(128)");
b.Property<Guid?>("TenantId")
.HasColumnType("uniqueidentifier")
.HasColumnName("TenantId");
b.Property<string>("Value")
.HasColumnType("nvarchar(max)");
b.HasKey("UserId", "LoginProvider", "Name");
b.ToTable("AbpUserTokens");
});
modelBuilder.Entity("Volo.Abp.Identity.OrganizationUnit", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<string>("Code")
.IsRequired()
.HasMaxLength(95)
.HasColumnType("nvarchar(95)")
.HasColumnName("Code");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasMaxLength(40)
.HasColumnType("nvarchar(40)")
.HasColumnName("ConcurrencyStamp");
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2")
.HasColumnName("CreationTime");
b.Property<Guid?>("CreatorId")
.HasColumnType("uniqueidentifier")
.HasColumnName("CreatorId");
b.Property<Guid?>("DeleterId")
.HasColumnType("uniqueidentifier")
.HasColumnName("DeleterId");
b.Property<DateTime?>("DeletionTime")
.HasColumnType("datetime2")
.HasColumnName("DeletionTime");
b.Property<string>("DisplayName")
.IsRequired()
.HasMaxLength(128)
.HasColumnType("nvarchar(128)")
.HasColumnName("DisplayName");
b.Property<string>("ExtraProperties")
.HasColumnType("nvarchar(max)")
.HasColumnName("ExtraProperties");
b.Property<bool>("IsDeleted")
.ValueGeneratedOnAdd()
.HasColumnType("bit")
.HasDefaultValue(false)
.HasColumnName("IsDeleted");
b.Property<DateTime?>("LastModificationTime")
.HasColumnType("datetime2")
.HasColumnName("LastModificationTime");
b.Property<Guid?>("LastModifierId")
.HasColumnType("uniqueidentifier")
.HasColumnName("LastModifierId");
b.Property<Guid?>("ParentId")
.HasColumnType("uniqueidentifier");
b.Property<Guid?>("TenantId")
.HasColumnType("uniqueidentifier")
.HasColumnName("TenantId");
b.HasKey("Id");
b.HasIndex("Code");
b.HasIndex("ParentId");
b.ToTable("AbpOrganizationUnits");
});
modelBuilder.Entity("Volo.Abp.Identity.OrganizationUnitRole", b =>
{
b.Property<Guid>("OrganizationUnitId")
.HasColumnType("uniqueidentifier");
b.Property<Guid>("RoleId")
.HasColumnType("uniqueidentifier");
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2")
.HasColumnName("CreationTime");
b.Property<Guid?>("CreatorId")
.HasColumnType("uniqueidentifier")
.HasColumnName("CreatorId");
b.Property<Guid?>("TenantId")
.HasColumnType("uniqueidentifier")
.HasColumnName("TenantId");
b.HasKey("OrganizationUnitId", "RoleId");
b.HasIndex("RoleId", "OrganizationUnitId");
b.ToTable("AbpOrganizationUnitRoles");
});
modelBuilder.Entity("Volo.Abp.IdentityServer.ApiResources.ApiResource", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<string>("AllowedAccessTokenSigningAlgorithms")
.HasMaxLength(100)
.HasColumnType("nvarchar(100)");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasMaxLength(40)
.HasColumnType("nvarchar(40)")
.HasColumnName("ConcurrencyStamp");
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2")
.HasColumnName("CreationTime");
b.Property<Guid?>("CreatorId")
.HasColumnType("uniqueidentifier")
.HasColumnName("CreatorId");
b.Property<Guid?>("DeleterId")
.HasColumnType("uniqueidentifier")
.HasColumnName("DeleterId");
b.Property<DateTime?>("DeletionTime")
.HasColumnType("datetime2")
.HasColumnName("DeletionTime");
b.Property<string>("Description")
.HasMaxLength(1000)
.HasColumnType("nvarchar(1000)");
b.Property<string>("DisplayName")
.HasMaxLength(200)
.HasColumnType("nvarchar(200)");
b.Property<bool>("Enabled")
.HasColumnType("bit");
b.Property<string>("ExtraProperties")
.HasColumnType("nvarchar(max)")
.HasColumnName("ExtraProperties");
b.Property<bool>("IsDeleted")
.ValueGeneratedOnAdd()
.HasColumnType("bit")
.HasDefaultValue(false)
.HasColumnName("IsDeleted");
b.Property<DateTime?>("LastModificationTime")
.HasColumnType("datetime2")
.HasColumnName("LastModificationTime");
b.Property<Guid?>("LastModifierId")
.HasColumnType("uniqueidentifier")
.HasColumnName("LastModifierId");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(200)
.HasColumnType("nvarchar(200)");
b.Property<bool>("ShowInDiscoveryDocument")
.HasColumnType("bit");
b.HasKey("Id");
b.ToTable("IdentityServerApiResources");
});
modelBuilder.Entity("Volo.Abp.IdentityServer.ApiResources.ApiResourceClaim", b =>
{
b.Property<Guid>("ApiResourceId")
.HasColumnType("uniqueidentifier");
b.Property<string>("Type")
.HasMaxLength(200)
.HasColumnType("nvarchar(200)");
b.HasKey("ApiResourceId", "Type");
b.ToTable("IdentityServerApiResourceClaims");
});
modelBuilder.Entity("Volo.Abp.IdentityServer.ApiResources.ApiResourceProperty", b =>
{
b.Property<Guid>("ApiResourceId")
.HasColumnType("uniqueidentifier");
b.Property<string>("Key")
.HasMaxLength(250)
.HasColumnType("nvarchar(250)");
b.Property<string>("Value")
.HasMaxLength(2000)
.HasColumnType("nvarchar(2000)");
b.HasKey("ApiResourceId", "Key", "Value");
b.ToTable("IdentityServerApiResourceProperties");
});
modelBuilder.Entity("Volo.Abp.IdentityServer.ApiResources.ApiResourceScope", b =>
{
b.Property<Guid>("ApiResourceId")
.HasColumnType("uniqueidentifier");
b.Property<string>("Scope")
.HasMaxLength(200)
.HasColumnType("nvarchar(200)");
b.HasKey("ApiResourceId", "Scope");
b.ToTable("IdentityServerApiResourceScopes");
});
modelBuilder.Entity("Volo.Abp.IdentityServer.ApiResources.ApiResourceSecret", b =>
{
b.Property<Guid>("ApiResourceId")
.HasColumnType("uniqueidentifier");
b.Property<string>("Type")
.HasMaxLength(250)
.HasColumnType("nvarchar(250)");
b.Property<string>("Value")
.HasMaxLength(4000)
.HasColumnType("nvarchar(4000)");
b.Property<string>("Description")
.HasMaxLength(1000)
.HasColumnType("nvarchar(1000)");
b.Property<DateTime?>("Expiration")
.HasColumnType("datetime2");
b.HasKey("ApiResourceId", "Type", "Value");
b.ToTable("IdentityServerApiResourceSecrets");
});
modelBuilder.Entity("Volo.Abp.IdentityServer.ApiScopes.ApiScope", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasMaxLength(40)
.HasColumnType("nvarchar(40)")
.HasColumnName("ConcurrencyStamp");
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2")
.HasColumnName("CreationTime");
b.Property<Guid?>("CreatorId")
.HasColumnType("uniqueidentifier")
.HasColumnName("CreatorId");
b.Property<Guid?>("DeleterId")
.HasColumnType("uniqueidentifier")
.HasColumnName("DeleterId");
b.Property<DateTime?>("DeletionTime")
.HasColumnType("datetime2")
.HasColumnName("DeletionTime");
b.Property<string>("Description")
.HasMaxLength(1000)
.HasColumnType("nvarchar(1000)");
b.Property<string>("DisplayName")
.HasMaxLength(200)
.HasColumnType("nvarchar(200)");
b.Property<bool>("Emphasize")
.HasColumnType("bit");
b.Property<bool>("Enabled")
.HasColumnType("bit");
b.Property<string>("ExtraProperties")
.HasColumnType("nvarchar(max)")
.HasColumnName("ExtraProperties");
b.Property<bool>("IsDeleted")
.ValueGeneratedOnAdd()
.HasColumnType("bit")
.HasDefaultValue(false)
.HasColumnName("IsDeleted");
b.Property<DateTime?>("LastModificationTime")
.HasColumnType("datetime2")
.HasColumnName("LastModificationTime");
b.Property<Guid?>("LastModifierId")
.HasColumnType("uniqueidentifier")
.HasColumnName("LastModifierId");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(200)
.HasColumnType("nvarchar(200)");
b.Property<bool>("Required")
.HasColumnType("bit");
b.Property<bool>("ShowInDiscoveryDocument")
.HasColumnType("bit");
b.HasKey("Id");
b.ToTable("IdentityServerApiScopes");
});
modelBuilder.Entity("Volo.Abp.IdentityServer.ApiScopes.ApiScopeClaim", b =>
{
b.Property<Guid>("ApiScopeId")
.HasColumnType("uniqueidentifier");
b.Property<string>("Type")
.HasMaxLength(200)
.HasColumnType("nvarchar(200)");
b.HasKey("ApiScopeId", "Type");
b.ToTable("IdentityServerApiScopeClaims");
});
modelBuilder.Entity("Volo.Abp.IdentityServer.ApiScopes.ApiScopeProperty", b =>
{
b.Property<Guid>("ApiScopeId")
.HasColumnType("uniqueidentifier");
b.Property<string>("Key")
.HasMaxLength(250)
.HasColumnType("nvarchar(250)");
b.Property<string>("Value")
.HasMaxLength(2000)
.HasColumnType("nvarchar(2000)");
b.HasKey("ApiScopeId", "Key", "Value");
b.ToTable("IdentityServerApiScopeProperties");
});
modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.Client", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<int>("AbsoluteRefreshTokenLifetime")
.HasColumnType("int");
b.Property<int>("AccessTokenLifetime")
.HasColumnType("int");
b.Property<int>("AccessTokenType")
.HasColumnType("int");
b.Property<bool>("AllowAccessTokensViaBrowser")
.HasColumnType("bit");
b.Property<bool>("AllowOfflineAccess")
.HasColumnType("bit");
b.Property<bool>("AllowPlainTextPkce")
.HasColumnType("bit");
b.Property<bool>("AllowRememberConsent")
.HasColumnType("bit");
b.Property<string>("AllowedIdentityTokenSigningAlgorithms")
.HasMaxLength(100)
.HasColumnType("nvarchar(100)");
b.Property<bool>("AlwaysIncludeUserClaimsInIdToken")
.HasColumnType("bit");
b.Property<bool>("AlwaysSendClientClaims")
.HasColumnType("bit");
b.Property<int>("AuthorizationCodeLifetime")
.HasColumnType("int");
b.Property<bool>("BackChannelLogoutSessionRequired")
.HasColumnType("bit");
b.Property<string>("BackChannelLogoutUri")
.HasMaxLength(2000)
.HasColumnType("nvarchar(2000)");
b.Property<string>("ClientClaimsPrefix")
.HasMaxLength(200)
.HasColumnType("nvarchar(200)");
b.Property<string>("ClientId")
.IsRequired()
.HasMaxLength(200)
.HasColumnType("nvarchar(200)");
b.Property<string>("ClientName")
.HasMaxLength(200)
.HasColumnType("nvarchar(200)");
b.Property<string>("ClientUri")
.HasMaxLength(2000)
.HasColumnType("nvarchar(2000)");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasMaxLength(40)
.HasColumnType("nvarchar(40)")
.HasColumnName("ConcurrencyStamp");
b.Property<int?>("ConsentLifetime")
.HasColumnType("int");
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2")
.HasColumnName("CreationTime");
b.Property<Guid?>("CreatorId")
.HasColumnType("uniqueidentifier")
.HasColumnName("CreatorId");
b.Property<Guid?>("DeleterId")
.HasColumnType("uniqueidentifier")
.HasColumnName("DeleterId");
b.Property<DateTime?>("DeletionTime")
.HasColumnType("datetime2")
.HasColumnName("DeletionTime");
b.Property<string>("Description")
.HasMaxLength(1000)
.HasColumnType("nvarchar(1000)");
b.Property<int>("DeviceCodeLifetime")
.HasColumnType("int");
b.Property<bool>("EnableLocalLogin")
.HasColumnType("bit");
b.Property<bool>("Enabled")
.HasColumnType("bit");
b.Property<string>("ExtraProperties")
.HasColumnType("nvarchar(max)")
.HasColumnName("ExtraProperties");
b.Property<bool>("FrontChannelLogoutSessionRequired")
.HasColumnType("bit");
b.Property<string>("FrontChannelLogoutUri")
.HasMaxLength(2000)
.HasColumnType("nvarchar(2000)");
b.Property<int>("IdentityTokenLifetime")
.HasColumnType("int");
b.Property<bool>("IncludeJwtId")
.HasColumnType("bit");
b.Property<bool>("IsDeleted")
.ValueGeneratedOnAdd()
.HasColumnType("bit")
.HasDefaultValue(false)
.HasColumnName("IsDeleted");
b.Property<DateTime?>("LastModificationTime")
.HasColumnType("datetime2")
.HasColumnName("LastModificationTime");
b.Property<Guid?>("LastModifierId")
.HasColumnType("uniqueidentifier")
.HasColumnName("LastModifierId");
b.Property<string>("LogoUri")
.HasMaxLength(2000)
.HasColumnType("nvarchar(2000)");
b.Property<string>("PairWiseSubjectSalt")
.HasMaxLength(200)
.HasColumnType("nvarchar(200)");
b.Property<string>("ProtocolType")
.IsRequired()
.HasMaxLength(200)
.HasColumnType("nvarchar(200)");
b.Property<int>("RefreshTokenExpiration")
.HasColumnType("int");
b.Property<int>("RefreshTokenUsage")
.HasColumnType("int");
b.Property<bool>("RequireClientSecret")
.HasColumnType("bit");
b.Property<bool>("RequireConsent")
.HasColumnType("bit");
b.Property<bool>("RequirePkce")
.HasColumnType("bit");
b.Property<bool>("RequireRequestObject")
.HasColumnType("bit");
b.Property<int>("SlidingRefreshTokenLifetime")
.HasColumnType("int");
b.Property<bool>("UpdateAccessTokenClaimsOnRefresh")
.HasColumnType("bit");
b.Property<string>("UserCodeType")
.HasMaxLength(100)
.HasColumnType("nvarchar(100)");
b.Property<int?>("UserSsoLifetime")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("ClientId");
b.ToTable("IdentityServerClients");
});
modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.ClientClaim", b =>
{
b.Property<Guid>("ClientId")
.HasColumnType("uniqueidentifier");
b.Property<string>("Type")
.HasMaxLength(250)
.HasColumnType("nvarchar(250)");
b.Property<string>("Value")
.HasMaxLength(250)
.HasColumnType("nvarchar(250)");
b.HasKey("ClientId", "Type", "Value");
b.ToTable("IdentityServerClientClaims");
});
modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.ClientCorsOrigin", b =>
{
b.Property<Guid>("ClientId")
.HasColumnType("uniqueidentifier");
b.Property<string>("Origin")
.HasMaxLength(150)
.HasColumnType("nvarchar(150)");
b.HasKey("ClientId", "Origin");
b.ToTable("IdentityServerClientCorsOrigins");
});
modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.ClientGrantType", b =>
{
b.Property<Guid>("ClientId")
.HasColumnType("uniqueidentifier");
b.Property<string>("GrantType")
.HasMaxLength(250)
.HasColumnType("nvarchar(250)");
b.HasKey("ClientId", "GrantType");
b.ToTable("IdentityServerClientGrantTypes");
});
modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.ClientIdPRestriction", b =>
{
b.Property<Guid>("ClientId")
.HasColumnType("uniqueidentifier");
b.Property<string>("Provider")
.HasMaxLength(200)
.HasColumnType("nvarchar(200)");
b.HasKey("ClientId", "Provider");
b.ToTable("IdentityServerClientIdPRestrictions");
});
modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.ClientPostLogoutRedirectUri", b =>
{
b.Property<Guid>("ClientId")
.HasColumnType("uniqueidentifier");
b.Property<string>("PostLogoutRedirectUri")
.HasMaxLength(2000)
.HasColumnType("nvarchar(2000)");
b.HasKey("ClientId", "PostLogoutRedirectUri");
b.ToTable("IdentityServerClientPostLogoutRedirectUris");
});
modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.ClientProperty", b =>
{
b.Property<Guid>("ClientId")
.HasColumnType("uniqueidentifier");
b.Property<string>("Key")
.HasMaxLength(250)
.HasColumnType("nvarchar(250)");
b.Property<string>("Value")
.HasMaxLength(2000)
.HasColumnType("nvarchar(2000)");
b.HasKey("ClientId", "Key", "Value");
b.ToTable("IdentityServerClientProperties");
});
modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.ClientRedirectUri", b =>
{
b.Property<Guid>("ClientId")
.HasColumnType("uniqueidentifier");
b.Property<string>("RedirectUri")
.HasMaxLength(2000)
.HasColumnType("nvarchar(2000)");
b.HasKey("ClientId", "RedirectUri");
b.ToTable("IdentityServerClientRedirectUris");
});
modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.ClientScope", b =>
{
b.Property<Guid>("ClientId")
.HasColumnType("uniqueidentifier");
b.Property<string>("Scope")
.HasMaxLength(200)
.HasColumnType("nvarchar(200)");
b.HasKey("ClientId", "Scope");
b.ToTable("IdentityServerClientScopes");
});
modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.ClientSecret", b =>
{
b.Property<Guid>("ClientId")
.HasColumnType("uniqueidentifier");
b.Property<string>("Type")
.HasMaxLength(250)
.HasColumnType("nvarchar(250)");
b.Property<string>("Value")
.HasMaxLength(4000)
.HasColumnType("nvarchar(4000)");
b.Property<string>("Description")
.HasMaxLength(2000)
.HasColumnType("nvarchar(2000)");
b.Property<DateTime?>("Expiration")
.HasColumnType("datetime2");
b.HasKey("ClientId", "Type", "Value");
b.ToTable("IdentityServerClientSecrets");
});
modelBuilder.Entity("Volo.Abp.IdentityServer.Devices.DeviceFlowCodes", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<string>("ClientId")
.IsRequired()
.HasMaxLength(200)
.HasColumnType("nvarchar(200)");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasMaxLength(40)
.HasColumnType("nvarchar(40)")
.HasColumnName("ConcurrencyStamp");
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2")
.HasColumnName("CreationTime");
b.Property<Guid?>("CreatorId")
.HasColumnType("uniqueidentifier")
.HasColumnName("CreatorId");
b.Property<string>("Data")
.IsRequired()
.HasMaxLength(50000)
.HasColumnType("nvarchar(max)");
b.Property<string>("Description")
.HasMaxLength(200)
.HasColumnType("nvarchar(200)");
b.Property<string>("DeviceCode")
.IsRequired()
.HasMaxLength(200)
.HasColumnType("nvarchar(200)");
b.Property<DateTime?>("Expiration")
.IsRequired()
.HasColumnType("datetime2");
b.Property<string>("ExtraProperties")
.HasColumnType("nvarchar(max)")
.HasColumnName("ExtraProperties");
b.Property<string>("SessionId")
.HasMaxLength(100)
.HasColumnType("nvarchar(100)");
b.Property<string>("SubjectId")
.HasMaxLength(200)
.HasColumnType("nvarchar(200)");
b.Property<string>("UserCode")
.IsRequired()
.HasMaxLength(200)
.HasColumnType("nvarchar(200)");
b.HasKey("Id");
b.HasIndex("DeviceCode")
.IsUnique();
b.HasIndex("Expiration");
b.HasIndex("UserCode");
b.ToTable("IdentityServerDeviceFlowCodes");
});
modelBuilder.Entity("Volo.Abp.IdentityServer.Grants.PersistedGrant", b =>
{
b.Property<string>("Key")
.HasMaxLength(200)
.HasColumnType("nvarchar(200)");
b.Property<string>("ClientId")
.IsRequired()
.HasMaxLength(200)
.HasColumnType("nvarchar(200)");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasMaxLength(40)
.HasColumnType("nvarchar(40)")
.HasColumnName("ConcurrencyStamp");
b.Property<DateTime?>("ConsumedTime")
.HasColumnType("datetime2");
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2");
b.Property<string>("Data")
.IsRequired()
.HasMaxLength(50000)
.HasColumnType("nvarchar(max)");
b.Property<string>("Description")
.HasMaxLength(200)
.HasColumnType("nvarchar(200)");
b.Property<DateTime?>("Expiration")
.HasColumnType("datetime2");
b.Property<string>("ExtraProperties")
.HasColumnType("nvarchar(max)")
.HasColumnName("ExtraProperties");
b.Property<Guid>("Id")
.HasColumnType("uniqueidentifier");
b.Property<string>("SessionId")
.HasMaxLength(100)
.HasColumnType("nvarchar(100)");
b.Property<string>("SubjectId")
.HasMaxLength(200)
.HasColumnType("nvarchar(200)");
b.Property<string>("Type")
.IsRequired()
.HasMaxLength(50)
.HasColumnType("nvarchar(50)");
b.HasKey("Key");
b.HasIndex("Expiration");
b.HasIndex("SubjectId", "ClientId", "Type");
b.HasIndex("SubjectId", "SessionId", "Type");
b.ToTable("IdentityServerPersistedGrants");
});
modelBuilder.Entity("Volo.Abp.IdentityServer.IdentityResources.IdentityResource", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasMaxLength(40)
.HasColumnType("nvarchar(40)")
.HasColumnName("ConcurrencyStamp");
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2")
.HasColumnName("CreationTime");
b.Property<Guid?>("CreatorId")
.HasColumnType("uniqueidentifier")
.HasColumnName("CreatorId");
b.Property<Guid?>("DeleterId")
.HasColumnType("uniqueidentifier")
.HasColumnName("DeleterId");
b.Property<DateTime?>("DeletionTime")
.HasColumnType("datetime2")
.HasColumnName("DeletionTime");
b.Property<string>("Description")
.HasMaxLength(1000)
.HasColumnType("nvarchar(1000)");
b.Property<string>("DisplayName")
.HasMaxLength(200)
.HasColumnType("nvarchar(200)");
b.Property<bool>("Emphasize")
.HasColumnType("bit");
b.Property<bool>("Enabled")
.HasColumnType("bit");
b.Property<string>("ExtraProperties")
.HasColumnType("nvarchar(max)")
.HasColumnName("ExtraProperties");
b.Property<bool>("IsDeleted")
.ValueGeneratedOnAdd()
.HasColumnType("bit")
.HasDefaultValue(false)
.HasColumnName("IsDeleted");
b.Property<DateTime?>("LastModificationTime")
.HasColumnType("datetime2")
.HasColumnName("LastModificationTime");
b.Property<Guid?>("LastModifierId")
.HasColumnType("uniqueidentifier")
.HasColumnName("LastModifierId");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(200)
.HasColumnType("nvarchar(200)");
b.Property<bool>("Required")
.HasColumnType("bit");
b.Property<bool>("ShowInDiscoveryDocument")
.HasColumnType("bit");
b.HasKey("Id");
b.ToTable("IdentityServerIdentityResources");
});
modelBuilder.Entity("Volo.Abp.IdentityServer.IdentityResources.IdentityResourceClaim", b =>
{
b.Property<Guid>("IdentityResourceId")
.HasColumnType("uniqueidentifier");
b.Property<string>("Type")
.HasMaxLength(200)
.HasColumnType("nvarchar(200)");
b.HasKey("IdentityResourceId", "Type");
b.ToTable("IdentityServerIdentityResourceClaims");
});
modelBuilder.Entity("Volo.Abp.IdentityServer.IdentityResources.IdentityResourceProperty", b =>
{
b.Property<Guid>("IdentityResourceId")
.HasColumnType("uniqueidentifier");
b.Property<string>("Key")
.HasMaxLength(250)
.HasColumnType("nvarchar(250)");
b.Property<string>("Value")
.HasMaxLength(2000)
.HasColumnType("nvarchar(2000)");
b.HasKey("IdentityResourceId", "Key", "Value");
b.ToTable("IdentityServerIdentityResourceProperties");
});
modelBuilder.Entity("Volo.Abp.PermissionManagement.PermissionGrant", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(128)
.HasColumnType("nvarchar(128)");
b.Property<string>("ProviderKey")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("nvarchar(64)");
b.Property<string>("ProviderName")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("nvarchar(64)");
b.Property<Guid?>("TenantId")
.HasColumnType("uniqueidentifier")
.HasColumnName("TenantId");
b.HasKey("Id");
b.HasIndex("Name", "ProviderName", "ProviderKey");
b.ToTable("AbpPermissionGrants");
});
modelBuilder.Entity("Volo.Abp.SettingManagement.Setting", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(128)
.HasColumnType("nvarchar(128)");
b.Property<string>("ProviderKey")
.HasMaxLength(64)
.HasColumnType("nvarchar(64)");
b.Property<string>("ProviderName")
.HasMaxLength(64)
.HasColumnType("nvarchar(64)");
b.Property<string>("Value")
.IsRequired()
.HasMaxLength(2048)
.HasColumnType("nvarchar(2048)");
b.HasKey("Id");
b.HasIndex("Name", "ProviderName", "ProviderKey");
b.ToTable("AbpSettings");
});
modelBuilder.Entity("Volo.Abp.TenantManagement.Tenant", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasMaxLength(40)
.HasColumnType("nvarchar(40)")
.HasColumnName("ConcurrencyStamp");
b.Property<DateTime>("CreationTime")
.HasColumnType("datetime2")
.HasColumnName("CreationTime");
b.Property<Guid?>("CreatorId")
.HasColumnType("uniqueidentifier")
.HasColumnName("CreatorId");
b.Property<Guid?>("DeleterId")
.HasColumnType("uniqueidentifier")
.HasColumnName("DeleterId");
b.Property<DateTime?>("DeletionTime")
.HasColumnType("datetime2")
.HasColumnName("DeletionTime");
b.Property<string>("ExtraProperties")
.HasColumnType("nvarchar(max)")
.HasColumnName("ExtraProperties");
b.Property<bool>("IsDeleted")
.ValueGeneratedOnAdd()
.HasColumnType("bit")
.HasDefaultValue(false)
.HasColumnName("IsDeleted");
b.Property<DateTime?>("LastModificationTime")
.HasColumnType("datetime2")
.HasColumnName("LastModificationTime");
b.Property<Guid?>("LastModifierId")
.HasColumnType("uniqueidentifier")
.HasColumnName("LastModifierId");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("nvarchar(64)");
b.HasKey("Id");
b.HasIndex("Name");
b.ToTable("AbpTenants");
});
modelBuilder.Entity("Volo.Abp.TenantManagement.TenantConnectionString", b =>
{
b.Property<Guid>("TenantId")
.HasColumnType("uniqueidentifier");
b.Property<string>("Name")
.HasMaxLength(64)
.HasColumnType("nvarchar(64)");
b.Property<string>("Value")
.IsRequired()
.HasMaxLength(1024)
.HasColumnType("nvarchar(1024)");
b.HasKey("TenantId", "Name");
b.ToTable("AbpTenantConnectionStrings");
});
modelBuilder.Entity("Volo.Abp.AuditLogging.AuditLogAction", b =>
{
b.HasOne("Volo.Abp.AuditLogging.AuditLog", null)
.WithMany("Actions")
.HasForeignKey("AuditLogId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Volo.Abp.AuditLogging.EntityChange", b =>
{
b.HasOne("Volo.Abp.AuditLogging.AuditLog", null)
.WithMany("EntityChanges")
.HasForeignKey("AuditLogId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Volo.Abp.AuditLogging.EntityPropertyChange", b =>
{
b.HasOne("Volo.Abp.AuditLogging.EntityChange", null)
.WithMany("PropertyChanges")
.HasForeignKey("EntityChangeId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Volo.Abp.Identity.IdentityRoleClaim", b =>
{
b.HasOne("Volo.Abp.Identity.IdentityRole", null)
.WithMany("Claims")
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Volo.Abp.Identity.IdentityUserClaim", b =>
{
b.HasOne("Volo.Abp.Identity.IdentityUser", null)
.WithMany("Claims")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Volo.Abp.Identity.IdentityUserLogin", b =>
{
b.HasOne("Volo.Abp.Identity.IdentityUser", null)
.WithMany("Logins")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Volo.Abp.Identity.IdentityUserOrganizationUnit", b =>
{
b.HasOne("Volo.Abp.Identity.OrganizationUnit", null)
.WithMany()
.HasForeignKey("OrganizationUnitId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Volo.Abp.Identity.IdentityUser", null)
.WithMany("OrganizationUnits")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Volo.Abp.Identity.IdentityUserRole", b =>
{
b.HasOne("Volo.Abp.Identity.IdentityRole", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Volo.Abp.Identity.IdentityUser", null)
.WithMany("Roles")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Volo.Abp.Identity.IdentityUserToken", b =>
{
b.HasOne("Volo.Abp.Identity.IdentityUser", null)
.WithMany("Tokens")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Volo.Abp.Identity.OrganizationUnit", b =>
{
b.HasOne("Volo.Abp.Identity.OrganizationUnit", null)
.WithMany()
.HasForeignKey("ParentId");
});
modelBuilder.Entity("Volo.Abp.Identity.OrganizationUnitRole", b =>
{
b.HasOne("Volo.Abp.Identity.OrganizationUnit", null)
.WithMany("Roles")
.HasForeignKey("OrganizationUnitId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Volo.Abp.Identity.IdentityRole", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Volo.Abp.IdentityServer.ApiResources.ApiResourceClaim", b =>
{
b.HasOne("Volo.Abp.IdentityServer.ApiResources.ApiResource", null)
.WithMany("UserClaims")
.HasForeignKey("ApiResourceId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Volo.Abp.IdentityServer.ApiResources.ApiResourceProperty", b =>
{
b.HasOne("Volo.Abp.IdentityServer.ApiResources.ApiResource", null)
.WithMany("Properties")
.HasForeignKey("ApiResourceId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Volo.Abp.IdentityServer.ApiResources.ApiResourceScope", b =>
{
b.HasOne("Volo.Abp.IdentityServer.ApiResources.ApiResource", null)
.WithMany("Scopes")
.HasForeignKey("ApiResourceId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Volo.Abp.IdentityServer.ApiResources.ApiResourceSecret", b =>
{
b.HasOne("Volo.Abp.IdentityServer.ApiResources.ApiResource", null)
.WithMany("Secrets")
.HasForeignKey("ApiResourceId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Volo.Abp.IdentityServer.ApiScopes.ApiScopeClaim", b =>
{
b.HasOne("Volo.Abp.IdentityServer.ApiScopes.ApiScope", null)
.WithMany("UserClaims")
.HasForeignKey("ApiScopeId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Volo.Abp.IdentityServer.ApiScopes.ApiScopeProperty", b =>
{
b.HasOne("Volo.Abp.IdentityServer.ApiScopes.ApiScope", null)
.WithMany("Properties")
.HasForeignKey("ApiScopeId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.ClientClaim", b =>
{
b.HasOne("Volo.Abp.IdentityServer.Clients.Client", null)
.WithMany("Claims")
.HasForeignKey("ClientId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.ClientCorsOrigin", b =>
{
b.HasOne("Volo.Abp.IdentityServer.Clients.Client", null)
.WithMany("AllowedCorsOrigins")
.HasForeignKey("ClientId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.ClientGrantType", b =>
{
b.HasOne("Volo.Abp.IdentityServer.Clients.Client", null)
.WithMany("AllowedGrantTypes")
.HasForeignKey("ClientId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.ClientIdPRestriction", b =>
{
b.HasOne("Volo.Abp.IdentityServer.Clients.Client", null)
.WithMany("IdentityProviderRestrictions")
.HasForeignKey("ClientId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.ClientPostLogoutRedirectUri", b =>
{
b.HasOne("Volo.Abp.IdentityServer.Clients.Client", null)
.WithMany("PostLogoutRedirectUris")
.HasForeignKey("ClientId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.ClientProperty", b =>
{
b.HasOne("Volo.Abp.IdentityServer.Clients.Client", null)
.WithMany("Properties")
.HasForeignKey("ClientId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.ClientRedirectUri", b =>
{
b.HasOne("Volo.Abp.IdentityServer.Clients.Client", null)
.WithMany("RedirectUris")
.HasForeignKey("ClientId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.ClientScope", b =>
{
b.HasOne("Volo.Abp.IdentityServer.Clients.Client", null)
.WithMany("AllowedScopes")
.HasForeignKey("ClientId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.ClientSecret", b =>
{
b.HasOne("Volo.Abp.IdentityServer.Clients.Client", null)
.WithMany("ClientSecrets")
.HasForeignKey("ClientId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Volo.Abp.IdentityServer.IdentityResources.IdentityResourceClaim", b =>
{
b.HasOne("Volo.Abp.IdentityServer.IdentityResources.IdentityResource", null)
.WithMany("UserClaims")
.HasForeignKey("IdentityResourceId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Volo.Abp.IdentityServer.IdentityResources.IdentityResourceProperty", b =>
{
b.HasOne("Volo.Abp.IdentityServer.IdentityResources.IdentityResource", null)
.WithMany("Properties")
.HasForeignKey("IdentityResourceId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Volo.Abp.TenantManagement.TenantConnectionString", b =>
{
b.HasOne("Volo.Abp.TenantManagement.Tenant", null)
.WithMany("ConnectionStrings")
.HasForeignKey("TenantId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Volo.Abp.AuditLogging.AuditLog", b =>
{
b.Navigation("Actions");
b.Navigation("EntityChanges");
});
modelBuilder.Entity("Volo.Abp.AuditLogging.EntityChange", b =>
{
b.Navigation("PropertyChanges");
});
modelBuilder.Entity("Volo.Abp.Identity.IdentityRole", b =>
{
b.Navigation("Claims");
});
modelBuilder.Entity("Volo.Abp.Identity.IdentityUser", b =>
{
b.Navigation("Claims");
b.Navigation("Logins");
b.Navigation("OrganizationUnits");
b.Navigation("Roles");
b.Navigation("Tokens");
});
modelBuilder.Entity("Volo.Abp.Identity.OrganizationUnit", b =>
{
b.Navigation("Roles");
});
modelBuilder.Entity("Volo.Abp.IdentityServer.ApiResources.ApiResource", b =>
{
b.Navigation("Properties");
b.Navigation("Scopes");
b.Navigation("Secrets");
b.Navigation("UserClaims");
});
modelBuilder.Entity("Volo.Abp.IdentityServer.ApiScopes.ApiScope", b =>
{
b.Navigation("Properties");
b.Navigation("UserClaims");
});
modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.Client", b =>
{
b.Navigation("AllowedCorsOrigins");
b.Navigation("AllowedGrantTypes");
b.Navigation("AllowedScopes");
b.Navigation("Claims");
b.Navigation("ClientSecrets");
b.Navigation("IdentityProviderRestrictions");
b.Navigation("PostLogoutRedirectUris");
b.Navigation("Properties");
b.Navigation("RedirectUris");
});
modelBuilder.Entity("Volo.Abp.IdentityServer.IdentityResources.IdentityResource", b =>
{
b.Navigation("Properties");
b.Navigation("UserClaims");
});
modelBuilder.Entity("Volo.Abp.TenantManagement.Tenant", b =>
{
b.Navigation("ConnectionStrings");
});
#pragma warning restore 612, 618
}
}
}
| 38.52255 | 106 | 0.443439 | [
"MIT"
] | 344089386/abp-samples | GrpcDemo/src/GrpcDemo.EntityFrameworkCore.DbMigrations/Migrations/GrpcDemoMigrationsDbContextModelSnapshot.cs | 88,835 | C# |
namespace CommandTab
{
partial class CreateLevelForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.label1 = new System.Windows.Forms.Label();
this.textBoxCount = new System.Windows.Forms.TextBox();
this.btnOK = new System.Windows.Forms.Button();
this.label2 = new System.Windows.Forms.Label();
this.textBoxOffset = new System.Windows.Forms.TextBox();
this.btnCancel = new System.Windows.Forms.Button();
this.checkBoxFirstLvl = new System.Windows.Forms.CheckBox();
this.SuspendLayout();
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(32, 71);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(64, 13);
this.label1.TabIndex = 0;
this.label1.Text = "Level Count";
//
// textBoxCount
//
this.textBoxCount.Location = new System.Drawing.Point(121, 64);
this.textBoxCount.Name = "textBoxCount";
this.textBoxCount.Size = new System.Drawing.Size(100, 20);
this.textBoxCount.TabIndex = 1;
//
// btnOK
//
this.btnOK.Location = new System.Drawing.Point(35, 157);
this.btnOK.Name = "btnOK";
this.btnOK.Size = new System.Drawing.Size(82, 31);
this.btnOK.TabIndex = 2;
this.btnOK.Text = "OK";
this.btnOK.UseVisualStyleBackColor = true;
this.btnOK.Click += new System.EventHandler(this.btnOK_Click);
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(32, 112);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(60, 13);
this.label2.TabIndex = 3;
this.label2.Text = "Offset (mm)";
//
// textBoxOffset
//
this.textBoxOffset.Location = new System.Drawing.Point(121, 112);
this.textBoxOffset.Name = "textBoxOffset";
this.textBoxOffset.Size = new System.Drawing.Size(100, 20);
this.textBoxOffset.TabIndex = 4;
//
// btnCancel
//
this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.btnCancel.Location = new System.Drawing.Point(139, 157);
this.btnCancel.Name = "btnCancel";
this.btnCancel.Size = new System.Drawing.Size(82, 31);
this.btnCancel.TabIndex = 5;
this.btnCancel.Text = "Cancel";
this.btnCancel.UseVisualStyleBackColor = true;
//
// checkBoxFirstLvl
//
this.checkBoxFirstLvl.AutoSize = true;
this.checkBoxFirstLvl.Location = new System.Drawing.Point(35, 32);
this.checkBoxFirstLvl.Name = "checkBoxFirstLvl";
this.checkBoxFirstLvl.Size = new System.Drawing.Size(84, 17);
this.checkBoxFirstLvl.TabIndex = 6;
this.checkBoxFirstLvl.Text = "Fİrst Level ?";
this.checkBoxFirstLvl.UseVisualStyleBackColor = true;
//
// CreateLevelForm
//
this.AcceptButton = this.btnOK;
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.CancelButton = this.btnCancel;
this.ClientSize = new System.Drawing.Size(244, 210);
this.Controls.Add(this.checkBoxFirstLvl);
this.Controls.Add(this.btnCancel);
this.Controls.Add(this.textBoxOffset);
this.Controls.Add(this.label2);
this.Controls.Add(this.btnOK);
this.Controls.Add(this.textBoxCount);
this.Controls.Add(this.label1);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "CreateLevelForm";
this.ShowIcon = false;
this.ShowInTaskbar = false;
this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "Create Multiple Level";
this.TopMost = true;
this.Load += new System.EventHandler(this.CreateLevelForm_Load);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Label label1;
private System.Windows.Forms.TextBox textBoxCount;
private System.Windows.Forms.Button btnOK;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.TextBox textBoxOffset;
private System.Windows.Forms.Button btnCancel;
private System.Windows.Forms.CheckBox checkBoxFirstLvl;
}
} | 41.830986 | 107 | 0.574242 | [
"MIT"
] | lSelectral/SELECTRA_REVIT | CommandTab/CommandTab/Commands/LevelUtils/CreateLevel/CreateLevelForm.Designer.cs | 5,943 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Http.Controllers;
namespace Microsoft.Bot.Connector.SkillAuthentication
{
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)]
public class SkillBotAuthentication : BotAuthentication
{
/// <summary>
/// Type which implements AuthenticationConfiguration to allow validation for Skills
/// </summary>
public Type AuthenticationConfigurationProviderType { get; set; }
private static HttpClient _httpClient = new HttpClient();
public override async Task OnActionExecutingAsync(HttpActionContext actionContext, CancellationToken cancellationToken)
{
var authorizationHeader = actionContext.Request.Headers.Authorization;
if (authorizationHeader != null && SkillValidation.IsSkillToken(authorizationHeader.ToString()))
{
var activities = base.GetActivities(actionContext);
if (activities.Any())
{
var authConfiguration = this.GetAuthenticationConfiguration();
var credentialProvider = this.GetCredentialProvider();
try
{
foreach (var activity in activities)
{
var claimsIdentity = await JwtTokenValidation.AuthenticateRequest(activity, authorizationHeader.ToString(), credentialProvider, authConfiguration, _httpClient).ConfigureAwait(false);
// this is done in JwtTokenValidation.AuthenticateRequest, but the oauthScope is not set so we update it here
MicrosoftAppCredentials.TrustServiceUrl(activity.ServiceUrl, oauthScope: JwtTokenValidation.GetAppIdFromClaims(claimsIdentity.Claims));
}
}
catch (UnauthorizedAccessException)
{
actionContext.Response = BotAuthenticator.GenerateUnauthorizedResponse(actionContext.Request, "BotAuthenticator failed to authenticate incoming request!");
return;
}
await base.ContinueOnActionExecutingAsync(actionContext, cancellationToken);
return;
}
}
await base.OnActionExecutingAsync(actionContext, cancellationToken);
}
protected AuthenticationConfiguration GetAuthenticationConfiguration()
{
AuthenticationConfiguration authenticationConfigurationProvider = null;
if (AuthenticationConfigurationProviderType != null)
{
authenticationConfigurationProvider = Activator.CreateInstance(AuthenticationConfigurationProviderType) as AuthenticationConfiguration;
if (authenticationConfigurationProvider == null)
throw new ArgumentNullException($"The AuthenticationConfigurationProviderType {AuthenticationConfigurationProviderType.Name} couldn't be instantiated with no params or doesn't implement AuthenticationConfiguration");
}
return authenticationConfigurationProvider ?? new SkillAuthenticationConfiguration();
}
}
}
| 49.842857 | 236 | 0.654915 | [
"MIT"
] | Bhaskers-Blu-Org2/BotBuilder-V3 | CSharp/Library/Microsoft.Bot.Connector.NetFramework/SkillBotAuthentication.cs | 3,491 | C# |
DateTime currentDateTime = DateTime.Now;
Console.WriteLine($"Current date and time is {currentDateTime}");
Random random = new Random();
int randomNumber = random.Next(1,100);
DateTime newDateTime = currentDateTime.AddDays(randomNumber);
Console.WriteLine($"Updated date and time is {newDateTime} after adding {randomNumber} days to {currentDateTime}"); | 50.714286 | 115 | 0.785915 | [
"MIT"
] | Mums-Who-Code/Lavanya.C.Sharp | Lavanya.C.Sharp/Set1Task5/Program.cs | 357 | C# |
using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using System.Windows.Forms.VisualStyles;
namespace VisualControl
{
[DesignerCategory("Code")]
public sealed class AeroBasicMinimizeButton : Control
{
public bool ParentMinimizeOnClick { get; set; } = true;
Boolean mouseDown = false;
Boolean enterDown = false;
Boolean mouseEnter = false;
protected override Size DefaultSize => new Size(32, 18);
protected override void OnClick(EventArgs e)
{
base.OnClick(e);
try
{
if (ParentMinimizeOnClick)
FindForm().WindowState = FormWindowState.Minimized;
}
catch { }
}
protected override void OnParentChanged(EventArgs e)
{
if (fOld != null)
try
{
fOld.SizeChanged -= AeroBasicMinimizeButton_SizeChanged;
}
catch { }
base.OnParentChanged(e);
FindForm().SizeChanged += AeroBasicMinimizeButton_SizeChanged; ;
fOld = FindForm();
}
private void AeroBasicMinimizeButton_SizeChanged(object sender, EventArgs e)
{
Invalidate();
}
Form fOld;
protected override void OnMouseEnter(EventArgs e)
{
base.OnMouseEnter(e);
mouseEnter = true;
Invalidate();
}
protected override void OnMouseLeave(EventArgs e)
{
base.OnMouseLeave(e);
mouseEnter = false;
Invalidate();
}
protected override void OnMouseDown(MouseEventArgs e)
{
base.OnMouseDown(e);
mouseDown = true;
Invalidate();
}
protected override void OnMouseUp(MouseEventArgs e)
{
base.OnMouseUp(e);
mouseDown = false;
Invalidate();
}
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
if (e.KeyCode == Keys.Enter)
{
enterDown = true;
Invalidate();
}
}
protected override void OnKeyUp(KeyEventArgs e)
{
base.OnKeyUp(e);
if (e.KeyCode == Keys.Enter)
{
enterDown = false;
Invalidate();
}
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
VisualStyleRenderer renderer;
if (!Enabled)
{
renderer = new VisualStyleRenderer(VisualStyleElement.Window.MinButton.Disabled);
renderer.DrawBackground(e.Graphics, e.ClipRectangle);
return;
}
if (mouseDown || enterDown)
{
renderer = new VisualStyleRenderer(VisualStyleElement.Window.MinButton.Pressed);
renderer.DrawBackground(e.Graphics, e.ClipRectangle);
}
else if (mouseEnter)
{
renderer = new VisualStyleRenderer(VisualStyleElement.Window.MinButton.Hot);
renderer.DrawBackground(e.Graphics, e.ClipRectangle);
}
else
{
renderer = new VisualStyleRenderer(VisualStyleElement.Window.MinButton.Normal);
renderer.DrawBackground(e.Graphics, e.ClipRectangle);
}
}
}
}
| 29.436508 | 98 | 0.508223 | [
"MIT"
] | ManuelSoftwareDev/AeroVisualStyle | VisualControl/AeroBasic/AeroBasicMinimizeButton.cs | 3,711 | C# |
using System;
using System.Collections.Generic;
using Octopus.Data.Model;
using Octopus.Server.Extensibility.HostServices.Diagnostics;
using Sashimi.Server.Contracts;
using Sashimi.Server.Contracts.Accounts;
using Sashimi.Server.Contracts.ServiceMessages;
namespace Sashimi.Azure.Accounts
{
class AzureServicePrincipalAccountServiceMessageHandler : ICreateAccountDetailsServiceMessageHandler
{
public string AuditEntryDescription => "Azure Service Principal account";
public string ServiceMessageName => CreateAzureAccountServiceMessagePropertyNames.CreateAccountName;
public IEnumerable<ScriptFunctionRegistration> ScriptFunctionRegistrations { get; } = new List<ScriptFunctionRegistration>
{
new("OctopusAzureServicePrincipalAccount",
"Creates a new Azure Service Principal Account.",
CreateAzureAccountServiceMessagePropertyNames.CreateAccountName,
new Dictionary<string, FunctionParameter>
{
{ CreateAzureAccountServiceMessagePropertyNames.NameAttribute, new FunctionParameter(ParameterType.String) },
{ CreateAzureAccountServiceMessagePropertyNames.SubscriptionAttribute, new FunctionParameter(ParameterType.String) },
{ CreateAzureAccountServiceMessagePropertyNames.ServicePrincipal.ApplicationAttribute, new FunctionParameter(ParameterType.String) },
{ CreateAzureAccountServiceMessagePropertyNames.ServicePrincipal.TenantAttribute, new FunctionParameter(ParameterType.String) },
{ CreateAzureAccountServiceMessagePropertyNames.ServicePrincipal.PasswordAttribute, new FunctionParameter(ParameterType.String) },
{ CreateAzureAccountServiceMessagePropertyNames.ServicePrincipal.EnvironmentAttribute, new FunctionParameter(ParameterType.String, CreateAzureAccountServiceMessagePropertyNames.ServicePrincipal.EnvironmentAttribute) },
{ CreateAzureAccountServiceMessagePropertyNames.ServicePrincipal.BaseUriAttribute, new FunctionParameter(ParameterType.String, CreateAzureAccountServiceMessagePropertyNames.ServicePrincipal.EnvironmentAttribute) },
{ CreateAzureAccountServiceMessagePropertyNames.ServicePrincipal.ResourceManagementBaseUriAttribute, new FunctionParameter(ParameterType.String, CreateAzureAccountServiceMessagePropertyNames.ServicePrincipal.EnvironmentAttribute) },
{ CreateAzureAccountServiceMessagePropertyNames.UpdateIfExistingAttribute, new FunctionParameter(ParameterType.Bool) }
})
};
public AccountDetails CreateAccountDetails(IDictionary<string, string> properties, ITaskLog taskLog)
{
properties.TryGetValue(CreateAzureAccountServiceMessagePropertyNames.SubscriptionAttribute,
out var subscriptionNumber);
properties.TryGetValue(CreateAzureAccountServiceMessagePropertyNames.ServicePrincipal.ApplicationAttribute,
out var clientId);
properties.TryGetValue(CreateAzureAccountServiceMessagePropertyNames.ServicePrincipal.PasswordAttribute,
out var password);
properties.TryGetValue(CreateAzureAccountServiceMessagePropertyNames.ServicePrincipal.TenantAttribute,
out var tenantId);
var details = new AzureServicePrincipalAccountDetails
{
SubscriptionNumber = subscriptionNumber,
ClientId = clientId,
Password = password.ToSensitiveString(),
TenantId = tenantId
};
if (properties.TryGetValue(CreateAzureAccountServiceMessagePropertyNames.ServicePrincipal.EnvironmentAttribute, out var environment) && !string.IsNullOrWhiteSpace(environment))
{
properties.TryGetValue(CreateAzureAccountServiceMessagePropertyNames.ServicePrincipal.BaseUriAttribute,
out var baseUri);
properties.TryGetValue(CreateAzureAccountServiceMessagePropertyNames.ServicePrincipal.ResourceManagementBaseUriAttribute,
out var resourceManagementBaseUri);
details.AzureEnvironment = environment;
details.ActiveDirectoryEndpointBaseUri = baseUri;
details.ResourceManagementEndpointBaseUri = resourceManagementBaseUri;
}
else
{
details.AzureEnvironment = string.Empty;
details.ActiveDirectoryEndpointBaseUri = string.Empty;
details.ResourceManagementEndpointBaseUri = string.Empty;
}
return details;
}
internal static class CreateAzureAccountServiceMessagePropertyNames
{
public const string CreateAccountName = "create-azureaccount";
public const string NameAttribute = "name";
public const string UpdateIfExistingAttribute = "updateIfExisting";
public const string SubscriptionAttribute = "azureSubscriptionId";
public static class ServicePrincipal
{
public const string ApplicationAttribute = "azureApplicationId";
public const string TenantAttribute = "azureTenantId";
public const string PasswordAttribute = "azurePassword";
public const string EnvironmentAttribute = "azureEnvironment";
public const string BaseUriAttribute = "azureBaseUri";
public const string ResourceManagementBaseUriAttribute = "azureResourceManagementBaseUri";
}
}
}
} | 61.457447 | 252 | 0.704691 | [
"Apache-2.0"
] | OctopusDeploy/Sashimi | source/Sashimi.Azure.Accounts/AzureServicePrincipalAccountServiceMessageHandler.cs | 5,779 | C# |
using System.Collections.Generic;
using System.ComponentModel;
using Microsoft.VisualStudio.Utilities;
namespace Microsoft.VisualStudio.UI.Text.Commanding.Implementation
{
public interface ICommandHandlerMetadata : IOrderable, IContentTypeMetadata
{
[DefaultValue(null)] // [TextViewRole] is optional
IEnumerable<string> TextViewRoles { get; }
}
}
| 27.071429 | 79 | 0.759894 | [
"MIT"
] | AmadeusW/vs-editor-api | src/Editor/Text/Impl/Commanding/ICommandHandlerMetadata.cs | 381 | C# |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure;
using Microsoft.AzureStack.Management.Models;
namespace Microsoft.AzureStack.Management
{
/// <summary>
/// Managed locations operations for admin. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/XXXX.aspx for
/// more information)
/// </summary>
public partial interface IManagedLocationOperations
{
/// <summary>
/// Create / Update the location.
/// </summary>
/// <param name='parameters'>
/// Location properties
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The location update result.
/// </returns>
Task<ManagedLocationCreateOrUpdateResult> CreateOrUpdateAsync(ManagedLocationCreateOrUpdateParameters parameters, CancellationToken cancellationToken);
/// <summary>
/// Delete a location.
/// </summary>
/// <param name='locationName'>
/// Name of location to delete.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
Task<AzureOperationResponse> DeleteAsync(string locationName, CancellationToken cancellationToken);
/// <summary>
/// Get the location.
/// </summary>
/// <param name='locationName'>
/// The location name.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Location get result.
/// </returns>
Task<ManagedLocationGetResult> GetAsync(string locationName, CancellationToken cancellationToken);
/// <summary>
/// Get locations under subscription.
/// </summary>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The location list result.
/// </returns>
Task<ManagedLocationListResult> ListAsync(CancellationToken cancellationToken);
/// <summary>
/// Gets locations with the next link.
/// </summary>
/// <param name='nextLink'>
/// The url to get the next set of results.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The location list result.
/// </returns>
Task<ManagedLocationListResult> ListNextAsync(string nextLink, CancellationToken cancellationToken);
}
}
| 33.971963 | 159 | 0.607703 | [
"MIT"
] | AzureDataBox/azure-powershell | src/StackAdmin/AzureStackAdmin/Commands.AzureStackAdmin/Generated/IManagedLocationOperations.cs | 3,635 | C# |
//======= Copyright (c) Valve Corporation, All rights reserved. ===============
//
// Purpose: Handles all the teleport logic
//
//=============================================================================
using UnityEngine;
using UnityEngine.Events;
using System.Collections;
namespace Valve.VR.InteractionSystem
{
//-------------------------------------------------------------------------
public class Teleport : MonoBehaviour
{
[SteamVR_DefaultAction("Teleport", "default")]
public SteamVR_Action_Boolean teleportAction;
public LayerMask traceLayerMask;
public LayerMask floorFixupTraceLayerMask;
public float floorFixupMaximumTraceDistance = 1.0f;
public Material areaVisibleMaterial;
public Material areaLockedMaterial;
public Material areaHighlightedMaterial;
public Material pointVisibleMaterial;
public Material pointLockedMaterial;
public Material pointHighlightedMaterial;
public Transform destinationReticleTransform;
public Transform invalidReticleTransform;
public GameObject playAreaPreviewCorner;
public GameObject playAreaPreviewSide;
public Color pointerValidColor;
public Color pointerInvalidColor;
public Color pointerLockedColor;
public bool showPlayAreaMarker = true;
public float teleportFadeTime = 0.1f;
public float meshFadeTime = 0.2f;
public float arcDistance = 10.0f;
[Header( "Effects" )]
public Transform onActivateObjectTransform;
public Transform onDeactivateObjectTransform;
public float activateObjectTime = 1.0f;
public float deactivateObjectTime = 1.0f;
[Header( "Audio Sources" )]
public AudioSource pointerAudioSource;
public AudioSource loopingAudioSource;
public AudioSource headAudioSource;
public AudioSource reticleAudioSource;
[Header( "Sounds" )]
public AudioClip teleportSound;
public AudioClip pointerStartSound;
public AudioClip pointerLoopSound;
public AudioClip pointerStopSound;
public AudioClip goodHighlightSound;
public AudioClip badHighlightSound;
[Header( "Debug" )]
public bool debugFloor = false;
public bool showOffsetReticle = false;
public Transform offsetReticleTransform;
public MeshRenderer floorDebugSphere;
public LineRenderer floorDebugLine;
public GameObject specificTeleportMarker;
private LineRenderer pointerLineRenderer;
private GameObject teleportPointerObject;
private Transform pointerStartTransform;
private Hand pointerHand = null;
private Player player = null;
private TeleportArc teleportArc = null;
private bool visible = false;
private TeleportMarkerBase[] teleportMarkers;
private TeleportMarkerBase pointedAtTeleportMarker;
private TeleportMarkerBase teleportingToMarker;
private Vector3 pointedAtPosition;
private Vector3 prevPointedAtPosition;
private bool teleporting = false;
private float currentFadeTime = 0.0f;
private float meshAlphaPercent = 1.0f;
private float pointerShowStartTime = 0.0f;
private float pointerHideStartTime = 0.0f;
private bool meshFading = false;
private float fullTintAlpha;
private float invalidReticleMinScale = 0.2f;
private float invalidReticleMaxScale = 1.0f;
private float invalidReticleMinScaleDistance = 0.4f;
private float invalidReticleMaxScaleDistance = 2.0f;
private Vector3 invalidReticleScale = Vector3.one;
private Quaternion invalidReticleTargetRotation = Quaternion.identity;
private Transform playAreaPreviewTransform;
private Transform[] playAreaPreviewCorners;
private Transform[] playAreaPreviewSides;
private float loopingAudioMaxVolume = 0.0f;
private Coroutine hintCoroutine = null;
private bool originalHoverLockState = false;
private Interactable originalHoveringInteractable = null;
private AllowTeleportWhileAttachedToHand allowTeleportWhileAttached = null;
private Vector3 startingFeetOffset = Vector3.zero;
private bool movedFeetFarEnough = false;
SteamVR_Events.Action chaperoneInfoInitializedAction;
// Events
public static SteamVR_Events.Event< float > ChangeScene = new SteamVR_Events.Event< float >();
public static SteamVR_Events.Action< float > ChangeSceneAction( UnityAction< float > action ) { return new SteamVR_Events.Action< float >( ChangeScene, action ); }
public static SteamVR_Events.Event< TeleportMarkerBase > Player = new SteamVR_Events.Event< TeleportMarkerBase >();
public static SteamVR_Events.Action< TeleportMarkerBase > PlayerAction( UnityAction< TeleportMarkerBase > action ) { return new SteamVR_Events.Action< TeleportMarkerBase >( Player, action ); }
public static SteamVR_Events.Event< TeleportMarkerBase > PlayerPre = new SteamVR_Events.Event< TeleportMarkerBase >();
public static SteamVR_Events.Action< TeleportMarkerBase > PlayerPreAction( UnityAction< TeleportMarkerBase > action ) { return new SteamVR_Events.Action< TeleportMarkerBase >( PlayerPre, action ); }
//-------------------------------------------------
private static Teleport _instance;
public static Teleport instance
{
get
{
if ( _instance == null )
{
_instance = GameObject.FindObjectOfType<Teleport>();
}
return _instance;
}
}
//-------------------------------------------------
void Awake()
{
_instance = this;
chaperoneInfoInitializedAction = ChaperoneInfo.InitializedAction( OnChaperoneInfoInitialized );
pointerLineRenderer = GetComponentInChildren<LineRenderer>();
teleportPointerObject = pointerLineRenderer.gameObject;
int tintColorID = Shader.PropertyToID( "_TintColor" );
fullTintAlpha = pointVisibleMaterial.GetColor( tintColorID ).a;
teleportArc = GetComponent<TeleportArc>();
teleportArc.traceLayerMask = traceLayerMask;
loopingAudioMaxVolume = loopingAudioSource.volume;
playAreaPreviewCorner.SetActive( false );
playAreaPreviewSide.SetActive( false );
float invalidReticleStartingScale = invalidReticleTransform.localScale.x;
invalidReticleMinScale *= invalidReticleStartingScale;
invalidReticleMaxScale *= invalidReticleStartingScale;
}
//-------------------------------------------------
void Start()
{
specificTeleportMarker.SetActive(true);
teleportMarkers = GameObject.FindObjectsOfType<TeleportMarkerBase>();
HidePointer();
player = InteractionSystem.Player.instance;
if ( player == null )
{
Debug.LogError( "Teleport: No Player instance found in map." );
Destroy( this.gameObject );
return;
}
CheckForSpawnPoint();
Invoke( "ShowTeleportHint", 5.0f );
}
//-------------------------------------------------
void OnEnable()
{
chaperoneInfoInitializedAction.enabled = true;
OnChaperoneInfoInitialized(); // In case it's already initialized
}
//-------------------------------------------------
void OnDisable()
{
chaperoneInfoInitializedAction.enabled = false;
HidePointer();
}
//-------------------------------------------------
private void CheckForSpawnPoint()
{
foreach ( TeleportMarkerBase teleportMarker in teleportMarkers )
{
TeleportPoint teleportPoint = teleportMarker as TeleportPoint;
if ( teleportPoint && teleportPoint.playerSpawnPoint )
{
teleportingToMarker = teleportMarker;
TeleportPlayer();
break;
}
}
}
//-------------------------------------------------
public void HideTeleportPointer()
{
if ( pointerHand != null )
{
HidePointer();
}
}
//-------------------------------------------------
void Update()
{
Hand oldPointerHand = pointerHand;
Hand newPointerHand = null;
foreach ( Hand hand in player.hands )
{
if ( visible )
{
if ( WasTeleportButtonReleased( hand ) )
{
if ( pointerHand == hand ) //This is the pointer hand
{
TryTeleportPlayer();
}
}
}
if ( WasTeleportButtonPressed( hand ) )
{
newPointerHand = hand;
}
}
//If something is attached to the hand that is preventing teleport
if ( allowTeleportWhileAttached && !allowTeleportWhileAttached.teleportAllowed )
{
HidePointer();
}
else
{
if ( !visible && newPointerHand != null )
{
//Begin showing the pointer
ShowPointer( newPointerHand, oldPointerHand );
}
else if ( visible )
{
if ( newPointerHand == null && !IsTeleportButtonDown( pointerHand ) )
{
//Hide the pointer
HidePointer();
}
else if ( newPointerHand != null )
{
//Move the pointer to a new hand
ShowPointer( newPointerHand, oldPointerHand );
}
}
}
if ( visible )
{
UpdatePointer();
if ( meshFading )
{
UpdateTeleportColors();
}
if ( onActivateObjectTransform.gameObject.activeSelf && Time.time - pointerShowStartTime > activateObjectTime )
{
onActivateObjectTransform.gameObject.SetActive( false );
}
}
else
{
if ( onDeactivateObjectTransform.gameObject.activeSelf && Time.time - pointerHideStartTime > deactivateObjectTime )
{
onDeactivateObjectTransform.gameObject.SetActive( false );
}
}
}
//-------------------------------------------------
private void UpdatePointer()
{
Vector3 pointerStart = pointerStartTransform.position;
Vector3 pointerEnd;
Vector3 pointerDir = pointerStartTransform.forward;
bool hitSomething = false;
bool showPlayAreaPreview = false;
Vector3 playerFeetOffset = player.trackingOriginTransform.position - player.feetPositionGuess;
Vector3 arcVelocity = pointerDir * arcDistance;
TeleportMarkerBase hitTeleportMarker = null;
//Check pointer angle
float dotUp = Vector3.Dot( pointerDir, Vector3.up );
float dotForward = Vector3.Dot( pointerDir, player.hmdTransform.forward );
bool pointerAtBadAngle = false;
if ( ( dotForward > 0 && dotUp > 0.75f ) || ( dotForward < 0.0f && dotUp > 0.5f ) )
{
pointerAtBadAngle = true;
}
//Trace to see if the pointer hit anything
RaycastHit hitInfo;
teleportArc.SetArcData( pointerStart, arcVelocity, true, pointerAtBadAngle );
if ( teleportArc.DrawArc( out hitInfo ) )
{
hitSomething = true;
hitTeleportMarker = hitInfo.collider.GetComponentInParent<TeleportMarkerBase>();
}
if ( pointerAtBadAngle )
{
hitTeleportMarker = null;
}
HighlightSelected( hitTeleportMarker );
if ( hitTeleportMarker != null ) //Hit a teleport marker
{
if ( hitTeleportMarker.locked )
{
teleportArc.SetColor( pointerLockedColor );
#if (UNITY_5_4)
pointerLineRenderer.SetColors( pointerLockedColor, pointerLockedColor );
#else
pointerLineRenderer.startColor = pointerLockedColor;
pointerLineRenderer.endColor = pointerLockedColor;
#endif
destinationReticleTransform.gameObject.SetActive( false );
}
else
{
teleportArc.SetColor( pointerValidColor );
#if (UNITY_5_4)
pointerLineRenderer.SetColors( pointerValidColor, pointerValidColor );
#else
pointerLineRenderer.startColor = pointerValidColor;
pointerLineRenderer.endColor = pointerValidColor;
#endif
destinationReticleTransform.gameObject.SetActive( hitTeleportMarker.showReticle );
}
offsetReticleTransform.gameObject.SetActive( true );
invalidReticleTransform.gameObject.SetActive( false );
pointedAtTeleportMarker = hitTeleportMarker;
pointedAtPosition = hitInfo.point;
if ( showPlayAreaMarker )
{
//Show the play area marker if this is a teleport area
TeleportArea teleportArea = pointedAtTeleportMarker as TeleportArea;
if ( teleportArea != null && !teleportArea.locked && playAreaPreviewTransform != null )
{
Vector3 offsetToUse = playerFeetOffset;
//Adjust the actual offset to prevent the play area marker from moving too much
if ( !movedFeetFarEnough )
{
float distanceFromStartingOffset = Vector3.Distance( playerFeetOffset, startingFeetOffset );
if ( distanceFromStartingOffset < 0.1f )
{
offsetToUse = startingFeetOffset;
}
else if ( distanceFromStartingOffset < 0.4f )
{
offsetToUse = Vector3.Lerp( startingFeetOffset, playerFeetOffset, ( distanceFromStartingOffset - 0.1f ) / 0.3f );
}
else
{
movedFeetFarEnough = true;
}
}
playAreaPreviewTransform.position = pointedAtPosition + offsetToUse;
showPlayAreaPreview = true;
}
}
pointerEnd = hitInfo.point;
}
else //Hit neither
{
destinationReticleTransform.gameObject.SetActive( false );
offsetReticleTransform.gameObject.SetActive( false );
teleportArc.SetColor( pointerInvalidColor );
#if (UNITY_5_4)
pointerLineRenderer.SetColors( pointerInvalidColor, pointerInvalidColor );
#else
pointerLineRenderer.startColor = pointerInvalidColor;
pointerLineRenderer.endColor = pointerInvalidColor;
#endif
invalidReticleTransform.gameObject.SetActive( !pointerAtBadAngle );
//Orient the invalid reticle to the normal of the trace hit point
Vector3 normalToUse = hitInfo.normal;
float angle = Vector3.Angle( hitInfo.normal, Vector3.up );
if ( angle < 15.0f )
{
normalToUse = Vector3.up;
}
invalidReticleTargetRotation = Quaternion.FromToRotation( Vector3.up, normalToUse );
invalidReticleTransform.rotation = Quaternion.Slerp( invalidReticleTransform.rotation, invalidReticleTargetRotation, 0.1f );
//Scale the invalid reticle based on the distance from the player
float distanceFromPlayer = Vector3.Distance( hitInfo.point, player.hmdTransform.position );
float invalidReticleCurrentScale = Util.RemapNumberClamped( distanceFromPlayer, invalidReticleMinScaleDistance, invalidReticleMaxScaleDistance, invalidReticleMinScale, invalidReticleMaxScale );
invalidReticleScale.x = invalidReticleCurrentScale;
invalidReticleScale.y = invalidReticleCurrentScale;
invalidReticleScale.z = invalidReticleCurrentScale;
invalidReticleTransform.transform.localScale = invalidReticleScale;
pointedAtTeleportMarker = null;
if ( hitSomething )
{
pointerEnd = hitInfo.point;
}
else
{
pointerEnd = teleportArc.GetArcPositionAtTime( teleportArc.arcDuration );
}
//Debug floor
if ( debugFloor )
{
floorDebugSphere.gameObject.SetActive( false );
floorDebugLine.gameObject.SetActive( false );
}
}
if ( playAreaPreviewTransform != null )
{
playAreaPreviewTransform.gameObject.SetActive( showPlayAreaPreview );
}
if ( !showOffsetReticle )
{
offsetReticleTransform.gameObject.SetActive( false );
}
destinationReticleTransform.position = pointedAtPosition;
invalidReticleTransform.position = pointerEnd;
onActivateObjectTransform.position = pointerEnd;
onDeactivateObjectTransform.position = pointerEnd;
offsetReticleTransform.position = pointerEnd - playerFeetOffset;
reticleAudioSource.transform.position = pointedAtPosition;
pointerLineRenderer.SetPosition( 0, pointerStart );
pointerLineRenderer.SetPosition( 1, pointerEnd );
}
//-------------------------------------------------
void FixedUpdate()
{
if ( !visible )
{
return;
}
if ( debugFloor )
{
//Debug floor
TeleportArea teleportArea = pointedAtTeleportMarker as TeleportArea;
if ( teleportArea != null )
{
if ( floorFixupMaximumTraceDistance > 0.0f )
{
floorDebugSphere.gameObject.SetActive( true );
floorDebugLine.gameObject.SetActive( true );
RaycastHit raycastHit;
Vector3 traceDir = Vector3.down;
traceDir.x = 0.01f;
if ( Physics.Raycast( pointedAtPosition + 0.05f * traceDir, traceDir, out raycastHit, floorFixupMaximumTraceDistance, floorFixupTraceLayerMask ) )
{
floorDebugSphere.transform.position = raycastHit.point;
floorDebugSphere.material.color = Color.green;
#if (UNITY_5_4)
floorDebugLine.SetColors( Color.green, Color.green );
#else
floorDebugLine.startColor = Color.green;
floorDebugLine.endColor = Color.green;
#endif
floorDebugLine.SetPosition( 0, pointedAtPosition );
floorDebugLine.SetPosition( 1, raycastHit.point );
}
else
{
Vector3 rayEnd = pointedAtPosition + ( traceDir * floorFixupMaximumTraceDistance );
floorDebugSphere.transform.position = rayEnd;
floorDebugSphere.material.color = Color.red;
#if (UNITY_5_4)
floorDebugLine.SetColors( Color.red, Color.red );
#else
floorDebugLine.startColor = Color.red;
floorDebugLine.endColor = Color.red;
#endif
floorDebugLine.SetPosition( 0, pointedAtPosition );
floorDebugLine.SetPosition( 1, rayEnd );
}
}
}
}
}
//-------------------------------------------------
private void OnChaperoneInfoInitialized()
{
ChaperoneInfo chaperone = ChaperoneInfo.instance;
if ( chaperone.initialized && chaperone.roomscale )
{
//Set up the render model for the play area bounds
if ( playAreaPreviewTransform == null )
{
playAreaPreviewTransform = new GameObject( "PlayAreaPreviewTransform" ).transform;
playAreaPreviewTransform.parent = transform;
Util.ResetTransform( playAreaPreviewTransform );
playAreaPreviewCorner.SetActive( true );
playAreaPreviewCorners = new Transform[4];
playAreaPreviewCorners[0] = playAreaPreviewCorner.transform;
playAreaPreviewCorners[1] = Instantiate( playAreaPreviewCorners[0] );
playAreaPreviewCorners[2] = Instantiate( playAreaPreviewCorners[0] );
playAreaPreviewCorners[3] = Instantiate( playAreaPreviewCorners[0] );
playAreaPreviewCorners[0].transform.parent = playAreaPreviewTransform;
playAreaPreviewCorners[1].transform.parent = playAreaPreviewTransform;
playAreaPreviewCorners[2].transform.parent = playAreaPreviewTransform;
playAreaPreviewCorners[3].transform.parent = playAreaPreviewTransform;
playAreaPreviewSide.SetActive( true );
playAreaPreviewSides = new Transform[4];
playAreaPreviewSides[0] = playAreaPreviewSide.transform;
playAreaPreviewSides[1] = Instantiate( playAreaPreviewSides[0] );
playAreaPreviewSides[2] = Instantiate( playAreaPreviewSides[0] );
playAreaPreviewSides[3] = Instantiate( playAreaPreviewSides[0] );
playAreaPreviewSides[0].transform.parent = playAreaPreviewTransform;
playAreaPreviewSides[1].transform.parent = playAreaPreviewTransform;
playAreaPreviewSides[2].transform.parent = playAreaPreviewTransform;
playAreaPreviewSides[3].transform.parent = playAreaPreviewTransform;
}
float x = chaperone.playAreaSizeX;
float z = chaperone.playAreaSizeZ;
playAreaPreviewSides[0].localPosition = new Vector3( 0.0f, 0.0f, 0.5f * z - 0.25f );
playAreaPreviewSides[1].localPosition = new Vector3( 0.0f, 0.0f, -0.5f * z + 0.25f );
playAreaPreviewSides[2].localPosition = new Vector3( 0.5f * x - 0.25f, 0.0f, 0.0f );
playAreaPreviewSides[3].localPosition = new Vector3( -0.5f * x + 0.25f, 0.0f, 0.0f );
playAreaPreviewSides[0].localScale = new Vector3( x - 0.5f, 1.0f, 1.0f );
playAreaPreviewSides[1].localScale = new Vector3( x - 0.5f, 1.0f, 1.0f );
playAreaPreviewSides[2].localScale = new Vector3( z - 0.5f, 1.0f, 1.0f );
playAreaPreviewSides[3].localScale = new Vector3( z - 0.5f, 1.0f, 1.0f );
playAreaPreviewSides[0].localRotation = Quaternion.Euler( 0.0f, 0.0f, 0.0f );
playAreaPreviewSides[1].localRotation = Quaternion.Euler( 0.0f, 180.0f, 0.0f );
playAreaPreviewSides[2].localRotation = Quaternion.Euler( 0.0f, 90.0f, 0.0f );
playAreaPreviewSides[3].localRotation = Quaternion.Euler( 0.0f, 270.0f, 0.0f );
playAreaPreviewCorners[0].localPosition = new Vector3( 0.5f * x - 0.25f, 0.0f, 0.5f * z - 0.25f );
playAreaPreviewCorners[1].localPosition = new Vector3( 0.5f * x - 0.25f, 0.0f, -0.5f * z + 0.25f );
playAreaPreviewCorners[2].localPosition = new Vector3( -0.5f * x + 0.25f, 0.0f, -0.5f * z + 0.25f );
playAreaPreviewCorners[3].localPosition = new Vector3( -0.5f * x + 0.25f, 0.0f, 0.5f * z - 0.25f );
playAreaPreviewCorners[0].localRotation = Quaternion.Euler( 0.0f, 0.0f, 0.0f );
playAreaPreviewCorners[1].localRotation = Quaternion.Euler( 0.0f, 90.0f, 0.0f );
playAreaPreviewCorners[2].localRotation = Quaternion.Euler( 0.0f, 180.0f, 0.0f );
playAreaPreviewCorners[3].localRotation = Quaternion.Euler( 0.0f, 270.0f, 0.0f );
playAreaPreviewTransform.gameObject.SetActive( false );
}
}
//-------------------------------------------------
private void HidePointer()
{
if ( visible )
{
pointerHideStartTime = Time.time;
}
visible = false;
if ( pointerHand )
{
if ( ShouldOverrideHoverLock() )
{
//Restore the original hovering interactable on the hand
if ( originalHoverLockState == true )
{
pointerHand.HoverLock( originalHoveringInteractable );
}
else
{
pointerHand.HoverUnlock( null );
}
}
//Stop looping sound
loopingAudioSource.Stop();
PlayAudioClip( pointerAudioSource, pointerStopSound );
}
teleportPointerObject.SetActive( false );
teleportArc.Hide();
specificTeleportMarker.SetActive(true);
teleportMarkers = GameObject.FindObjectsOfType<TeleportMarkerBase>();
foreach ( TeleportMarkerBase teleportMarker in teleportMarkers )
{
if ( teleportMarker != null && teleportMarker.markerActive && teleportMarker.gameObject != null )
{
teleportMarker.gameObject.SetActive( false );
}
}
destinationReticleTransform.gameObject.SetActive( false );
invalidReticleTransform.gameObject.SetActive( false );
offsetReticleTransform.gameObject.SetActive( false );
if ( playAreaPreviewTransform != null )
{
playAreaPreviewTransform.gameObject.SetActive( false );
}
if ( onActivateObjectTransform.gameObject.activeSelf )
{
onActivateObjectTransform.gameObject.SetActive( false );
}
onDeactivateObjectTransform.gameObject.SetActive( true );
pointerHand = null;
}
//-------------------------------------------------
private void ShowPointer( Hand newPointerHand, Hand oldPointerHand )
{
if ( !visible )
{
pointedAtTeleportMarker = null;
pointerShowStartTime = Time.time;
visible = true;
meshFading = true;
teleportPointerObject.SetActive( false );
teleportArc.Show();
foreach ( TeleportMarkerBase teleportMarker in teleportMarkers )
{
if ( teleportMarker.markerActive && teleportMarker.ShouldActivate( player.feetPositionGuess ) )
{
teleportMarker.gameObject.SetActive( true );
teleportMarker.Highlight( false );
}
}
startingFeetOffset = player.trackingOriginTransform.position - player.feetPositionGuess;
movedFeetFarEnough = false;
if ( onDeactivateObjectTransform.gameObject.activeSelf )
{
onDeactivateObjectTransform.gameObject.SetActive( false );
}
onActivateObjectTransform.gameObject.SetActive( true );
loopingAudioSource.clip = pointerLoopSound;
loopingAudioSource.loop = true;
loopingAudioSource.Play();
loopingAudioSource.volume = 0.0f;
}
if ( oldPointerHand )
{
if ( ShouldOverrideHoverLock() )
{
//Restore the original hovering interactable on the hand
if ( originalHoverLockState == true )
{
oldPointerHand.HoverLock( originalHoveringInteractable );
}
else
{
oldPointerHand.HoverUnlock( null );
}
}
}
pointerHand = newPointerHand;
if ( visible && oldPointerHand != pointerHand )
{
PlayAudioClip( pointerAudioSource, pointerStartSound );
}
if ( pointerHand )
{
pointerStartTransform = GetPointerStartTransform( pointerHand );
if ( pointerHand.currentAttachedObject != null )
{
allowTeleportWhileAttached = pointerHand.currentAttachedObject.GetComponent<AllowTeleportWhileAttachedToHand>();
}
//Keep track of any existing hovering interactable on the hand
originalHoverLockState = pointerHand.hoverLocked;
originalHoveringInteractable = pointerHand.hoveringInteractable;
if ( ShouldOverrideHoverLock() )
{
pointerHand.HoverLock( null );
}
pointerAudioSource.transform.SetParent( pointerStartTransform );
pointerAudioSource.transform.localPosition = Vector3.zero;
loopingAudioSource.transform.SetParent( pointerStartTransform );
loopingAudioSource.transform.localPosition = Vector3.zero;
}
}
//-------------------------------------------------
private void UpdateTeleportColors()
{
float deltaTime = Time.time - pointerShowStartTime;
if ( deltaTime > meshFadeTime )
{
meshAlphaPercent = 1.0f;
meshFading = false;
}
else
{
meshAlphaPercent = Mathf.Lerp( 0.0f, 1.0f, deltaTime / meshFadeTime );
}
//Tint color for the teleport points
foreach ( TeleportMarkerBase teleportMarker in teleportMarkers )
{
teleportMarker.SetAlpha( fullTintAlpha * meshAlphaPercent, meshAlphaPercent );
}
}
//-------------------------------------------------
private void PlayAudioClip( AudioSource source, AudioClip clip )
{
source.clip = clip;
source.Play();
}
//-------------------------------------------------
private void PlayPointerHaptic( bool validLocation )
{
if ( pointerHand != null )
{
if ( validLocation )
{
pointerHand.TriggerHapticPulse( 800 );
}
else
{
pointerHand.TriggerHapticPulse( 100 );
}
}
}
//-------------------------------------------------
private void TryTeleportPlayer()
{
if ( visible && !teleporting )
{
if ( pointedAtTeleportMarker != null && pointedAtTeleportMarker.locked == false )
{
//Pointing at an unlocked teleport marker
teleportingToMarker = pointedAtTeleportMarker;
InitiateTeleportFade();
CancelTeleportHint();
}
}
}
//-------------------------------------------------
private void InitiateTeleportFade()
{
teleporting = true;
currentFadeTime = teleportFadeTime;
TeleportPoint teleportPoint = teleportingToMarker as TeleportPoint;
if ( teleportPoint != null && teleportPoint.teleportType == TeleportPoint.TeleportPointType.SwitchToNewScene )
{
currentFadeTime *= 3.0f;
Teleport.ChangeScene.Send( currentFadeTime );
}
SteamVR_Fade.Start( Color.clear, 0 );
SteamVR_Fade.Start( Color.black, currentFadeTime );
headAudioSource.transform.SetParent( player.hmdTransform );
headAudioSource.transform.localPosition = Vector3.zero;
PlayAudioClip( headAudioSource, teleportSound );
Invoke( "TeleportPlayer", currentFadeTime );
}
//-------------------------------------------------
private void TeleportPlayer()
{
teleporting = false;
Teleport.PlayerPre.Send( pointedAtTeleportMarker );
SteamVR_Fade.Start( Color.clear, currentFadeTime );
TeleportPoint teleportPoint = teleportingToMarker as TeleportPoint;
Vector3 teleportPosition = pointedAtPosition;
if ( teleportPoint != null )
{
teleportPosition = teleportPoint.transform.position;
//Teleport to a new scene
if ( teleportPoint.teleportType == TeleportPoint.TeleportPointType.SwitchToNewScene )
{
teleportPoint.TeleportToScene();
return;
}
}
// Find the actual floor position below the navigation mesh
TeleportArea teleportArea = teleportingToMarker as TeleportArea;
if ( teleportArea != null )
{
if ( floorFixupMaximumTraceDistance > 0.0f )
{
RaycastHit raycastHit;
if ( Physics.Raycast( teleportPosition + 0.05f * Vector3.down, Vector3.down, out raycastHit, floorFixupMaximumTraceDistance, floorFixupTraceLayerMask ) )
{
teleportPosition = raycastHit.point;
}
}
}
if ( teleportingToMarker.ShouldMovePlayer() )
{
Vector3 playerFeetOffset = player.trackingOriginTransform.position - player.feetPositionGuess;
player.trackingOriginTransform.position = teleportPosition + playerFeetOffset;
}
else
{
teleportingToMarker.TeleportPlayer( pointedAtPosition );
}
Teleport.Player.Send( pointedAtTeleportMarker );
}
//-------------------------------------------------
private void HighlightSelected( TeleportMarkerBase hitTeleportMarker )
{
if ( pointedAtTeleportMarker != hitTeleportMarker ) //Pointing at a new teleport marker
{
if ( pointedAtTeleportMarker != null )
{
pointedAtTeleportMarker.Highlight( false );
}
if ( hitTeleportMarker != null )
{
hitTeleportMarker.Highlight( true );
prevPointedAtPosition = pointedAtPosition;
PlayPointerHaptic( !hitTeleportMarker.locked );
PlayAudioClip( reticleAudioSource, goodHighlightSound );
loopingAudioSource.volume = loopingAudioMaxVolume;
}
else if ( pointedAtTeleportMarker != null )
{
PlayAudioClip( reticleAudioSource, badHighlightSound );
loopingAudioSource.volume = 0.0f;
}
}
else if ( hitTeleportMarker != null ) //Pointing at the same teleport marker
{
if ( Vector3.Distance( prevPointedAtPosition, pointedAtPosition ) > 1.0f )
{
prevPointedAtPosition = pointedAtPosition;
PlayPointerHaptic( !hitTeleportMarker.locked );
}
}
}
//-------------------------------------------------
public void ShowTeleportHint()
{
CancelTeleportHint();
hintCoroutine = StartCoroutine( TeleportHintCoroutine() );
}
//-------------------------------------------------
public void CancelTeleportHint()
{
if ( hintCoroutine != null )
{
ControllerButtonHints.HideTextHint(player.leftHand, teleportAction);
ControllerButtonHints.HideTextHint(player.rightHand, teleportAction);
StopCoroutine( hintCoroutine );
hintCoroutine = null;
}
CancelInvoke( "ShowTeleportHint" );
}
//-------------------------------------------------
private IEnumerator TeleportHintCoroutine()
{
float prevBreakTime = Time.time;
float prevHapticPulseTime = Time.time;
while ( true )
{
bool pulsed = false;
//Show the hint on each eligible hand
foreach ( Hand hand in player.hands )
{
bool showHint = IsEligibleForTeleport( hand );
bool isShowingHint = !string.IsNullOrEmpty( ControllerButtonHints.GetActiveHintText( hand, teleportAction) );
if ( showHint )
{
if ( !isShowingHint )
{
ControllerButtonHints.ShowTextHint( hand, teleportAction, "Teleport" );
prevBreakTime = Time.time;
prevHapticPulseTime = Time.time;
}
if ( Time.time > prevHapticPulseTime + 0.05f )
{
//Haptic pulse for a few seconds
pulsed = true;
hand.TriggerHapticPulse( 500 );
}
}
else if ( !showHint && isShowingHint )
{
ControllerButtonHints.HideTextHint( hand, teleportAction);
}
}
if ( Time.time > prevBreakTime + 3.0f )
{
//Take a break for a few seconds
yield return new WaitForSeconds( 3.0f );
prevBreakTime = Time.time;
}
if ( pulsed )
{
prevHapticPulseTime = Time.time;
}
yield return null;
}
}
//-------------------------------------------------
public bool IsEligibleForTeleport( Hand hand )
{
if ( hand == null )
{
return false;
}
if ( !hand.gameObject.activeInHierarchy )
{
return false;
}
if ( hand.hoveringInteractable != null )
{
return false;
}
if ( hand.noSteamVRFallbackCamera == null )
{
if ( hand.isActive == false)
{
return false;
}
//Something is attached to the hand
if ( hand.currentAttachedObject != null )
{
AllowTeleportWhileAttachedToHand allowTeleportWhileAttachedToHand = hand.currentAttachedObject.GetComponent<AllowTeleportWhileAttachedToHand>();
if ( allowTeleportWhileAttachedToHand != null && allowTeleportWhileAttachedToHand.teleportAllowed == true )
{
return true;
}
else
{
return false;
}
}
}
return true;
}
//-------------------------------------------------
private bool ShouldOverrideHoverLock()
{
if ( !allowTeleportWhileAttached || allowTeleportWhileAttached.overrideHoverLock )
{
return true;
}
return false;
}
//-------------------------------------------------
private bool WasTeleportButtonReleased( Hand hand )
{
if ( IsEligibleForTeleport( hand ) )
{
if ( hand.noSteamVRFallbackCamera != null )
{
return Input.GetKeyUp( KeyCode.T );
}
else
{
return teleportAction.GetStateUp(hand.handType);
//return hand.controller.GetPressUp( SteamVR_Controller.ButtonMask.Touchpad );
}
}
return false;
}
//-------------------------------------------------
private bool IsTeleportButtonDown( Hand hand )
{
if ( IsEligibleForTeleport( hand ) )
{
if ( hand.noSteamVRFallbackCamera != null )
{
return Input.GetKey( KeyCode.T );
}
else
{
return teleportAction.GetState(hand.handType);
//return hand.controller.GetPress( SteamVR_Controller.ButtonMask.Touchpad );
}
}
return false;
}
//-------------------------------------------------
private bool WasTeleportButtonPressed( Hand hand )
{
if ( IsEligibleForTeleport( hand ) )
{
if ( hand.noSteamVRFallbackCamera != null )
{
return Input.GetKeyDown( KeyCode.T );
}
else
{
return teleportAction.GetStateDown(hand.handType);
//return hand.controller.GetPressDown( SteamVR_Controller.ButtonMask.Touchpad );
}
}
return false;
}
//-------------------------------------------------
private Transform GetPointerStartTransform( Hand hand )
{
if ( hand.noSteamVRFallbackCamera != null )
{
return hand.noSteamVRFallbackCamera.transform;
}
else
{
return hand.transform;
}
}
}
}
| 29.316695 | 200 | 0.669113 | [
"MIT"
] | jarett-lee/TowerDefenseVR | Assets/SteamVR/InteractionSystem/Teleport/Scripts/Teleport.cs | 34,068 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.