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;
using System.Collections.Generic;
using System.Linq;
using AngleSharp.Dom;
using AngleSharp.Html.Dom;
using MechParser.NET.Extensions;
using MechParser.NET.Mechs;
using MechParser.NET.Mechs.Engines;
using MechParser.NET.Mechs.Parts;
using MechParser.NET.Mechs.Slots;
namespace MechParser.NET.Smurfy
{
public class SmurfyMechRow
{
private const string BallisticSpanSelector = "span.label-mech-hardpoint-ballistic";
private const string EnergySpanSelector = "span.label-mech-hardpoint-beam";
private const string MissileSpanSelector = "span.label-mech-hardpoint-missle";
private const string AmsSpanSelector = "span.label-mech-hardpoint-ams";
private const string EcmSpanSelector = "span.label-mech-hardpoint-ecm";
private const string BallisticHardpointSelector = "div.label-mech-hardpoint-ballistic";
private const string EnergyHardpointSelector = "div.label-mech-hardpoint-beam";
private const string MissileHardpointSelector = "div.label-mech-hardpoint-missle";
public SmurfyMechRow(IHtmlTableRowElement row)
{
Variant = row.Cells[0];
LeftArm = row.Cells[1];
LeftTorso = row.Cells[2];
Center = row.Cells[3];
RightTorso = row.Cells[4];
RightArm = row.Cells[5];
Head = row.Cells[6];
JumpJets = row.Cells[7];
Ecm = row.Cells[8];
Masc = row.Cells[9];
Engines = row.Cells[10];
Hardpoints = row.Cells[11];
TorsoArm = row.Cells[12];
Cost = row.Cells[13];
}
private IHtmlTableCellElement Variant { get; }
private IHtmlTableCellElement LeftArm { get; }
private IHtmlTableCellElement LeftTorso { get; }
private IHtmlTableCellElement Center { get; }
private IHtmlTableCellElement RightTorso { get; }
private IHtmlTableCellElement RightArm { get; }
private IHtmlTableCellElement Head { get; }
private IHtmlTableCellElement JumpJets { get; }
private IHtmlTableCellElement Ecm { get; }
private IHtmlTableCellElement Masc { get; }
private IHtmlTableCellElement Engines { get; }
private IHtmlTableCellElement Hardpoints { get; }
private IHtmlTableCellElement TorsoArm { get; }
private IHtmlTableCellElement Cost { get; }
public Faction ParseFaction()
{
return Variant.ParentElement!.GetAttribute("data-mechfilter-faction")!.ToLowerInvariant() switch
{
"innersphere" => Faction.InnerSphere,
"clan" => Faction.Clan,
_ => throw new ArgumentOutOfRangeException()
};
}
public string ParseVariant()
{
return Variant.QuerySelector("a")!.TextContent;
}
private int ParseHardpointCount(IElement element)
{
return int.Parse(element.QuerySelector("span.count")!.TextContent);
}
private IEnumerable<Hardpoint> ParseMissiles(string text)
{
text = text.Replace(" ", "");
var openingIndex = text.IndexOf('(');
var closingIndex = text.IndexOf(')');
var sizeString = text.Substring(openingIndex + 1, closingIndex - 1 - openingIndex);
var sizes = new List<int>();
for (var j = 0; j < sizeString.Length; j++)
{
var missileSizeString = sizeString.TakeWhile(char.IsDigit).ToArray();
var size = int.Parse(missileSizeString);
j += missileSizeString.Length;
if (sizeString.Length <= j)
{
sizes.Add(size);
break;
}
switch (sizeString[j])
{
case 'x':
var setsChars = sizeString
.Substring(j + 1)
.TakeWhile(char.IsDigit)
.ToArray();
var sets = int.Parse(setsChars);
for (var k = 0; k < sets; k++)
{
sizes.Add(size);
}
j += setsChars.Length;
break;
default:
sizes.Add(size);
break;
}
}
foreach (var width in sizes)
{
yield return new Hardpoint(HardpointType.Missile, width);
}
}
private List<Hardpoint> ParseHardpoints(IHtmlTableCellElement cell)
{
var hardpoints = new List<Hardpoint>();
if (cell.QuerySelector(BallisticSpanSelector) is { } ballisticSpan)
{
var count = ParseHardpointCount(ballisticSpan);
for (var i = 0; i < count; i++)
{
var hardpoint = new Hardpoint(HardpointType.Ballistic, null);
hardpoints.Add(hardpoint);
}
}
if (cell.QuerySelector(EnergySpanSelector) is { } energySpan)
{
var count = ParseHardpointCount(energySpan);
for (var i = 0; i < count; i++)
{
var hardpoint = new Hardpoint(HardpointType.Energy, null);
hardpoints.Add(hardpoint);
}
}
if (cell.QuerySelector(MissileSpanSelector)?.TextContent.Trim() is { } missileSpan)
{
foreach (var missile in ParseMissiles(missileSpan))
{
hardpoints.Add(missile);
}
}
if (cell.QuerySelector(AmsSpanSelector) is { } amsSpan)
{
var count = ParseHardpointCount(amsSpan);
for (var i = 0; i < count; i++)
{
var hardpoint = new Hardpoint(HardpointType.Ams, null);
hardpoints.Add(hardpoint);
}
}
if (cell.QuerySelector(EcmSpanSelector) is { } ecmSpan)
{
var count = ParseHardpointCount(ecmSpan);
for (var i = 0; i < count; i++)
{
var hardpoint = new Hardpoint(HardpointType.Ecm, null);
hardpoints.Add(hardpoint);
}
}
return hardpoints;
}
private IHtmlTableCellElement? GetPartCell(PartType type)
{
return type switch
{
PartType.Head => Head,
PartType.LeftArm => LeftArm,
PartType.LeftTorso => LeftTorso,
PartType.Center => Center,
PartType.RightTorso => RightTorso,
PartType.RightArm => RightArm,
PartType.LeftLeg => null,
PartType.RightLeg => null,
_ => throw new ArgumentOutOfRangeException(nameof(type), type, null)
};
}
public Dictionary<PartType, Part> ParseParts()
{
var parts = new Dictionary<PartType, Part>();
foreach (var type in Enum.GetValues<PartType>())
{
var cell = GetPartCell(type);
if (cell == null)
{
parts.Add(type, new Part(type, new List<Hardpoint>()));
continue;
}
var hardpoints = ParseHardpoints(cell);
parts.Add(type, new Part(type, hardpoints));
}
return parts;
}
public int ParseJumpJets()
{
var span = JumpJets.QuerySelector("span");
if (span == null ||
!int.TryParse(span.TextContent, out var jumpJets))
{
return 0;
}
return jumpJets;
}
public bool ParseEcm()
{
return Ecm.QuerySelector("i.icon-ok") != null;
}
public bool ParseMasc()
{
return Masc.QuerySelector("i.icon-ok") != null;
}
public (int minimum, int maximum) ParseEngineRange()
{
var engine = Engines.QuerySelector("a.engine-popover-show")!;
var minimum = int.Parse(engine.GetAttribute("data-engine-min")!);
var maximum = int.Parse(engine.GetAttribute("data-engine-max")!);
return (minimum, maximum);
}
public Engine ParseDefaultEngine()
{
var engine = Engines.QuerySelector("small") is { } engineElement
? engineElement.TextContent
: Engines.TextContent.Trim();
var engineStrings = engine.Split(" ");
var engineType = engineStrings[0].ToLowerInvariant() switch
{
"std" => EngineType.STD,
"xl" => EngineType.XL,
"light" => EngineType.Light,
_ => throw new ArgumentOutOfRangeException()
};
var engineLevel = int.Parse(engineStrings[1]);
return new Engine(engineType, engineLevel);
}
public Dictionary<HardpointType, int> ParseHardpoints()
{
var hardpoints = new Dictionary<HardpointType, int>();
var ballistic = int.Parse(Hardpoints.QuerySelector(BallisticHardpointSelector)!.TextContent);
hardpoints.Add(HardpointType.Ballistic, ballistic);
var energy = int.Parse(Hardpoints.QuerySelector(EnergyHardpointSelector)!.TextContent);
hardpoints.Add(HardpointType.Energy, energy);
var missile = int.Parse(Hardpoints.QuerySelector(MissileHardpointSelector)!.TextContent);
hardpoints.Add(HardpointType.Missile, missile);
return hardpoints;
}
public (double torsoYaw, double torsoPitch, double armYaw, double armPitch) ParseTwist()
{
var lines = TorsoArm.TextContent.Trim().Replace("°", " ").Split("\n");
var firstLine = lines[0].Split('/');
var secondLine = lines[1].Split('/');
var torsoYaw = double.Parse(firstLine[0]);
var torsoPitch = double.Parse(secondLine[0]);
var armYaw = double.Parse(firstLine[1]);
var armPitch = double.Parse(secondLine[1]);
return (torsoYaw, torsoPitch, armYaw, armPitch);
}
public (int? mcCost, int? cBillsCost) ParseCost()
{
var mcCostString = Cost.QuerySelector("span.prices-mc")?.TextContent;
var cBillsCostString = Cost.QuerySelector("span.prices-cb")?.TextContent.Replace(",", "");
var mcCost = IntExtensions.ParseOrNull(mcCostString);
var cBills = IntExtensions.ParseOrNull(cBillsCostString);
return (mcCost, cBills);
}
public bool ParseChampion()
{
return Variant.QuerySelector("small")?.TextContent.ToLowerInvariant() == "champion";
}
public bool ParseHero()
{
return Variant.QuerySelector("small")?.TextContent.ToLowerInvariant() == "hero";
}
}
}
| 33.201754 | 108 | 0.533069 | [
"MIT"
] | DrSmugleaf/MechParser.NET | MechParser.NET/Smurfy/SmurfyMechRow.cs | 11,358 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using MediatR;
namespace Monito.Application.Model.Query
{
public class GetRequestLinksByUUIDQuery : IRequest<IEnumerable<MinimalLinkApplicationModel>> {
public Guid UUID { get; set; }
public static GetRequestLinksByUUIDQuery Build(Guid uuid) {
return new GetRequestLinksByUUIDQuery() {
UUID = uuid
};
}
}
} | 28.3125 | 98 | 0.677704 | [
"Apache-2.0"
] | Wufe/monito | Application/Monito.Application.Model/Query/GetRequestLinksByUUIDQuery.cs | 453 | C# |
using System;
using System.Reflection;
using System.Threading.Tasks;
using Plugin.Iconize;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Xamarin.Forms;
using Xamarin.Forms.Platform.UWP;
[assembly: ExportRenderer(typeof(IconNavigationPage), typeof(IconNavigationPageRenderer))]
namespace Plugin.Iconize
{
/// <summary>
/// Defines the <see cref="IconNavigationPage" /> renderer.
/// </summary>
/// <seealso cref="Xamarin.Forms.Platform.UWP.NavigationPageRenderer" />
public class IconNavigationPageRenderer : NavigationPageRenderer
{
/// <summary>
/// Initializes a new instance of the <see cref="IconNavigationPageRenderer"/> class.
/// </summary>
public IconNavigationPageRenderer()
{
MessagingCenter.Subscribe<Object>(this, IconToolbarItem.UpdateToolbarItemsMessage, OnUpdateToolbarItems);
ElementChanged += OnElementChanged;
}
/// <summary>
/// Called when [element changed].
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The <see cref="VisualElementChangedEventArgs"/> instance containing the event data.</param>
private void OnElementChanged(Object sender, VisualElementChangedEventArgs e)
{
ContainerElement.Loaded += OnContainerLoaded;
ContainerElement.Unloaded += OnContainerUnloaded;
}
/// <summary>
/// Called when [container unloaded].
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The <see cref="RoutedEventArgs"/> instance containing the event data.</param>
private void OnContainerUnloaded(Object sender, RoutedEventArgs e)
{
ContainerElement.Unloaded -= OnContainerUnloaded;
ContainerElement.Loaded -= OnContainerLoaded;
}
/// <summary>
/// Called when [container loaded].
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The <see cref="RoutedEventArgs"/> instance containing the event data.</param>
private void OnContainerLoaded(Object sender, RoutedEventArgs e)
{
MessagingCenter.Send(sender, IconToolbarItem.UpdateToolbarItemsMessage);
}
/// <summary>
/// Called when [update toolbar items].
/// </summary>
private async void UpdateToolbarItems()
{
if (Element == null)
return;
if (ContainerElement is MasterDetailControl masterDetailControl)
{
var mInfo = typeof(MasterDetailControl).GetTypeInfo().GetDeclaredMethod("Xamarin.Forms.Platform.UWP.IToolbarProvider.GetCommandBarAsync");
var commandBar = await (mInfo.Invoke(masterDetailControl, new Object[] { }) as Task<CommandBar>);
commandBar.UpdateToolbarItems();
}
}
/// <summary>
/// Called when [update toolbar items].
/// </summary>
/// <param name="sender">The sender.</param>
private async void OnUpdateToolbarItems(Object sender)
{
if (Element is null)
return;
// a workaround for MasterDetailPage
if (Element.Parent is MasterDetailPage)
{
var ms = Element.Parent as MasterDetailPage;
ms.IsPresentedChanged += (s, e) => UpdateToolbarItems();
UpdateToolbarItems();
}
var method = typeof(NavigationPageRenderer).GetTypeInfo().GetDeclaredMethod("Xamarin.Forms.Platform.UWP.IToolbarProvider.GetCommandBarAsync");
var bar = await (method.Invoke(this, new Object[] { }) as Task<CommandBar>);
bar.UpdateToolbarItems();
}
}
}
| 38.858586 | 154 | 0.617884 | [
"Apache-2.0"
] | EndlessDelirium/Iconize | src/Plugin.Iconize/Platform/UWP/Renderers/IconNavigationPageRenderer.cs | 3,849 | C# |
using Microsoft.Rest;
using Polly.CircuitBreaker;
namespace BookFast.Web.Proxy
{
internal static class Extensions
{
public static int StatusCode(this HttpOperationException exception)
{
return (int)exception.Response.StatusCode;
}
public static int StatusCode(this BrokenCircuitException exception)
{
return StatusCode((HttpOperationException)exception.InnerException);
}
}
}
| 24.368421 | 80 | 0.676026 | [
"MIT"
] | PeterJD/book-fast-service-fabric | BookFast.Web.Proxy/Extensions.cs | 465 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HeartShape
{
class HeartShape
{
static void Main(string[] args)
{
Console.WriteLine(" 0 0 ");
Console.WriteLine("0 0 0 0");
Console.WriteLine(" 0 0 0 0");
Console.WriteLine(" 0 00 0");
Console.WriteLine(" 0 0 ");
Console.WriteLine(" 0 0 ");
Console.WriteLine(" 0 0 ");
Console.WriteLine(" 00 ");
Console.WriteLine(" ©");
Console.WriteLine(" © ©");
Console.WriteLine(" © ©");
Console.WriteLine(" © ©");
Console.WriteLine("© © © © ©");
}
}
}
| 27.533333 | 48 | 0.46368 | [
"MIT"
] | AlexanderPetrovv/Programming-Basics-December-2016 | SimpleCalculations/HeartShape/HeartShape.cs | 840 | C# |
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Hosting;
using Ploeh.AutoFixture;
namespace API.WindowsService.Test.Helpers
{
internal class HttpRequestMessageCustomization : ICustomization
{
public void Customize(IFixture fixture)
{
fixture.Customize<HttpRequestMessage>(c => c
.Without(x => x.Content)
.Do(x => x.Properties[HttpPropertyKeys.HttpConfigurationKey] =
new HttpConfiguration()));
}
}
} | 28.944444 | 78 | 0.639155 | [
"BSD-3-Clause"
] | drdk/ffmpeg-farm | ffmpeg-farm-server/API.WindowsService.Test/Helpers/HttpRequestMessageCustomization.cs | 523 | C# |
namespace Lykke.Service.FakeExchangeConnector.Core.Domain
{
public enum RabbitMessageFormat
{
Json = 0,
MessagePack = 1,
}
}
| 17.111111 | 58 | 0.636364 | [
"MIT"
] | LykkeBusiness/Lykke.Service.FakeExchangeConnector | src/Lykke.Service.FakeExchangeConnector.Core/Domain/RabbitMessageFormat.cs | 156 | C# |
using System;
using Terraria;
using Terraria.ID;
using Terraria.ModLoader;
namespace Virtuous
{
class VirtuousMod : Mod
{
public VirtuousMod()
{
Properties = new ModProperties()
{
Autoload = true,
AutoloadGores = true,
AutoloadSounds = true
};
}
//public override void Load()
//{
// var translatable = Assembly.GetAssembly(typeof(VirtuousMod)).GetTypes()
// .Where(x => x.IsClass && !x.IsAbstract && x.IsSubclassOf(typeof(ITranslatable)))
// .Select(x => (ITranslatable)Activator.CreateInstance(x));
// foreach (var obj in translatable)
// {
// obj.AddTranslations(this);
// }
//}
public override void AddRecipeGroups()
{
RecipeGroup.RegisterGroup("Virtuous:Wings", new RecipeGroup(() => "Any Wings", new int[] {
ItemID.DemonWings,
ItemID.AngelWings,
ItemID.RedsWings,
ItemID.ButterflyWings,
ItemID.FairyWings,
ItemID.HarpyWings,
ItemID.BoneWings,
ItemID.FlameWings,
ItemID.FrozenWings,
ItemID.GhostWings,
ItemID.SteampunkWings,
ItemID.LeafWings,
ItemID.BatWings,
ItemID.BeeWings,
ItemID.DTownsWings,
ItemID.WillsWings,
ItemID.CrownosWings,
ItemID.CenxsWings,
ItemID.TatteredFairyWings,
ItemID.SpookyWings,
ItemID.FestiveWings,
ItemID.BeetleWings,
ItemID.FinWings,
ItemID.FishronWings,
ItemID.MothronWings,
ItemID.WingsSolar,
ItemID.WingsVortex,
ItemID.WingsNebula,
ItemID.WingsStardust,
ItemID.Yoraiz0rWings,
ItemID.JimsWings,
ItemID.SkiphsWings,
ItemID.LokisWings,
ItemID.BetsyWings,
ItemID.ArkhalisWings,
ItemID.LeinforsWings,
}));
RecipeGroup.RegisterGroup("Virtuous:CelestialWings", new RecipeGroup(() => "Any Celestial Wings", new int[] {
ItemID.WingsSolar,
ItemID.WingsVortex,
ItemID.WingsNebula,
ItemID.WingsStardust,
}));
}
}
}
| 30.470588 | 121 | 0.49305 | [
"MIT"
] | orchidalloy/Virtuous | VirtuousMod.cs | 2,590 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("01-OfficeSpace")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Hewlett-Packard")]
[assembly: AssemblyProduct("01-OfficeSpace")]
[assembly: AssemblyCopyright("Copyright © Hewlett-Packard 2018")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("8da35943-319c-4c13-8dd1-924a6189091d")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.540541 | 84 | 0.751052 | [
"MIT"
] | alekhristov/TelerikAcademyAlpha | 02-Module2/01-DSA/07-ExamPrepDSA/01-OfficeSpace/Properties/AssemblyInfo.cs | 1,429 | C# |
namespace EFCore.Mapping.TPT.Scenario.Entities
{
public class Pet : Animal
{
public string Name { get; set; }
}
}
| 16.875 | 47 | 0.614815 | [
"MIT"
] | dimitrietataru/efcore-mapping | src/EntityFrameworkCore.Prototype.Mapping.TablePerType/Scenario/Entities/Pet.cs | 137 | C# |
// Copyright (c) Tunnel Vision Laboratories, LLC. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace TunnelVisionLabs.LanguageTypes.SourceGenerator
{
using Microsoft.CodeAnalysis;
[Generator(LanguageNames.CSharp)]
internal class IsExternalInitSourceGenerator : IIncrementalGenerator
{
private const string IsExternalInitSource = @"// <auto-generated/>
#nullable enable
namespace System.Runtime.CompilerServices
{
using System.ComponentModel;
/// <summary>
/// Reserved to be used by the compiler for tracking metadata.
/// This class should not be used by developers in source code.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
internal static class IsExternalInit
{
}
}
";
public void Initialize(IncrementalGeneratorInitializationContext context)
{
var referencedTypesData = context.CompilationProvider.Select(
(compilation, cancellationToken) =>
{
var hasIsExternalInit = IsCompilerTypeAvailable(compilation, "System.Runtime.CompilerServices.IsExternalInit");
return new ReferencedTypesData(
hasIsExternalInit: hasIsExternalInit);
});
context.RegisterSourceOutput(
referencedTypesData,
(context, referencedTypesData) =>
{
var forwarders = new List<string>();
if (!referencedTypesData.HasIsExternalInit)
{
context.AddSource("IsExternalInit.g.cs", IsExternalInitSource.ReplaceLineEndings("\r\n"));
}
else
{
forwarders.Add("IsExternalInit");
}
if (forwarders.Count > 0)
{
var compilerForwarders = $@"// <auto-generated/>
#nullable enable
using System.Runtime.CompilerServices;
{string.Join("\r\n", forwarders.Select(forwarder => $"[assembly: TypeForwardedTo(typeof({forwarder}))]"))}
";
context.AddSource("CompilerForwarders.g.cs", compilerForwarders.ReplaceLineEndings("\r\n"));
}
});
}
private static bool IsCompilerTypeAvailable(Compilation compilation, string fullyQualifiedMetadataName)
=> compilation.GetBestTypeByMetadataName(fullyQualifiedMetadataName, requiresAccess: true) is not null;
private sealed class ReferencedTypesData
{
public ReferencedTypesData(bool hasIsExternalInit)
{
HasIsExternalInit = hasIsExternalInit;
}
public bool HasIsExternalInit { get; }
}
}
}
| 33.546512 | 131 | 0.604853 | [
"MIT"
] | sharwell/language-types | src/TunnelVisionLabs.LanguageTypes.SourceGenerator/IsExternalInitSourceGenerator.cs | 2,887 | C# |
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.OracleClient;
using System.IO;
using System.Collections.Generic;
using System.Data.SqlClient;
namespace NRCAPPS.WP
{
public partial class WpItemSalesWs : System.Web.UI.Page
{
string strConnString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
OracleCommand cmdu, cmdi, cmdl;
OracleDataAdapter oradata;
DataTable dt;
int RowCount;
string IS_PAGE_ACTIVE = "";
string IS_ADD_ACTIVE = "";
string IS_EDIT_ACTIVE = "";
string IS_DELETE_ACTIVE = "";
string IS_VIEW_ACTIVE = "";
public bool IsLoad { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
if (Session["USER_NAME"] != null)
{
string requestedFile = Path.GetFileName(Request.Path);
OracleConnection conn = new OracleConnection(strConnString);
conn.Open();
string makeSQL = " SELECT NUPP.IS_PAGE_ACTIVE, NUPP.IS_ADD_ACTIVE, NUPP.IS_EDIT_ACTIVE, NUPP.IS_DELETE_ACTIVE, NUPP.IS_VIEW_ACTIVE FROM NRC_USER_PAGE_PERMISSION NUPP LEFT JOIN NRC_USER_PAGES NUP ON NUP.USER_PAGE_ID = NUPP.USER_PAGE_ID WHERE NUPP.USER_ID = '" + Session["USER_ID"] + "' AND NUP.IS_ACTIVE = 'Enable' AND NUP.PAGE_URL = '" + requestedFile + "' ";
cmdl = new OracleCommand(makeSQL);
oradata = new OracleDataAdapter(cmdl.CommandText, conn);
dt = new DataTable();
oradata.Fill(dt);
RowCount = dt.Rows.Count;
for (int i = 0; i < RowCount; i++)
{
IS_PAGE_ACTIVE = dt.Rows[i]["IS_PAGE_ACTIVE"].ToString();
IS_ADD_ACTIVE = dt.Rows[i]["IS_ADD_ACTIVE"].ToString();
IS_EDIT_ACTIVE = dt.Rows[i]["IS_EDIT_ACTIVE"].ToString();
IS_DELETE_ACTIVE = dt.Rows[i]["IS_DELETE_ACTIVE"].ToString();
IS_VIEW_ACTIVE = dt.Rows[i]["IS_VIEW_ACTIVE"].ToString();
}
if (IS_PAGE_ACTIVE == "Enable")
{
if (!IsPostBack)
{
DataTable dtItemID = new DataTable();
DataSet dsi = new DataSet();
string makeDropDownItemSQL = " SELECT ITEM_ID, ITEM_NAME || ' - ' || ITEM_CODE AS ITEM_NAME FROM WP_ITEM WHERE IS_ACTIVE = 'Enable' ORDER BY ITEM_ID ASC";
dsi = ExecuteBySqlString(makeDropDownItemSQL);
dtItemID = (DataTable)dsi.Tables[0];
DropDownItemID.DataSource = dtItemID;
DropDownItemID.DataValueField = "ITEM_ID";
DropDownItemID.DataTextField = "ITEM_NAME";
DropDownItemID.DataBind();
DropDownItemID.Items.Insert(0, new ListItem("Select Item", "0"));
BtnUpdate.Attributes.Add("aria-disabled", "false");
BtnUpdate.Attributes.Add("class", "btn btn-success disabled");
BtnDelete.Attributes.Add("aria-disabled", "false");
BtnDelete.Attributes.Add("class", "btn btn-danger disabled");
Display();
alert_box.Visible = false;
}
IsLoad = false;
}
else {
Response.Redirect("~/PagePermissionError.aspx");
}
}
else
{
Response.Redirect("~/Default.aspx");
}
}
public void BtnAdd_Click(object sender, EventArgs e)
{
try
{
if (IS_ADD_ACTIVE == "Enable")
{
OracleConnection conn = new OracleConnection(strConnString);
conn.Open();
int userID = Convert.ToInt32(Session["USER_ID"]);
int ItemID = Convert.ToInt32(DropDownItemID.Text);
string get_id = "select WP_WS_ITEM_ID_SEQ.nextval from dual";
cmdu = new OracleCommand(get_id, conn);
int newItemID = Int16.Parse(cmdu.ExecuteScalar().ToString());
string ISActive = CheckIsActive.Checked ? "Enable" : "Disable";
string u_date = System.DateTime.Now.ToString("dd-MM-yyyy h:mm:ss tt");
string insert_user = "insert into WP_WS_ITEM (ITEM_WS_ID, ITEM_WS_DESCRIPTION, ITEM_ID, IS_ACTIVE, CREATE_DATE, C_USER_ID) VALUES ( :NoItemSalesID, :TextItemSalesDescription, :NoItemID, :TextIsActive, TO_DATE(:u_date, 'DD-MM-YYYY HH:MI:SS AM'), :NoCuserID)";
cmdi = new OracleCommand(insert_user, conn);
OracleParameter[] objPrm = new OracleParameter[6];
objPrm[0] = cmdi.Parameters.Add("NoItemSalesID", newItemID);
objPrm[1] = cmdi.Parameters.Add("TextItemSalesDescription", TextItemSalesDescription.Text);
objPrm[2] = cmdi.Parameters.Add("NoItemID", ItemID);
objPrm[3] = cmdi.Parameters.Add("TextIsActive", ISActive);
objPrm[4] = cmdi.Parameters.Add("u_date", u_date);
objPrm[5] = cmdi.Parameters.Add("NoCuserID", userID);
cmdi.ExecuteNonQuery();
cmdi.Parameters.Clear();
cmdi.Dispose();
conn.Close();
alert_box.Visible = true;
alert_box.Controls.Add(new LiteralControl("Insert New Sales Item successfully"));
alert_box.Attributes.Add("class", "alert alert-success alert-dismissible");
clearText();
Display();
}
else {
Response.Redirect("~/PagePermissionError.aspx");
}
}
catch
{
Response.Redirect("~/ParameterError.aspx");
}
}
protected void linkSelectClick(object sender, EventArgs e)
{
OracleConnection conn = new OracleConnection(strConnString);
conn.Open();
LinkButton btn = (LinkButton)sender;
Session["user_page_data_id"] = btn.CommandArgument;
int USER_DATA_ID = Convert.ToInt32(Session["user_page_data_id"]);
string makeSQL = " select * from WP_WS_ITEM where ITEM_WS_ID = '" + USER_DATA_ID + "'";
cmdl = new OracleCommand(makeSQL);
oradata = new OracleDataAdapter(cmdl.CommandText, conn);
dt = new DataTable();
oradata.Fill(dt);
RowCount = dt.Rows.Count;
for (int i = 0; i < RowCount; i++)
{
TextItemSalesID.Text = dt.Rows[i]["ITEM_WS_ID"].ToString();
TextItemSalesDescription.Text = dt.Rows[i]["ITEM_WS_DESCRIPTION"].ToString();
DropDownItemID.Text = dt.Rows[i]["ITEM_ID"].ToString();
CheckIsActive.Checked = Convert.ToBoolean(dt.Rows[i]["IS_ACTIVE"].ToString() == "Enable" ? true : false);
}
conn.Close();
Display();
alert_box.Visible = false;
BtnAdd.Attributes.Add("aria-disabled", "false");
BtnAdd.Attributes.Add("class", "btn btn-primary disabled");
BtnUpdate.Attributes.Add("aria-disabled", "true");
BtnUpdate.Attributes.Add("class", "btn btn-success active");
BtnDelete.Attributes.Add("aria-disabled", "true");
BtnDelete.Attributes.Add("class", "btn btn-danger active");
}
public void Display()
{
if (IS_VIEW_ACTIVE == "Enable")
{
OracleConnection conn = new OracleConnection(strConnString);
conn.Open();
DataTable dtUserTypeID = new DataTable();
DataSet ds = new DataSet();
string makeSQL = "";
if (txtSearchUserRole.Text == "")
{
makeSQL = " select WSI.*, WI.ITEM_NAME, WI.ITEM_CODE from WP_WS_ITEM WSI LEFT JOIN WP_ITEM WI ON WI.ITEM_ID = WSI.ITEM_ID ORDER BY WSI.ITEM_ID";
}
else
{
makeSQL = " select * from WP_WS_ITEM where ITEM_ID like '" + txtSearchUserRole.Text + "%' or ITEM_NAME like '" + txtSearchUserRole.Text + "%' or IS_ACTIVE like '" + txtSearchUserRole.Text + "%' ORDER BY UPDATE_DATE desc, CREATE_DATE desc";
alert_box.Visible = false;
}
cmdl = new OracleCommand(makeSQL);
oradata = new OracleDataAdapter(cmdl.CommandText, conn);
dt = new DataTable();
oradata.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataKeyNames = new string[] { "ITEM_ID" };
GridView1.DataBind();
conn.Close();
//alert_box.Visible = false;
}
else
{
// Response.Redirect("~/PagePermissionError.aspx");
}
}
protected void GridViewSearchUser(object sender, EventArgs e)
{
this.Display();
}
protected void GridViewUser_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
Display();
alert_box.Visible = false;
}
protected void BtnUpdate_Click(object sender, EventArgs e)
{
if (IS_EDIT_ACTIVE == "Enable")
{
OracleConnection conn = new OracleConnection(strConnString);
conn.Open();
int userID = Convert.ToInt32(Session["USER_ID"]);
int USER_DATA_ID = Convert.ToInt32(TextItemSalesID.Text);
int ItemID = Convert.ToInt32(DropDownItemID.Text);
string ISActive = CheckIsActive.Checked ? "Enable" : "Disable";
string u_date = System.DateTime.Now.ToString("dd-MM-yyyy h:mm:ss tt");
string update_user = "update WP_WS_ITEM set ITEM_WS_DESCRIPTION = :TextItemSalesDescription, ITEM_ID =: NoItemID, UPDATE_DATE = TO_DATE(:u_date, 'DD-MM-YYYY HH:MI:SS AM') , U_USER_ID = :NoC_USER_ID, IS_ACTIVE = :TextIsActive where ITEM_WS_ID = :NoItemSalesID ";
cmdi = new OracleCommand(update_user, conn);
OracleParameter[] objPrm = new OracleParameter[6];
objPrm[0] = cmdi.Parameters.Add("TextItemSalesDescription", TextItemSalesDescription.Text);
objPrm[1] = cmdi.Parameters.Add("NoItemID", ItemID);
objPrm[2] = cmdi.Parameters.Add("u_date", u_date);
objPrm[3] = cmdi.Parameters.Add("NoItemSalesID", USER_DATA_ID);
objPrm[4] = cmdi.Parameters.Add("NoC_USER_ID", userID);
objPrm[5] = cmdi.Parameters.Add("TextIsActive", ISActive);
cmdi.ExecuteNonQuery();
cmdi.Parameters.Clear();
cmdi.Dispose();
conn.Close();
alert_box.Visible = true;
alert_box.Controls.Add(new LiteralControl("Sales Item Update successfully"));
alert_box.Attributes.Add("class", "alert alert-success alert-dismissible");
clearText();
Display();
}
else {
Response.Redirect("~/PagePermissionError.aspx");
}
}
protected void BtnDelete_Click(object sender, EventArgs e)
{
try
{
if (IS_DELETE_ACTIVE == "Enable")
{
OracleConnection conn = new OracleConnection(strConnString);
conn.Open();
int USER_DATA_ID = Convert.ToInt32(TextItemSalesID.Text);
string delete_user_page = " delete from WP_WS_ITEM where ITEM_WS_ID = '" + USER_DATA_ID + "'";
cmdi = new OracleCommand(delete_user_page, conn);
cmdi.ExecuteNonQuery();
cmdi.Parameters.Clear();
cmdi.Dispose();
conn.Close();
alert_box.Visible = true;
alert_box.Controls.Add(new LiteralControl("Sales Item Delete successfully"));
alert_box.Attributes.Add("class", "alert alert-danger alert-dismissible");
clearText();
Display();
}
else
{
Response.Redirect("~/PagePermissionError.aspx");
}
}
catch
{
Response.Redirect("~/ParameterError.aspx");
}
}
public void clearTextField(object sender, EventArgs e)
{
TextItemSalesID.Text = "";
TextItemSalesDescription.Text = "";
CheckItemSalesName.Text = "";
BtnAdd.Attributes.Add("aria-disabled", "true");
BtnAdd.Attributes.Add("class", "btn btn-primary active");
}
public void clearText()
{
TextItemSalesID.Text = "";
TextItemSalesDescription.Text = "";
CheckItemSalesName.Text = "";
BtnAdd.Attributes.Add("aria-disabled", "false");
BtnAdd.Attributes.Add("class", "btn btn-primary disabled");
}
public void TextItemSalesName_TextChanged(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(TextItemSalesDescription.Text))
{
alert_box.Visible = false;
OracleConnection conn = new OracleConnection(strConnString);
conn.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
cmd.CommandText = "select * from WP_WS_ITEM where ITEM_WS_DESCRIPTION = '" + TextItemSalesDescription.Text + "'";
cmd.CommandType = CommandType.Text;
OracleDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
CheckItemSalesName.Text = "<label class='control-label'><i class='fa fa-times-circle-o'></i> Sales Item description is already entry</label>";
CheckItemSalesName.ForeColor = System.Drawing.Color.Red;
TextItemSalesDescription.Focus();
BtnAdd.Attributes.Add("aria-disabled", "false");
BtnAdd.Attributes.Add("class", "btn btn-primary disabled");
}
else
{
CheckItemSalesName.Text = "<label class='control-label'><i class='fa fa fa-check'></i> Sales Item description is available</label>";
CheckItemSalesName.ForeColor = System.Drawing.Color.Green;
CheckIsActive.Focus();
BtnAdd.Attributes.Add("aria-disabled", "true");
BtnAdd.Attributes.Add("class", "btn btn-primary active");
}
}
else {
CheckItemSalesName.Text = "<label class='control-label'><i class='fa fa-hand-o-left'></i> Sales Item description is not blank</label>";
CheckItemSalesName.ForeColor = System.Drawing.Color.Red;
TextItemSalesDescription.Focus();
}
}
public DataSet ExecuteBySqlString(string sqlString)
{
string connStr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
DataSet ds = new DataSet();
OracleConnection conn = new OracleConnection(connStr);
try
{
conn.Open();
OracleCommand cmd = new OracleCommand(sqlString, conn);
cmd.CommandType = CommandType.Text;
cmd.CommandText = sqlString;
bool mustCloseConnection = false;
using (OracleDataAdapter da = new OracleDataAdapter(cmd))
{
da.Fill(ds);
cmd.Parameters.Clear();
if (mustCloseConnection)
{
conn.Close();
}
}
}
catch (SqlException ex)
{
}
finally
{
conn.Close();
}
return ds;
}
}
} | 41.480769 | 377 | 0.526599 | [
"MIT"
] | nscseiu/nrcapps | WP/WpItemSalesWs.aspx.cs | 17,258 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis;
using Analyzer.Utilities;
using System.Linq;
using Analyzer.Utilities.Extensions;
namespace Microsoft.CodeQuality.Analyzers.QualityGuidelines
{
public abstract class AbstractRemoveEmptyFinalizersAnalyzer : DiagnosticAnalyzer
{
public const string RuleId = "CA1821";
private static readonly LocalizableString s_localizableTitle = new LocalizableResourceString(nameof(MicrosoftCodeQualityAnalyzersResources.RemoveEmptyFinalizers), MicrosoftCodeQualityAnalyzersResources.ResourceManager, typeof(MicrosoftCodeQualityAnalyzersResources));
private static readonly LocalizableString s_localizableMessage = new LocalizableResourceString(nameof(MicrosoftCodeQualityAnalyzersResources.RemoveEmptyFinalizers), MicrosoftCodeQualityAnalyzersResources.ResourceManager, typeof(MicrosoftCodeQualityAnalyzersResources));
private static readonly LocalizableString s_localizableDescription = new LocalizableResourceString(nameof(MicrosoftCodeQualityAnalyzersResources.RemoveEmptyFinalizersDescription), MicrosoftCodeQualityAnalyzersResources.ResourceManager, typeof(MicrosoftCodeQualityAnalyzersResources));
internal static DiagnosticDescriptor Rule = new DiagnosticDescriptor(RuleId,
s_localizableTitle,
s_localizableMessage,
DiagnosticCategory.Performance,
DiagnosticHelpers.DefaultDiagnosticSeverity,
isEnabledByDefault: DiagnosticHelpers.EnabledByDefaultForVsixAndNuget,
description: s_localizableDescription,
helpLinkUri: "https://docs.microsoft.com/visualstudio/code-quality/ca1821-remove-empty-finalizers",
customTags: FxCopWellKnownDiagnosticTags.PortedFxCopRule);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule);
public override void Initialize(AnalysisContext analysisContext)
{
analysisContext.EnableConcurrentExecution();
analysisContext.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
analysisContext.RegisterCodeBlockAction(codeBlockContext =>
{
if (codeBlockContext.OwningSymbol.Kind != SymbolKind.Method)
{
return;
}
var methodSymbol = (IMethodSymbol)codeBlockContext.OwningSymbol;
if (!methodSymbol.IsDestructor())
{
return;
}
var methodBody = methodSymbol.DeclaringSyntaxReferences.Single().GetSyntax();
if (IsEmptyFinalizer(methodBody, codeBlockContext))
{
codeBlockContext.ReportDiagnostic(methodSymbol.CreateDiagnostic(Rule));
}
});
}
protected static bool InvocationIsConditional(IMethodSymbol methodSymbol, INamedTypeSymbol conditionalAttributeSymbol) =>
methodSymbol.GetAttributes().Any(n => n.AttributeClass.Equals(conditionalAttributeSymbol));
protected abstract bool IsEmptyFinalizer(SyntaxNode methodBody, CodeBlockAnalysisContext analysisContext);
}
}
| 61.0625 | 292 | 0.647646 | [
"Apache-2.0"
] | nathanstocking/roslyn-analyzers | src/Microsoft.CodeQuality.Analyzers/Core/QualityGuidelines/AbstractRemoveEmptyFinalizers.cs | 3,908 | C# |
// *****************************************************************************
// BSD 3-Clause License (https://github.com/ComponentFactory/Krypton/blob/master/LICENSE)
// © Component Factory Pty Ltd, 2006 - 2016, All rights reserved.
// The software and associated documentation supplied hereunder are the
// proprietary information of Component Factory Pty Ltd, 13 Swallows Close,
// Mornington, Vic 3931, Australia and are supplied subject to license terms.
//
// Modifications by Megakraken & Simon Coghlan(aka Smurf-IV) 2017 - 2020. All rights reserved. (https://github.com/Wagnerp/Krypton-NET-5.461)
// Version 5.461.0.0 www.ComponentFactory.com
// *****************************************************************************
using System;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.IO;
using System.Windows.Forms;
namespace ComponentFactory.Krypton.Toolkit
{
/// <summary>
/// A simple hex-editor form for displaying binary data.
/// </summary>
public class ByteViewerForm : KryptonForm
{
#region Instance Members
KryptonByteViewer _byteViewer;
IContainer components;
#endregion
#region Identity
/// <summary>
/// Initializes a new instance of the ByteViewerForm class.
/// </summary>
public ByteViewerForm()
{
InitializeComponent();
}
#endregion
#region Protected Overrides
/// <summary>
/// Raises the Load event.
/// </summary>
/// <param name="e">
/// The event arguments.
/// </param>
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
// We re-use the Tag property as input/output mechanism, so we don't have to create
// a new interface just for that. Kind of a hack, I know.
if (Tag is byte[] bytes)
{
_byteViewer.SetBytes(bytes);
}
}
/// <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?.Dispose();
}
base.Dispose(disposing);
}
#endregion
#region Private
private void OnCheckedButtonChanged(object sender, EventArgs e)
{
KryptonCheckSet checkset = (KryptonCheckSet)sender;
DisplayMode mode;
switch (checkset.CheckedButton.Text)
{
case "ANSI":
mode = DisplayMode.Ansi;
break;
case "Unicode":
mode = DisplayMode.Unicode;
break;
//case "Hex":
default:
mode = DisplayMode.Hexdump;
break;
}
// Sets the display mode.
if (_byteViewer != null && _byteViewer.GetDisplayMode() != mode)
{
_byteViewer.SetDisplayMode(mode);
}
}
private void OnClickExport(object sender, EventArgs e)
{
using (SaveFileDialog sfd = new SaveFileDialog
{
CheckFileExists = false,
CheckPathExists = false,
Filter = @"All Files (*.*)|*.*"
})
{
if (sfd.ShowDialog(this) == DialogResult.OK)
{
if (Tag is byte[] bytes)
{
File.WriteAllBytes(sfd.FileName, bytes);
// FIXME: string literal.
KryptonMessageBox.Show(this, $"Data exported to {sfd.FileName}", "Data Export",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
}
/// <summary>
/// Initializes the Form's components.
/// </summary>
private void InitializeComponent()
{
components = new Container();
_byteViewer = new KryptonByteViewer();
KryptonPanel bottomPanel = new KryptonPanel();
KryptonPanel topPanel = new KryptonPanel();
KryptonGroupBox groupBox = new KryptonGroupBox();
KryptonCheckButton unicodeButton = new KryptonCheckButton();
KryptonCheckButton hexButton = new KryptonCheckButton();
KryptonCheckButton ansiButton = new KryptonCheckButton();
KryptonCheckButton export = new KryptonCheckButton();
KryptonCheckSet displayModeCheckset = new KryptonCheckSet(components);
((ISupportInitialize)(topPanel)).BeginInit();
topPanel.SuspendLayout();
((ISupportInitialize)(groupBox)).BeginInit();
groupBox.Panel.BeginInit();
groupBox.Panel.SuspendLayout();
groupBox.SuspendLayout();
((ISupportInitialize)(displayModeCheckset)).BeginInit();
((ISupportInitialize)(bottomPanel)).BeginInit();
SuspendLayout();
//
// topPanel
//
topPanel.AutoSize = true;
topPanel.Controls.Add(groupBox);
topPanel.Controls.Add(export);
topPanel.Dock = DockStyle.Top;
topPanel.Location = new System.Drawing.Point(0, 0);
topPanel.Name = "topPanel";
topPanel.Padding = new Padding(5);
topPanel.Size = new System.Drawing.Size(639, 65);
topPanel.TabIndex = 0;
//
// groupBox
//
groupBox.AutoSize = true;
groupBox.Location = new System.Drawing.Point(5, 0);
groupBox.Name = "groupBox";
//
// groupBox.Panel
//
groupBox.Panel.Controls.Add(unicodeButton);
groupBox.Panel.Controls.Add(hexButton);
groupBox.Panel.Controls.Add(ansiButton);
groupBox.Size = new System.Drawing.Size(280, 57);
groupBox.TabIndex = 0;
groupBox.Values.Heading = @"Display Mode";
//
// unicodeButton
//
unicodeButton.Location = new System.Drawing.Point(141, 3);
unicodeButton.Name = "unicodeButton";
unicodeButton.Size = new System.Drawing.Size(63, 25);
unicodeButton.TabIndex = 3;
unicodeButton.Values.Text = @"Unicode";
//
// hexButton
//
hexButton.Checked = true;
hexButton.Location = new System.Drawing.Point(3, 3);
hexButton.Name = "hexButton";
hexButton.Size = new System.Drawing.Size(63, 25);
hexButton.TabIndex = 2;
hexButton.Values.Text = @"Hex";
//
// ansiButton
//
ansiButton.Location = new System.Drawing.Point(72, 3);
ansiButton.Name = "ansiButton";
ansiButton.Size = new System.Drawing.Size(63, 25);
ansiButton.TabIndex = 1;
ansiButton.Values.Text = @"ANSI";
//
// displayModeCheckset
//
displayModeCheckset.CheckButtons.Add(ansiButton);
displayModeCheckset.CheckButtons.Add(hexButton);
displayModeCheckset.CheckButtons.Add(unicodeButton);
displayModeCheckset.CheckedButton = hexButton;
displayModeCheckset.CheckedButtonChanged += OnCheckedButtonChanged;
//
// export
//
export.Location = new System.Drawing.Point(535, 22);
export.Name = "export";
export.Size = new System.Drawing.Size(80, 25);
export.TabIndex = 4;
export.Values.Text = @"Export...";
export.Click += OnClickExport;
//
// bottomPanel
//
bottomPanel.Dock = DockStyle.Fill;
bottomPanel.Location = new System.Drawing.Point(0, 65);
bottomPanel.Name = "bottomPanel";
bottomPanel.Size = new System.Drawing.Size(639, 401);
bottomPanel.TabIndex = 1;
bottomPanel.Controls.Add(_byteViewer);
//
// byteViewer
//
_byteViewer.Dock = DockStyle.Fill;
_byteViewer.CellBorderStyle = TableLayoutPanelCellBorderStyle.None;
//
// Form1
//
AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new System.Drawing.Size(639, 466);
Controls.Add(bottomPanel);
Controls.Add(topPanel);
FormBorderStyle = FormBorderStyle.FixedToolWindow;
StartPosition = FormStartPosition.CenterParent;
Name = @"Binary Viewer";
Text = @"Binary Viewer";
((ISupportInitialize)(topPanel)).EndInit();
topPanel.ResumeLayout(false);
topPanel.PerformLayout();
groupBox.Panel.EndInit();
groupBox.Panel.ResumeLayout(false);
((ISupportInitialize)(groupBox)).EndInit();
groupBox.ResumeLayout(false);
((ISupportInitialize)(displayModeCheckset)).EndInit();
((ISupportInitialize)(bottomPanel)).EndInit();
ResumeLayout(false);
PerformLayout();
}
#endregion
}
}
| 38.03937 | 142 | 0.534568 | [
"BSD-3-Clause"
] | Krypton-Suite-Legacy/Krypton-NET-5.461 | Source/Krypton Components/ComponentFactory.Krypton.Toolkit/Controls Visuals/ByteViewerForm.cs | 9,665 | C# |
using System;
using System.Collections.Generic;
using Android.Content;
using Android.Views;
using Android.Util;
using Android.Graphics;
using Android.Animation;
using Android.Views.Animations;
using Java.Interop;
namespace com.frankcalise.widgets
{
public class FitChart : View
{
const int AnimationDuration = 1000;
const int AnimationModeLinear = 0;
const int AnimationModeOverdraw = 1;
const int DefaultViewRadius = 0;
const int DefaultMinValue = 0;
const int DefaultMaxValue = 100;
const int DesignModeSweepAngle = 216;
const float InitialAnimationProgress = 0.0f;
const float MaximumSweepAngle = 360f;
public const float StartAngle = -90;
public float MinValue { get; set; }
public float MaxValue { get; set; }
public AnimationMode AnimationMode { get; set; }
List<FitChartValue> chartValues;
float animationProgress = FitChart.InitialAnimationProgress;
float maxSweepAngle = FitChart.MaximumSweepAngle;
Paint backStrokePaint;
Paint valueDesignPaint;
RectF drawingArea;
Color backStrokeColor;
Color valueStrokeColor;
float strokeSize;
public FitChart (Context context) : base(context)
{
InitializeView (null);
}
public FitChart(Context context, IAttributeSet attrs) : base(context, attrs)
{
InitializeView (attrs);
}
public FitChart(Context context, IAttributeSet attrs, int defStyleAttr)
: base(context, attrs, defStyleAttr)
{
InitializeView(attrs);
}
public void SetValue(float value)
{
chartValues.Clear ();
var chartValue = new FitChartValue (value, valueStrokeColor);
chartValue.Paint = BuildPaintForValue();
chartValue.StartAngle = StartAngle;
chartValue.SweepAngle = CalculateSweepAngle(value);
chartValues.Add(chartValue);
maxSweepAngle = chartValue.SweepAngle;
PlayAnimation();
}
public void SetValues(List<FitChartValue> values)
{
chartValues.Clear ();
maxSweepAngle = 0;
var offsetSweetAngle = StartAngle;
foreach (var chartValue in values)
{
var sweepAngle = CalculateSweepAngle (chartValue.Value);
chartValue.Paint = BuildPaintForValue();
chartValue.StartAngle = offsetSweetAngle;
chartValue.SweepAngle = sweepAngle;
chartValues.Add (chartValue);
offsetSweetAngle += sweepAngle;
maxSweepAngle += sweepAngle;
}
PlayAnimation ();
}
[Export]
private void setAnimationSeek(float value)
{
animationProgress = value;
base.Invalidate();
}
private Paint BuildPaintForValue()
{
var paint = GetPaint ();
paint.SetStyle (Paint.Style.Stroke);
paint.StrokeWidth = strokeSize;
paint.StrokeCap = Paint.Cap.Round;
return paint;
}
private void InitializeView(IAttributeSet attrs)
{
AnimationMode = AnimationMode.Linear;
MaxValue = DefaultMaxValue;
MinValue = DefaultMinValue;
chartValues = new List<FitChartValue> ();
InitializeBackground ();
ReadAttributes (attrs);
PreparePaints ();
}
private void InitializeBackground()
{
if (!IsInEditMode)
{
if (Background == null)
{
SetBackgroundColor (Context.Resources.GetColor (Resource.Color.default_back_color));
}
}
}
private void CalculateDrawableArea()
{
var drawPadding = strokeSize / 2;
var width = (float)Width;
var height = (float)Height;
var left = drawPadding;
var top = drawPadding;
var right = width - drawPadding;
var bottom = height - drawPadding;
drawingArea = new RectF(left, top, right, bottom);
}
private void ReadAttributes(IAttributeSet attrs)
{
valueStrokeColor = Context.Resources.GetColor (Resource.Color.default_chart_value_color);
backStrokeColor = Context.Resources.GetColor (Resource.Color.default_back_stroke_color);
strokeSize = Context.Resources.GetDimension (Resource.Dimension.default_stroke_size);
if (attrs != null)
{
var attributes = Context.Theme.ObtainStyledAttributes (attrs, Resource.Styleable.FitChart, 0, 0);
strokeSize = attributes.GetDimensionPixelSize (Resource.Styleable.FitChart_strokeSize, (int)strokeSize);
valueStrokeColor = attributes.GetColor (Resource.Styleable.FitChart_valueStrokeColor, valueStrokeColor);
backStrokeColor = attributes.GetColor (Resource.Styleable.FitChart_backStrokeColor, backStrokeColor);
var attrAnimationMode = attributes.GetInt (Resource.Styleable.FitChart_animationMode, AnimationModeLinear);
if (attrAnimationMode == AnimationModeLinear)
{
AnimationMode = AnimationMode.Linear;
}
else
{
AnimationMode = AnimationMode.Overdraw;
}
attributes.Recycle ();
}
}
private void PreparePaints()
{
backStrokePaint = GetPaint ();
backStrokePaint.Color = backStrokeColor;
backStrokePaint.SetStyle (Paint.Style.Stroke);
backStrokePaint.StrokeWidth = strokeSize;
valueDesignPaint = GetPaint ();
valueDesignPaint.Color = valueStrokeColor;
valueDesignPaint.SetStyle (Paint.Style.Stroke);
valueDesignPaint.StrokeCap = Paint.Cap.Round;
valueDesignPaint.StrokeWidth = strokeSize;
}
private Paint GetPaint()
{
if (!IsInEditMode)
{
return new Paint (PaintFlags.AntiAlias);
}
else
{
return new Paint ();
}
}
private float GetViewRadius()
{
if (drawingArea != null)
{
return (drawingArea.Width() / 2);
}
else
{
return DefaultViewRadius;
}
}
protected override void OnSizeChanged(int w, int h, int oldw, int oldh)
{
base.OnSizeChanged (w, h, oldw, oldh);
CalculateDrawableArea ();
}
protected override void OnMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
base.OnMeasure (widthMeasureSpec, heightMeasureSpec);
var size = Math.Max (MeasuredWidth, MeasuredHeight);
SetMeasuredDimension (size, size);
}
protected override void OnDraw(Canvas canvas)
{
base.OnDraw (canvas);
RenderBack (canvas);
RenderValues (canvas);
}
private void RenderBack(Canvas canvas)
{
var Path = new Path();
var viewRadius = GetViewRadius ();
Path.AddCircle (drawingArea.CenterX(), drawingArea.CenterY(), viewRadius, Path.Direction.Ccw);
canvas.DrawPath (Path, backStrokePaint);
}
private void RenderValues(Canvas canvas)
{
if (!IsInEditMode)
{
var valuesCounter = chartValues.Count - 1;
for (var index = valuesCounter; index >= 0; index--)
{
RenderValue (canvas, chartValues [index]);
}
}
else
{
RenderValue (canvas, null);
}
}
private void RenderValue(Canvas canvas, FitChartValue value)
{
if (!IsInEditMode)
{
var animationSeek = CalculateAnimationSeek ();
var renderer = RendererFactory.Renderer (AnimationMode, value, drawingArea);
var path = renderer.BuildPath (animationProgress, animationSeek);
if (path != null)
{
canvas.DrawPath (path, value.Paint);
}
}
else
{
var path = new Path ();
path.AddArc (drawingArea, StartAngle, DesignModeSweepAngle);
canvas.DrawPath (path, valueDesignPaint);
}
}
private float CalculateAnimationSeek()
{
return ((MaximumSweepAngle * animationProgress) + StartAngle);
}
private float CalculateSweepAngle(float value)
{
var chartValuesWindow = Math.Max (MinValue, MaxValue) - Math.Min (MinValue, MaxValue);
var chartValuesScale = (360.0f / chartValuesWindow);
return (value * chartValuesScale);
}
private void PlayAnimation()
{
var animator = ObjectAnimator.OfFloat (this, "animationSeek", 0.0f, 1.0f);
var animatorSet = new AnimatorSet ();
animatorSet.SetDuration (AnimationDuration);
animatorSet.SetInterpolator (new DecelerateInterpolator ());
animatorSet.SetTarget (this);
animatorSet.Play(animator);
animatorSet.Start();
}
}
}
| 24.949045 | 111 | 0.698494 | [
"Apache-2.0"
] | frankcalise/XamDroid.FitChart | Library/XamDroid.FitChart/FitChart.cs | 7,836 | C# |
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Text.RegularExpressions;
using Microsoft.Recognizers.Definitions.Spanish;
namespace Microsoft.Recognizers.Text.Number.Spanish
{
public class OrdinalExtractor : BaseNumberExtractor
{
internal sealed override ImmutableDictionary<Regex, TypeTag> Regexes { get; }
protected sealed override string ExtractType { get; } = Constants.SYS_NUM_ORDINAL; // "Ordinal";
public OrdinalExtractor()
{
var regexes = new Dictionary<Regex, TypeTag>
{
{
new Regex(
NumbersDefinitions.OrdinalSuffixRegex,
RegexOptions.IgnoreCase | RegexOptions.Singleline)
, RegexTagGenerator.GenerateRegexTag(Constants.ORDINAL_PREFIX, Constants.NUMBER_SUFFIX)
},
{
new Regex(NumbersDefinitions.OrdinalNounRegex,
RegexOptions.IgnoreCase | RegexOptions.Singleline)
, RegexTagGenerator.GenerateRegexTag(Constants.ORDINAL_PREFIX, Constants.SPANISH)
}
};
this.Regexes = regexes.ToImmutableDictionary();
}
}
} | 37.514286 | 108 | 0.597867 | [
"MIT"
] | Josverl/Recognizers-Text | .NET/Microsoft.Recognizers.Text.Number/Spanish/Extractors/OrdinalExtractor.cs | 1,315 | C# |
using System;
using System.Collections.Generic;
namespace WebMagicSharp
{
/// <summary>
///
/// </summary>
public interface IMultiPageModel
{
/// <summary>
///
/// </summary>
/// <returns></returns>
string GetPageKey();
/// <summary>
///
/// </summary>
/// <returns></returns>
string GetPage();
/// <summary>
///
/// </summary>
/// <returns></returns>
ICollection<String> GetOtherPages();
/// <summary>
///
/// </summary>
/// <param name="multiPageModel"></param>
/// <returns></returns>
IMultiPageModel Combine(IMultiPageModel multiPageModel);
}
}
| 20.297297 | 64 | 0.474035 | [
"Apache-2.0"
] | Peefy/DuGu.WebMagicSharp | WebMagicSharp.Extensions/IMultiPageModel.cs | 753 | C# |
using System;
using Pango;
using VisualStudio.Mac.CoreUI;
namespace VisualStudio.Mac.Helpers
{
public static class FontDescriptionHelper
{
internal static FontDescription CreateFontDescription(double fontSize, string fontFamily, FontAttributes attributes)
{
FontDescription fontDescription = new FontDescription();
fontDescription.Size = (int)(fontSize * Scale.PangoScale);
fontDescription.Family = fontFamily;
fontDescription.Weight = attributes == FontAttributes.Bold ? Weight.Bold : Weight.Normal;
fontDescription.Style = attributes == FontAttributes.Italic ? Pango.Style.Italic : Pango.Style.Normal;
return fontDescription;
}
}
}
| 35.47619 | 124 | 0.695302 | [
"MIT"
] | andreinitescu/HotReloading | IDE/VisualStudio.Mac/Helpers/FontDescriptionHelper.cs | 747 | C# |
using System;
using System.Collections.Generic;
namespace PierresVendors.Models
{
public class Vendor
{
private static List<Vendor> _vendors = new List<Vendor>{};
private static int _count = 0;
public string Name {get;set;}
public string Description {get;set;}
public int Id {get;}
public List<Order> Orders {get;set;}
public Vendor(string name, string description)
{
Name = name;
Description = description;
_vendors.Add(this);
Id = _count++;
Orders = new List<Order>{};
}
public static List<Vendor> GetAll()
{
return _vendors;
}
public static Vendor Find(int id)
{
int index = _vendors.FindIndex(vendor => vendor.Id == id);
return _vendors[index];
}
public void AddOrder(Order order)
{
Orders.Add(order);
}
}
} | 20.238095 | 64 | 0.618824 | [
"MIT"
] | PRKille/PierresVendors.Solution | PierresVendors/Models/Vendor.cs | 850 | C# |
/*
* Copyright 2018 JDCLOUD.COM
*
* 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.
*
* Monitoring Rules APIs
* 云监控规则相关接口,提供创建、查询、修改、删除监控规则等功能
*
* OpenAPI spec version: v2
* Contact:
*
* NOTE: This class is auto generated by the jdcloud code generator program.
*/
using System;
using System.Collections.Generic;
using System.Text;
using JDCloudSDK.Core.Service;
namespace JDCloudSDK.Monitor.Apis
{
/// <summary>
/// 查询规则列表
/// </summary>
public class DescribeAlarmsResponse : JdcloudResponse<DescribeAlarmsResult>
{
}
} | 25.97561 | 79 | 0.723005 | [
"Apache-2.0"
] | jdcloud-api/jdcloud-sdk-net | sdk/src/Service/Monitor/Apis/DescribeAlarmsResponse.cs | 1,137 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System;
using System.Globalization;
using System.Threading;
using Microsoft.WindowsAzure.Storage.Table;
namespace Microsoft.Azure.WebJobs.Logging.Internal
{
/// <summary>
/// Entity for logging function instance counts
/// </summary>
public class InstanceCountEntity : TableEntity
{
const string PartitionKeyFormat = TableScheme.InstanceCountPK;
const string RowKeyPrefix = "{0:D20}-";
const string RowKeyFormat = "{0:D20}-{1}-{2}"; // timestamp ticks, container name, salt
// Have a salt value for writing to avoid collisions since timeBucket is not gauranteed to be unique
// when many functions are quickly run within a single time tick.
static int _salt;
public InstanceCountEntity()
{
}
// from rowKey
public long GetTicks()
{
var time = TableScheme.Get1stTerm(this.RowKey);
long ticks = long.Parse(time, CultureInfo.InvariantCulture);
return ticks;
}
public long GetEndTicks()
{
var startTicks = GetTicks();
var endTime = new DateTime(startTicks).AddMilliseconds(this.DurationMilliseconds);
var endTicks = endTime.Ticks;
return endTicks;
}
public long GetDurationInTicks()
{
return TimeSpan.FromMilliseconds(DurationMilliseconds).Ticks;
}
public InstanceCountEntity(long ticks, string containerName)
{
int salt = Interlocked.Increment(ref _salt);
this.PartitionKey = PartitionKeyFormat;
this.RowKey = string.Format(CultureInfo.InvariantCulture, RowKeyFormat, ticks, containerName, salt);
}
public static TableQuery<InstanceCountEntity> GetQuery(DateTime startTime, DateTime endTime)
{
if (startTime > endTime)
{
throw new InvalidOperationException("Start time must be less than or equal to end time");
}
string rowKeyStart = string.Format(CultureInfo.InvariantCulture, RowKeyPrefix, startTime.Ticks);
string rowKeyEnd = string.Format(CultureInfo.InvariantCulture, RowKeyPrefix, endTime.Ticks);
var query = TableScheme.GetRowsInRange<InstanceCountEntity>(PartitionKeyFormat, rowKeyStart, rowKeyEnd);
return query;
}
/// <summary>
/// Number of individual instances active in this period
/// </summary>
public int CurrentActive { get; set; }
/// <summary>
/// Number of total instances started during this period
/// </summary>
public int TotalThisPeriod { get; set; }
/// <summary>
/// Size of the machine that these instances ran on.
/// </summary>
public int MachineSize { get; set; }
/// <summary>
/// Polling duration in MS.
/// </summary>
public int DurationMilliseconds { get; set; }
}
} | 35.1 | 116 | 0.626148 | [
"MIT"
] | gcollic/azure-webjobs-sdk | src/Microsoft.Azure.WebJobs.Logging/Entities/InstanceCountEntity.cs | 3,161 | C# |
// (c) Copyright HutongGames, LLC 2010-2013. All rights reserved.
using UnityEngine;
namespace HutongGames.PlayMaker.Actions
{
[ActionCategory(ActionCategory.Animation)]
[Tooltip("Stops all playing Animations on a Game Object. Optionally, specify a single Animation to Stop.")]
public class StopAnimation : BaseAnimationAction
{
[RequiredField]
[CheckForComponent(typeof(Animation))]
public FsmOwnerDefault gameObject;
[Tooltip("Leave empty to stop all playing animations.")]
[UIHint(UIHint.Animation)]
public FsmString animName;
public override void Reset()
{
gameObject = null;
animName = null;
}
public override void OnEnter()
{
DoStopAnimation();
Finish();
}
private void DoStopAnimation()
{
var go = Fsm.GetOwnerDefaultTarget(gameObject);
if (!UpdateCache(go))
{
return;
}
if (FsmString.IsNullOrEmpty(animName))
{
animation.Stop();
}
else
{
animation.Stop(animName.Value);
}
}
/*
public override string ErrorCheck()
{
return ErrorCheckHelpers.CheckAnimationSetup(gameObject.value);
}*/
}
} | 22.018182 | 108 | 0.636664 | [
"MIT"
] | 517752548/UnityFramework | GameFrameWork/ThirdParty/PlayMaker/Actions/Animation/StopAnimation.cs | 1,211 | C# |
namespace ZbW.DependencyInjection.Console
{
public interface IWritable
{
void Write(string message);
}
} | 17.857143 | 42 | 0.672 | [
"MIT"
] | michikeiser/ZbW.DependencyInjection | ZbW.DependencyInjection.Console/IWritable.cs | 127 | C# |
// ==============================================================================================================
// Microsoft patterns & practices
// CQRS Journey project
// ==============================================================================================================
// ©2012 Microsoft. All rights reserved. Certain content used with permission from contributors
// http://cqrsjourney.github.com/contributors/members
// 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 Conference.Web.Public.Tests.Controllers.PaymentControllerFixture
{
using System;
using System.Collections.Specialized;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Conference.Web.Public.Controllers;
using Infrastructure.Messaging;
using Moq;
using Payments.Contracts.Commands;
using Payments.ReadModel;
using Xunit;
public class given_controller
{
private PaymentController sut;
private Mock<ICommandBus> commandBusMock;
private Mock<IPaymentDao> paymentDaoMock;
public given_controller()
{
var routes = new RouteCollection();
routes.MapRoute("PaymentAccept", "accept", new { controller = "Payment", action = "ThirdPartyProcessorPaymentAccepted" });
routes.MapRoute("PaymentReject", "reject", new { controller = "Payment", action = "ThirdPartyProcessorPaymentRejected" });
routes.MapRoute("Pay", "payment", new { controller = "ThirdPartyProcessorPayment", action = "Pay" });
var requestMock = new Mock<HttpRequestBase>(MockBehavior.Strict);
requestMock.SetupGet(x => x.ApplicationPath).Returns("/");
requestMock.SetupGet(x => x.Url).Returns(new Uri("http://localhost/request", UriKind.Absolute));
requestMock.SetupGet(x => x.ServerVariables).Returns(new NameValueCollection());
var responseMock = new Mock<HttpResponseBase>(MockBehavior.Strict);
responseMock.Setup(x => x.ApplyAppPathModifier(It.IsAny<string>())).Returns<string>(s => s);
var context = Mock.Of<HttpContextBase>(c => c.Request == requestMock.Object && c.Response == responseMock.Object);
this.commandBusMock = new Mock<ICommandBus>();
this.paymentDaoMock = new Mock<IPaymentDao>();
this.sut = new PaymentController(this.commandBusMock.Object, this.paymentDaoMock.Object);
this.sut.ControllerContext = new ControllerContext(context, new RouteData(), this.sut);
this.sut.Url = new UrlHelper(new RequestContext(context, new RouteData()), routes);
}
[Fact]
public void when_initiating_third_party_processor_payment_then_redirects_to_thid_party()
{
// Arrange
var paymentId = Guid.NewGuid();
this.paymentDaoMock
.Setup(pd => pd.GetThirdPartyProcessorPaymentDetails(It.IsAny<Guid>()))
.Returns(new ThirdPartyProcessorPaymentDetailsDTO(Guid.NewGuid(), Payments.ThirdPartyProcessorPayment.States.Initiated, Guid.NewGuid(), "payment", 100));
// Act
var result = (RedirectResult)this.sut.ThirdPartyProcessorPayment("conference", paymentId, "accept", "reject");
// Assert
Assert.False(result.Permanent);
Assert.True(result.Url.StartsWith("/payment"));
}
[Fact]
public void when_payment_is_accepted_then_redirects_to_order()
{
// Arrange
var paymentId = Guid.NewGuid();
// Act
var result = (RedirectResult)this.sut.ThirdPartyProcessorPaymentAccepted("conference", paymentId, "accept");
// Assert
Assert.Equal("accept", result.Url);
Assert.False(result.Permanent);
}
[Fact]
public void when_payment_is_accepted_then_publishes_command()
{
// Arrange
var paymentId = Guid.NewGuid();
// Act
var result = (RedirectResult)this.sut.ThirdPartyProcessorPaymentAccepted("conference", paymentId, "accept");
// Assert
this.commandBusMock.Verify(
cb => cb.Send(It.Is<Envelope<ICommand>>(e => ((CompleteThirdPartyProcessorPayment)e.Body).PaymentId == paymentId)),
Times.Once());
}
[Fact]
public void when_payment_is_rejected_then_redirects_to_order()
{
// Arrange
var paymentId = Guid.NewGuid();
// Act
var result = (RedirectResult)this.sut.ThirdPartyProcessorPaymentRejected("conference", paymentId, "reject");
// Assert
Assert.Equal("reject", result.Url);
Assert.False(result.Permanent);
}
[Fact]
public void when_payment_is_rejected_then_publishes_command()
{
// Arrange
var paymentId = Guid.NewGuid();
// Act
var result = (RedirectResult)this.sut.ThirdPartyProcessorPaymentRejected("conference", paymentId, "reject");
// Assert
this.commandBusMock.Verify(
cb => cb.Send(It.Is<Envelope<ICommand>>(e => ((CancelThirdPartyProcessorPayment)e.Body).PaymentId == paymentId)),
Times.Once());
}
}
}
| 45.328358 | 170 | 0.594007 | [
"Apache-2.0"
] | gmelnik/cqrs-journey-code | source/Conference/Conference.Web.Public.Tests/Controllers/PaymentControllerFixture.cs | 6,077 | C# |
using System;
namespace services.Models.Data
{
public class StreamNet_JuvOutmigrantsDetail_Header : DataHeader
{
}
} | 14.555556 | 67 | 0.732824 | [
"Unlicense"
] | samanthas14/cdms-be-public | services/Models/Data/StreamNet_JuvOutmigrantsDetail_Header.cs | 133 | C# |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="FlightTracking.xaml.cs" company="OpenSky">
// OpenSky project 2021-2022
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace OpenSky.Agent.Views
{
using System;
using System.Diagnostics;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using Microsoft.Maps.MapControl.WPF;
using OpenSky.Agent.Controls;
using OpenSky.Agent.Converters;
using OpenSky.Agent.Simulator;
using OpenSky.Agent.Simulator.Enums;
using OpenSky.Agent.Simulator.Models;
using OpenSky.Agent.Simulator.Tools;
using OpenSky.Agent.Views.Models;
/// -------------------------------------------------------------------------------------------------
/// <content>
/// Flight tracking view.
/// </content>
/// -------------------------------------------------------------------------------------------------
public partial class FlightTracking
{
/// -------------------------------------------------------------------------------------------------
/// <summary>
/// Initializes a new instance of the <see cref="FlightTracking"/> class.
/// </summary>
/// <remarks>
/// sushi.at, 17/03/2021.
/// </remarks>
/// -------------------------------------------------------------------------------------------------
private FlightTracking()
{
this.InitializeComponent();
}
/// -------------------------------------------------------------------------------------------------
/// <summary>
/// The single instance of this view.
/// </summary>
/// -------------------------------------------------------------------------------------------------
public static FlightTracking Instance { get; private set; }
/// -------------------------------------------------------------------------------------------------
/// <summary>
/// Open the flight tracking view or bring the existing instance into view.
/// </summary>
/// <remarks>
/// sushi.at, 17/03/2021.
/// </remarks>
/// -------------------------------------------------------------------------------------------------
public static void Open()
{
if (Instance == null)
{
if (!UserSessionService.Instance.IsUserLoggedIn)
{
LoginNotification.Open();
return;
}
Instance = new FlightTracking();
Instance.Closed += (_, _) => Instance = null;
Instance.Show();
}
else
{
Instance.BringIntoView();
Instance.Activate();
}
}
/// -------------------------------------------------------------------------------------------------
/// <summary>
/// Adds aircraft and trails to the map view.
/// </summary>
/// <remarks>
/// sushi.at, 22/03/2021.
/// </remarks>
/// -------------------------------------------------------------------------------------------------
private void AddAircraftAndTrailsToMap()
{
Debug.WriteLine("Adding aircraft and trails to the map view");
// Add Simbrief route to map
var simbriefRoute = new MapPolyline { Stroke = new SolidColorBrush(OpenSkyColors.OpenSkySimBrief), StrokeThickness = 4, Locations = ((FlightTrackingViewModel)this.DataContext).Simulator.SimbriefRouteLocations };
this.MapView.Children.Add(simbriefRoute);
// Add aircraft trail to map
var aircraftTrail = new MapPolyline { Stroke = new SolidColorBrush(OpenSkyColors.OpenSkyTeal), StrokeThickness = 4, Locations = ((FlightTrackingViewModel)this.DataContext).Simulator.AircraftTrailLocations };
this.MapView.Children.Add(aircraftTrail);
// Add aircraft position to map
var aircraftPosition = new Image { Width = 40, Height = 40 };
aircraftPosition.SetValue(Panel.ZIndexProperty, 999);
aircraftPosition.SetValue(MapLayer.PositionOriginProperty, PositionOrigin.Center);
var rotateTransform = new RotateTransform { CenterX = 20, CenterY = 20 };
var headingBinding = new Binding { Source = this.DataContext, Path = new PropertyPath("AircraftHeading"), Mode = BindingMode.OneWay };
BindingOperations.SetBinding(rotateTransform, RotateTransform.AngleProperty, headingBinding);
aircraftPosition.RenderTransform = rotateTransform;
var aircraftDrawingImage = this.FindResource("OpenSkyLogoPointingUpForMap") as DrawingImage;
aircraftPosition.Source = aircraftDrawingImage;
var positionBinding = new Binding { Source = this.DataContext, Path = new PropertyPath("AircraftLocation"), Mode = BindingMode.OneWay };
BindingOperations.SetBinding(aircraftPosition, MapLayer.PositionProperty, positionBinding);
this.MapView.Children.Add(aircraftPosition);
}
/// -------------------------------------------------------------------------------------------------
/// <summary>
/// Event log mouse double click.
/// </summary>
/// <remarks>
/// sushi.at, 17/03/2021.
/// </remarks>
/// <param name="sender">
/// Source of the event.
/// </param>
/// <param name="e">
/// Mouse button event information.
/// </param>
/// -------------------------------------------------------------------------------------------------
private void EventLogMouseDoubleClick(object sender, MouseButtonEventArgs e)
{
if (this.EventLog.SelectedItem is TrackingEventLogEntry selectedEventLog)
{
Debug.WriteLine($"User double clicked event log entry: {selectedEventLog.LogMessage}");
this.MapView.Center = selectedEventLog.Location;
this.UserMapInteraction(this, EventArgs.Empty);
}
}
/// -------------------------------------------------------------------------------------------------
/// <summary>
/// Flight tracking loaded.
/// </summary>
/// <remarks>
/// sushi.at, 18/03/2021.
/// </remarks>
/// <param name="sender">
/// Source of the event.
/// </param>
/// <param name="e">
/// Routed event information.
/// </param>
/// -------------------------------------------------------------------------------------------------
private void FlightTrackingLoaded(object sender, RoutedEventArgs e)
{
if (this.DataContext is FlightTrackingViewModel viewModelViewRef)
{
viewModelViewRef.ViewReference = this;
}
// Configure map view
this.MapView.CredentialsProvider = new ApplicationIdCredentialsProvider(UserSessionService.Instance.LinkedAccounts?.BingMapsKey);
this.AddAircraftAndTrailsToMap();
// Add fuel tank controls
foreach (FuelTank tank in Enum.GetValues(typeof(FuelTank)))
{
var control = new FuelTankControl { FuelTankName = tank.GetStringValue(), Margin = new Thickness(5, 2, 5, 2) };
var capacityBinding = new Binding { Source = this.DataContext, Path = new PropertyPath($"SimConnect.FuelTanks.Capacities[{(int)tank}]"), Mode = BindingMode.OneWay };
BindingOperations.SetBinding(control, FuelTankControl.FuelTankCapacityProperty, capacityBinding);
var quantityBinding = new Binding { Source = this.DataContext, Path = new PropertyPath($"FuelTankQuantities[{(int)tank}]"), Mode = BindingMode.TwoWay, UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged };
BindingOperations.SetBinding(control, FuelTankControl.FuelTankQuantityProperty, quantityBinding);
var visibilityBinding = new Binding { Source = this.DataContext, Path = new PropertyPath($"SimConnect.FuelTanks.Capacities[{(int)tank}]"), Mode = BindingMode.OneWay, Converter = new FuelTankCapacityVisibilityConverter() };
BindingOperations.SetBinding(control, VisibilityProperty, visibilityBinding);
var infoStringBinding = new Binding { Source = this.DataContext, Path = new PropertyPath($"FuelTankInfos[{(int)tank}]"), Mode = BindingMode.OneWay };
BindingOperations.SetBinding(control, FuelTankControl.FuelTankInfoProperty, infoStringBinding);
this.FuelTanksPanel.Children.Add(control);
}
// Add payload station controls
for (var i = 0; i < 15; i++)
{
var control = new PayloadStationControl { Margin = new Thickness(5, 2, 5, 2) };
var nameBinding = new Binding { Source = this.DataContext, Path = new PropertyPath($"SimConnect.PayloadStations.Names[{i}]"), Mode = BindingMode.OneWay };
BindingOperations.SetBinding(control, PayloadStationControl.PayloadStationNameProperty, nameBinding);
var weightBinding = new Binding { Source = this.DataContext, Path = new PropertyPath($"PayloadStationWeights[{i}]"), Mode = BindingMode.TwoWay, UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged };
BindingOperations.SetBinding(control, PayloadStationControl.PayloadStationWeightProperty, weightBinding);
var visibilityBinding = new Binding
{ Source = this.DataContext, Path = new PropertyPath("SimConnect.PayloadStations.Count"), Mode = BindingMode.OneWay, Converter = new PayloadStationsVisibilityConverter(), ConverterParameter = i + 1 };
BindingOperations.SetBinding(control, VisibilityProperty, visibilityBinding);
this.PayloadStationsPanel.Children.Add(control);
}
// Replay past tracking markers to add to this view
if (this.DataContext is FlightTrackingViewModel viewModel)
{
viewModel.Simulator.ReplayMapMarkers();
viewModel.Simulator.NextStepFlashingChanged += this.SimConnectNextStepFlashingChanged;
this.SimConnectNextStepFlashingChanged(this, viewModel.Simulator.NextStepFlashing);
}
}
/// -------------------------------------------------------------------------------------------------
/// <summary>
/// Flight tracking window on unloaded.
/// </summary>
/// <remarks>
/// sushi.at, 24/03/2021.
/// </remarks>
/// <param name="sender">
/// Source of the event.
/// </param>
/// <param name="e">
/// Routed event information.
/// </param>
/// -------------------------------------------------------------------------------------------------
private void FlightTrackingOnUnloaded(object sender, RoutedEventArgs e)
{
foreach (UIElement child in this.MapView.Children)
{
if (child is SimbriefWaypointMarker simbrief)
{
BindingOperations.ClearAllBindings(simbrief);
}
if (child is TrackingEventMarker { IsAirportMarker: true })
{
BindingOperations.ClearAllBindings(child);
}
}
this.MapView.Children.Clear();
}
/// -------------------------------------------------------------------------------------------------
/// <summary>
/// Flight tracking view model on map position updated.
/// </summary>
/// <remarks>
/// sushi.at, 24/03/2021.
/// </remarks>
/// <param name="sender">
/// Source of the event.
/// </param>
/// <param name="e">
/// A Location to process.
/// </param>
/// -------------------------------------------------------------------------------------------------
private void FlightTrackingViewModelOnMapPositionUpdated(object sender, MapPositionUpdate e)
{
if (e.IsUserAction)
{
this.MapView.Center = e.Location;
}
else
{
// Check if the plane is out of bounds before we move the map
var point = this.MapView.LocationToViewportPoint(e.Location);
var horizontalBorder = Math.Min(this.MapView.ActualWidth * 0.1, 40);
var verticalBorder = Math.Min(this.MapView.ActualHeight * 0.1, 40);
if (point.X <= horizontalBorder || point.X >= (this.MapView.ActualWidth - horizontalBorder) || point.Y <= verticalBorder || point.Y >= (this.MapView.ActualHeight - verticalBorder))
{
Debug.WriteLine($"Plane icon out-of-bounds on mapview, re-centering to {e.Location.Latitude} {e.Location.Longitude}");
this.MapView.Center = e.Location;
}
}
}
/// -------------------------------------------------------------------------------------------------
/// <summary>
/// Flight tracking view model wants to reset the tracking map.
/// </summary>
/// <remarks>
/// sushi.at, 22/03/2021.
/// </remarks>
/// <param name="sender">
/// Source of the event.
/// </param>
/// <param name="e">
/// Event information.
/// </param>
/// -------------------------------------------------------------------------------------------------
private void FlightTrackingViewModelOnResetTrackingMap(object sender, EventArgs e)
{
this.MapView.Children.Clear();
this.AddAircraftAndTrailsToMap();
}
/// -------------------------------------------------------------------------------------------------
/// <summary>
/// Flight tracking view model on simbrief waypoint marker added.
/// </summary>
/// <remarks>
/// sushi.at, 22/03/2021.
/// </remarks>
/// <param name="sender">
/// Source of the event.
/// </param>
/// <param name="e">
/// A SimbriefWaypointMarker to process.
/// </param>
/// -------------------------------------------------------------------------------------------------
private void FlightTrackingViewModelOnSimbriefWaypointMarkerAdded(object sender, SimbriefWaypointMarker e)
{
try
{
// Make sure we remove it from any previous map layers
var existingMapLayer = e.Parent as MapLayer;
existingMapLayer?.Children.Remove(e);
if (BindingOperations.IsDataBound(e, SimbriefWaypointMarker.TextLabelVisibleProperty))
{
BindingOperations.ClearBinding(e, SimbriefWaypointMarker.TextLabelVisibleProperty);
}
if (BindingOperations.IsDataBound(e, SimbriefWaypointMarker.TextLabelFontSizeProperty))
{
BindingOperations.ClearBinding(e, SimbriefWaypointMarker.TextLabelFontSizeProperty);
}
this.MapView.Children.Add(e);
// Add zoom level -> visibility binding with custom converter
var zoomLevelBinding = new Binding { Source = this.MapView, Path = new PropertyPath("ZoomLevel"), Converter = new MapZoomLevelVisibilityConverter(), ConverterParameter = 6.0 };
BindingOperations.SetBinding(e, SimbriefWaypointMarker.TextLabelVisibleProperty, zoomLevelBinding);
var fontSizeBinding = new Binding { Source = this.MapView, Path = new PropertyPath("ZoomLevel"), Converter = new MapZoomLevelFontSizeConverter() };
BindingOperations.SetBinding(e, SimbriefWaypointMarker.TextLabelFontSizeProperty, fontSizeBinding);
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
}
/// -------------------------------------------------------------------------------------------------
/// <summary>
/// Flight tracking view model tracking event marker added.
/// </summary>
/// <remarks>
/// sushi.at, 17/03/2021.
/// </remarks>
/// <param name="sender">
/// Source of the event.
/// </param>
/// <param name="e">
/// A TrackingEventMarker to process.
/// </param>
/// -------------------------------------------------------------------------------------------------
private void FlightTrackingViewModelTrackingEventMarkerAdded(object sender, TrackingEventMarker e)
{
try
{
// Make sure we remove it from any previous map layers
var existingMapLayer = e.Parent as MapLayer;
existingMapLayer?.Children.Remove(e);
if (BindingOperations.IsDataBound(e, VisibilityProperty))
{
BindingOperations.ClearBinding(e, VisibilityProperty);
}
this.MapView.Children.Add(e);
if (e.IsAirportMarker)
{
if (e.IsAirportDetailMarker)
{
var zoomLevelBinding = new Binding { Source = this.MapView, Path = new PropertyPath("ZoomLevel"), Converter = new MapZoomLevelVisibilityConverter(), ConverterParameter = 12.0 };
BindingOperations.SetBinding(e, VisibilityProperty, zoomLevelBinding);
}
else
{
var zoomLevelBinding = new Binding { Source = this.MapView, Path = new PropertyPath("ZoomLevel"), Converter = new MapZoomLevelVisibilityConverter(), ConverterParameter = -12.0 };
BindingOperations.SetBinding(e, VisibilityProperty, zoomLevelBinding);
}
}
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
}
/// -------------------------------------------------------------------------------------------------
/// <summary>
/// Ground handling warning on is visible changed.
/// </summary>
/// <remarks>
/// sushi.at, 21/03/2021.
/// </remarks>
/// <param name="sender">
/// Source of the event.
/// </param>
/// <param name="e">
/// Dependency property changed event information.
/// </param>
/// -------------------------------------------------------------------------------------------------
private void GroundHandlingWarningOnIsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
{
var storyboard = this.Resources["WarningFade"] as Storyboard;
if (this.GroundHandlingWarning.IsVisible)
{
storyboard?.Begin();
}
else
{
storyboard?.Stop();
}
}
/// -------------------------------------------------------------------------------------------------
/// <summary>
/// Map type selection changed.
/// </summary>
/// <remarks>
/// sushi.at, 25/03/2021.
/// </remarks>
/// <param name="sender">
/// Source of the event.
/// </param>
/// <param name="e">
/// Selection changed event information.
/// </param>
/// -------------------------------------------------------------------------------------------------
private void MapTypeOnSelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (this.MapType.SelectedItem is ComboBoxItem item)
{
switch (item.Content as string)
{
case "Road":
this.MapView.Mode = new RoadMode();
break;
case "Aerial":
this.MapView.Mode = new AerialMode();
break;
}
}
}
/// -------------------------------------------------------------------------------------------------
/// <summary>
/// SimConnect next step flashing changed.
/// </summary>
/// <remarks>
/// sushi.at, 22/03/2021.
/// </remarks>
/// <param name="sender">
/// Source of the event.
/// </param>
/// <param name="nextStepFlashing">
/// True to make the next step flashing.
/// </param>
/// -------------------------------------------------------------------------------------------------
private void SimConnectNextStepFlashingChanged(object sender, bool nextStepFlashing)
{
if (nextStepFlashing)
{
UpdateGUIDelegate toggleStoryboard = () =>
{
var storyboard = this.Resources["NextStepFade"] as Storyboard;
storyboard?.Begin();
};
this.Dispatcher.BeginInvoke(toggleStoryboard);
}
else
{
UpdateGUIDelegate toggleStoryboard = () =>
{
var storyboard = this.Resources["NextStepFade"] as Storyboard;
storyboard?.Stop();
};
this.Dispatcher.BeginInvoke(toggleStoryboard);
}
}
/// -------------------------------------------------------------------------------------------------
/// <summary>
/// The user interacted with the map.
/// </summary>
/// <remarks>
/// sushi.at, 24/03/2021.
/// </remarks>
/// <param name="sender">
/// Source of the event.
/// </param>
/// <param name="e">
/// Mouse button event information.
/// </param>
/// -------------------------------------------------------------------------------------------------
private void UserMapInteraction(object sender, EventArgs e)
{
var viewModel = (FlightTrackingViewModel)this.DataContext;
viewModel.LastUserMapInteraction = DateTime.UtcNow;
}
}
} | 46.293173 | 238 | 0.473627 | [
"MIT"
] | opensky-to/agent | OpenSky.Agent/Views/FlightTracking.xaml.cs | 23,056 | 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 Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.VisualStudio.IntegrationTest.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Roslyn.VisualStudio.IntegrationTests.CSharp
{
[Collection(nameof(SharedIntegrationHostFixture))]
public class CSharpSquigglesDesktop : CSharpSquigglesCommon
{
public CSharpSquigglesDesktop(VisualStudioInstanceFactory instanceFactory)
: base(instanceFactory, WellKnownProjectTemplates.ClassLibrary)
{
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ErrorSquiggles)]
public override void VerifySyntaxErrorSquiggles()
{
base.VerifySyntaxErrorSquiggles();
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ErrorSquiggles)]
public override void VerifySemanticErrorSquiggles()
{
base.VerifySemanticErrorSquiggles();
}
}
}
| 34.741935 | 161 | 0.722377 | [
"Apache-2.0"
] | DustinCampbell/roslyn | src/VisualStudio/IntegrationTest/IntegrationTests/CSharp/CSharpSquigglesDesktop.cs | 1,079 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;
namespace Digiseller.Client.Core.Models.ProductDiscounts.Request
{
[XmlRoot(ElementName = "product")]
public class Product
{
public Product()
{
}
public Product(int id, string currencyCode)
{
Id = id;
Currency = currencyCode;
}
[XmlElement(ElementName = "id")]
public int Id { get; set; }
[XmlElement(ElementName = "currency")]
public string Currency { get; set; }
}
}
| 21.178571 | 64 | 0.591906 | [
"Apache-2.0"
] | Mistand/Digiseller.Client.Core | src/Digiseller.Client.Core/Models/ProductDiscounts/Request/Product.cs | 595 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Maui.Controls.CustomAttributes;
using Microsoft.Maui.Controls.Internals;
namespace Microsoft.Maui.Controls.Compatibility.ControlGallery.Issues
{
[Preserve(AllMembers = true)]
[Issue(IssueTracker.None, 0, "Modal ContentPage", PlatformAffected.All, NavigationBehavior.PushModalAsync)]
public class ModalContentPage : ContentPage
{
public ModalContentPage()
{
Title = "Test Modal";
Content = new Button
{
Text = "I am button",
VerticalOptions = LayoutOptions.CenterAndExpand,
HorizontalOptions = LayoutOptions.CenterAndExpand
};
}
}
}
| 25.962963 | 108 | 0.766049 | [
"MIT"
] | 10088/maui | src/Compatibility/ControlGallery/src/Issues.Shared/ModelContentPage.cs | 703 | C# |
using Puppy.Elastic.Utils;
namespace Puppy.Elastic.ContextAddDeleteUpdate.IndexModel
{
public class RoutingDefinition
{
public object RoutingId { get; set; }
public object ParentId { get; set; }
public static string GetRoutingUrl(RoutingDefinition routingDefinition)
{
var parameters = new ParameterCollection();
if (routingDefinition != null && routingDefinition.ParentId != null)
parameters.Add("parent", routingDefinition.ParentId.ToString());
if (routingDefinition != null && routingDefinition.RoutingId != null)
parameters.Add("routing", routingDefinition.RoutingId.ToString());
return parameters.ToString();
}
}
} | 34.363636 | 82 | 0.649471 | [
"Unlicense"
] | stssoftware/Puppy | Puppy.Elastic/ContextAddDeleteUpdate/IndexModel/RoutingDefinition.cs | 758 | C# |
using TaleWorlds.Core;
using TaleWorlds.MountAndBlade.View.Screen;
namespace RTSCamera.Patch
{
public class Patch_MissionScreen
{
public static bool OnMissionModeChange_Prefix(MissionScreen __instance, MissionMode oldMissionMode, bool atStart)
{
if (__instance.Mission.Mode == MissionMode.Battle && oldMissionMode == MissionMode.Deployment)
{
Utility.SmoothMoveToAgent(__instance, true);
return false;
}
return true;
}
}
}
| 27.1 | 121 | 0.636531 | [
"MIT"
] | cnedwin/Bannerlord.RTSCamera | source/RTSCamera/src/Patch/Patch_MissionScreen.cs | 544 | C# |
namespace Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210
{
using static Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Extensions;
/// <summary>Existing recovery availability set input.</summary>
public partial class ExistingRecoveryAvailabilitySet
{
/// <summary>
/// <c>AfterFromJson</c> will be called after the json deserialization has finished, allowing customization of the object
/// before it is returned. Implement this method in a partial class to enable this behavior
/// </summary>
/// <param name="json">The JsonNode that should be deserialized into this object.</param>
partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject json);
/// <summary>
/// <c>AfterToJson</c> will be called after the json erialization has finished, allowing customization of the <see cref="Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject"
/// /> before it is returned. Implement this method in a partial class to enable this behavior
/// </summary>
/// <param name="container">The JSON container that the serialization result will be placed in.</param>
partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject container);
/// <summary>
/// <c>BeforeFromJson</c> will be called before the json deserialization has commenced, allowing complete customization of
/// the object before it is deserialized.
/// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter.
/// Implement this method in a partial class to enable this behavior.
/// </summary>
/// <param name="json">The JsonNode that should be deserialized into this object.</param>
/// <param name="returnNow">Determines if the rest of the deserialization should be processed, or if the method should return
/// instantly.</param>
partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject json, ref bool returnNow);
/// <summary>
/// <c>BeforeToJson</c> will be called before the json serialization has commenced, allowing complete customization of the
/// object before it is serialized.
/// If you wish to disable the default serialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter.
/// Implement this method in a partial class to enable this behavior.
/// </summary>
/// <param name="container">The JSON container that the serialization result will be placed in.</param>
/// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return
/// instantly.</param>
partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject container, ref bool returnNow);
/// <summary>
/// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject into a new instance of <see cref="ExistingRecoveryAvailabilitySet" />.
/// </summary>
/// <param name="json">A Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject instance to deserialize from.</param>
internal ExistingRecoveryAvailabilitySet(Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject json)
{
bool returnNow = false;
BeforeFromJson(json, ref returnNow);
if (returnNow)
{
return;
}
__recoveryAvailabilitySetCustomDetails = new Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.RecoveryAvailabilitySetCustomDetails(json);
{_recoveryAvailabilitySetId = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonString>("recoveryAvailabilitySetId"), out var __jsonRecoveryAvailabilitySetId) ? (string)__jsonRecoveryAvailabilitySetId : (string)RecoveryAvailabilitySetId;}
AfterFromJson(json);
}
/// <summary>
/// Deserializes a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonNode"/> into an instance of Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IExistingRecoveryAvailabilitySet.
/// </summary>
/// <param name="node">a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonNode" /> to deserialize from.</param>
/// <returns>
/// an instance of Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IExistingRecoveryAvailabilitySet.
/// </returns>
public static Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IExistingRecoveryAvailabilitySet FromJson(Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonNode node)
{
return node is Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject json ? new ExistingRecoveryAvailabilitySet(json) : null;
}
/// <summary>
/// Serializes this instance of <see cref="ExistingRecoveryAvailabilitySet" /> into a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonNode" />.
/// </summary>
/// <param name="container">The <see cref="Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject"/> container to serialize this object into. If the caller
/// passes in <c>null</c>, a new instance will be created and returned to the caller.</param>
/// <param name="serializationMode">Allows the caller to choose the depth of the serialization. See <see cref="Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.SerializationMode"/>.</param>
/// <returns>
/// a serialized instance of <see cref="ExistingRecoveryAvailabilitySet" /> as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonNode" />.
/// </returns>
public Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.SerializationMode serializationMode)
{
container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject();
bool returnNow = false;
BeforeToJson(ref container, ref returnNow);
if (returnNow)
{
return container;
}
__recoveryAvailabilitySetCustomDetails?.ToJson(container, serializationMode);
AddIf( null != (((object)this._recoveryAvailabilitySetId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonString(this._recoveryAvailabilitySetId.ToString()) : null, "recoveryAvailabilitySetId" ,container.Add );
AfterToJson(ref container);
return container;
}
}
} | 69.679612 | 321 | 0.695973 | [
"MIT"
] | AverageDesigner/azure-powershell | src/Migrate/generated/api/Models/Api20210210/ExistingRecoveryAvailabilitySet.json.cs | 7,075 | C# |
using System.Diagnostics.CodeAnalysis;
namespace Manatee.Json.Path.Parsing
{
internal class SearchParser : IJsonPathParser
{
private const string _allowedChars = "_'\"*";
public bool Handles(string input, int index)
{
if (index + 2 >= input.Length)
return false;
var check = index + 2;
if (input[index] != '.' || input[index + 1] != '.')
return false;
if (input[index + 2] == '[' && _allowedChars.IndexOf(input[index + 3]) >= 0)
check++;
return char.IsLetterOrDigit(input[check]) || _allowedChars.IndexOf(input[check]) >= 0;
//return input[index] == '.' &&
// input[index + 1] == '.' &&
// (char.IsLetterOrDigit(input[index + 2]) || _allowedChars.IndexOf(input[index + 2]) >= 0);
}
public bool TryParse(string source, ref int index, [NotNullWhen(true)] ref JsonPath? path, [NotNullWhen(false)] out string? errorMessage)
{
if (path == null)
{
errorMessage = "Start token not found.";
return false;
}
index += 2;
if (source[index] == '*')
{
path = path.Search();
index++;
errorMessage = null!;
return true;
}
if (!source.TryGetKey(ref index, out var key, out errorMessage)) return false;
path = path.Search(key);
return true;
}
}
} | 25.666667 | 140 | 0.58518 | [
"MIT"
] | Magicianred/Manatee.Json | Manatee.Json/Path/Parsing/SearchParser.cs | 1,311 | C# |
using System;
namespace Beeffective.ViewModels
{
public class GoalViewModel : ViewModel
{
private TimeSpan timeSpent;
public GoalViewModel(string title)
{
Title = title ?? throw new ArgumentNullException(nameof(title));
TimeSpent = new TimeSpan();
}
public string Title { get; }
public TimeSpan TimeSpent
{
get => timeSpent;
set
{
if (Equals(timeSpent, value)) return;
timeSpent = value;
OnPropertyChanged();
}
}
}
} | 22.035714 | 76 | 0.510535 | [
"MIT"
] | PeterMilovcik/DoThis | DoThis/ViewModels/GoalViewModel.cs | 619 | C# |
// ***********************************************************************
// Assembly : XLabs.Sample.Droid
// Author : XLabs Team
// Created : 12-27-2015
//
// Last Modified By : XLabs Team
// Last Modified On : 01-04-2016
// ***********************************************************************
// <copyright file="MainActivity.cs" company="XLabs Team">
// Copyright (c) XLabs Team. All rights reserved.
// </copyright>
// <summary>
// This project is licensed under the Apache 2.0 license
// https://github.com/XLabs/Xamarin-Forms-Labs/blob/master/LICENSE
//
// XLabs is a open source project that aims to provide a powerfull and cross
// platform set of controls tailored to work with Xamarin Forms.
// </summary>
// ***********************************************************************
//
using System.IO;
using Android.App;
using Android.Content.PM;
using Android.OS;
using SQLite.Net;
using SQLite.Net.Platform.XamarinAndroid;
using XLabs.Caching;
using XLabs.Caching.SQLite;
using XLabs.Forms;
using XLabs.Forms.Services;
using XLabs.Ioc;
using XLabs.Platform.Device;
using XLabs.Platform.Mvvm;
using XLabs.Platform.Services;
using XLabs.Platform.Services.Email;
using XLabs.Platform.Services.Media;
using XLabs.Serialization;
using XLabs.Serialization.ServiceStack;
namespace XLabs.Sample.Droid
{
/// <summary>
/// Class MainActivity.
/// </summary>
[Activity(Label = "XLabs.Sample.Droid", MainLauncher = true,
ConfigurationChanges = ConfigChanges.Orientation | ConfigChanges.ScreenSize)]
public class MainActivity : XFormsApplicationDroid
{
/// <summary>
/// Called when [create].
/// </summary>
/// <param name="bundle">The bundle.</param>
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
if (Build.VERSION.SdkInt >= BuildVersionCodes.Kitkat)
{
Android.Webkit.WebView.SetWebContentsDebuggingEnabled(true);
}
XLabs.Forms.Controls.HybridWebViewRenderer.GetWebViewClientDelegate = r => new CustomClient(r);
XLabs.Forms.Controls.HybridWebViewRenderer.GetWebChromeClientDelegate = r => new CustomChromeClient();
if (!Resolver.IsSet)
{
this.SetIoc();
}
else
{
var app = Resolver.Resolve<IXFormsApp>() as IXFormsApp<XFormsApplicationDroid>;
if (app != null) app.AppContext = this;
}
Xamarin.Forms.Forms.Init(this, bundle);
Xamarin.Forms.Forms.ViewInitialized += (sender, e) =>
{
if (!string.IsNullOrWhiteSpace(e.View.StyleId))
{
e.NativeView.ContentDescription = e.View.StyleId;
}
};
this.LoadApplication(new App());
}
/// <summary>
/// Sets the IoC.
/// </summary>
private void SetIoc()
{
var resolverContainer = new SimpleContainer();
var app = new XFormsAppDroid();
app.Init(this);
var documents = app.AppDataDirectory;
var pathToDatabase = Path.Combine(documents, "xforms.db");
resolverContainer.Register<IDevice>(t => AndroidDevice.CurrentDevice)
.Register<IDisplay>(t => t.Resolve<IDevice>().Display)
.Register<IFontManager>(t => new FontManager(t.Resolve<IDisplay>()))
//.Register<IJsonSerializer, Services.Serialization.JsonNET.JsonSerializer>()
.Register<IJsonSerializer, JsonSerializer>()
.Register<IEmailService, EmailService>()
.Register<IMediaPicker, MediaPicker>()
.Register<ITextToSpeechService, TextToSpeechService>()
.Register<IDependencyContainer>(resolverContainer)
.Register<IXFormsApp>(app)
.Register<ISecureStorage>(t => new KeyVaultStorage(t.Resolve<IDevice>().Id.ToCharArray()))
.Register<ICacheProvider>(
t => new SQLiteSimpleCache(new SQLitePlatformAndroid(),
new SQLiteConnectionString(pathToDatabase, true), t.Resolve<IJsonSerializer>()));
Resolver.SetResolver(resolverContainer.GetResolver());
}
}
}
| 36.4 | 115 | 0.562418 | [
"Apache-2.0"
] | jdluzen/Xamarin-Forms-Labs | Samples/XLabs.Sample.Droid/MainActivity.cs | 4,552 | C# |
namespace Reservation.Domain
{
public class PricingMapping
{
public int FirstPricingCategoryPrice { get; }
public int SecondPricingCategoryPrice { get; }
public int ThirdPricingCategoryPrice { get; }
public PricingMapping(int firstPricingCategoryPrice, int secondPricingCategoryPrice,
int thirdPricingCategoryPrice)
{
FirstPricingCategoryPrice = firstPricingCategoryPrice;
SecondPricingCategoryPrice = secondPricingCategoryPrice;
ThirdPricingCategoryPrice = thirdPricingCategoryPrice;
}
}
} | 35.294118 | 92 | 0.7 | [
"Apache-2.0"
] | 42skillz/talk-AMDDD19 | code/TicketOffice/External.Apis/Reservation.Domain/PricingMapping.cs | 602 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Reflection;
using System.Web.UI.WebControls;
using DotNetNuke;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Entities.Modules.Actions;
using DotNetNuke.Security;
using DotNetNuke.Services.Exceptions;
using DotNetNuke.Services.Localization;
using System.Web.SessionState;
using System.IO;
using System.Net.Mail;
using System.Text.RegularExpressions;
using ola.HRMangmntSyst;
// copied namepace
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Text;
using System.Web.SessionState;
namespace ola.HRMangmntSyst
{
public partial class InterviewPage : PortalModuleBase, IActionable
{
#region Optional Interfaces
public ModuleActionCollection ModuleActions
{
get
{
ModuleActionCollection Actions = new ModuleActionCollection();
Actions.Add(this.GetNextActionID(), Localization.GetString(ModuleActionType.AddContent, this.LocalResourceFile), ModuleActionType.AddContent, "", "", this.EditUrl(), false, SecurityAccessLevel.Edit, true, false);
return Actions;
}
}
#endregion
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
MViewInterview.ActiveViewIndex = 0;
// day dropdownlist
#region
var day = new ArrayList();
day.Add("Day");
for (var i = 1; i <= 31; i++)
{
day.Add(i);
}
// interviewDayList.DataSource = day;
// interviewDayList.DataBind();
ddlInterviewDay.DataSource = day;
ddlInterviewDay.DataBind();
ddlDay.DataSource = day;
ddlDay.DataBind();
#endregion
// year dropdownlist
#region
var al = new ArrayList();
al.Add("Year");
for (var i = 2018; i >= 1900; i--)
{
al.Add(i);
}
//interviewYearList.DataSource = al;
//interviewYearList.DataBind();
ddlInterviewYear.DataSource = al;
ddlInterviewYear.DataBind();
ddlYear.DataSource = al;
ddlYear.DataBind();
ddlYear.Items.Insert(0, new ListItem("---Please Select---", "-1"));
#endregion
#region
//Loading Applicant Depatartment
ArrayList objAppDept = new ArrayList();
objAppDept = (new ApplicantDepartmentTableController()).List();
if (objAppDept.Count > 0)
{
ddShortListAvailDept.DataSource = objAppDept;
ddShortListAvailDept.DataTextField = "DeptName";
ddShortListAvailDept.DataValueField = "DeptID";
ddShortListAvailDept.DataBind();
ddShortListAvailDept.Items.Insert(0, new ListItem("---Please Select---", "-1"));
ddShotListAvailPosition.Items.Insert(0, new ListItem("---Please Select---", "-1"));
ddInterViewDecisionAvailDept.DataSource = objAppDept;
ddInterViewDecisionAvailDept.DataTextField = "DeptName";
ddInterViewDecisionAvailDept.DataValueField = "DeptID";
ddInterViewDecisionAvailDept.DataBind();
ddInterViewDecisionAvailDept.Items.Insert(0, new ListItem("---Please Select---", "-1"));
ddInterviewDecisionAvailPosition.Items.Insert(0, new ListItem("---Please select---", "-1"));
ddManagDecisionAvailDept.DataSource = objAppDept;
ddManagDecisionAvailDept.DataTextField = "DeptName";
ddManagDecisionAvailDept.DataValueField = "DeptID";
ddManagDecisionAvailDept.DataBind();
ddManagDecisionAvailDept.Items.Insert(0, new ListItem("---Please Select---", "-1"));
ddManagDecisionAvailPosition.Items.Insert(0, new ListItem("---Please Select---", "-1"));
ddSendOfferAvailDept.DataSource = objAppDept;
ddSendOfferAvailDept.DataTextField = "DeptName";
ddSendOfferAvailDept.DataValueField = "DeptID";
ddSendOfferAvailDept.DataBind();
ddSendOfferAvailDept.Items.Insert(0, new ListItem("---Please Select---", "-1"));
ddSendOfferAvailPosition.Items.Insert(0, new ListItem("---Please Select---", "-1"));
ddReportVacantDept.DataSource = objAppDept;
ddReportVacantDept.DataTextField = "DeptName";
ddReportVacantDept.DataValueField = "DeptID";
ddReportVacantDept.DataBind();
ddReportVacantDept.Items.Insert(0, new ListItem("---Please Select---", "-1"));
ddReportVacantPosition.Items.Insert(0, new ListItem("---Please Select---", "-1"));
}
// loading Employeee DEPARTMENT
ArrayList objDept= new ArrayList();
objDept = (new EmployeeDepartmentTableController()).List();
if (objDept.Count > 0)
{
ddlDept.DataSource = objDept;
ddlDept.DataTextField = "DeptName";
ddlDept.DataValueField = "DeptID";
ddlDept.DataBind();
ddlDept.Items.Insert(0, new ListItem("---Please Select---", "-1"));
}
ddlApprovePosition.Items.Insert(0, new ListItem("---Please Select---", "-1"));
#endregion
//loading worklocation on ddlWorkLocation
#region
ArrayList objLocation = new ArrayList();
objLocation = (new EmployeeWorkLocationsController()).List();
if (objLocation.Count > 0)
{
ddlWorkLocation.DataSource = objLocation;
ddlWorkLocation.DataTextField = "LocationName";
ddlWorkLocation.DataValueField = "WorkLocationID";
ddlWorkLocation.DataBind();
ddlWorkLocation.Items.Insert(0, new ListItem("---Please Select---", "-1"));
}
#endregion
// LOAD RATING KEY1
#region
//// LOAD RATING KEY1
//ArrayList objRatingKey1 = new ArrayList();
//objRatingKey1 = (new InterviewRatingKey1Controller()).List();
//if (objRatingKey1.Count > 0)
//{
// ExperienceKeyList.DataSource = objRatingKey1;
// ExperienceKeyList.DataTextField = "ratingDescription";
// ExperienceKeyList.DataValueField = "ratingKeyID";
// ExperienceKeyList.DataBind();
// ExperienceKeyList.Items.Insert(0, new ListItem("---Please Select---", "-1"));
// edcationKeyList.DataSource = objRatingKey1;
// edcationKeyList.DataTextField = "ratingDescription";
// edcationKeyList.DataValueField = "ratingKeyID";
// edcationKeyList.DataBind();
// edcationKeyList.Items.Insert(0, new ListItem("---Please Select---", "-1"));
// communicationKeyList.DataSource = objRatingKey1;
// communicationKeyList.DataTextField = "ratingDescription";
// communicationKeyList.DataValueField = "ratingKeyID";
// communicationKeyList.DataBind();
// communicationKeyList.Items.Insert(0, new ListItem("---Please Select---", "-1"));
// interestKeyList.DataSource = objRatingKey1;
// interestKeyList.DataTextField = "ratingDescription";
// interestKeyList.DataValueField = "ratingKeyID";
// interestKeyList.DataBind();
// interestKeyList.Items.Insert(0, new ListItem("---Please Select---", "-1"));
// presentationKeyList.DataSource = objRatingKey1;
// presentationKeyList.DataTextField = "ratingDescription";
// presentationKeyList.DataValueField = "ratingKeyID";
// presentationKeyList.DataBind();
// presentationKeyList.Items.Insert(0, new ListItem("---Please Select---", "-1"));
// problemKeyList.DataSource = objRatingKey1;
// problemKeyList.DataTextField = "ratingDescription";
// problemKeyList.DataValueField = "ratingKeyID";
// problemKeyList.DataBind();
// problemKeyList.Items.Insert(0, new ListItem("---Please Select---", "-1"));
// computerKeyList.DataSource = objRatingKey1;
// computerKeyList.DataTextField = "ratingDescription";
// computerKeyList.DataValueField = "ratingKeyID";
// computerKeyList.DataBind();
// computerKeyList.Items.Insert(0, new ListItem("---Please Select---", "-1"));
// jobStabilityKeyList.DataSource = objRatingKey1;
// jobStabilityKeyList.DataTextField = "ratingDescription";
// jobStabilityKeyList.DataValueField = "ratingKeyID";
// jobStabilityKeyList.DataBind();
// jobStabilityKeyList.Items.Insert(0, new ListItem("---Please Select---", "-1"));
// otherKeyList.DataSource = objRatingKey1;
// otherKeyList.DataTextField = "ratingDescription";
// otherKeyList.DataValueField = "ratingKeyID";
// otherKeyList.DataBind();
// otherKeyList.Items.Insert(0, new ListItem("---Please Select---", "-1"));
//}
//// LOAD RATING KEY1
//ArrayList objRatingKey2 = new ArrayList();
//objRatingKey2 = (new InterviewRatingKey2Controller()).List();
//if (objRatingKey2.Count > 0)
//{
// knowledgeRatingKeyList.DataSource = objRatingKey2;
// knowledgeRatingKeyList.DataTextField = "ratingKeyDescription";
// knowledgeRatingKeyList.DataValueField = "ratingKeyID";
// knowledgeRatingKeyList.DataBind();
// knowledgeRatingKeyList.Items.Insert(0, new ListItem("---Please Select---", "-1"));
// excitmentRatingKeyList.DataSource = objRatingKey2;
// excitmentRatingKeyList.DataTextField = "ratingKeyDescription";
// excitmentRatingKeyList.DataValueField = "ratingKeyID";
// excitmentRatingKeyList.DataBind();
// excitmentRatingKeyList.Items.Insert(0, new ListItem("---Please Select---", "-1"));
// experienceRatingKeyList.DataSource = objRatingKey2;
// experienceRatingKeyList.DataTextField = "ratingKeyDescription";
// experienceRatingKeyList.DataValueField = "ratingKeyID";
// experienceRatingKeyList.DataBind();
// experienceRatingKeyList.Items.Insert(0, new ListItem("---Please Select---", "-1"));
// teamRatingKeyList.DataSource = objRatingKey2;
// teamRatingKeyList.DataTextField = "ratingKeyDescription";
// teamRatingKeyList.DataValueField = "ratingKeyID";
// teamRatingKeyList.DataBind();
// teamRatingKeyList.Items.Insert(0, new ListItem("---Please Select---", "-1"));
// communicationRatingKeyList.DataSource = objRatingKey2;
// communicationRatingKeyList.DataTextField = "ratingKeyDescription";
// communicationRatingKeyList.DataValueField = "ratingKeyID";
// communicationRatingKeyList.DataBind();
// communicationRatingKeyList.Items.Insert(0, new ListItem("---Please Select---", "-1"));
// RecommendtionRatingKeyList.DataSource = objRatingKey2;
// RecommendtionRatingKeyList.DataTextField = "ratingKeyDescription";
// RecommendtionRatingKeyList.DataValueField = "ratingKeyID";
// RecommendtionRatingKeyList.DataBind();
// RecommendtionRatingKeyList.Items.Insert(0, new ListItem("---Please Select---", "-1"));
//}
#endregion
}
}
protected void sendInterviewInviteBtn_Click(object sender, EventArgs e)
{
MViewInterview.ActiveViewIndex = 1;
}
protected void backToWelcomBtn_Click(object sender, EventArgs e)
{
MViewInterview.ActiveViewIndex = 0;
}
protected void interviewApplicantBtn_Click(object sender, EventArgs e)
{
MViewInterview.ActiveViewIndex = 2;
}
protected void interviewNextBtn_Click(object sender, EventArgs e)
{
MViewInterview.ActiveViewIndex = 3;
}
protected void evaluationBackBtn_Click(object sender, EventArgs e)
{
MViewInterview.ActiveViewIndex = 1;
}
protected void evaluationWelcomPageBtn_Click(object sender, EventArgs e)
{
MViewInterview.ActiveViewIndex = 0;
}
protected void interviewBackBtn_Click(object sender, EventArgs e)
{
MViewInterview.ActiveViewIndex = 2;
}
protected void responseWelcomPage_Click(object sender, EventArgs e)
{
MViewInterview.ActiveViewIndex = 0;
}
protected void btnSendIniteMenu_Click(object sender, EventArgs e)
{
MViewInterview.ActiveViewIndex = 1;
PanelShortListForInterview.Visible = true;
btnShortListFinish.Visible = false;
btnShortListTryAgain.Visible = false;
}
protected void Button2_Click(object sender, EventArgs e)
{
MViewInterview.ActiveViewIndex = 2;
}
protected void Button3_Click(object sender, EventArgs e)
{
MViewInterview.ActiveViewIndex = 4;
}
protected void btnSendOfferMenu_Click(object sender, EventArgs e)
{
MViewInterview.ActiveViewIndex = 5;
btnMangDecClose.Visible = false;
btnMangDecitionFinish.Visible = false;
btnMangDecTryAgain.Visible = false;
}
protected void btnInterwierDecision_Click(object sender, EventArgs e)
{
MViewInterview.ActiveViewIndex = 2;
}
protected void btnReportMenu_Click(object sender, EventArgs e)
{
MViewInterview.ActiveViewIndex = 3;
}
protected void LinkApproveApplicant_Click(object sender, EventArgs e)
{
string position = ddReportVacantPosition.SelectedItem.Text.Trim();
ArrayList objArr = new ArrayList();
objArr = (new ApplicantPersonalDetailsController()).ListByPositionApprove(position);
if (objArr.Count > 0)
{
GVReport.DataSource = objArr;
GVReport.DataBind();
GVReport.Visible = true;
lblReport.Visible = false;
}
else
{
GVReport.Visible = false;
lblReport.Text = "No applicant has been approved for the position of " + ddReportVacantPosition.SelectedItem.Text.Trim();
lblReport.Visible = true;
}
}
protected void ddlDept_SelectedIndexChanged(object sender, EventArgs e)
{
int deptID = Convert.ToInt32(ddlDept.SelectedItem.Value);
ArrayList objPosition = new ArrayList();
objPosition = (new EmployeePositionTableController()).GetByEmployeeDepartmentTable(deptID);
if (objPosition.Count > 0)
{
ddlApprovePosition.DataSource = objPosition;
ddlApprovePosition.DataTextField = "PositionName";
ddlApprovePosition.DataValueField = "PositionID";
ddlApprovePosition.DataBind();
ddlApprovePosition.Items.Insert(0, new ListItem("---Please Select---", "-1"));
}
//int deptID = Convert.ToInt32(ddlDept.SelectedItem.Value);
ArrayList objLevel = new ArrayList();
// int pos = Convert.ToInt32(ddlApprovePosition.SelectedValue);
objLevel = (new EmployeeLevelController()).GetByEmployeeDepartmentTable(deptID);
if (objLevel.Count > 0)
{
ddlLevel.DataSource = objLevel;
ddlLevel.DataTextField = "LevelName";
ddlLevel.DataValueField = "LevelID";
ddlLevel.DataBind();
ddlLevel.Items.Insert(0, new ListItem("---Please Select---", "-1"));
}
}
protected void ddlLevel_SelectedIndexChanged(object sender, EventArgs e)
{
int levelID = Convert.ToInt32(ddlLevel.SelectedItem.Value);
EmployeeLevelInfo objLevel = new EmployeeLevelInfo();
objLevel = new EmployeeLevelController().Get(levelID);
lblSalary.Text = objLevel.Salary;
}
protected void btnMangDecClose_Click1(object sender, System.EventArgs e)
{
PanelApplicantDetails.Visible = false;
}
protected void btnInterviewerDecisionFinish_Click(object sender, System.EventArgs e)
{
MViewInterview.ActiveViewIndex = 0;
}
protected void btnInterDecClose_Click(object sender, EventArgs e)
{
PanelShortListViewAppDetails.Visible = false;
}
protected void btnMangDecClose_Click(object sender, EventArgs e)
{
btnMangDecClose.Visible = false;
btnMangDecClose.Visible = false;
}
protected void btnShotListClose_Click(object sender, System.EventArgs e)
{
PanelApplicantDetails.Visible = false;
}
//Listing available position indexChange
#region
protected void ddlAvailableDept_SelectedIndexChanged(object sender, System.EventArgs e)
{
ArrayList objShortListAvailPost = new ArrayList();
int dept1 = Convert.ToInt32(ddShortListAvailDept.SelectedValue);
objShortListAvailPost = (new ApplicantAvailablePositiontableController()).GetByApplicantDepartmentTable(dept1);
if (objShortListAvailPost.Count > 0)
{
ddShotListAvailPosition.DataSource = objShortListAvailPost;
ddShotListAvailPosition.DataTextField = "positionAppliedForName";
ddShotListAvailPosition.DataValueField = "positionAppliedforID";
ddShotListAvailPosition.DataBind();
// ddShortListAvailDept.Items.Insert(0, new ListItem("---Please Select---", "-1"));
}
}
protected void ddShotListAvailPosition_SelectedIndexChanged(object sender, EventArgs e)
{
PanelShortListForInterview.Visible = true;
lblInviteSend1.Visible = false;
lblInviteSend.Visible = false;
btnShortListTryAgain.Visible = false;
btnShortListFinish.Visible = false;
ArrayList objArr = new ArrayList();
string positionAppliedFor = ddShotListAvailPosition.SelectedItem.Text;
objArr = (new ApplicantPersonalDetailsController()).ListByPositionNotShortlisted(positionAppliedFor);
if (objArr.Count > 0)
{
GViewAllApplicantsList.DataSource = objArr;
GViewAllApplicantsList.DataBind();
GViewAllApplicantsList.Visible = true;
//sendInterviewInvite1.Visible = true;
PanelInterviewParameter.Visible = true;
lblShortlist.Visible = false;
}
else
{
GViewAllApplicantsList.Visible = false;
PanelInterviewParameter.Visible = false;
lblShortlist.Text = "It might be that no one applied for the position of " + ddShotListAvailPosition.SelectedItem.Text + " or All applicants has been shortlisted";
lblShortlist.Visible = true;
}
}
#endregion
//Sending interview invites
#region
protected void sendInterviewInvite1_Click(object sender, EventArgs e)
{
try
{
Panel1.Visible = true;
ArrayList ObjArr = new ArrayList();
foreach (GridViewRow g1 in GViewAllApplicantsList.Rows)
{
lblName.Text = g1.Cells[2].Text + " " + g1.Cells[4].Text; ;
lblPositionApplied.Text = g1.Cells[1].Text;
lblApplicantEmail.Text = g1.Cells[8].Text;
}
}
catch { }
}
#endregion
//Viewing Applicant details
#region
protected void GViewAllApplicantsList_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "View")
{
ApplicantPersonalDetailsInfo objPersonalInfo = new ApplicantPersonalDetailsInfo();
objPersonalInfo = (new ApplicantPersonalDetailsController()).Get(Convert.ToInt32(e.CommandArgument));
lblDeptAppliedTo.Text = objPersonalInfo.DeptAppliedTo;
lblPositionAppliedFor.Text = objPersonalInfo.PositionAppliedFor;
lblApplicantNum.Text = objPersonalInfo.ApplicantNum;
lblFirstName.Text = objPersonalInfo.FirstName;
lblLastName.Text = objPersonalInfo.LastName;
lblMiddleName.Text = objPersonalInfo.MiiddleName;
lblGender.Text = objPersonalInfo.Gender;
lblMaritalStatus.Text = objPersonalInfo.MaritalStatus;
lblNationality.Text = objPersonalInfo.countryName;
lblStateofOrigin.Text = objPersonalInfo.stateName;
lblSenDistrict.Text = objPersonalInfo.senName;
lblLGA.Text = objPersonalInfo.LgaName;
lblHomeTown.Text = objPersonalInfo.HomeTown;
lblEmail.Text = objPersonalInfo.Email;
lblContactAddress.Text = objPersonalInfo.ContactAddress;
lblDOB.Text = objPersonalInfo.DateOfBirth;
lblAge.Text = objPersonalInfo.Age;
ImagePassport.ImageUrl = "~/Image/" + objPersonalInfo.Passport.Substring(objPersonalInfo.Passport.LastIndexOf('\\') + 1);
int applicantID = Convert.ToInt32(e.CommandArgument);
// Qualification summary
ArrayList ObjArrQualification = new ArrayList();
ObjArrQualification = (new ApplicantQualificationController()).GetByApplicantPersonalDetails(applicantID);
if (ObjArrQualification.Count > 0)
{
GViewQualification.DataSource = ObjArrQualification;
GViewQualification.DataBind();
GViewQualification.Visible = true;
}
// professional Qualification summary
ArrayList ObjArrProfQualification = new ArrayList();
ObjArrProfQualification = (new ApplicantProfQualificationController()).GetByApplicantPersonalDetails(applicantID);
if (ObjArrProfQualification.Count > 0)
{
GViewProfQualification.DataSource = ObjArrProfQualification;
GViewProfQualification.DataBind();
GViewProfQualification.Visible = true;
}
// Wwork Experience summary
ArrayList ObjArrWorkExp = new ArrayList();
ObjArrWorkExp = (new ApplicantWorkExperienceController()).GetByApplicantPersonalDetails(applicantID);
if (ObjArrWorkExp.Count > 0)
{
GViewWrkExp.DataSource = ObjArrWorkExp;
GViewWrkExp.DataBind();
GViewWrkExp.Visible = true;
}
// Document summary
ArrayList ObjArrDoc = new ArrayList();
ObjArrDoc = (new ApplicantDocumentController()).GetByApplicantPersonalDetails(applicantID);
if (ObjArrDoc.Count > 0)
{
GViewDocument.DataSource = ObjArrDoc;
GViewDocument.DataBind();
GViewDocument.Visible = true;
}
PanelApplicantDetails.Visible = true;
btnShotListClose.Visible = true;
// MViewInterview.ActiveViewIndex = 4;
}
}
#endregion
//Hire Applicant
#region
protected void btnHireApplicantSave_Click(object sender, EventArgs e)
{
btnInterviewerDecisionFinish.Visible = false;
int count = 0;
foreach (GridViewRow x in GVShortlistedApplicants.Rows)
{
TextBox b = new TextBox();
b = (TextBox)x.FindControl("TextBoxApplicantID");
int id = Convert.ToInt32(b.Text);
CheckBox c = new CheckBox();
c = (CheckBox)x.FindControl("CheckBox2");
if (c.Checked == true)
{
try
{
ApplicantPersonalDetailsInfo objPersonalInfo = new ApplicantPersonalDetailsInfo();
objPersonalInfo.ApplicantID = Convert.ToInt32(id);
objPersonalInfo.WorkLocationID_FK = Convert.ToInt32(ddlWorkLocation.SelectedValue);
objPersonalInfo.DepartmentID_FK = Convert.ToInt32(ddlDept.SelectedValue);
objPersonalInfo.PositionApproved_FK = Convert.ToInt32(ddlApprovePosition.SelectedValue);
objPersonalInfo.LevelID_FK = Convert.ToInt32(ddlLevel.SelectedValue);
objPersonalInfo.ResumptionDate = ddlDay.SelectedValue + "-" + ddlMonth.SelectedValue + "-" + ddlYear.SelectedValue;
objPersonalInfo.InterviwerDecision = "Hire";
new ApplicantPersonalDetailsController().UpdateInterviewerDecision(objPersonalInfo);
count += 1;
ApplicantPersonalDetailsInfo objPersonalInfo3 = new ApplicantPersonalDetailsInfo();
objPersonalInfo3 = (new ApplicantPersonalDetailsController()).Get(Convert.ToInt32(id));
if (objPersonalInfo3.InterviwerDecision == "Hire")
{
lblhire.Text = "You have successfully hired " + count + " applicants for the position of " + ddlApprovePosition.SelectedItem.Text;
lblhire.Visible = true;
lblhire1.Text = "You have successfully hired " + count + " applicants for the position of " + ddlApprovePosition.SelectedItem.Text;
lblhire1.Visible = true;
PanelInterviewParameter.Visible = false;
PanelHire.Visible = false;
btnInterviewerDecisionFinish.Visible = true;
btnInterviewerDecisionTryAgain.Visible = false;
}
else
{
lblhire.Text = "You have NOT hired ";
lblhire.Visible = true;
lblhire1.Text = "You have NOT hired ";
lblhire1.Visible = true;
PanelInterviewParameter.Visible = false;
PanelHire.Visible = false;
btnInterviewerDecisionFinish.Visible = false;
btnInterviewerDecisionTryAgain.Visible = true;
}
}
catch { }
}
// reload the gridview
string position = ddInterViewDecisionAvailDept.SelectedItem.Text;
ArrayList objArr = new ArrayList();
objArr = new ApplicantPersonalDetailsController().ListByPositionShortlisted(position);
if (objArr.Count > 0)
{
GVShortlistedApplicants.DataSource = objArr;
GVShortlistedApplicants.DataBind();
GVShortlistedApplicants.Visible = true;
Label57.Visible = true;
lblNoShortlistedApplicant.Visible = false;
}
}
}
#endregion
//Shortlisting and sent interview invite
#region
protected void btnShotlistAndSendingInvite_Click(object sender, EventArgs e)
{
foreach (GridViewRow x in GViewAllApplicantsList.Rows)
{
// declare a variable as textbox
TextBox b = new TextBox();
// find the textbox containing the applicantID on the gridview
b = (TextBox)x.FindControl("TextBox2");
string id = b.Text;
string applicantName = x.Cells[2].Text + " " + x.Cells[4].Text; ;
string PositionAppliedFor = x.Cells[1].Text;
string applicantEmail = x.Cells[8].Text;
// ApplicantPersonalDetailsInfo objPersonalInfo = new ApplicantPersonalDetailsInfo();
CheckBox c = new CheckBox();
c = (CheckBox)x.FindControl("CheckBox1");
if (c.Checked == true)
{
// lblInterMsg.Text = id;
try
{
// Update application Status of that applicant as shortlisted
ApplicantPersonalDetailsInfo objPersonalInfo = new ApplicantPersonalDetailsInfo();
objPersonalInfo.ApplicantID = Convert.ToInt32(id);
objPersonalInfo.ApplicationStatus = "Shortlisted";
new ApplicantPersonalDetailsController().UpdateApplicationStatus(objPersonalInfo);
ApplicantPersonalDetailsInfo objPersonalInfo2 = new ApplicantPersonalDetailsInfo();
objPersonalInfo2 = (new ApplicantPersonalDetailsController()).Get(Convert.ToInt32(id));
if (objPersonalInfo2.ApplicationStatus == "Shortlisted")
{
lblInviteSend.Text = "Interview Letter SUCCESSFULLY sent";
PanelShortListForInterview.Visible = false;
lblInviteSend1.Text = "Interview Letter SUCCESSFULLY sent";
lblInviteSend1.Visible = true;
btnShortListFinish.Visible = true;
btnShortListTryAgain.Visible = false;
PanelInterviewParameter.Visible = false;
}
else
{
lblInviteSend.Text = "Interview Letter NOT sent";
PanelShortListForInterview.Visible = false;
lblInviteSend1.Text = "Interview Letter NOT sent";
lblInviteSend1.Visible = true;
btnShortListFinish.Visible = false;
btnShortListTryAgain.Visible=true;
PanelInterviewParameter.Visible = false;
}
//send an email from a Gmail address using SMTP server.
//The Gmail SMTP server name is smtp.gmail.com and
//the port using send mail is 587 and also using
//NetworkCredential for password based authentication;
//string _subjectEmail = "";
//MailMessage mail = new MailMessage();
//SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
// mail.IsBodyHtml = true;
//mail.From = new MailAddress("your_email_address@gmail.com");
// mail.From = new MailAddress("olami@neetbeettech@gmail.com");
//Loading all Mail contents
//Composing mail content
//string salutaion = ("dear" + applicantName + ",");
//string subjectEmail = "Invitation to Interview";
//string bodyEmail = ("dear" + applicantName + ","+ "In response to your application for the post of "
// + PositionAppliedFor +" Neetbeet Technogies Limited, we are please to invite you for interview as scheduled below:");
//string InterviewDetails = ("Date: " + ddlInterviewDay.SelectedValue + ddlInterviewMonth.SelectedValue +ddlInterviewYear.SelectedValue
// + " Time: " + txtInterviewTime.Text + " Venue: " + txtInterviewVenue.Text);
//bodyEmail += InterviewDetails;
//mail.To.Add(applicantEmail);
//mail.Subject = subjectEmail;
//mail.Body = bodyEmail;
//Adding an attachments
//mail.Attachments.Add(new Attachment(MailAttachementPath));
//SmtpServer.Port = 587;
//// SmtpServer.Port = 25;
//SmtpServer.Credentials = new System.Net.NetworkCredential("olami@neetbeettech@gmail.com", "Adeniyi@2018");
////SmtpServer.UseDefaultCredentials = false;
//SmtpServer.EnableSsl = true;
//SmtpServer.Send(mail);
//lblInviteSend.Text = "Interview Letter SUCCESSFULLY sent";
//mail.Dispose();
}
catch (Exception ex)
{
// lblInviteSend.Text = "Interview Letter NOT sent" ;
PanelShortListForInterview.Visible = false;
lblInviteSend1.Text = "Interview Letter NOT sent";
lblInviteSend1.Visible = true;
btnShortListFinish.Visible = false;
btnShortListTryAgain.Visible = true;
}
// reload
ArrayList objArr = new ArrayList();
string positionAppliedFor = ddShortListAvailDept.SelectedItem.Text;
objArr = (new ApplicantPersonalDetailsController()).ListByPositionNotShortlisted(positionAppliedFor);
if (objArr.Count > 0)
{
GViewAllApplicantsList.DataSource = objArr;
GViewAllApplicantsList.DataBind();
GViewAllApplicantsList.Visible = true;
// sendInterviewInvite1.Visible = true;
PanelInterviewParameter.Visible = true;
lblShortlist.Visible = false;
}
}
}
}
#endregion
//Loading shortlisted applicants for Interviewer decision
//and setting employment parameters
#region
protected void ddInterViewDecisionAvailDept_SelectedIndexChanged(object sender, System.EventArgs e)
{
ArrayList objInterDecisionAvailPost = new ArrayList();
int dept2 = Convert.ToInt32(ddInterViewDecisionAvailDept.SelectedValue);
objInterDecisionAvailPost = (new ApplicantAvailablePositiontableController()).GetByApplicantDepartmentTable(dept2);
if (objInterDecisionAvailPost.Count > 0)
{
ddInterviewDecisionAvailPosition.DataSource = objInterDecisionAvailPost;
ddInterviewDecisionAvailPosition.DataTextField = "positionAppliedForName";
ddInterviewDecisionAvailPosition.DataValueField = "positionAppliedforID";
ddInterviewDecisionAvailPosition.DataBind();
// ddShortListAvailDept.Items.Insert(0, new ListItem("---Please Select---", "-1"));
}
}
protected void ddInterviewDecisionAvailPosition_SelectedIndexChanged(object sender, EventArgs e)
{
PanelEmploymentParameter.Visible = true;
PanelHire.Visible = true;
btnInterviewerDecisionFinish.Visible = false;
lblhire.Visible = false;
ArrayList objArr = new ArrayList();
string position = ddInterviewDecisionAvailPosition.SelectedItem.Text.Trim();
objArr = new ApplicantPersonalDetailsController().ListByPositionShortlisted(position);
if (objArr.Count > 0)
{
GVShortlistedApplicants.DataSource = objArr;
GVShortlistedApplicants.DataBind();
GVShortlistedApplicants.Visible = true;
Label57.Visible = true;
lblNoShortlistedApplicant.Visible = false;
PanelEmploymentParameter.Visible = true;
}
else
{
GVShortlistedApplicants.Visible = false;
Label57.Visible = false;
lblNoShortlistedApplicant.Text = "No applicant has been shorlisted for the position of " + ddInterviewDecisionAvailPosition.SelectedItem.Text.Trim() + "Or all shortlisted applicants have been hired";
lblNoShortlistedApplicant.Visible = true;
PanelEmploymentParameter.Visible = false;
}
}
#endregion
//Tryagain buttons
#region
//btnInterviewerDecisionTryAgain
protected void btnInterviewerDecisionTryAgain_Click(object sender, System.EventArgs e)
{
PanelEmploymentParameter.Visible = true;
PanelHire.Visible = true;
btnInterviewerDecisionFinish.Visible = false;
btnInterviewerDecisionTryAgain.Visible = false;
lblhire1.Visible=false;
}
//btnMangDecTryAgain
protected void btnMangDecTryAgain_Click(object sender, System.EventArgs e)
{
PanelManagementDecision.Visible = true;
lblhire.Visible = false;
PanelManagementDecision.Visible = false;
btnSendOfferTryAgain.Visible = false;
btnSendOfferFinish.Visible = false;
}
//btnShortListTryAgain
protected void btnShortListTryAgain_Click(object sender, System.EventArgs e)
{
PanelShortListForInterview.Visible = true;
btnShortListFinish.Visible = false;
btnShortListTryAgain.Visible = false;
lblInviteSend1.Text = "Interview Letter SUCCESSFULLY sent";
lblInviteSend1.Visible = false;
btnShortListFinish.Visible = true;
btnShortListTryAgain.Visible = false;
PanelInterviewParameter.Visible = false;
}
#endregion
//Finish buttons
#region
//btnShortListFinish
protected void btnShortListFinish_Click(object sender, System.EventArgs e)
{
MViewInterview.ActiveViewIndex = 0;
}
//btnSendOfferFinish
protected void btnSendOffer_Click(object sender, System.EventArgs e)
{
MViewInterview.ActiveViewIndex = 0;
}
#endregion
//View shortlisted applicant's profile
#region
protected void GVShortlistedApplicants_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "View")
{
ApplicantPersonalDetailsInfo objPersonalInfo = new ApplicantPersonalDetailsInfo();
objPersonalInfo=(new ApplicantPersonalDetailsController()).Get(Convert.ToInt32(e.CommandArgument));
LbShortListAvailDept.Text = objPersonalInfo.DeptAppliedTo;
LbShotListAvailPosition.Text = objPersonalInfo.PositionAppliedFor;
LabelApplicantNo.Text = objPersonalInfo.ApplicantNum;
LabelFName.Text = objPersonalInfo.FirstName;
LabelMidName.Text = objPersonalInfo.MiiddleName;
LabelLName.Text = objPersonalInfo.LastName;
LabelGender.Text = objPersonalInfo.Gender;
LabelMaritalStatus.Text = objPersonalInfo.MaritalStatus;
LabelNationality.Text = objPersonalInfo.countryName;
lbSenDist.Text = objPersonalInfo.senName;
LbState.Text = objPersonalInfo.stateName;
LabelLga.Text = objPersonalInfo.LgaName;
LabelHomeTown.Text = objPersonalInfo.HomeTown;
LabelEmail.Text = objPersonalInfo.Email;
LabelAddress.Text = objPersonalInfo.ContactAddress;
LabelDob.Text = objPersonalInfo.DateOfBirth;
LabelAge.Text = objPersonalInfo.Age;
Image1.ImageUrl = "~/Image/" + objPersonalInfo.Passport.Substring(objPersonalInfo.Passport.LastIndexOf('\\') + 1);
int applicantID = Convert.ToInt32(e.CommandArgument);
//label
ArrayList ObjArrQualification = new ArrayList();
ObjArrQualification = (new ApplicantQualificationController()).GetByApplicantPersonalDetails(applicantID);
if (ObjArrQualification.Count > 0)
{
GridViewQualification.DataSource = ObjArrQualification;
GridViewQualification.DataBind();
GridViewQualification.Visible = true;
}
//// professional Qualification summary
ArrayList ObjArrProfQualification = new ArrayList();
ObjArrProfQualification = (new ApplicantProfQualificationController()).GetByApplicantPersonalDetails(applicantID);
if (ObjArrProfQualification.Count > 0)
{
GridViewProfQualification.DataSource = ObjArrProfQualification;
GridViewProfQualification.DataBind();
GridViewProfQualification.Visible = true;
}
//// Wwork Experience summary
ArrayList ObjArrWorkExp = new ArrayList();
ObjArrWorkExp = (new ApplicantWorkExperienceController()).GetByApplicantPersonalDetails(applicantID);
if (ObjArrWorkExp.Count > 0)
{
GridViewWorkExperience.DataSource = ObjArrWorkExp;
GridViewWorkExperience.DataBind();
GridViewWorkExperience.Visible = true;
}
//// Document summary
ArrayList ObjArrDoc = new ArrayList();
ObjArrDoc = (new ApplicantDocumentController()).GetByApplicantPersonalDetails(applicantID);
if (ObjArrDoc.Count > 0)
{
GridViewDocument.DataSource = ObjArrDoc;
GridViewDocument.DataBind();
GridViewDocument.Visible = true;
}
PanelShortListViewAppDetails.Visible = true;
//Button5.Visible = true;
}
}
#endregion
protected void Button12_Click(object sender, EventArgs e)
{
string position = ddReportVacantPosition.SelectedItem.Text.Trim();
ArrayList objArr = new ArrayList();
objArr = (new ApplicantPersonalDetailsController()).ListByPositionAppliedForAll(position);
if (objArr.Count > 0)
{
GVReport.DataSource = objArr;
GVReport.DataBind();
GVReport.Visible = true;
lblReport.Visible = false;
}
else
{
GVReport.Visible = false;
lblReport.Text = "No one apply for this position";
lblReport.Visible = true;
}
}
//Report
#region
//Loading vacant position for reporting
#region
protected void ddReportVacantDept_SelectedIndexChanged(object sender, System.EventArgs e)
{
ArrayList objGetReportPost = new ArrayList();
int dept5 = Convert.ToInt32(ddReportVacantDept.SelectedValue);
objGetReportPost = (new ApplicantAvailablePositiontableController()).GetByApplicantDepartmentTable(dept5);
if (objGetReportPost.Count > 0)
{
ddReportVacantPosition.DataSource = objGetReportPost;
ddReportVacantPosition.DataTextField = "positionAppliedForName";
ddReportVacantPosition.DataValueField = "positionAppliedforID";
ddReportVacantPosition.DataBind();
}
}
protected void ddReportVacantPosition_SelectedIndexChanged(object sender, EventArgs e)
{
lblSelect.Text = "Select the report you want to view";
//Button12.Visible = true;
// Button13.Visible = true;
// Button14.Visible = true;
linkAllapplicants.Visible = true;
linkShortlistedApplicants.Visible = true;
linkHireApplicants.Visible = true;
LinkApproveApplicant.Visible = true;
GVReport.Visible = false;
}
#endregion
//List all applicants that applied for a position
#region
protected void LinkButton2_Click(object sender, EventArgs e)
{
string position = ddReportVacantPosition.SelectedItem.Text.Trim();
ArrayList objArr = new ArrayList();
objArr = (new ApplicantPersonalDetailsController()).ListByPositionAppliedForAll(position);
if (objArr.Count > 0)
{
GVReport.DataSource = objArr;
GVReport.DataBind();
GVReport.Visible = true;
lblReport.Visible = false;
}
else
{
GVReport.Visible = false;
lblReport.Text = "No one apply for this position";
lblReport.Visible = true;
}
}
#endregion
//Shortlisted applicants
#region
protected void linkShortlistedApplicants_Click(object sender, EventArgs e)
{
string position = ddReportVacantPosition.SelectedItem.Text.Trim();
ArrayList objArr = new ArrayList();
// get shortlisted applicants either hire or not
objArr = (new ApplicantPersonalDetailsController()).ListByPositionHireOrNot(position);
if (objArr.Count > 0)
{
GVReport.DataSource = objArr;
GVReport.DataBind();
GVReport.Visible = true;
lblReport.Visible = false;
}
else
{
GVReport.Visible = false;
lblReport.Text = "No applicant has been shortlisted for the position of " + ddReportVacantPosition.SelectedItem.Text.Trim();
lblReport.Visible = true;
}
}
#endregion
//Hire applicants
#region
protected void linkHireApplicants_Click(object sender, EventArgs e)
{
string position = ddReportVacantPosition.SelectedItem.Text.Trim();
ArrayList objArr = new ArrayList();
objArr = (new ApplicantPersonalDetailsController()).ListByPositionHire(position);
if (objArr.Count > 0)
{
GVReport.DataSource = objArr;
GVReport.DataBind();
GVReport.Visible = true;
lblReport.Visible = false;
}
else
{
GVReport.Visible = false;
lblReport.Text = "No applicant has been hire for the position of " + ddReportVacantPosition.SelectedItem.Text.Trim();
lblReport.Visible = true;
}
}
#endregion
#endregion
//Loading position for management decision
#region
protected void ddManagDecisionAvailDept_SelectedIndexChanged(object sender, System.EventArgs e)
{
ArrayList objGetMangDecisionPost = new ArrayList();
int dept3 = Convert.ToInt32(ddManagDecisionAvailDept.SelectedValue);
objGetMangDecisionPost = (new ApplicantAvailablePositiontableController()).GetByApplicantDepartmentTable(dept3);
if (objGetMangDecisionPost.Count > 0)
{
ddManagDecisionAvailPosition.DataSource = objGetMangDecisionPost;
ddManagDecisionAvailPosition.DataTextField = "positionAppliedForName";
ddManagDecisionAvailPosition.DataValueField = "positionAppliedforID";
ddManagDecisionAvailPosition.DataBind();
//ddManagDecisionAvailPosition.Items.Insert(0, ListItem("--"))
}
}
protected void ddManagDecisionAvailPosition_SelectedIndexChanged(object sender, EventArgs e)
{
btnMangDecitionFinish.Visible = false;
btnMangDecTryAgain.Visible = false;
lblhire1.Visible= false;
PanelManagementDecision.Visible = true;
string position = ddManagDecisionAvailPosition.SelectedItem.Text.Trim();
ArrayList objArr = new ArrayList();
// get hire applicants
objArr = new ApplicantPersonalDetailsController().ListByPositionHire(position);
if (objArr.Count > 0)
{
GVHireApplicants.DataSource = objArr;
GVHireApplicants.DataBind();
GVHireApplicants.Visible = true;
lblHireReport.Visible = false;
btnSaveManagementApproval.Visible = true;
}
else
{
ArrayList objArr2 = new ArrayList();
// get shortlisted but not hire
objArr2 = new ApplicantPersonalDetailsController().ListByPositionShortlisted(position);
if (objArr2.Count > 0)
{
lblHireReport.Text = "No one has be hired for the position of " + ddManagDecisionAvailPosition.SelectedItem.Text;
lblHireReport.Visible = true;
GVHireApplicants.Visible = false;
btnSaveManagementApproval.Visible = false;
}
else
{
// get applied but not shortlisted
objArr2 = new ApplicantPersonalDetailsController().ListByPositionNotShortlisted(position);
if (objArr2.Count > 0)
{
lblHireReport.Text = "No one has be Shortlisted for the position of " + ddManagDecisionAvailPosition.SelectedItem.Text;
lblHireReport.Visible = true;
GVHireApplicants.Visible = false;
btnSaveManagementApproval.Visible = false;
}
else
{
// get applied applicants
objArr2 = new ApplicantPersonalDetailsController().ListByPositionAppliedForAll(position);
if (objArr2.Count== 0)
{
lblHireReport.Text = "Nobody apply for the position of " + ddManagDecisionAvailDept.SelectedItem.Text;
lblHireReport.Visible = true;
GVHireApplicants.Visible = false;
btnSaveManagementApproval.Visible = false;
}
}
}
//GVHireApplicants.Visible = false;
//lblHireReport.Text = "No one has be hired for the position of " + ddlPositionMgt.SelectedItem.Text;
//lblHireReport.Visible = true;
}
}
#endregion
//Saving Management Approval
#region
protected void btnManagementDecision_Click(object sender, EventArgs e)
{
MViewInterview.ActiveViewIndex = 4;
PanelManagementDecision.Visible = true;
lblhire.Visible = false;
PanelManagementDecision.Visible = false;
btnSendOfferTryAgain.Visible = false;
btnSendOfferFinish.Visible = false;
}
protected void btnSaveManagementApproval_Click(object sender, System.EventArgs e)
{
int count = 0;
foreach (GridViewRow x in GVHireApplicants.Rows)
{
TextBox b = new TextBox();
b = (TextBox)x.FindControl("TextBoxID");
int id = Convert.ToInt32(b.Text);
CheckBox c = new CheckBox();
c = (CheckBox)x.FindControl("CheckBox1");
if (c.Checked == true)
{
try
{
ApplicantPersonalDetailsInfo objPersonalInfo = new ApplicantPersonalDetailsInfo();
objPersonalInfo.ApplicantID = Convert.ToInt32(id);
objPersonalInfo.ManagementDecition = "Approve";
new ApplicantPersonalDetailsController().UpdateManagementDecision(objPersonalInfo);
count += 1;
ApplicantPersonalDetailsInfo objPersonalInfo1 = new ApplicantPersonalDetailsInfo();
objPersonalInfo1 = (new ApplicantPersonalDetailsController()).Get(Convert.ToInt32(id));
if (objPersonalInfo1.ManagementDecition == "Approve")
{
lblHireReport.Text = "Approve successfull";
lblHireReport.Visible = true;
PanelManagementDecision.Visible = false;
btnSendOfferTryAgain.Visible = false;
btnSendOfferFinish.Visible = true;
}
else
{
lblHireReport.Text = "Approve NOT successfull";
lblHireReport.Visible = true;
PanelManagementDecision.Visible = false;
btnSendOfferTryAgain.Visible = true;
btnSendOfferFinish.Visible = false;
}
}
catch (Exception ex)
{
lblhire.Text = (ex.Message);
lblhire.Visible = true;
}
}
// /reload the gridview
string position = ddManagDecisionAvailDept.SelectedItem.Text;
ArrayList objArr = new ArrayList();
objArr = new ApplicantPersonalDetailsController().ListByPositionHire(position);
if (objArr.Count > 0)
{
GVHireApplicants.DataSource = objArr;
GVHireApplicants.DataBind();
GVHireApplicants.Visible = true;
Label57.Visible = true;
//lblNoShortlistedApplicant.Visible = false;
}
}
}
#endregion
//Management View shortlisted applicants for approval
#region
protected void GVHireApplicants_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "View")
{
ApplicantPersonalDetailsInfo objPersonalInfo = new ApplicantPersonalDetailsInfo();
objPersonalInfo = (new ApplicantPersonalDetailsController()).Get(Convert.ToInt32(e.CommandArgument));
lbApproveDept.Text = objPersonalInfo.DeptAppliedTo;
lblApprovePosition.Text= objPersonalInfo.PositionAppliedFor;
lblApproveName.Text = objPersonalInfo.FirstName;
lblapproveMName.Text = objPersonalInfo.MiiddleName;
lblapproveLName.Text = objPersonalInfo.LastName;
lblApproveGender.Text = objPersonalInfo.Gender;
lblapproveMaritalStatus.Text = objPersonalInfo.MaritalStatus;
lblApproveNationality.Text = objPersonalInfo.countryName;
lblApproveState.Text = objPersonalInfo.stateName;
lblApproveSenatorial.Text = objPersonalInfo.senName;
lblLGA.Text = objPersonalInfo.LastName;
lblApproveLga.Text = objPersonalInfo.LGA;
lblapproveHTown.Text = objPersonalInfo.HomeTown;
lblApproveEmail.Text = objPersonalInfo.Email;
lblapproveAddr.Text = objPersonalInfo.ContactAddress;
lblApproveAge.Text = objPersonalInfo.Age;
Image2.ImageUrl = "~/Image/" + objPersonalInfo.Passport.Substring(objPersonalInfo.Passport.LastIndexOf('\\') + 1);
int applicantID = Convert.ToInt32(e.CommandArgument);
//label
ArrayList ObjArrQualification = new ArrayList();
ObjArrQualification = (new ApplicantQualificationController()).GetByApplicantPersonalDetails(applicantID);
if (ObjArrQualification.Count > 0)
{
GVQualif.DataSource = ObjArrQualification;
GVQualif.DataBind();
GVQualif.Visible = true;
}
//// professional Qualification summary
ArrayList ObjArrProfQualification = new ArrayList();
ObjArrProfQualification = (new ApplicantProfQualificationController()).GetByApplicantPersonalDetails(applicantID);
if (ObjArrProfQualification.Count > 0)
{
GVProfQualif.DataSource = ObjArrProfQualification;
GVProfQualif.DataBind();
GVProfQualif.Visible = true;
}
//// Wwork Experience summary
ArrayList ObjArrWorkExp = new ArrayList();
ObjArrWorkExp = (new ApplicantWorkExperienceController()).GetByApplicantPersonalDetails(applicantID);
if (ObjArrWorkExp.Count > 0)
{
GVWrkExp.DataSource = ObjArrWorkExp;
GVWrkExp.DataBind();
GVWrkExp.Visible = true;
}
//// Document summary
ArrayList ObjArrDoc = new ArrayList();
ObjArrDoc = (new ApplicantDocumentController()).GetByApplicantPersonalDetails(applicantID);
if (ObjArrDoc.Count > 0)
{
GVDoc.DataSource = ObjArrDoc;
GVDoc.DataBind();
GVDoc.Visible = true;
}
c.Visible = true;
}
}
#endregion
//List position for sending offer
#region
protected void ddSendOfferAvailDept_SelectedIndexChanged(object sender, System.EventArgs e)
{
ArrayList objGetSendOfferPost = new ArrayList();
int dept4 = Convert.ToInt32(ddSendOfferAvailDept.SelectedValue);
objGetSendOfferPost = (new ApplicantAvailablePositiontableController()).GetByApplicantDepartmentTable(dept4);
if (objGetSendOfferPost.Count > 0)
{
ddSendOfferAvailPosition.DataSource = objGetSendOfferPost;
ddSendOfferAvailPosition.DataTextField = "positionAppliedForName";
ddSendOfferAvailPosition.DataValueField = "positionAppliedforID";
ddSendOfferAvailPosition.DataBind();
}
}
protected void ddlAvailablePosition_SelectedIndexChanged(object sender, EventArgs e)
{
PanelOfferEmployment.Visible = true;
string position = ddSendOfferAvailPosition.SelectedItem.Text;
ArrayList objArr = new ArrayList();
objArr = new ApplicantPersonalDetailsController().ListByPositionApprove(position);
if (objArr.Count > 0)
{
GVSendOffer.DataSource = objArr;
GVSendOffer.DataBind();
GVSendOffer.Visible = true;
lblReport2.Visible = false;
// Button16.Visible = true;
}
else
{
GVSendOffer.Visible = false;
lblReport2.Text = "No applicant has been approved for the position of " + ddSendOfferAvailPosition.SelectedItem.Text;
lblReport2.Visible = true;
}
}
#endregion
//Sending Offer letter
#region
protected void btnSendOfferletter_Click(object sender, EventArgs e)
{
foreach (GridViewRow x in GVSendOffer.Rows)
{
// declare a variable as textbox
TextBox b = new TextBox();
// find the textbox containing the applicantID on the gridview
b = (TextBox)x.FindControl("txtApplicantID");
string applicantID = b.Text;
CheckBox c = new CheckBox();
c = (CheckBox)x.FindControl("CheckBox1");
if (c.Checked == true)
{
try
{
ApplicantPersonalDetailsInfo objPersonalInfo = new ApplicantPersonalDetailsInfo();
objPersonalInfo = new ApplicantPersonalDetailsController().GetOfferDetails(Convert.ToInt32(applicantID));
lblName2.Text = objPersonalInfo.LastName + " " + objPersonalInfo.FirstName;
lblPosition.Text = objPersonalInfo.ApprovedPositionName;
lblOfferDept.Text = objPersonalInfo.DeptName;
lblOfferPosition.Text = objPersonalInfo.ApprovedPositionName;
lblOfferDept2.Text = objPersonalInfo.DeptName;
lblOfferLevel.Text = objPersonalInfo.LevelName;
lblOfferSalary.Text = objPersonalInfo.Salary;
lblOfferWrkLocatn.Text = objPersonalInfo.LocationName;
lblOfferRsmptDate.Text = objPersonalInfo.ResumptionDate;
//Composing mail content
//string salutaion = ("dear" + objPersonalInfo.LastName + ",");
string subjectEmail = "Employment Offer";
string bodyEmail = ("Dear " + objPersonalInfo.LastName + ", " + objPersonalInfo.FirstName + " Further to your application and subsquent interviewat Neetbeet Technogies Limited, we are please to offer you"
+ objPersonalInfo.ApprovedPositionName + " under the department of " + objPersonalInfo.DeptName);
string offerDetails = ("The following are your appointment detail: " +
"Position: " + objPersonalInfo.ApprovedPositionName +
"Department: " + objPersonalInfo.DeptName +
"Level: " + objPersonalInfo.LevelName +
"Salary: " + objPersonalInfo.Salary +
"Work Loction: " + objPersonalInfo.LocationName +
"Resumption Date:" + objPersonalInfo.ResumptionDate +
"The first six months of your employment with us will be regarded as a propationary period, during which , either you o the company could terminate the appointment by giving one (1) month's notice in writing or paying one (1) month's basic salary in lieuof notice. ");
bodyEmail += offerDetails;
string receiverEmail = objPersonalInfo.Email;
Utility.SendMail(subjectEmail, bodyEmail, receiverEmail);
string url = "http://" + Request.Url.Authority + "/Print5.aspx?id=" + applicantID.ToString();
Response.Write("<script language=javascript> window.open( '" + url + "','_blank');</script>");
ApplicantPersonalDetailsInfo objPersonalInfo1 = new ApplicantPersonalDetailsInfo();
objPersonalInfo1 = (new ApplicantPersonalDetailsController()).GetOfferDetails(Convert.ToInt32(applicantID));
if ((objPersonalInfo1.DepartmentID_FK != null) && (objPersonalInfo1.PositionApproved_FK != null) &&
(objPersonalInfo1.LevelID_FK != null) && (objPersonalInfo1.WorkLocationID_FK != null))
{
PanelOfferEmployment.Visible = false;
LbOfferLetterSentSuccessfully.Text = "Employment Letter sent successfully";
LbOfferLetterSentSuccessfully.Visible = true;
btnSendOfferFinish.Visible = true;
btnSendOfferTryAgain.Visible = false;
lblReport2.Visible = false;
}
else
{
PanelOfferEmployment.Visible = false;
LbOfferLetterSentSuccessfully.Text = "Employment Letter NOT sent";
LbOfferLetterSentSuccessfully.Visible = true;
btnSendOfferFinish.Visible = false;
btnSendOfferTryAgain.Visible = true;
lblReport2.Visible = false;
}
}
catch { }
}
// MViewInterview.ActiveViewIndex = 9;
}
}
protected void btnSendOfferTryAgain_Click(object sender, System.EventArgs e)
{
PanelOfferEmployment.Visible = true;
LbOfferLetterSentSuccessfully.Visible = false;
btnSendOfferFinish.Visible = false;
lblReport2.Visible = false;
btnSendOfferTryAgain.Visible = false;
}
#endregion
//Printing offer letter
#region
protected void btnPrint_Click(object sender, EventArgs e)
{
HttpContext.Current.Response.Write("<script>Print5.print();</script>");
btnPrint.Visible = false;
}
#endregion
}
} | 42.822236 | 296 | 0.560853 | [
"Apache-2.0",
"BSD-3-Clause"
] | deyeni2001/HRMSDEV60 | DesktopModules/HRMangmntSyst/InterviewPage.ascx.cs | 68,175 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ExpandedSpawnning : MonoBehaviour
{
public GameObject cubeModel;
public float spawnSpacingX;
public float spawnSpacingY;
public float xPower;
public float yPower;
private void Start()
{
xPower = staticScript.xPower;
yPower = staticScript.yPower;
for (float i = 0f; i < xPower; i += 1f)
{
for (float j = 0f; j < yPower; j += 1f)
{
Vector3 spawnPosition = new Vector3(i * spawnSpacingX, transform.position.y, j * spawnSpacingY);
GameObject mainPlayer = Instantiate(cubeModel, spawnPosition, Quaternion.identity);
}
}
}
}
| 26.964286 | 112 | 0.619868 | [
"MIT"
] | Ujjwal-Shekhawat/BattleRoyale | Assets/Scripts/ExpandedSpawnning.cs | 757 | C# |
using Miki.Discord.Common.Packets;
using System.Runtime.Serialization;
namespace Miki.Discord.Common.Events
{
[DataContract]
public class RoleEventArgs
{
[DataMember(Name = "guild_id")] public ulong GuildId;
[DataMember(Name = "role")] public DiscordRolePacket Role;
}
} | 23.461538 | 66 | 0.698361 | [
"MIT"
] | Mikibot/Miki.Discord | Miki.Discord.Common/Packets/Events/RoleEventArgs.cs | 307 | C# |
using System.Collections.Generic;
namespace GitStats.Lib
{
public interface IGetStats
{
void Get(string gitRepo, int commitsNum = 200, string branch = null);
}
} | 19.555556 | 72 | 0.710227 | [
"MIT"
] | gookcedemir/GitStats | src/GitStats.Lib/IGetStats.cs | 178 | C# |
#pragma checksum "C:\Users\Terry\Downloads\BeautySalon\Web\BeautyBooking.Web\Areas\Administration\Views\Salons\Index.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "36540c86c291ec9080bb960ae8a0d05a58ce0fc4"
// <auto-generated/>
#pragma warning disable 1591
[assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCore.Areas_Administration_Views_Salons_Index), @"mvc.1.0.view", @"/Areas/Administration/Views/Salons/Index.cshtml")]
namespace AspNetCore
{
#line hidden
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
#nullable restore
#line 1 "C:\Users\Terry\Downloads\BeautySalon\Web\BeautyBooking.Web\Areas\Administration\Views\_ViewImports.cshtml"
using BeautyBooking.Web;
#line default
#line hidden
#nullable disable
#nullable restore
#line 2 "C:\Users\Terry\Downloads\BeautySalon\Web\BeautyBooking.Web\Areas\Administration\Views\_ViewImports.cshtml"
using BeautyBooking.Web.ViewModels;
#line default
#line hidden
#nullable disable
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"36540c86c291ec9080bb960ae8a0d05a58ce0fc4", @"/Areas/Administration/Views/Salons/Index.cshtml")]
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"9061ceacb3f8e30506ec034bed1cdd1c222cf1d3", @"/Areas/Administration/Views/_ViewImports.cshtml")]
public class Areas_Administration_Views_Salons_Index : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<BeautyBooking.Web.ViewModels.Salons.SalonsListViewModel>
{
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_0 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("class", new global::Microsoft.AspNetCore.Html.HtmlString("btn btn-info"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_1 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-area", "Administration", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_2 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-controller", "Salons", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_3 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-action", "AddSalon", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_4 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("type", new global::Microsoft.AspNetCore.Html.HtmlString("submit"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_5 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("class", new global::Microsoft.AspNetCore.Html.HtmlString("btn btn-danger btn-sm"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_6 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-action", "DeleteSalon", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_7 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("method", "post", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
#line hidden
#pragma warning disable 0649
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext __tagHelperExecutionContext;
#pragma warning restore 0649
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner __tagHelperRunner = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner();
#pragma warning disable 0169
private string __tagHelperStringValueBuffer;
#pragma warning restore 0169
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __backed__tagHelperScopeManager = null;
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __tagHelperScopeManager
{
get
{
if (__backed__tagHelperScopeManager == null)
{
__backed__tagHelperScopeManager = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager(StartTagHelperWritingScope, EndTagHelperWritingScope);
}
return __backed__tagHelperScopeManager;
}
}
private global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper;
private global::Microsoft.AspNetCore.Mvc.TagHelpers.FormTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper;
private global::Microsoft.AspNetCore.Mvc.TagHelpers.RenderAtEndOfFormTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper;
private global::Microsoft.AspNetCore.Mvc.TagHelpers.FormActionTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_FormActionTagHelper;
#pragma warning disable 1998
public async override global::System.Threading.Tasks.Task ExecuteAsync()
{
#nullable restore
#line 2 "C:\Users\Terry\Downloads\BeautySalon\Web\BeautyBooking.Web\Areas\Administration\Views\Salons\Index.cshtml"
this.ViewData["Title"] = "Салоны";
#line default
#line hidden
#nullable disable
WriteLiteral("\n<h2>\n Все салоны (");
#nullable restore
#line 7 "C:\Users\Terry\Downloads\BeautySalon\Web\BeautyBooking.Web\Areas\Administration\Views\Salons\Index.cshtml"
Write(Model.Salons.Count());
#line default
#line hidden
#nullable disable
WriteLiteral(")\n <span>\n ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("a", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "36540c86c291ec9080bb960ae8a0d05a58ce0fc46845", async() => {
WriteLiteral("Добавить новый салон");
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Area = (string)__tagHelperAttribute_1.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_1);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Controller = (string)__tagHelperAttribute_2.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_2);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Action = (string)__tagHelperAttribute_3.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_3);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral(@"
</span>
</h2>
<table class=""table table-bordered table-striped"">
<thead class=""thead-light"">
<tr>
<th scope=""col"">Название</th>
<th scope=""col"">Картинка</th>
<th scope=""col"">Категория</th>
<th scope=""col"">Город</th>
<th scope=""col"">Адрес</th>
<th scope=""col"">Рейтинг</th>
<th scope=""col"">Записи</th>
<th scope=""col"">Удалить салон?</th>
</tr>
</thead>
<tbody>
");
#nullable restore
#line 27 "C:\Users\Terry\Downloads\BeautySalon\Web\BeautyBooking.Web\Areas\Administration\Views\Salons\Index.cshtml"
foreach (var salon in this.Model.Salons)
{
#line default
#line hidden
#nullable disable
WriteLiteral(" <tr>\n <th scope=\"row\">");
#nullable restore
#line 30 "C:\Users\Terry\Downloads\BeautySalon\Web\BeautyBooking.Web\Areas\Administration\Views\Salons\Index.cshtml"
Write(salon.Name);
#line default
#line hidden
#nullable disable
WriteLiteral("</th>\n <td>\n <img class=\"align-self-center\"");
BeginWriteAttribute("src", " src=\"", 977, "\"", 998, 1);
#nullable restore
#line 32 "C:\Users\Terry\Downloads\BeautySalon\Web\BeautyBooking.Web\Areas\Administration\Views\Salons\Index.cshtml"
WriteAttributeValue("", 983, salon.ImageUrl, 983, 15, false);
#line default
#line hidden
#nullable disable
EndWriteAttribute();
WriteLiteral(" style=\"width:180px;height:120px;\">\n </td>\n <td>");
#nullable restore
#line 34 "C:\Users\Terry\Downloads\BeautySalon\Web\BeautyBooking.Web\Areas\Administration\Views\Salons\Index.cshtml"
Write(salon.CategoryName);
#line default
#line hidden
#nullable disable
WriteLiteral("</td>\n <td>");
#nullable restore
#line 35 "C:\Users\Terry\Downloads\BeautySalon\Web\BeautyBooking.Web\Areas\Administration\Views\Salons\Index.cshtml"
Write(salon.CityName);
#line default
#line hidden
#nullable disable
WriteLiteral("</td>\n <td>");
#nullable restore
#line 36 "C:\Users\Terry\Downloads\BeautySalon\Web\BeautyBooking.Web\Areas\Administration\Views\Salons\Index.cshtml"
Write(salon.Address);
#line default
#line hidden
#nullable disable
WriteLiteral("</td>\n <td><strong>");
#nullable restore
#line 37 "C:\Users\Terry\Downloads\BeautySalon\Web\BeautyBooking.Web\Areas\Administration\Views\Salons\Index.cshtml"
Write(salon.Rating.ToString("F"));
#line default
#line hidden
#nullable disable
WriteLiteral(" / 5.00</strong> from <strong>");
#nullable restore
#line 37 "C:\Users\Terry\Downloads\BeautySalon\Web\BeautyBooking.Web\Areas\Administration\Views\Salons\Index.cshtml"
Write(salon.RatersCount);
#line default
#line hidden
#nullable disable
WriteLiteral("</strong> votes</td>\n <td>");
#nullable restore
#line 38 "C:\Users\Terry\Downloads\BeautySalon\Web\BeautyBooking.Web\Areas\Administration\Views\Salons\Index.cshtml"
Write(salon.AppointmentsCount);
#line default
#line hidden
#nullable disable
WriteLiteral("</td>\n <td>\n");
#nullable restore
#line 40 "C:\Users\Terry\Downloads\BeautySalon\Web\BeautyBooking.Web\Areas\Administration\Views\Salons\Index.cshtml"
if (salon.Id.StartsWith("seeded"))
{
#line default
#line hidden
#nullable disable
WriteLiteral(" <div class=\"text-muted\" style=\"font-size:smaller\">\n Изначально заведенные салоны <br />Нельзя удалить!\n </div>\n");
#nullable restore
#line 45 "C:\Users\Terry\Downloads\BeautySalon\Web\BeautyBooking.Web\Areas\Administration\Views\Salons\Index.cshtml"
}
else
{
#line default
#line hidden
#nullable disable
WriteLiteral(" ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("form", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "36540c86c291ec9080bb960ae8a0d05a58ce0fc412784", async() => {
WriteLiteral("\n ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("button", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "36540c86c291ec9080bb960ae8a0d05a58ce0fc413069", async() => {
WriteLiteral("\n Удалить\n ");
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_FormActionTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.FormActionTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_FormActionTagHelper);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_4);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_5);
__Microsoft_AspNetCore_Mvc_TagHelpers_FormActionTagHelper.Area = (string)__tagHelperAttribute_1.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_1);
__Microsoft_AspNetCore_Mvc_TagHelpers_FormActionTagHelper.Controller = (string)__tagHelperAttribute_2.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_2);
__Microsoft_AspNetCore_Mvc_TagHelpers_FormActionTagHelper.Action = (string)__tagHelperAttribute_6.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_6);
if (__Microsoft_AspNetCore_Mvc_TagHelpers_FormActionTagHelper.RouteValues == null)
{
throw new InvalidOperationException(InvalidTagHelperIndexerAssignment("asp-route-id", "Microsoft.AspNetCore.Mvc.TagHelpers.FormActionTagHelper", "RouteValues"));
}
BeginWriteTagHelperAttribute();
#nullable restore
#line 50 "C:\Users\Terry\Downloads\BeautySalon\Web\BeautyBooking.Web\Areas\Administration\Views\Salons\Index.cshtml"
WriteLiteral(salon.Id);
#line default
#line hidden
#nullable disable
__tagHelperStringValueBuffer = EndWriteTagHelperAttribute();
__Microsoft_AspNetCore_Mvc_TagHelpers_FormActionTagHelper.RouteValues["id"] = __tagHelperStringValueBuffer;
__tagHelperExecutionContext.AddTagHelperAttribute("asp-route-id", __Microsoft_AspNetCore_Mvc_TagHelpers_FormActionTagHelper.RouteValues["id"], global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\n ");
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.FormTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper);
__Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.RenderAtEndOfFormTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper);
__Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper.Method = (string)__tagHelperAttribute_7.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_7);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\n");
#nullable restore
#line 54 "C:\Users\Terry\Downloads\BeautySalon\Web\BeautyBooking.Web\Areas\Administration\Views\Salons\Index.cshtml"
}
#line default
#line hidden
#nullable disable
WriteLiteral(" </td>\n </tr>\n");
#nullable restore
#line 57 "C:\Users\Terry\Downloads\BeautySalon\Web\BeautyBooking.Web\Areas\Administration\Views\Salons\Index.cshtml"
}
#line default
#line hidden
#nullable disable
WriteLiteral(" </tbody>\n</table>\n");
}
#pragma warning restore 1998
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<BeautyBooking.Web.ViewModels.Salons.SalonsListViewModel> Html { get; private set; }
}
}
#pragma warning restore 1591
| 61.072368 | 359 | 0.717063 | [
"MIT"
] | DiePathologie/BeautySalon | Web/BeautyBooking.Web/obj/Debug/netcoreapp3.1/Razor/Areas/Administration/Views/Salons/Index.cshtml.g.cs | 18,705 | C# |
using System.Text;
using _0_Framework.Infrastructure;
namespace ShopManagement.Infrastructure.Configuration.Permissions {
public class ShopPermissionExposer: IPermissionExposer {
public Dictionary<string, List<PermissionDto>> Expose () {
return new Dictionary<string, List<PermissionDto>> {
{
"Products", new List<PermissionDto> {
new(ShopPermissions.ListProduct, "لیست محصولات"),
new(ShopPermissions.SearchProducts, "جستجو در محصولات"),
new(ShopPermissions.EditProduct, "ویرایش محصول"),
new(ShopPermissions.CreateProduct, "ساخت محصول"),
}
},
{
"Product Category", new List<PermissionDto> {
new(ShopPermissions.ListProductCategories, "لیست گروه محصولات"),
new(ShopPermissions.SearchProductCategories, "جستجو در گروه محصولات"),
new(ShopPermissions.EditProductCategory, "ویرایش گروه محصول"),
new(ShopPermissions.CreateProductCategory, "ساخت گروه محصول"),
}
},
{
"Product Picture", new List<PermissionDto> {
new(ShopPermissions.ListProductPictures, "لیست عکس ها"),
new(ShopPermissions.SearchProductPictures, "جستجو در عکس ها"),
new(ShopPermissions.EditProductPicture, "ویرایش عکس"),
new(ShopPermissions.CreateProductPicture, "ساخت عکس"),
new(ShopPermissions.RemoveProductPicture, "حذف عکس"),
}
},
{
"Slide", new List<PermissionDto> {
new(ShopPermissions.ListSlides, "لیست اسلاید ها"),
new(ShopPermissions.SearchSlides, "جستجو در اسلاید ها"),
new(ShopPermissions.EditSlide, "ویرایش اسلاید"),
new(ShopPermissions.CreateSlide, "ساخت اسلاید"),
new(ShopPermissions.RemoveSlide, "حذف اسلاید"),
}
}
};
}
}
}
| 49.304348 | 94 | 0.520723 | [
"MIT"
] | AmirhosseinKeshtkar/Lampshade | ShopManagement.Configuraion/Permissions/ShopPermissionExposer.cs | 2,477 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Buffers;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using EditorBrowsableAttribute = System.ComponentModel.EditorBrowsableAttribute;
using EditorBrowsableState = System.ComponentModel.EditorBrowsableState;
using Internal.Runtime.CompilerServices;
#pragma warning disable SA1121 // explicitly using type aliases instead of built-in types
#if BIT64
using nuint = System.UInt64;
#else // BIT64
using nuint = System.UInt32;
#endif // BIT64
namespace System
{
/// <summary>
/// Memory represents a contiguous region of arbitrary memory similar to <see cref="Span{T}"/>.
/// Unlike <see cref="Span{T}"/>, it is not a byref-like type.
/// </summary>
[DebuggerTypeProxy(typeof(MemoryDebugView<>))]
[DebuggerDisplay("{ToString(),raw}")]
public readonly struct Memory<T> : IEquatable<Memory<T>>
{
// NOTE: With the current implementation, Memory<T> and ReadOnlyMemory<T> must have the same layout,
// as code uses Unsafe.As to cast between them.
// The highest order bit of _index is used to discern whether _object is a pre-pinned array.
// (_index < 0) => _object is a pre-pinned array, so Pin() will not allocate a new GCHandle
// (else) => Pin() needs to allocate a new GCHandle to pin the object.
private readonly object? _object;
private readonly int _index;
private readonly int _length;
/// <summary>
/// Creates a new memory over the entirety of the target array.
/// </summary>
/// <param name="array">The target array.</param>
/// <remarks>Returns default when <paramref name="array"/> is null.</remarks>
/// <exception cref="System.ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant and array's type is not exactly T[].</exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Memory(T[]? array)
{
if (array == null)
{
this = default;
return; // returns default
}
if (default(T)! == null && array.GetType() != typeof(T[])) // TODO-NULLABLE: default(T) == null warning (https://github.com/dotnet/roslyn/issues/34757)
ThrowHelper.ThrowArrayTypeMismatchException();
_object = array;
_index = 0;
_length = array.Length;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal Memory(T[]? array, int start)
{
if (array == null)
{
if (start != 0)
ThrowHelper.ThrowArgumentOutOfRangeException();
this = default;
return; // returns default
}
if (default(T)! == null && array.GetType() != typeof(T[])) // TODO-NULLABLE: default(T) == null warning (https://github.com/dotnet/roslyn/issues/34757)
ThrowHelper.ThrowArrayTypeMismatchException();
if ((uint)start > (uint)array.Length)
ThrowHelper.ThrowArgumentOutOfRangeException();
_object = array;
_index = start;
_length = array.Length - start;
}
/// <summary>
/// Creates a new memory over the portion of the target array beginning
/// at 'start' index and ending at 'end' index (exclusive).
/// </summary>
/// <param name="array">The target array.</param>
/// <param name="start">The index at which to begin the memory.</param>
/// <param name="length">The number of items in the memory.</param>
/// <remarks>Returns default when <paramref name="array"/> is null.</remarks>
/// <exception cref="System.ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant and array's type is not exactly T[].</exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="start"/> or end index is not in the range (<0 or >Length).
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Memory(T[]? array, int start, int length)
{
if (array == null)
{
if (start != 0 || length != 0)
ThrowHelper.ThrowArgumentOutOfRangeException();
this = default;
return; // returns default
}
if (default(T)! == null && array.GetType() != typeof(T[])) // TODO-NULLABLE: default(T) == null warning (https://github.com/dotnet/roslyn/issues/34757)
ThrowHelper.ThrowArrayTypeMismatchException();
#if BIT64
// See comment in Span<T>.Slice for how this works.
if ((ulong)(uint)start + (ulong)(uint)length > (ulong)(uint)array.Length)
ThrowHelper.ThrowArgumentOutOfRangeException();
#else
if ((uint)start > (uint)array.Length || (uint)length > (uint)(array.Length - start))
ThrowHelper.ThrowArgumentOutOfRangeException();
#endif
_object = array;
_index = start;
_length = length;
}
/// <summary>
/// Creates a new memory from a memory manager that provides specific method implementations beginning
/// at 0 index and ending at 'end' index (exclusive).
/// </summary>
/// <param name="manager">The memory manager.</param>
/// <param name="length">The number of items in the memory.</param>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="length"/> is negative.
/// </exception>
/// <remarks>For internal infrastructure only</remarks>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal Memory(MemoryManager<T> manager, int length)
{
Debug.Assert(manager != null);
if (length < 0)
ThrowHelper.ThrowArgumentOutOfRangeException();
_object = manager;
_index = 0;
_length = length;
}
/// <summary>
/// Creates a new memory from a memory manager that provides specific method implementations beginning
/// at 'start' index and ending at 'end' index (exclusive).
/// </summary>
/// <param name="manager">The memory manager.</param>
/// <param name="start">The index at which to begin the memory.</param>
/// <param name="length">The number of items in the memory.</param>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="start"/> or <paramref name="length"/> is negative.
/// </exception>
/// <remarks>For internal infrastructure only</remarks>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal Memory(MemoryManager<T> manager, int start, int length)
{
Debug.Assert(manager != null);
if (length < 0 || start < 0)
ThrowHelper.ThrowArgumentOutOfRangeException();
_object = manager;
_index = start;
_length = length;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal Memory(object? obj, int start, int length)
{
// No validation performed in release builds; caller must provide any necessary validation.
// 'obj is T[]' below also handles things like int[] <-> uint[] being convertible
Debug.Assert((obj == null)
|| (typeof(T) == typeof(char) && obj is string)
#if FEATURE_UTF8STRING
|| ((typeof(T) == typeof(byte) || typeof(T) == typeof(Char8)) && obj is Utf8String)
#endif // FEATURE_UTF8STRING
|| (obj is T[])
|| (obj is MemoryManager<T>));
_object = obj;
_index = start;
_length = length;
}
/// <summary>
/// Defines an implicit conversion of an array to a <see cref="Memory{T}"/>
/// </summary>
public static implicit operator Memory<T>(T[]? array) => new Memory<T>(array);
/// <summary>
/// Defines an implicit conversion of a <see cref="ArraySegment{T}"/> to a <see cref="Memory{T}"/>
/// </summary>
public static implicit operator Memory<T>(ArraySegment<T> segment) => new Memory<T>(segment.Array, segment.Offset, segment.Count);
/// <summary>
/// Defines an implicit conversion of a <see cref="Memory{T}"/> to a <see cref="ReadOnlyMemory{T}"/>
/// </summary>
public static implicit operator ReadOnlyMemory<T>(Memory<T> memory) =>
Unsafe.As<Memory<T>, ReadOnlyMemory<T>>(ref memory);
/// <summary>
/// Returns an empty <see cref="Memory{T}"/>
/// </summary>
public static Memory<T> Empty => default;
/// <summary>
/// The number of items in the memory.
/// </summary>
public int Length => _length;
/// <summary>
/// Returns true if Length is 0.
/// </summary>
public bool IsEmpty => _length == 0;
/// <summary>
/// For <see cref="Memory{Char}"/>, returns a new instance of string that represents the characters pointed to by the memory.
/// Otherwise, returns a <see cref="string"/> with the name of the type and the number of elements.
/// </summary>
public override string ToString()
{
if (typeof(T) == typeof(char))
{
return (_object is string str) ? str.Substring(_index, _length) : Span.ToString();
}
#if FEATURE_UTF8STRING
else if (typeof(T) == typeof(Char8))
{
// TODO_UTF8STRING: Call into optimized transcoding routine when it's available.
Span<T> span = Span;
return Encoding.UTF8.GetString(new ReadOnlySpan<byte>(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), span.Length));
}
#endif // FEATURE_UTF8STRING
return string.Format("System.Memory<{0}>[{1}]", typeof(T).Name, _length);
}
/// <summary>
/// Forms a slice out of the given memory, beginning at 'start'.
/// </summary>
/// <param name="start">The index at which to begin this slice.</param>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="start"/> index is not in range (<0 or >Length).
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Memory<T> Slice(int start)
{
if ((uint)start > (uint)_length)
{
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start);
}
// It is expected for _index + start to be negative if the memory is already pre-pinned.
return new Memory<T>(_object, _index + start, _length - start);
}
/// <summary>
/// Forms a slice out of the given memory, beginning at 'start', of given length
/// </summary>
/// <param name="start">The index at which to begin this slice.</param>
/// <param name="length">The desired length for the slice (exclusive).</param>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="start"/> or end index is not in range (<0 or >Length).
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Memory<T> Slice(int start, int length)
{
#if BIT64
// See comment in Span<T>.Slice for how this works.
if ((ulong)(uint)start + (ulong)(uint)length > (ulong)(uint)_length)
ThrowHelper.ThrowArgumentOutOfRangeException();
#else
if ((uint)start > (uint)_length || (uint)length > (uint)(_length - start))
ThrowHelper.ThrowArgumentOutOfRangeException();
#endif
// It is expected for _index + start to be negative if the memory is already pre-pinned.
return new Memory<T>(_object, _index + start, length);
}
/// <summary>
/// Returns a span from the memory.
/// </summary>
public unsafe Span<T> Span
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
// This property getter has special support for returning a mutable Span<char> that wraps
// an immutable String instance. This is obviously a dangerous feature and breaks type safety.
// However, we need to handle the case where a ReadOnlyMemory<char> was created from a string
// and then cast to a Memory<T>. Such a cast can only be done with unsafe or marshaling code,
// in which case that's the dangerous operation performed by the dev, and we're just following
// suit here to make it work as best as possible.
ref T refToReturn = ref Unsafe.NullRef<T>();
int lengthOfUnderlyingSpan = 0;
// Copy this field into a local so that it can't change out from under us mid-operation.
object? tmpObject = _object;
if (tmpObject != null)
{
if (typeof(T) == typeof(char) && tmpObject.GetType() == typeof(string))
{
// Special-case string since it's the most common for ROM<char>.
refToReturn = ref Unsafe.As<char, T>(ref Unsafe.As<string>(tmpObject).GetRawStringData());
lengthOfUnderlyingSpan = Unsafe.As<string>(tmpObject).Length;
}
#if FEATURE_UTF8STRING
else if ((typeof(T) == typeof(byte) || typeof(T) == typeof(Char8)) && tmpObject.GetType() == typeof(Utf8String))
{
refToReturn = ref Unsafe.As<byte, T>(ref Unsafe.As<Utf8String>(tmpObject).DangerousGetMutableReference());
lengthOfUnderlyingSpan = Unsafe.As<Utf8String>(tmpObject).Length;
}
#endif // FEATURE_UTF8STRING
else if (RuntimeHelpers.ObjectHasComponentSize(tmpObject))
{
// We know the object is not null, it's not a string, and it is variable-length. The only
// remaining option is for it to be a T[] (or a U[] which is blittable to T[], like int[]
// and uint[]). As a special case of this, ROM<T> allows some amount of array variance
// that Memory<T> disallows. For example, an array of actual type string[] cannot be turned
// into a Memory<object> or a Span<object>, but it can be turned into a ROM/ROS<object>.
// We'll assume these checks succeeded because they're performed during Memory<T> construction.
// It's always possible for somebody to use private reflection to bypass these checks, but
// preventing type safety violations due to misuse of reflection is out of scope of this logic.
// 'tmpObject is T[]' below also handles things like int[] <-> uint[] being convertible
Debug.Assert(tmpObject is T[]);
refToReturn = ref MemoryMarshal.GetArrayDataReference(Unsafe.As<T[]>(tmpObject));
lengthOfUnderlyingSpan = Unsafe.As<T[]>(tmpObject).Length;
}
else
{
// We know the object is not null, and it's not variable-length, so it must be a MemoryManager<T>.
// Otherwise somebody used private reflection to set this field, and we're not too worried about
// type safety violations at that point. Note that it can't be a MemoryManager<U>, even if U and
// T are blittable (e.g., MemoryManager<int> to MemoryManager<uint>), since there exists no
// constructor or other public API which would allow such a conversion.
Debug.Assert(tmpObject is MemoryManager<T>);
Span<T> memoryManagerSpan = Unsafe.As<MemoryManager<T>>(tmpObject).GetSpan();
refToReturn = ref MemoryMarshal.GetReference(memoryManagerSpan);
lengthOfUnderlyingSpan = memoryManagerSpan.Length;
}
// If the Memory<T> or ReadOnlyMemory<T> instance is torn, this property getter has undefined behavior.
// We try to detect this condition and throw an exception, but it's possible that a torn struct might
// appear to us to be valid, and we'll return an undesired span. Such a span is always guaranteed at
// least to be in-bounds when compared with the original Memory<T> instance, so using the span won't
// AV the process.
nuint desiredStartIndex = (uint)_index & (uint)ReadOnlyMemory<T>.RemoveFlagsBitMask;
int desiredLength = _length;
#if BIT64
// See comment in Span<T>.Slice for how this works.
if ((ulong)desiredStartIndex + (ulong)(uint)desiredLength > (ulong)(uint)lengthOfUnderlyingSpan)
{
ThrowHelper.ThrowArgumentOutOfRangeException();
}
#else
if ((uint)desiredStartIndex > (uint)lengthOfUnderlyingSpan || (uint)desiredLength > (uint)(lengthOfUnderlyingSpan - desiredStartIndex))
{
ThrowHelper.ThrowArgumentOutOfRangeException();
}
#endif
refToReturn = ref Unsafe.Add(ref refToReturn, (IntPtr)(void*)desiredStartIndex);
lengthOfUnderlyingSpan = desiredLength;
}
return new Span<T>(ref refToReturn, lengthOfUnderlyingSpan);
}
}
/// <summary>
/// Copies the contents of the memory into the destination. If the source
/// and destination overlap, this method behaves as if the original values are in
/// a temporary location before the destination is overwritten.
///
/// <param name="destination">The Memory to copy items into.</param>
/// <exception cref="System.ArgumentException">
/// Thrown when the destination is shorter than the source.
/// </exception>
/// </summary>
public void CopyTo(Memory<T> destination) => Span.CopyTo(destination.Span);
/// <summary>
/// Copies the contents of the memory into the destination. If the source
/// and destination overlap, this method behaves as if the original values are in
/// a temporary location before the destination is overwritten.
///
/// <returns>If the destination is shorter than the source, this method
/// return false and no data is written to the destination.</returns>
/// </summary>
/// <param name="destination">The span to copy items into.</param>
public bool TryCopyTo(Memory<T> destination) => Span.TryCopyTo(destination.Span);
/// <summary>
/// Creates a handle for the memory.
/// The GC will not move the memory until the returned <see cref="MemoryHandle"/>
/// is disposed, enabling taking and using the memory's address.
/// <exception cref="System.ArgumentException">
/// An instance with nonprimitive (non-blittable) members cannot be pinned.
/// </exception>
/// </summary>
public unsafe MemoryHandle Pin()
{
// Just like the Span property getter, we have special support for a mutable Memory<char>
// that wraps an immutable String instance. This might happen if a caller creates an
// immutable ROM<char> wrapping a String, then uses Unsafe.As to create a mutable M<char>.
// This needs to work, however, so that code that uses a single Memory<char> field to store either
// a readable ReadOnlyMemory<char> or a writable Memory<char> can still be pinned and
// used for interop purposes.
// It's possible that the below logic could result in an AV if the struct
// is torn. This is ok since the caller is expecting to use raw pointers,
// and we're not required to keep this as safe as the other Span-based APIs.
object? tmpObject = _object;
if (tmpObject != null)
{
if (typeof(T) == typeof(char) && tmpObject is string s)
{
GCHandle handle = GCHandle.Alloc(tmpObject, GCHandleType.Pinned);
ref char stringData = ref Unsafe.Add(ref s.GetRawStringData(), _index);
return new MemoryHandle(Unsafe.AsPointer(ref stringData), handle);
}
#if FEATURE_UTF8STRING
else if ((typeof(T) == typeof(byte) || typeof(T) == typeof(Char8)) && tmpObject is Utf8String utf8String)
{
GCHandle handle = GCHandle.Alloc(tmpObject, GCHandleType.Pinned);
ref byte stringData = ref utf8String.DangerousGetMutableReference(_index);
return new MemoryHandle(Unsafe.AsPointer(ref stringData), handle);
}
#endif // FEATURE_UTF8STRING
else if (RuntimeHelpers.ObjectHasComponentSize(tmpObject))
{
// 'tmpObject is T[]' below also handles things like int[] <-> uint[] being convertible
Debug.Assert(tmpObject is T[]);
// Array is already pre-pinned
if (_index < 0)
{
void* pointer = Unsafe.Add<T>(Unsafe.AsPointer(ref MemoryMarshal.GetArrayDataReference(Unsafe.As<T[]>(tmpObject))), _index & ReadOnlyMemory<T>.RemoveFlagsBitMask);
return new MemoryHandle(pointer);
}
else
{
GCHandle handle = GCHandle.Alloc(tmpObject, GCHandleType.Pinned);
void* pointer = Unsafe.Add<T>(Unsafe.AsPointer(ref MemoryMarshal.GetArrayDataReference(Unsafe.As<T[]>(tmpObject))), _index);
return new MemoryHandle(pointer, handle);
}
}
else
{
Debug.Assert(tmpObject is MemoryManager<T>);
return Unsafe.As<MemoryManager<T>>(tmpObject).Pin(_index);
}
}
return default;
}
/// <summary>
/// Copies the contents from the memory into a new array. This heap
/// allocates, so should generally be avoided, however it is sometimes
/// necessary to bridge the gap with APIs written in terms of arrays.
/// </summary>
public T[] ToArray() => Span.ToArray();
/// <summary>
/// Determines whether the specified object is equal to the current object.
/// Returns true if the object is Memory or ReadOnlyMemory and if both objects point to the same array and have the same length.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object? obj)
{
if (obj is ReadOnlyMemory<T>)
{
return ((ReadOnlyMemory<T>)obj).Equals(this);
}
else if (obj is Memory<T> memory)
{
return Equals(memory);
}
else
{
return false;
}
}
/// <summary>
/// Returns true if the memory points to the same array and has the same length. Note that
/// this does *not* check to see if the *contents* are equal.
/// </summary>
public bool Equals(Memory<T> other)
{
return
_object == other._object &&
_index == other._index &&
_length == other._length;
}
/// <summary>
/// Serves as the default hash function.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode()
{
// We use RuntimeHelpers.GetHashCode instead of Object.GetHashCode because the hash
// code is based on object identity and referential equality, not deep equality (as common with string).
return (_object != null) ? HashCode.Combine(RuntimeHelpers.GetHashCode(_object), _index, _length) : 0;
}
}
}
| 48.429119 | 187 | 0.581725 | [
"MIT"
] | AzureMentor/runtime | src/libraries/System.Private.CoreLib/src/System/Memory.cs | 25,280 | C# |
using System.Threading.Tasks;
using Kledex.Domain;
using Kledex.Queries;
using Kledex.UI.Models;
namespace Kledex.UI.Queries.Handlers
{
public class GetAggregateModelHandler : IQueryHandlerAsync<GetAggregateModel, AggregateModel>
{
private readonly IDomainStore _domainStore;
public GetAggregateModelHandler(IDomainStore domainStore)
{
_domainStore = domainStore;
}
public async Task<AggregateModel> HandleAsync(GetAggregateModel query)
{
var events = await _domainStore.GetEventsAsync(query.AggregateRootId);
var aggregate = new AggregateModel(events);
return aggregate;
}
}
}
| 27.92 | 97 | 0.690544 | [
"Apache-2.0"
] | lampo1024/Kledex | src/Kledex.UI/Queries/Handlers/GetAggregateModelHandler.cs | 700 | C# |
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Reflection;
namespace sly.i18n
{
public enum Message
{
UnexpectedTokenExpecting,
UnexpectedEosExpecting,
UnexpectedToken,
UnexpectedEos,
UnexpectedChar,
CannotMixGenericAndRegex,
DuplicateStringCharDelimiters,
TooManyComment,
TooManyMultilineComment,
TooManySingleLineComment,
CannotMixCommentAndSingleOrMulti,
SameValueUsedManyTime,
StringDelimiterMustBe1Char,
StringDelimiterCannotBeLetterOrDigit,
StringEscapeCharMustBe1Char,
StringEscapeCharCannotBeLetterOrDigit,
CharDelimiterMustBe1Char,
CharDelimiterCannotBeLetter,
CharEscapeCharMustBe1Char,
CharEscapeCharCannotBeLetterOrDigit,
SugarTokenCannotStartWithLetter,
MissingOperand,
ReferenceNotFound,
MixedChoices,
NonTerminalChoiceCannotBeDiscarded,
IncorrectVisitorReturnType,
IncorrectVisitorParameterType,
IncorrectVisitorParameterNumber,
LeftRecursion,
NonTerminalNeverUsed
}
public class I18N
{
public static IDictionary<string, IDictionary<Message, string>> Translations;
private static I18N _instance;
public static I18N Instance
{
get
{
if (_instance == null)
{
_instance = new I18N();
}
return _instance;
}
}
protected I18N()
{
Translations = new Dictionary<string, IDictionary<Message, string>>();
}
public string GetText(Message key, params string[] args)
{
var lang = CultureInfo.CurrentCulture.TwoLetterISOLanguageName;
return GetText(lang,key,args);
}
public string GetText(string lang, Message key, params string[] args)
{
lang = lang ?? CultureInfo.CurrentCulture.TwoLetterISOLanguageName;
IDictionary<Message, string> translation = new Dictionary<Message, string>();
if (!Translations.TryGetValue(lang, out translation))
{
translation = Load(lang);
}
string pattern = null;
if (translation.TryGetValue(key, out pattern))
{
return string.Format(pattern, args);
}
return "";
}
private IDictionary<Message,string> Load(string lang)
{
var translation = new Dictionary<Message, string>();
Assembly assembly = GetType().Assembly;
var res = assembly.GetManifestResourceNames();
using (var stream = assembly.GetManifestResourceStream($"sly.i18n.translations.{lang}.txt"))
{
if (stream != null)
{
using (StreamReader reader = new StreamReader(stream))
{
string line = reader.ReadLine();
while (line != null)
{
if (!line.StartsWith("#"))
{
var items = line.Split(new[] {'='});
if (items.Length == 2)
{
var key = EnumConverter.ConvertStringToEnum<Message>(items[0]);
translation[key] = items[1];
}
}
line = reader.ReadLine();
}
}
}
else
{
return Load("en");
}
}
Translations[lang] = translation;
return translation;
}
}
} | 29.635036 | 104 | 0.505911 | [
"MIT"
] | Qiu233/csly | sly/i18n/I18N.cs | 4,060 | C# |
// Copyright © 2017 onwards, Andrew Whewell
// All rights reserved.
//
// Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
// * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
// * Neither the name of the author nor the names of the program's contributors may be used to endorse or promote products derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OF THE SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using InterfaceFactory;
namespace VirtualRadar.Interface
{
/// <summary>
/// The interface for objects that handle signals.
/// </summary>
[Singleton]
public interface IShutdownSignalHandler
{
/// <summary>
/// Ensures that the main view's CloseView method is called when a shutdown signal is raised by the OS.
/// </summary>
/// <remarks>
/// Under Mono this adds a signal handler for SIGINT that calls CloseView when raised. Under .NET it
/// hooks the console's Ctrl+C event to achieve the same result.
/// </remarks>
void CloseMainViewOnShutdownSignal();
/// <summary>
/// Shuts down any background threads that might be running, unhooks events etc.
/// </summary>
void Cleanup();
}
}
| 60.119048 | 750 | 0.729109 | [
"BSD-3-Clause"
] | AlexAX135/vrs | VirtualRadar.Interface/IShutdownSignalHandler.cs | 2,528 | C# |
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
namespace SampleApp.Controls
{
public sealed partial class ProgressOverlayControl : UserControl
{
public ProgressOverlayControl()
{
this.InitializeComponent();
DataContext = this;
}
private string _text = "Working";
public string Text
{
get { return _text; }
set { _text = value; }
}
public void Show(string text = null)
{
if (text != null)
Text = text;
ProgBar.IsIndeterminate = true;
Visibility = Visibility.Visible;
}
public void Hide()
{
ProgBar.IsIndeterminate = false;
Visibility = Visibility.Collapsed;
}
}
}
| 16 | 65 | 0.671875 | [
"Apache-2.0"
] | BAStevens/Lego-Ev3 | SampleApps/SampleApp (WinRT)/Controls/ProgressOverlayControl.xaml.cs | 642 | C# |
// -----------------------------------------------------------------------------------------
// <copyright file="AccountSasTests.cs" company="Microsoft">
// Copyright 2013 Microsoft Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
// -----------------------------------------------------------------------------------------
namespace Microsoft.WindowsAzure.Storage
{
using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Auth;
using Microsoft.WindowsAzure.Storage.Blob;
using Microsoft.WindowsAzure.Storage.File;
using Microsoft.WindowsAzure.Storage.Queue;
using Microsoft.WindowsAzure.Storage.Queue.Protocol;
using Microsoft.WindowsAzure.Storage.Shared.Protocol;
using Microsoft.WindowsAzure.Storage.Core;
using Microsoft.WindowsAzure.Storage.Shared;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;
using Windows.Networking;
using System.Net.Http;
using Windows.Storage.Streams;
using Windows.Networking.Connectivity;
[TestClass]
public class AccountSASTests : TestBase
{
[TestMethod]
[Description("Test account SAS all permissions, all services")]
[TestCategory(ComponentCategory.Core)]
[TestCategory(TestTypeCategory.UnitTest)]
[TestCategory(SmokeTestCategory.NonSmoke)]
[TestCategory(TenantTypeCategory.DevStore), TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)]
public void AccountSASPermissions()
{
// Single-threaded, takes 10 minutes to run
// Parallelized, 1 minute.
for (int i = 0; i < 0x100; i++)
{
Task[] tasks = new Task[3]; //each permission (0x100) times four services.
SharedAccessAccountPermissions permissions = (SharedAccessAccountPermissions)i;
SharedAccessAccountPolicy policy = GetPolicyWithFullPermissions();
policy.Permissions = permissions;
tasks[0] = this.RunPermissionsTestBlobs(policy);
tasks[2] = this.RunPermissionsTestQueues(policy);
tasks[3] = this.RunPermissionsTestFiles(policy);
Task.WaitAll(tasks);
}
}
[TestMethod]
[Description("Test account SAS various combinations of resource types")]
[TestCategory(ComponentCategory.Core)]
[TestCategory(TestTypeCategory.UnitTest)]
[TestCategory(SmokeTestCategory.NonSmoke)]
[TestCategory(TenantTypeCategory.DevStore), TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)]
public void AccountSASResourceTypes()
{
Task[] tasks = new Task[8*3];
for (int i = 0; i < 0x8; i++)
{
SharedAccessAccountResourceTypes resourceTypes = (SharedAccessAccountResourceTypes)i;
SharedAccessAccountPolicy policy = GetPolicyWithFullPermissions();
policy.ResourceTypes = resourceTypes;
tasks[i] = this.RunPermissionsTestBlobs(policy);
tasks[16 + i] = this.RunPermissionsTestQueues(policy);
tasks[24 + i] = this.RunPermissionsTestFiles(policy);
}
Task.WaitAll(tasks);
}
[TestMethod]
[Description("Test account SAS various combinations of services")]
[TestCategory(ComponentCategory.Core)]
[TestCategory(TestTypeCategory.UnitTest)]
[TestCategory(SmokeTestCategory.NonSmoke)]
[TestCategory(TenantTypeCategory.DevStore), TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)]
public async Task AccountSASServices()
{
for (int i = 1; i < 0x10; i++)
{
OperationContext opContext = new OperationContext();
SharedAccessAccountPolicy policy = this.GetPolicyWithFullPermissions();
policy.Services = (SharedAccessAccountServices)i;
bool expectBlobException = !((policy.Services & SharedAccessAccountServices.Blob) == SharedAccessAccountServices.Blob);
bool expectQueueException = !((policy.Services & SharedAccessAccountServices.Queue) == SharedAccessAccountServices.Queue);
bool expectTableException = !((policy.Services & SharedAccessAccountServices.Table) == SharedAccessAccountServices.Table);
bool expectFileException = !((policy.Services & SharedAccessAccountServices.File) == SharedAccessAccountServices.File);
if (expectBlobException)
{
await TestHelper.ExpectedExceptionAsync((async () => await RunBlobTest(policy, null, opContext)), opContext, "Operation should have failed without Blob access.", HttpStatusCode.Forbidden, "AuthorizationServiceMismatch");
}
else
{
await RunBlobTest(policy, null);
}
if (expectQueueException)
{
await TestHelper.ExpectedExceptionAsync((async () => await RunQueueTest(policy, null, opContext)), opContext, "Operation should have failed without Queue access.", HttpStatusCode.Forbidden, "AuthorizationServiceMismatch");
}
else
{
await RunQueueTest(policy, null);
}
if (expectFileException)
{
await TestHelper.ExpectedExceptionAsync((async () => await RunFileTest(policy, null, opContext)), opContext, "Operation should have failed without File access.", HttpStatusCode.Forbidden, "AuthorizationServiceMismatch");
}
else
{
await RunFileTest(policy, null);
}
}
}
[TestMethod]
[Description("Test account SAS various combinations of start and expiry times")]
[TestCategory(ComponentCategory.Core)]
[TestCategory(TestTypeCategory.UnitTest)]
[TestCategory(SmokeTestCategory.NonSmoke)]
[TestCategory(TenantTypeCategory.DevStore), TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)]
public async Task AccountSASStartExpiryTimes()
{
int?[] startOffsets = new int?[] { null, -5, 5 };
int[] endOffsets = new int[] { -5, 5 };
foreach (int? startOffset in startOffsets)
{
foreach (int endOffset in endOffsets)
{
OperationContext opContext = new OperationContext();
SharedAccessAccountPolicy policy = this.GetPolicyWithFullPermissions();
if (startOffset.HasValue)
{
policy.SharedAccessStartTime = DateTime.Now + TimeSpan.FromMinutes(startOffset.Value);
}
else
{
policy.SharedAccessStartTime = null;
}
policy.SharedAccessExpiryTime = DateTime.Now + TimeSpan.FromMinutes(endOffset);
bool expectException;
if (!policy.SharedAccessStartTime.HasValue)
{
expectException = (policy.SharedAccessExpiryTime < DateTime.Now);
}
else
{
expectException = ((policy.SharedAccessStartTime.Value > DateTime.Now) || (policy.SharedAccessExpiryTime < DateTime.Now));
}
if (expectException)
{
await TestHelper.ExpectedExceptionAsync((async () => await RunBlobTest(policy, null, opContext)), opContext, "Operation should have failed with invalid start/expiry times.", HttpStatusCode.Forbidden, "AuthenticationFailed");
await TestHelper.ExpectedExceptionAsync((async () => await RunQueueTest(policy, null, opContext)), opContext, "Operation should have failed with invalid start/expiry times.", HttpStatusCode.Forbidden, "AuthenticationFailed");
await TestHelper.ExpectedExceptionAsync((async () => await RunFileTest(policy, null, opContext)), opContext, "Operation should have failed with invalid start/expiry times.", HttpStatusCode.Forbidden, "AuthenticationFailed");
}
else
{
await RunBlobTest(policy, null);
await RunQueueTest(policy, null);
await RunFileTest(policy, null);
}
}
}
}
[TestMethod]
[Description("Test account SAS various combinations of signedIPs")]
[TestCategory(ComponentCategory.Core)]
[TestCategory(TestTypeCategory.UnitTest)]
[TestCategory(SmokeTestCategory.NonSmoke)]
[TestCategory(TenantTypeCategory.DevStore), TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)]
public async Task AccountSASSignedIPs()
{
OperationContext opContext = new OperationContext();
HostName invalidIP = new HostName("255.255.255.255");
SharedAccessAccountPolicy policy = GetPolicyWithFullPermissions();
policy.IPAddressOrRange = new IPAddressOrRange(invalidIP.ToString());
await TestHelper.ExpectedExceptionAsync((async () => await RunBlobTest(policy, null, opContext)), opContext, "Operation should have failed with invalid IP access.", HttpStatusCode.Forbidden, "AuthorizationFailure");
await TestHelper.ExpectedExceptionAsync((async () => await RunQueueTest(policy, null, opContext)), opContext, "Operation should have failed with invalid IP access.", HttpStatusCode.Forbidden, "AuthorizationFailure");
await TestHelper.ExpectedExceptionAsync((async () => await RunFileTest(policy, null, opContext)), opContext, "Operation should have failed with invalid IP access.", HttpStatusCode.Forbidden, "AuthorizationFailure");
policy.IPAddressOrRange = null;
await RunBlobTest(policy, null);
await RunQueueTest(policy, null);
await RunFileTest(policy, null);
policy.IPAddressOrRange = new IPAddressOrRange(new HostName("255.255.255.0").ToString(), invalidIP.ToString());
await TestHelper.ExpectedExceptionAsync((async () => await RunBlobTest(policy, null, opContext)), opContext, "Operation should have failed with invalid IP access.", HttpStatusCode.Forbidden, "AuthorizationFailure");
await TestHelper.ExpectedExceptionAsync((async () => await RunQueueTest(policy, null, opContext)), opContext, "Operation should have failed with invalid IP access.", HttpStatusCode.Forbidden, "AuthorizationFailure");
await TestHelper.ExpectedExceptionAsync((async () => await RunFileTest(policy, null, opContext)), opContext, "Operation should have failed with invalid IP access.", HttpStatusCode.Forbidden, "AuthorizationFailure");
}
[TestMethod]
[Description("Test account SAS various combinations of signed protocols")]
[TestCategory(ComponentCategory.Core)]
[TestCategory(TestTypeCategory.UnitTest)]
[TestCategory(SmokeTestCategory.NonSmoke)]
[TestCategory(TenantTypeCategory.DevStore), TestCategory(TenantTypeCategory.DevFabric), TestCategory(TenantTypeCategory.Cloud)]
public async Task AccountSASSignedProtocols()
{
int blobHttpsPort = 443;
int tableHttpsPort = 443;
int queueHttpsPort = 443;
int fileHttpsPort = 443;
if (!string.IsNullOrEmpty(TestBase.TargetTenantConfig.BlobSecurePortOverride))
{
blobHttpsPort = Int32.Parse(TestBase.TargetTenantConfig.BlobSecurePortOverride);
}
if (!string.IsNullOrEmpty(TestBase.TargetTenantConfig.TableSecurePortOverride))
{
tableHttpsPort = Int32.Parse(TestBase.TargetTenantConfig.TableSecurePortOverride);
}
if (!string.IsNullOrEmpty(TestBase.TargetTenantConfig.QueueSecurePortOverride))
{
queueHttpsPort = Int32.Parse(TestBase.TargetTenantConfig.QueueSecurePortOverride);
}
if (!string.IsNullOrEmpty(TestBase.TargetTenantConfig.FileSecurePortOverride))
{
fileHttpsPort = Int32.Parse(TestBase.TargetTenantConfig.FileSecurePortOverride);
}
OperationContext opContext = new OperationContext();
for (int i = 0; i < 3; i++)
{
SharedAccessAccountPolicy policy = this.GetPolicyWithFullPermissions();
policy.Protocols = i == 0 ? (SharedAccessProtocol?)null : (SharedAccessProtocol)i;
bool expectException = !(!policy.Protocols.HasValue || (policy.Protocols == SharedAccessProtocol.HttpsOrHttp));
if (expectException)
{
await TestHelper.ExpectedExceptionAsync((async () => await RunBlobTest(policy, null, opContext)), opContext, "Operation should have failed without using Https.", HttpStatusCode.Unused, null);
await TestHelper.ExpectedExceptionAsync((async () => await RunQueueTest(policy, null, opContext)), opContext, "Operation should have failed without using Https.", HttpStatusCode.Unused, null);
await TestHelper.ExpectedExceptionAsync((async () => await RunFileTest(policy, null, opContext)), opContext, "Operation should have failed without using Https.", HttpStatusCode.Unused, null);
}
else
{
await RunBlobTest(policy, null);
await RunQueueTest(policy, null);
await RunFileTest(policy, null);
}
await RunBlobTest(policy, blobHttpsPort);
await RunQueueTest(policy, queueHttpsPort);
await RunFileTest(policy, fileHttpsPort);
}
}
public async Task RunPermissionsTestBlobs(SharedAccessAccountPolicy policy)
{
CloudBlobClient blobClient = GenerateCloudBlobClient();
string containerName = "c" + Guid.NewGuid().ToString("N");
try
{
CloudStorageAccount account = new CloudStorageAccount(blobClient.Credentials, false);
string accountSASToken = account.GetSharedAccessSignature(policy);
StorageCredentials accountSAS = new StorageCredentials(accountSASToken);
CloudStorageAccount accountWithSAS = new CloudStorageAccount(accountSAS, blobClient.StorageUri, null, null, null);
CloudBlobClient blobClientWithSAS = accountWithSAS.CreateCloudBlobClient();
CloudBlobContainer containerWithSAS = blobClientWithSAS.GetContainerReference(containerName);
CloudBlobContainer container = blobClient.GetContainerReference(containerName);
// General pattern - If current perms support doing a thing with SAS, do the thing with SAS and validate with shared
// Otherwise, make sure SAS fails and then do the thing with shared key.
// Things to do:
// Create the container (Create / Write perms, Container RT)
// List containers with prefix (List perms, Service RT)
// Create an append blob (Create / Write perms, Object RT)
// Append a block to append blob (Add / Write perms, Object RT)
// Read the data from the append blob (Read perms, Object RT)
// Delete the blob (Delete perms, Object RT)
if ((((policy.Permissions & SharedAccessAccountPermissions.Create) == SharedAccessAccountPermissions.Create) || ((policy.Permissions & SharedAccessAccountPermissions.Write) == SharedAccessAccountPermissions.Write)) &&
((policy.ResourceTypes & SharedAccessAccountResourceTypes.Container) == SharedAccessAccountResourceTypes.Container))
{
await containerWithSAS.CreateAsync();
}
else
{
await TestHelper.ExpectedExceptionAsync<StorageException>(async () => await containerWithSAS.CreateAsync(), "Create a container should fail with SAS without Create or Write and Container-level permissions.");
await container.CreateAsync();
}
Assert.IsTrue(await container.ExistsAsync());
if (((policy.Permissions & SharedAccessAccountPermissions.List) == SharedAccessAccountPermissions.List) &&
((policy.ResourceTypes & SharedAccessAccountResourceTypes.Service) == SharedAccessAccountResourceTypes.Service))
{
ContainerResultSegment segment = null;
BlobContinuationToken ct =null;
IEnumerable<CloudBlobContainer> results = null;
do
{
segment = await blobClientWithSAS.ListContainersSegmentedAsync(container.Name, ct);
ct = segment.ContinuationToken;
results = segment.Results;
}while(ct != null && !results.Any());
Assert.AreEqual(container.Name, segment.Results.First().Name);
}
else
{
await TestHelper.ExpectedExceptionAsync<StorageException>(async () => { ContainerResultSegment segment = await blobClientWithSAS.ListContainersSegmentedAsync(container.Name, null); segment.Results.First(); }, "List containers should fail with SAS without List and Service-level permissions.");
}
string blobName = "blob";
CloudAppendBlob appendBlob = container.GetAppendBlobReference(blobName);
CloudAppendBlob appendBlobWithSAS = containerWithSAS.GetAppendBlobReference(blobName);
//Try creating credentials using SAS Uri directly
CloudAppendBlob appendBlobWithSASUri = new CloudAppendBlob(new Uri(container.Uri + accountSASToken));
if ((((policy.Permissions & SharedAccessAccountPermissions.Create) == SharedAccessAccountPermissions.Create) || ((policy.Permissions & SharedAccessAccountPermissions.Write) == SharedAccessAccountPermissions.Write)) &&
((policy.ResourceTypes & SharedAccessAccountResourceTypes.Object) == SharedAccessAccountResourceTypes.Object))
{
await appendBlobWithSAS.CreateOrReplaceAsync();
}
else
{
await TestHelper.ExpectedExceptionAsync<StorageException>(async () => await appendBlobWithSAS.CreateOrReplaceAsync(), "Creating an append blob should fail with SAS without Create or Write and Object-level perms.");
await appendBlob.CreateOrReplaceAsync();
}
Assert.IsTrue(await appendBlob.ExistsAsync());
string blobText = "blobText";
if ((((policy.Permissions & SharedAccessAccountPermissions.Add) == SharedAccessAccountPermissions.Add) || ((policy.Permissions & SharedAccessAccountPermissions.Write) == SharedAccessAccountPermissions.Write)) &&
((policy.ResourceTypes & SharedAccessAccountResourceTypes.Object) == SharedAccessAccountResourceTypes.Object))
{
using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(blobText)))
{
await appendBlobWithSAS.AppendBlockAsync(stream);
}
}
else
{
using (MemoryStream memStream = new MemoryStream(Encoding.UTF8.GetBytes(blobText)))
{
await TestHelper.ExpectedExceptionAsync<StorageException>(async () => await appendBlobWithSAS.AppendBlockAsync(memStream), "Append a block to an append blob should fail with SAS without Add or Write and Object-level perms.");
memStream.Seek(0, SeekOrigin.Begin);
await appendBlob.AppendBlockAsync(memStream);
}
}
Assert.AreEqual(blobText, await appendBlob.DownloadTextAsync());
if (((policy.Permissions & SharedAccessAccountPermissions.Read) == SharedAccessAccountPermissions.Read) &&
((policy.ResourceTypes & SharedAccessAccountResourceTypes.Object) == SharedAccessAccountResourceTypes.Object))
{
Assert.AreEqual(blobText, await appendBlobWithSAS.DownloadTextAsync());
}
else
{
await TestHelper.ExpectedExceptionAsync<StorageException>(async () => await appendBlobWithSAS.DownloadTextAsync(), "Reading a blob's contents with SAS without Read and Object-level permissions should fail.");
}
if (((policy.Permissions & SharedAccessAccountPermissions.Delete) == SharedAccessAccountPermissions.Delete) &&
((policy.ResourceTypes & SharedAccessAccountResourceTypes.Object) == SharedAccessAccountResourceTypes.Object))
{
await appendBlobWithSAS.DeleteAsync();
}
else
{
await TestHelper.ExpectedExceptionAsync<StorageException>(async () => await appendBlobWithSAS.DeleteAsync(), "Deleting a blob with SAS without Delete and Object-level perms should fail.");
await appendBlob.DeleteAsync();
}
Assert.IsFalse(await appendBlob.ExistsAsync());
}
finally
{
blobClient.GetContainerReference(containerName).DeleteIfExistsAsync().Wait();
}
}
public async Task RunPermissionsTestQueues(SharedAccessAccountPolicy policy)
{
CloudQueueClient queueClient = GenerateCloudQueueClient();
string queueName = "q" + Guid.NewGuid().ToString("N");
try
{
CloudStorageAccount account = new CloudStorageAccount(queueClient.Credentials, false);
string accountSASToken = account.GetSharedAccessSignature(policy);
StorageCredentials accountSAS = new StorageCredentials(accountSASToken);
CloudStorageAccount accountWithSAS = new CloudStorageAccount(accountSAS, null, queueClient.StorageUri, null, null);
CloudQueueClient queueClientWithSAS = accountWithSAS.CreateCloudQueueClient();
CloudQueue queueWithSAS = queueClientWithSAS.GetQueueReference(queueName);
CloudQueue queue = queueClient.GetQueueReference(queueName);
// General pattern - If current perms support doing a thing with SAS, do the thing with SAS and validate with shared
// Otherwise, make sure SAS fails and then do the thing with shared key.
// Things to do:
// Create the queue (Create or Write perms, Container RT)
// List queues (List perms, Service RT)
// Set queue metadata (Write perms, Container RT)
// Insert a message (Add perms, Object RT)
// Peek a message (Read perms, Object RT)
// Get a message (Process perms, Object RT)
// Update a message (Update perms, Object RT)
// Clear all messages (Delete perms, Object RT)
if ((((policy.Permissions & SharedAccessAccountPermissions.Create) == SharedAccessAccountPermissions.Create) || ((policy.Permissions & SharedAccessAccountPermissions.Write) == SharedAccessAccountPermissions.Write)) &&
((policy.ResourceTypes & SharedAccessAccountResourceTypes.Container) == SharedAccessAccountResourceTypes.Container))
{
await queueWithSAS.CreateAsync();
}
else
{
await TestHelper.ExpectedExceptionAsync<StorageException>(async () => await queueWithSAS.CreateAsync(), "Creating a queue with SAS should fail without Add and Container-level permissions.");
await queue.CreateAsync();
}
Assert.IsTrue(await queue.ExistsAsync());
if (((policy.Permissions & SharedAccessAccountPermissions.List) == SharedAccessAccountPermissions.List) &&
((policy.ResourceTypes & SharedAccessAccountResourceTypes.Service) == SharedAccessAccountResourceTypes.Service))
{
Assert.AreEqual(queueName, (await queueClientWithSAS.ListQueuesSegmentedAsync(queueName, null)).Results.First().Name);
}
else
{
await TestHelper.ExpectedExceptionAsync<StorageException>(async () => (await queueClientWithSAS.ListQueuesSegmentedAsync(queueName, null)).Results.First(), "Listing queues with SAS should fail without Read and Service-level permissions.");
}
queueWithSAS.Metadata["metadatakey"] = "metadatavalue";
if (((policy.Permissions & SharedAccessAccountPermissions.Write) == SharedAccessAccountPermissions.Write) &&
((policy.ResourceTypes & SharedAccessAccountResourceTypes.Container) == SharedAccessAccountResourceTypes.Container))
{
await queueWithSAS.SetMetadataAsync();
await queue.FetchAttributesAsync();
Assert.AreEqual("metadatavalue", queue.Metadata["metadatakey"]);
}
else
{
await TestHelper.ExpectedExceptionAsync<StorageException>(async () => await queueWithSAS.SetMetadataAsync(), "Setting a queue's metadata with SAS should fail without Write and Container-level permissions.");
}
string messageText = "messageText";
CloudQueueMessage message = new CloudQueueMessage(messageText);
if (((policy.Permissions & SharedAccessAccountPermissions.Add) == SharedAccessAccountPermissions.Add) &&
((policy.ResourceTypes & SharedAccessAccountResourceTypes.Object) == SharedAccessAccountResourceTypes.Object))
{
await queueWithSAS.AddMessageAsync(message);
}
else
{
await TestHelper.ExpectedExceptionAsync<StorageException>(async () => await queueWithSAS.AddMessageAsync(message), "Adding a queue message should fail with SAS without Add and Object-level permissions.");
await queue.AddMessageAsync(message);
}
Assert.AreEqual(messageText, ((await queue.PeekMessageAsync()).AsString));
if (((policy.Permissions & SharedAccessAccountPermissions.Read) == SharedAccessAccountPermissions.Read) &&
((policy.ResourceTypes & SharedAccessAccountResourceTypes.Object) == SharedAccessAccountResourceTypes.Object))
{
Assert.AreEqual(messageText, (await queueWithSAS.PeekMessageAsync()).AsString);
}
else
{
await TestHelper.ExpectedExceptionAsync<StorageException>(async () => await queueWithSAS.PeekMessageAsync(), "Peeking a queue message should fail with SAS without Read and Object-level permissions.");
}
CloudQueueMessage messageResult = null;
if (((policy.Permissions & SharedAccessAccountPermissions.ProcessMessages) == SharedAccessAccountPermissions.ProcessMessages) &&
((policy.ResourceTypes & SharedAccessAccountResourceTypes.Object) == SharedAccessAccountResourceTypes.Object))
{
messageResult = await queueWithSAS.GetMessageAsync();
}
else
{
await TestHelper.ExpectedExceptionAsync<StorageException>(async () => await queueWithSAS.GetMessageAsync(), "Getting a message should fail with SAS without Process and Object-level permissions.");
messageResult = await queue.GetMessageAsync();
}
Assert.AreEqual(messageText, messageResult.AsString);
string newMessageContent = "new content";
messageResult.SetMessageContent(newMessageContent);
if (((policy.Permissions & SharedAccessAccountPermissions.Update) == SharedAccessAccountPermissions.Update) &&
((policy.ResourceTypes & SharedAccessAccountResourceTypes.Object) == SharedAccessAccountResourceTypes.Object))
{
await queueWithSAS.UpdateMessageAsync(messageResult, TimeSpan.Zero, MessageUpdateFields.Content | MessageUpdateFields.Visibility);
}
else
{
await TestHelper.ExpectedExceptionAsync<StorageException>(async () => await queueWithSAS.UpdateMessageAsync(messageResult, TimeSpan.Zero, MessageUpdateFields.Content | MessageUpdateFields.Visibility), "Updating a message should fail with SAS without Update and Object-level permissions.");
await queue.UpdateMessageAsync(messageResult, TimeSpan.Zero, MessageUpdateFields.Content | MessageUpdateFields.Visibility);
}
messageResult = await queue.PeekMessageAsync();
Assert.AreEqual(newMessageContent, messageResult.AsString);
if (((policy.Permissions & SharedAccessAccountPermissions.Delete) == SharedAccessAccountPermissions.Delete) &&
((policy.ResourceTypes & SharedAccessAccountResourceTypes.Object) == SharedAccessAccountResourceTypes.Object))
{
await queueWithSAS.ClearAsync();
}
else
{
await TestHelper.ExpectedExceptionAsync<StorageException>(async () => await queueWithSAS.ClearAsync(), "Clearing messages should fail with SAS without delete and Object-level permissions.");
}
}
finally
{
queueClient.GetQueueReference(queueName).DeleteIfExistsAsync().Wait();
}
}
public async Task RunPermissionsTestFiles(SharedAccessAccountPolicy policy)
{
CloudFileClient fileClient = GenerateCloudFileClient();
string shareName = "s" + Guid.NewGuid().ToString("N");
try
{
CloudStorageAccount account = new CloudStorageAccount(fileClient.Credentials, false);
string accountSASToken = account.GetSharedAccessSignature(policy);
StorageCredentials accountSAS = new StorageCredentials(accountSASToken);
CloudStorageAccount accountWithSAS = new CloudStorageAccount(accountSAS, null, null, null, fileClient.StorageUri);
CloudFileClient fileClientWithSAS = accountWithSAS.CreateCloudFileClient();
CloudFileShare shareWithSAS = fileClientWithSAS.GetShareReference(shareName);
CloudFileShare share = fileClient.GetShareReference(shareName);
// General pattern - If current perms support doing a thing with SAS, do the thing with SAS and validate with shared
// Otherwise, make sure SAS fails and then do the thing with shared key.
// Things to do:
// Create the share (Create / Write perms, Container RT)
// List shares with prefix (List perms, Service RT)
// Create a new file (Create / Write, Object RT)
// Add a range to the file (Write, Object RT)
// Read the data from the file (Read, Object RT)
// Overwrite a file (Write, Object RT)
// Delete the file (Delete perms, Object RT)
if ((((policy.Permissions & SharedAccessAccountPermissions.Create) == SharedAccessAccountPermissions.Create) || ((policy.Permissions & SharedAccessAccountPermissions.Write) == SharedAccessAccountPermissions.Write)) &&
((policy.ResourceTypes & SharedAccessAccountResourceTypes.Container) == SharedAccessAccountResourceTypes.Container))
{
await shareWithSAS.CreateAsync();
}
else
{
await TestHelper.ExpectedExceptionAsync<StorageException>(async () => await shareWithSAS.CreateAsync(), "Creating a share with SAS should fail without Create or Write and Container-level perms.");
await share.CreateAsync();
}
Assert.IsTrue(await share.ExistsAsync());
if (((policy.Permissions & SharedAccessAccountPermissions.List) == SharedAccessAccountPermissions.List) &&
((policy.ResourceTypes & SharedAccessAccountResourceTypes.Service) == SharedAccessAccountResourceTypes.Service))
{
Assert.AreEqual(shareName, (await fileClientWithSAS.ListSharesSegmentedAsync(shareName, null)).Results.First().Name);
}
else
{
await TestHelper.ExpectedExceptionAsync<StorageException>(async () => (await fileClientWithSAS.ListSharesSegmentedAsync(shareName, null)).Results.First(), "Listing shared with SAS should fail without List and Service-level perms.");
}
string filename = "fileName";
CloudFile fileWithSAS = shareWithSAS.GetRootDirectoryReference().GetFileReference(filename);
CloudFile file = share.GetRootDirectoryReference().GetFileReference(filename);
//Try creating credentials using SAS Uri directly
CloudFile fileWithSASUri = new CloudFile(new Uri(share.Uri + accountSASToken));
byte[] content = new byte[] { 0x1, 0x2, 0x3, 0x4 };
if ((((policy.Permissions & SharedAccessAccountPermissions.Create) == SharedAccessAccountPermissions.Create) || ((policy.Permissions & SharedAccessAccountPermissions.Write) == SharedAccessAccountPermissions.Write)) &&
((policy.ResourceTypes & SharedAccessAccountResourceTypes.Object) == SharedAccessAccountResourceTypes.Object))
{
await fileWithSAS.CreateAsync(content.Length);
}
else
{
await TestHelper.ExpectedExceptionAsync<StorageException>(async () => await fileWithSAS.CreateAsync(content.Length), "Creating a file with SAS should fail without Create or Write and Object-level perms.");
await file.CreateAsync(content.Length);
}
Assert.IsTrue(await file.ExistsAsync());
using (MemoryStream stream = new MemoryStream(content))
{
if (((policy.Permissions & SharedAccessAccountPermissions.Write) == SharedAccessAccountPermissions.Write) &&
((policy.ResourceTypes & SharedAccessAccountResourceTypes.Object) == SharedAccessAccountResourceTypes.Object))
{
await fileWithSAS.WriteRangeAsync(stream, 0, null);
}
else
{
await TestHelper.ExpectedExceptionAsync<StorageException>(async () => await fileWithSAS.WriteRangeAsync(stream, 0, null), "Writing a range to a file with SAS should fail without Write and Object-level perms.");
stream.Seek(0, SeekOrigin.Begin);
await file.WriteRangeAsync(stream, 0, null);
}
}
byte[] result = new byte[content.Length];
await file.DownloadRangeToByteArrayAsync(result, 0, 0, content.Length);
for (int i = 0; i < content.Length; i++)
{
Assert.AreEqual(content[i], result[i]);
}
if (((policy.Permissions & SharedAccessAccountPermissions.Read) == SharedAccessAccountPermissions.Read) &&
((policy.ResourceTypes & SharedAccessAccountResourceTypes.Object) == SharedAccessAccountResourceTypes.Object))
{
result = new byte[content.Length];
await fileWithSAS.DownloadRangeToByteArrayAsync(result, 0, 0, content.Length);
for (int i = 0; i < content.Length; i++)
{
Assert.AreEqual(content[i], result[i]);
}
}
else
{
await TestHelper.ExpectedExceptionAsync<StorageException>(async () => await fileWithSAS.DownloadRangeToByteArrayAsync(result, 0, 0, content.Length), "Reading a file with SAS should fail without Read and Object-level perms.");
}
if (((policy.Permissions & SharedAccessAccountPermissions.Write) == SharedAccessAccountPermissions.Write) &&
((policy.ResourceTypes & SharedAccessAccountResourceTypes.Object) == SharedAccessAccountResourceTypes.Object))
{
await fileWithSAS.CreateAsync(2);
}
else
{
await TestHelper.ExpectedExceptionAsync<StorageException>(async () => await fileWithSAS.CreateAsync(2), "Overwriting a file with SAS should fail without Write and Object-level perms.");
await file.CreateAsync(2);
}
result = new byte[content.Length];
await file.DownloadRangeToByteArrayAsync(result, 0, 0, content.Length);
for (int i = 0; i < content.Length; i++)
{
Assert.AreEqual(0, result[i]);
}
if (((policy.Permissions & SharedAccessAccountPermissions.Delete) == SharedAccessAccountPermissions.Delete) &&
((policy.ResourceTypes & SharedAccessAccountResourceTypes.Object) == SharedAccessAccountResourceTypes.Object))
{
await fileWithSAS.DeleteAsync();
}
else
{
await TestHelper.ExpectedExceptionAsync<StorageException>(async () => await fileWithSAS.DeleteAsync(), "Deleting a file with SAS should fail without Delete and Object-level perms.");
await file.DeleteAsync();
}
Assert.IsFalse(await file.ExistsAsync());
}
finally
{
fileClient.GetShareReference(shareName).DeleteIfExistsAsync().Wait();
}
}
public async Task RunBlobTest(SharedAccessAccountPolicy policy, int? httpsPort, OperationContext opContext = null)
{
CloudBlobClient blobClient = GenerateCloudBlobClient();
string containerName = "c" + Guid.NewGuid().ToString("N");
try
{
CloudStorageAccount account = new CloudStorageAccount(blobClient.Credentials, false);
string accountSASToken = account.GetSharedAccessSignature(policy);
StorageCredentials accountSAS = new StorageCredentials(accountSASToken);
StorageUri storageUri = blobClient.StorageUri;
if (httpsPort != null)
{
storageUri = new StorageUri(TransformSchemeAndPort(storageUri.PrimaryUri, "https", httpsPort.Value), TransformSchemeAndPort(storageUri.SecondaryUri, "https", httpsPort.Value));
}
else
{
storageUri = new StorageUri(TransformSchemeAndPort(storageUri.PrimaryUri, "http", 80), TransformSchemeAndPort(storageUri.SecondaryUri, "http", 80));
}
CloudStorageAccount accountWithSAS = new CloudStorageAccount(accountSAS, storageUri, null, null, null);
CloudBlobClient blobClientWithSAS = accountWithSAS.CreateCloudBlobClient();
CloudBlobContainer containerWithSAS = blobClientWithSAS.GetContainerReference(containerName);
CloudBlobContainer container = blobClient.GetContainerReference(containerName);
await container.CreateAsync();
string blobName = "blob";
CloudBlockBlob blob = container.GetBlockBlobReference(blobName);
string blobText = "blobText";
await blob.UploadTextAsync(blobText);
CloudBlockBlob blobWithSAS = containerWithSAS.GetBlockBlobReference(blobName);
Assert.AreEqual(blobText, await blobWithSAS.DownloadTextAsync(null, null, opContext));
}
finally
{
blobClient.GetContainerReference(containerName).DeleteIfExistsAsync().Wait();
}
}
public async Task RunQueueTest(SharedAccessAccountPolicy policy, int? httpsPort, OperationContext opContext = null)
{
CloudQueueClient queueClient = GenerateCloudQueueClient();
string queueName = "q" + Guid.NewGuid().ToString("N");
try
{
CloudStorageAccount account = new CloudStorageAccount(queueClient.Credentials, false);
string accountSASToken = account.GetSharedAccessSignature(policy);
StorageCredentials accountSAS = new StorageCredentials(accountSASToken);
StorageUri storageUri = queueClient.StorageUri;
if (httpsPort != null)
{
storageUri = new StorageUri(TransformSchemeAndPort(storageUri.PrimaryUri, "https", httpsPort.Value), TransformSchemeAndPort(storageUri.SecondaryUri, "https", httpsPort.Value));
}
else
{
storageUri = new StorageUri(TransformSchemeAndPort(storageUri.PrimaryUri, "http", 80), TransformSchemeAndPort(storageUri.SecondaryUri, "http", 80));
}
CloudStorageAccount accountWithSAS = new CloudStorageAccount(accountSAS, null, storageUri, null, null);
CloudQueueClient queueClientWithSAS = accountWithSAS.CreateCloudQueueClient();
CloudQueue queueWithSAS = queueClientWithSAS.GetQueueReference(queueName);
CloudQueue queue = queueClient.GetQueueReference(queueName);
await queue.CreateAsync();
string messageText = "message text";
CloudQueueMessage message = new CloudQueueMessage(messageText);
await queue.AddMessageAsync(message);
Assert.AreEqual(messageText, (await queueWithSAS.GetMessageAsync(null, null, opContext)).AsString);
}
finally
{
queueClient.GetQueueReference(queueName).DeleteIfExistsAsync().Wait();
}
}
public async Task RunFileTest(SharedAccessAccountPolicy policy, int? httpsPort, OperationContext opContext = null)
{
CloudFileClient fileClient = GenerateCloudFileClient();
string shareName = "s" + Guid.NewGuid().ToString("N");
try
{
CloudStorageAccount account = new CloudStorageAccount(fileClient.Credentials, false);
string accountSASToken = account.GetSharedAccessSignature(policy);
StorageCredentials accountSAS = new StorageCredentials(accountSASToken);
StorageUri storageUri = fileClient.StorageUri;
if (httpsPort != null)
{
storageUri = new StorageUri(TransformSchemeAndPort(storageUri.PrimaryUri, "https", httpsPort.Value), TransformSchemeAndPort(storageUri.SecondaryUri, "https", httpsPort.Value));
}
else
{
storageUri = new StorageUri(TransformSchemeAndPort(storageUri.PrimaryUri, "http", 80), TransformSchemeAndPort(storageUri.SecondaryUri, "http", 80));
}
CloudStorageAccount accountWithSAS = new CloudStorageAccount(accountSAS, null, null, null, storageUri);
CloudFileClient fileClientWithSAS = accountWithSAS.CreateCloudFileClient();
CloudFileShare shareWithSAS = fileClientWithSAS.GetShareReference(shareName);
CloudFileShare share = fileClient.GetShareReference(shareName);
await share.CreateAsync();
string fileName = "file";
CloudFile file = share.GetRootDirectoryReference().GetFileReference(fileName);
CloudFile fileWithSAS = shareWithSAS.GetRootDirectoryReference().GetFileReference(fileName);
byte[] content = new byte[] { 0x1, 0x2, 0x3, 0x4 };
await file.CreateAsync(content.Length);
using (MemoryStream stream = new MemoryStream(content))
{
await file.WriteRangeAsync(stream, 0, null);
}
byte[] result = new byte[content.Length];
await fileWithSAS.DownloadRangeToByteArrayAsync(result, 0, 0, content.Length, null, null, opContext);
for (int i = 0; i < content.Length; i++)
{
Assert.AreEqual(content[i], result[i]);
}
}
finally
{
fileClient.GetShareReference(shareName).DeleteIfExistsAsync().Wait();
}
}
private SharedAccessAccountPolicy GetPolicyWithFullPermissions()
{
SharedAccessAccountPolicy policy = new SharedAccessAccountPolicy();
policy.SharedAccessStartTime = DateTime.Now - TimeSpan.FromMinutes(5);
policy.SharedAccessExpiryTime = DateTime.Now + TimeSpan.FromMinutes(30);
policy.Permissions = (SharedAccessAccountPermissions)(0x100 - 0x1);
policy.Services = (SharedAccessAccountServices)(0x10 - 0x1);
policy.ResourceTypes = (SharedAccessAccountResourceTypes)(0x8 - 0x1);
policy.Protocols = SharedAccessProtocol.HttpsOrHttp;
policy.IPAddressOrRange = null;
return policy;
}
private static Uri TransformSchemeAndPort(Uri input, string scheme, int port)
{
UriBuilder builder = new UriBuilder(input);
builder.Scheme = scheme;
builder.Port = port;
return builder.Uri;
}
}
}
| 57.368421 | 313 | 0.618369 | [
"Apache-2.0"
] | Azure/azure-storage-net | Test/WindowsRuntime/AccountSasTests.cs | 47,962 | C# |
using System;
using Elsa.Extensions;
using Elsa.Mapping;
using Elsa.Persistence.YesSql.Indexes;
using Elsa.Persistence.YesSql.Mapping;
using Elsa.Persistence.YesSql.Schema;
using Elsa.Persistence.YesSql.Services;
using Elsa.Persistence.YesSql.StartupTasks;
using Elsa.Runtime;
using Microsoft.Extensions.DependencyInjection;
using YesSql;
using YesSql.Indexes;
namespace Elsa.Persistence.YesSql.Extensions
{
public static class YesSqlServiceCollectionExtensions
{
public static YesSqlElsaBuilder AddYesSqlProvider(
this ElsaBuilder configuration,
Action<IConfiguration> configure)
{
configuration.Services
.AddSingleton(sp => StoreFactory.CreateStore(sp, configure))
.AddSingleton<IIndexProvider, WorkflowDefinitionIndexProvider>()
.AddSingleton<IIndexProvider, WorkflowInstanceIndexProvider>()
.AddTransient<ISchemaVersionStore, SchemaVersionStore>()
.AddScoped(CreateSession)
.AddMapperProfile<NodaTimeProfile>(ServiceLifetime.Singleton)
.AddMapperProfile<DocumentProfile>(ServiceLifetime.Singleton)
.AddStartupTask<InitializeStoreTask>();
return new YesSqlElsaBuilder(configuration.Services);
}
public static YesSqlElsaBuilder AddYesSqlStores(
this ElsaBuilder configuration,
Action<IConfiguration> configure)
{
return configuration.AddYesSqlProvider(configure).AddWorkflowDefinitionStore()
.AddWorkflowInstanceStore();
}
public static YesSqlElsaBuilder AddWorkflowInstanceStore(
this YesSqlElsaBuilder configuration)
{
configuration.Services.AddScoped<IWorkflowInstanceStore, YesSqlWorkflowInstanceStore>();
return configuration;
}
public static YesSqlElsaBuilder AddWorkflowDefinitionStore(
this YesSqlElsaBuilder configuration)
{
configuration.Services
.AddScoped<IWorkflowDefinitionStore, YesSqlWorkflowDefinitionStore>();
return configuration;
}
private static ISession CreateSession(IServiceProvider services)
{
var store = services.GetRequiredService<IStore>();
return store.CreateSession();
}
}
} | 36.707692 | 100 | 0.684409 | [
"BSD-3-Clause"
] | 1000sprites/elsa-core | src/persistence/Elsa.Persistence.YesSql/Extensions/YesSqlServiceCollectionExtensions.cs | 2,386 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Threading.Tasks;
using System.Windows;
using VaccineTracker.Domain;
using VaccineTracker.Services;
using VaccineTracker.ViewModel;
using VaccineTracker.Views;
namespace VaccineTracker
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow
{
private readonly List<TrackerComponentViewModel> _viewModels = new List<TrackerComponentViewModel>();
public MainWindow()
{
InitializeComponent();
LoadSettingsAsync();
}
private void SetBusy(bool isBusy)
{
if (isBusy)
{
BusyIndicator.IsBusy = true;
BusyIndicator.Visibility = Visibility.Visible;
}
else
{
BusyIndicator.IsBusy = false;
BusyIndicator.Visibility = Visibility.Collapsed;
}
}
private async void LoadSettingsAsync()
{
try
{
SetBusy(true);
var persistence = new SettingsPersistService();
var settings = await persistence.LoadSettingsAsync();
if (settings?.TrackerSettings == null)
{
SetBusy(false);
return;
}
foreach (var setting in settings.TrackerSettings)
{
var vm = await AddTracker();
var trackerSettings = vm.TrackerSettings;
trackerSettings.Name = setting.Name;
trackerSettings.SelectedState = setting.State;
trackerSettings.SelectedDistrict = setting.District;
trackerSettings.SelectedAgeGroup = setting.AgeGroup;
trackerSettings.MinimumAvailability = setting.MinimumSlots;
trackerSettings.StartDate = setting.StartDate;
trackerSettings.EndDate = setting.EndDate;
trackerSettings.Email = setting.Email;
trackerSettings.SoundAlarm = setting.SoundAlarm;
vm.StartTracker();
}
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
finally
{
SetBusy(false);
}
}
private async Task SaveSettingsAsync()
{
SetBusy(true);
var persistence = new SettingsPersistService();
var userSettings = new UserSettings
{
TrackerSettings = new List<TrackerSettings>()
};
foreach (var vm in _viewModels)
{
var vmSettings = vm.TrackerSettings;
var setting = new TrackerSettings
{
Name = vmSettings.Name,
State = vmSettings.SelectedState,
District = vmSettings.SelectedDistrict,
AgeGroup = vmSettings.SelectedAgeGroup,
MinimumSlots = vmSettings.MinimumAvailability,
StartDate = vmSettings.StartDate,
EndDate = vmSettings.EndDate,
Email = vmSettings.Email,
SoundAlarm = vmSettings.SoundAlarm
};
userSettings.TrackerSettings.Add(setting);
}
await persistence.SaveSettingsAsync(userSettings);
SetBusy(false);
}
private async void OnAddTrackerClick(object sender, RoutedEventArgs e)
{
await AddTracker();
}
private async Task<TrackerComponentViewModel> AddTracker()
{
try
{
var vm = new TrackerComponentViewModel();
await vm.InitializeAsync();
var view = new TrackerComponent { DataContext = vm };
Panel.Children.Add(view);
vm.TrackerDeleted += async (o, args) =>
{
Panel.Children.Remove(view);
_viewModels.Remove(vm);
await SaveSettingsAsync();
};
vm.TrackerSaved += async (sender, args) =>
{
await SaveSettingsAsync();
};
_viewModels.Add(vm);
return vm;
}
catch (Exception e)
{
MessageBox.Show(e.Message);
return null;
}
}
private void MainWindow_OnClosing(object sender, CancelEventArgs e)
{
var result = MessageBox.Show("Tracking will stop if you close the application. Are you sure?", "Warning", MessageBoxButton.YesNo);
if (result == MessageBoxResult.No)
e.Cancel = true;
}
private void HelpButton_OnClick(object sender, RoutedEventArgs e)
{
const string url = @"https://www.harshmaurya.in/covid-vaccine-tracker-india/";
Process.Start("explorer.exe", url);
}
}
public class UserSettings
{
public List<TrackerSettings> TrackerSettings { get; set; }
}
}
| 33.02454 | 142 | 0.519599 | [
"MIT"
] | harshmaurya/covidvaccinetracker | VaccineTracker/Views/MainWindow.xaml.cs | 5,385 | C# |
namespace Hermit.Service.Log
{
public interface ILog
{
void Log(object obj);
void Warn(object warning);
void Error(object error);
void Assert(bool condition, string message);
}
} | 17.307692 | 52 | 0.608889 | [
"MIT"
] | Cushmily/Herm | Runtime/Service/Log/ILog.cs | 225 | C# |
using System;
using System.Drawing.Printing;
using System.Windows.Forms;
using EasyBrailleEdit.Common;
namespace EasyBrailleEdit.Printing
{
public partial class ConfigTextPrinterPanel : UserControl
{
private string m_PaperSourceName;
private string m_PaperName;
private Margins m_OddPageMargins;
private Margins m_EvenPageMargins;
private string m_TextFontName;
private double m_TextFontSize;
public ConfigTextPrinterPanel()
{
InitializeComponent();
}
public void LoadSettings()
{
var cfg = AppGlobals.Config.Printing;
m_PaperSourceName = cfg.PrintTextPaperSourceName;
m_PaperName = cfg.PrintTextPaperName;
m_TextFontName = cfg.PrintTextFontName;
m_TextFontSize = cfg.PrintTextFontSize;
m_OddPageMargins = new Margins(cfg.PrintTextMarginLeft, cfg.PrintTextMarginRight, cfg.PrintTextMarginTop, cfg.PrintTextMarginBottom);
m_EvenPageMargins = new Margins(cfg.PrintTextMarginLeft2, cfg.PrintTextMarginRight2, cfg.PrintTextMarginTop2, cfg.PrintTextMarginBottom2);
cboPrinters.Items.Clear();
foreach (string s in PrinterSettings.InstalledPrinters)
{
cboPrinters.Items.Add(s);
}
if (!String.IsNullOrEmpty(cfg.DefaultTextPrinter))
{
cboPrinters.SelectedIndex = cboPrinters.Items.IndexOf(cfg.DefaultTextPrinter);
}
}
public void SaveSettings()
{
var cfg = AppGlobals.Config.Printing;
cfg.DefaultTextPrinter = cboPrinters.Text;
cfg.PrintTextPaperSourceName = m_PaperSourceName;
cfg.PrintTextPaperName = m_PaperName;
cfg.PrintTextMarginLeft = m_OddPageMargins.Left;
cfg.PrintTextMarginTop = m_OddPageMargins.Top;
cfg.PrintTextMarginRight = m_OddPageMargins.Right;
cfg.PrintTextMarginBottom = m_OddPageMargins.Bottom;
cfg.PrintTextMarginLeft2 = m_EvenPageMargins.Left;
cfg.PrintTextMarginTop2 = m_EvenPageMargins.Top;
cfg.PrintTextMarginRight2 = m_EvenPageMargins.Right;
cfg.PrintTextMarginBottom2 = m_EvenPageMargins.Bottom;
cfg.PrintTextFontName = m_TextFontName;
cfg.PrintTextFontSize = m_TextFontSize;
}
private void ConfigTextPrinterPanel_Load(object sender, EventArgs e)
{
LoadSettings(); // 載入上次的設定。
}
private void btnPageSetup_Click(object sender, EventArgs e)
{
if (String.IsNullOrWhiteSpace(cboPrinters.Text))
{
MessageBox.Show("請先選擇印表機!");
return;
}
TextPageSetupDialog dlg = new TextPageSetupDialog(cboPrinters.Text)
{
PaperSourceName = m_PaperSourceName,
PaperName = m_PaperName,
FontName = m_TextFontName,
FontSize = m_TextFontSize,
OddPageMargins = m_OddPageMargins,
EvenPageMargins = m_EvenPageMargins
};
if (dlg.ShowDialog() == DialogResult.OK)
{
m_PaperSourceName = dlg.PaperSourceName;
m_PaperName = dlg.PaperName;
m_OddPageMargins = dlg.OddPageMargins;
m_EvenPageMargins = dlg.EvenPageMargins;
m_TextFontName = dlg.FontName;
m_TextFontSize = dlg.FontSize;
}
}
}
}
| 36.744898 | 150 | 0.616773 | [
"MIT"
] | huanlin/EasyBrailleEdit | Source/EasyBrailleEdit/Printing/ConfigTextPrinterPanel.cs | 3,633 | 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.Collections.Concurrent;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using System.Text.Encodings.Web;
using System.Text.Json.Nodes;
using System.Text.Json.Serialization;
using System.Text.Json.Serialization.Metadata;
namespace System.Text.Json
{
/// <summary>
/// Provides options to be used with <see cref="JsonSerializer"/>.
/// </summary>
public sealed partial class JsonSerializerOptions
{
internal const int BufferSizeDefault = 16 * 1024;
internal static readonly JsonSerializerOptions s_defaultOptions = new JsonSerializerOptions();
private readonly ConcurrentDictionary<Type, JsonTypeInfo> _classes = new ConcurrentDictionary<Type, JsonTypeInfo>();
// Simple LRU cache for the public (de)serialize entry points that avoid some lookups in _classes.
// Although this may be written by multiple threads, 'volatile' was not added since any local affinity is fine.
private JsonTypeInfo? _lastClass { get; set; }
internal JsonSerializerContext? _context;
private Func<Type, JsonSerializerOptions, JsonTypeInfo>? _typeInfoCreationFunc;
// For any new option added, adding it to the options copied in the copy constructor below must be considered.
private MemberAccessor? _memberAccessorStrategy;
private JsonNamingPolicy? _dictionaryKeyPolicy;
private JsonNamingPolicy? _jsonPropertyNamingPolicy;
private JsonCommentHandling _readCommentHandling;
private ReferenceHandler? _referenceHandler;
private JavaScriptEncoder? _encoder;
private JsonIgnoreCondition _defaultIgnoreCondition;
private JsonNumberHandling _numberHandling;
private JsonUnknownTypeHandling _unknownTypeHandling;
private int _defaultBufferSize = BufferSizeDefault;
private int _maxDepth;
private bool _allowTrailingCommas;
private bool _haveTypesBeenCreated;
private bool _ignoreNullValues;
private bool _ignoreReadOnlyProperties;
private bool _ignoreReadonlyFields;
private bool _includeFields;
private bool _propertyNameCaseInsensitive;
private bool _writeIndented;
/// <summary>
/// Constructs a new <see cref="JsonSerializerOptions"/> instance.
/// </summary>
public JsonSerializerOptions()
{
Converters = new ConverterList(this);
TrackOptionsInstance(this);
}
/// <summary>
/// Copies the options from a <see cref="JsonSerializerOptions"/> instance to a new instance.
/// </summary>
/// <param name="options">The <see cref="JsonSerializerOptions"/> instance to copy options from.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="options"/> is <see langword="null"/>.
/// </exception>
public JsonSerializerOptions(JsonSerializerOptions options)
{
if (options == null)
{
throw new ArgumentNullException(nameof(options));
}
_memberAccessorStrategy = options._memberAccessorStrategy;
_dictionaryKeyPolicy = options._dictionaryKeyPolicy;
_jsonPropertyNamingPolicy = options._jsonPropertyNamingPolicy;
_readCommentHandling = options._readCommentHandling;
_referenceHandler = options._referenceHandler;
_encoder = options._encoder;
_defaultIgnoreCondition = options._defaultIgnoreCondition;
_numberHandling = options._numberHandling;
_unknownTypeHandling = options._unknownTypeHandling;
_defaultBufferSize = options._defaultBufferSize;
_maxDepth = options._maxDepth;
_allowTrailingCommas = options._allowTrailingCommas;
_ignoreNullValues = options._ignoreNullValues;
_ignoreReadOnlyProperties = options._ignoreReadOnlyProperties;
_ignoreReadonlyFields = options._ignoreReadonlyFields;
_includeFields = options._includeFields;
_propertyNameCaseInsensitive = options._propertyNameCaseInsensitive;
_writeIndented = options._writeIndented;
Converters = new ConverterList(this, (ConverterList)options.Converters);
EffectiveMaxDepth = options.EffectiveMaxDepth;
ReferenceHandlingStrategy = options.ReferenceHandlingStrategy;
// _classes is not copied as sharing the JsonTypeInfo and JsonPropertyInfo caches can result in
// unnecessary references to type metadata, potentially hindering garbage collection on the source options.
// _haveTypesBeenCreated is not copied; it's okay to make changes to this options instance as (de)serialization has not occurred.
TrackOptionsInstance(this);
}
/// <summary>Tracks the options instance to enable all instances to be enumerated.</summary>
private static void TrackOptionsInstance(JsonSerializerOptions options) => TrackedOptionsInstances.All.Add(options, null);
internal static class TrackedOptionsInstances
{
/// <summary>Tracks all live JsonSerializerOptions instances.</summary>
/// <remarks>Instances are added to the table in their constructor.</remarks>
public static ConditionalWeakTable<JsonSerializerOptions, object?> All { get; } =
// TODO https://github.com/dotnet/runtime/issues/51159:
// Look into linking this away / disabling it when hot reload isn't in use.
new ConditionalWeakTable<JsonSerializerOptions, object?>();
}
/// <summary>
/// Constructs a new <see cref="JsonSerializerOptions"/> instance with a predefined set of options determined by the specified <see cref="JsonSerializerDefaults"/>.
/// </summary>
/// <param name="defaults"> The <see cref="JsonSerializerDefaults"/> to reason about.</param>
public JsonSerializerOptions(JsonSerializerDefaults defaults) : this()
{
if (defaults == JsonSerializerDefaults.Web)
{
_propertyNameCaseInsensitive = true;
_jsonPropertyNamingPolicy = JsonNamingPolicy.CamelCase;
_numberHandling = JsonNumberHandling.AllowReadingFromString;
}
else if (defaults != JsonSerializerDefaults.General)
{
throw new ArgumentOutOfRangeException(nameof(defaults));
}
}
/// <summary>
/// Binds current <see cref="JsonSerializerOptions"/> instance with a new instance of the specified <see cref="JsonSerializerContext"/> type.
/// </summary>
/// <typeparam name="TContext">The generic definition of the specified context type.</typeparam>
/// <remarks>When serializing and deserializing types using the options
/// instance, metadata for the types will be fetched from the context instance.
/// </remarks>
public void AddContext<TContext>() where TContext : JsonSerializerContext, new()
{
if (_context != null)
{
ThrowHelper.ThrowInvalidOperationException_JsonSerializerOptionsAlreadyBoundToContext();
}
TContext context = new();
_context = context;
context._options = this;
}
/// <summary>
/// Defines whether an extra comma at the end of a list of JSON values in an object or array
/// is allowed (and ignored) within the JSON payload being deserialized.
/// </summary>
/// <exception cref="InvalidOperationException">
/// Thrown if this property is set after serialization or deserialization has occurred.
/// </exception>
/// <remarks>
/// By default, it's set to false, and <exception cref="JsonException"/> is thrown if a trailing comma is encountered.
/// </remarks>
public bool AllowTrailingCommas
{
get
{
return _allowTrailingCommas;
}
set
{
VerifyMutable();
_allowTrailingCommas = value;
}
}
/// <summary>
/// The default buffer size in bytes used when creating temporary buffers.
/// </summary>
/// <remarks>The default size is 16K.</remarks>
/// <exception cref="System.ArgumentException">Thrown when the buffer size is less than 1.</exception>
/// <exception cref="InvalidOperationException">
/// Thrown if this property is set after serialization or deserialization has occurred.
/// </exception>
public int DefaultBufferSize
{
get
{
return _defaultBufferSize;
}
set
{
VerifyMutable();
if (value < 1)
{
throw new ArgumentException(SR.SerializationInvalidBufferSize);
}
_defaultBufferSize = value;
}
}
/// <summary>
/// The encoder to use when escaping strings, or <see langword="null" /> to use the default encoder.
/// </summary>
public JavaScriptEncoder? Encoder
{
get
{
return _encoder;
}
set
{
VerifyMutable();
_encoder = value;
}
}
/// <summary>
/// Specifies the policy used to convert a <see cref="System.Collections.IDictionary"/> key's name to another format, such as camel-casing.
/// </summary>
/// <remarks>
/// This property can be set to <see cref="JsonNamingPolicy.CamelCase"/> to specify a camel-casing policy.
/// It is not used when deserializing.
/// </remarks>
public JsonNamingPolicy? DictionaryKeyPolicy
{
get
{
return _dictionaryKeyPolicy;
}
set
{
VerifyMutable();
_dictionaryKeyPolicy = value;
}
}
/// <summary>
/// Determines whether null values are ignored during serialization and deserialization.
/// The default value is false.
/// </summary>
/// <exception cref="InvalidOperationException">
/// Thrown if this property is set after serialization or deserialization has occurred.
/// or <see cref="DefaultIgnoreCondition"/> has been set to a non-default value. These properties cannot be used together.
/// </exception>
[Obsolete(Obsoletions.JsonSerializerOptionsIgnoreNullValuesMessage, DiagnosticId = Obsoletions.JsonSerializerOptionsIgnoreNullValuesDiagId, UrlFormat = Obsoletions.SharedUrlFormat)]
[EditorBrowsable(EditorBrowsableState.Never)]
public bool IgnoreNullValues
{
get
{
return _ignoreNullValues;
}
set
{
VerifyMutable();
if (value && _defaultIgnoreCondition != JsonIgnoreCondition.Never)
{
throw new InvalidOperationException(SR.DefaultIgnoreConditionAlreadySpecified);
}
_ignoreNullValues = value;
}
}
/// <summary>
/// Specifies a condition to determine when properties with default values are ignored during serialization or deserialization.
/// The default value is <see cref="JsonIgnoreCondition.Never" />.
/// </summary>
/// <exception cref="ArgumentException">
/// Thrown if this property is set to <see cref="JsonIgnoreCondition.Always"/>.
/// </exception>
/// <exception cref="InvalidOperationException">
/// Thrown if this property is set after serialization or deserialization has occurred,
/// or <see cref="IgnoreNullValues"/> has been set to <see langword="true"/>. These properties cannot be used together.
/// </exception>
public JsonIgnoreCondition DefaultIgnoreCondition
{
get
{
return _defaultIgnoreCondition;
}
set
{
VerifyMutable();
if (value == JsonIgnoreCondition.Always)
{
throw new ArgumentException(SR.DefaultIgnoreConditionInvalid);
}
if (value != JsonIgnoreCondition.Never && _ignoreNullValues)
{
throw new InvalidOperationException(SR.DefaultIgnoreConditionAlreadySpecified);
}
_defaultIgnoreCondition = value;
}
}
/// <summary>
/// Specifies how number types should be handled when serializing or deserializing.
/// </summary>
/// <exception cref="InvalidOperationException">
/// Thrown if this property is set after serialization or deserialization has occurred.
/// </exception>
public JsonNumberHandling NumberHandling
{
get => _numberHandling;
set
{
VerifyMutable();
if (!JsonSerializer.IsValidNumberHandlingValue(value))
{
throw new ArgumentOutOfRangeException(nameof(value));
}
_numberHandling = value;
}
}
/// <summary>
/// Determines whether read-only properties are ignored during serialization.
/// A property is read-only if it contains a public getter but not a public setter.
/// The default value is false.
/// </summary>
/// <remarks>
/// Read-only properties are not deserialized regardless of this setting.
/// </remarks>
/// <exception cref="InvalidOperationException">
/// Thrown if this property is set after serialization or deserialization has occurred.
/// </exception>
public bool IgnoreReadOnlyProperties
{
get
{
return _ignoreReadOnlyProperties;
}
set
{
VerifyMutable();
_ignoreReadOnlyProperties = value;
}
}
/// <summary>
/// Determines whether read-only fields are ignored during serialization.
/// A field is read-only if it is marked with the <c>readonly</c> keyword.
/// The default value is false.
/// </summary>
/// <remarks>
/// Read-only fields are not deserialized regardless of this setting.
/// </remarks>
/// <exception cref="InvalidOperationException">
/// Thrown if this property is set after serialization or deserialization has occurred.
/// </exception>
public bool IgnoreReadOnlyFields
{
get
{
return _ignoreReadonlyFields;
}
set
{
VerifyMutable();
_ignoreReadonlyFields = value;
}
}
/// <summary>
/// Determines whether fields are handled on serialization and deserialization.
/// The default value is false.
/// </summary>
/// <exception cref="InvalidOperationException">
/// Thrown if this property is set after serialization or deserialization has occurred.
/// </exception>
public bool IncludeFields
{
get
{
return _includeFields;
}
set
{
VerifyMutable();
_includeFields = value;
}
}
/// <summary>
/// Gets or sets the maximum depth allowed when serializing or deserializing JSON, with the default (i.e. 0) indicating a max depth of 64.
/// </summary>
/// <exception cref="InvalidOperationException">
/// Thrown if this property is set after serialization or deserialization has occurred.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// Thrown when the max depth is set to a negative value.
/// </exception>
/// <remarks>
/// Going past this depth will throw a <exception cref="JsonException"/>.
/// </remarks>
public int MaxDepth
{
get => _maxDepth;
set
{
VerifyMutable();
if (value < 0)
{
throw ThrowHelper.GetArgumentOutOfRangeException_MaxDepthMustBePositive(nameof(value));
}
_maxDepth = value;
EffectiveMaxDepth = (value == 0 ? JsonReaderOptions.DefaultMaxDepth : value);
}
}
// The default is 64 because that is what the reader uses, so re-use the same JsonReaderOptions.DefaultMaxDepth constant.
internal int EffectiveMaxDepth { get; private set; } = JsonReaderOptions.DefaultMaxDepth;
/// <summary>
/// Specifies the policy used to convert a property's name on an object to another format, such as camel-casing.
/// The resulting property name is expected to match the JSON payload during deserialization, and
/// will be used when writing the property name during serialization.
/// </summary>
/// <remarks>
/// The policy is not used for properties that have a <see cref="JsonPropertyNameAttribute"/> applied.
/// This property can be set to <see cref="JsonNamingPolicy.CamelCase"/> to specify a camel-casing policy.
/// </remarks>
public JsonNamingPolicy? PropertyNamingPolicy
{
get
{
return _jsonPropertyNamingPolicy;
}
set
{
VerifyMutable();
_jsonPropertyNamingPolicy = value;
}
}
/// <summary>
/// Determines whether a property's name uses a case-insensitive comparison during deserialization.
/// The default value is false.
/// </summary>
/// <remarks>There is a performance cost associated when the value is true.</remarks>
public bool PropertyNameCaseInsensitive
{
get
{
return _propertyNameCaseInsensitive;
}
set
{
VerifyMutable();
_propertyNameCaseInsensitive = value;
}
}
/// <summary>
/// Defines how the comments are handled during deserialization.
/// </summary>
/// <exception cref="InvalidOperationException">
/// Thrown if this property is set after serialization or deserialization has occurred.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// Thrown when the comment handling enum is set to a value that is not supported (or not within the <see cref="JsonCommentHandling"/> enum range).
/// </exception>
/// <remarks>
/// By default <exception cref="JsonException"/> is thrown if a comment is encountered.
/// </remarks>
public JsonCommentHandling ReadCommentHandling
{
get
{
return _readCommentHandling;
}
set
{
VerifyMutable();
Debug.Assert(value >= 0);
if (value > JsonCommentHandling.Skip)
throw new ArgumentOutOfRangeException(nameof(value), SR.JsonSerializerDoesNotSupportComments);
_readCommentHandling = value;
}
}
/// <summary>
/// Defines how deserializing a type declared as an <see cref="object"/> is handled during deserialization.
/// </summary>
public JsonUnknownTypeHandling UnknownTypeHandling
{
get => _unknownTypeHandling;
set
{
VerifyMutable();
_unknownTypeHandling = value;
}
}
/// <summary>
/// Defines whether JSON should pretty print which includes:
/// indenting nested JSON tokens, adding new lines, and adding white space between property names and values.
/// By default, the JSON is serialized without any extra white space.
/// </summary>
/// <exception cref="InvalidOperationException">
/// Thrown if this property is set after serialization or deserialization has occurred.
/// </exception>
public bool WriteIndented
{
get
{
return _writeIndented;
}
set
{
VerifyMutable();
_writeIndented = value;
}
}
/// <summary>
/// Configures how object references are handled when reading and writing JSON.
/// </summary>
public ReferenceHandler? ReferenceHandler
{
get => _referenceHandler;
set
{
VerifyMutable();
_referenceHandler = value;
ReferenceHandlingStrategy = value?.HandlingStrategy ?? ReferenceHandlingStrategy.None;
}
}
// The cached value used to determine if ReferenceHandler should use Preserve or IgnoreCycles semanitcs or None of them.
internal ReferenceHandlingStrategy ReferenceHandlingStrategy = ReferenceHandlingStrategy.None;
internal MemberAccessor MemberAccessorStrategy
{
get
{
if (_memberAccessorStrategy == null)
{
#if NETCOREAPP
// if dynamic code isn't supported, fallback to reflection
_memberAccessorStrategy = RuntimeFeature.IsDynamicCodeSupported ?
new ReflectionEmitMemberAccessor() :
new ReflectionMemberAccessor();
#elif NETFRAMEWORK
_memberAccessorStrategy = new ReflectionEmitMemberAccessor();
#else
_memberAccessorStrategy = new ReflectionMemberAccessor();
#endif
}
return _memberAccessorStrategy;
}
}
[RequiresUnreferencedCode(JsonSerializer.SerializationUnreferencedCodeMessage)]
internal void RootBuiltInConvertersAndTypeInfoCreator()
{
RootBuiltInConverters();
_typeInfoCreationFunc ??= CreateJsonTypeInfo;
[RequiresUnreferencedCode(JsonSerializer.SerializationUnreferencedCodeMessage)]
static JsonTypeInfo CreateJsonTypeInfo(Type type, JsonSerializerOptions options) => new JsonTypeInfo(type, options);
}
internal JsonTypeInfo GetOrAddClass(Type type)
{
_haveTypesBeenCreated = true;
// todo: for performance and reduced instances, consider using the converters and JsonTypeInfo from s_defaultOptions by cloning (or reference directly if no changes).
// https://github.com/dotnet/runtime/issues/32357
if (!_classes.TryGetValue(type, out JsonTypeInfo? result))
{
result = _classes.GetOrAdd(type, GetClassFromContextOrCreate(type));
}
return result;
}
internal JsonTypeInfo GetClassFromContextOrCreate(Type type)
{
JsonTypeInfo? info = _context?.GetTypeInfo(type);
if (info != null)
{
return info;
}
if (_typeInfoCreationFunc == null)
{
ThrowHelper.ThrowNotSupportedException_NoMetadataForType(type);
return null!;
}
return _typeInfoCreationFunc(type, this);
}
/// <summary>
/// Return the TypeInfo for root API calls.
/// This has a LRU cache that is intended only for public API calls that specify the root type.
/// </summary>
internal JsonTypeInfo GetOrAddClassForRootType(Type type)
{
JsonTypeInfo? jsonTypeInfo = _lastClass;
if (jsonTypeInfo?.Type != type)
{
jsonTypeInfo = GetOrAddClass(type);
_lastClass = jsonTypeInfo;
}
return jsonTypeInfo;
}
internal bool TypeIsCached(Type type)
{
return _classes.ContainsKey(type);
}
internal void ClearClasses()
{
_classes.Clear();
_lastClass = null;
}
internal JsonDocumentOptions GetDocumentOptions()
{
return new JsonDocumentOptions
{
AllowTrailingCommas = AllowTrailingCommas,
CommentHandling = ReadCommentHandling,
MaxDepth = MaxDepth
};
}
internal JsonNodeOptions GetNodeOptions()
{
return new JsonNodeOptions
{
PropertyNameCaseInsensitive = PropertyNameCaseInsensitive
};
}
internal JsonReaderOptions GetReaderOptions()
{
return new JsonReaderOptions
{
AllowTrailingCommas = AllowTrailingCommas,
CommentHandling = ReadCommentHandling,
MaxDepth = MaxDepth
};
}
internal JsonWriterOptions GetWriterOptions()
{
return new JsonWriterOptions
{
Encoder = Encoder,
Indented = WriteIndented,
#if !DEBUG
SkipValidation = true
#endif
};
}
internal void VerifyMutable()
{
// The default options are hidden and thus should be immutable.
Debug.Assert(this != s_defaultOptions);
if (_haveTypesBeenCreated || _context != null)
{
ThrowHelper.ThrowInvalidOperationException_SerializerOptionsImmutable(_context);
}
}
}
}
| 37.992837 | 189 | 0.590558 | [
"MIT"
] | AerisG222/runtime | src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializerOptions.cs | 26,519 | C# |
namespace _03BarracksFactory.Contracts
{
public interface IExecutable
{
string Execute();
}
}
| 15.25 | 40 | 0.614754 | [
"MIT"
] | Gandjurov/AdvancedOOP_CSharp | 04.ReflectionAndAttributes/03.BarracksWarsNewFactory/Contracts/IExecutable.cs | 124 | C# |
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Catalog.Api.Entities;
using MongoDB.Bson;
using MongoDB.Driver;
namespace Catalog.Api.Repositories
{
public class MongoDbItemsRepository : IItemsRepository
{
private const string databaseName = "catalog";
private const string collectionName = "items";
private readonly IMongoCollection<Item> itemsCollection;
private readonly FilterDefinitionBuilder<Item> filterBuilder = Builders<Item>.Filter;
public MongoDbItemsRepository(IMongoClient mongoClient)
{
IMongoDatabase database = mongoClient.GetDatabase(databaseName);
itemsCollection = database.GetCollection<Item>(collectionName);
}
public async Task CreateItemAsync(Item item)
{
await itemsCollection.InsertOneAsync(item);
}
public async Task DeleteItemAsync(Guid id)
{
var filter = filterBuilder.Eq(item => item.Id, id);
await itemsCollection.DeleteOneAsync(filter);
}
public async Task<Item> GetItemAsync(Guid id)
{
var filter = filterBuilder.Eq(item => item.Id, id);
return await itemsCollection.Find(filter).SingleOrDefaultAsync();
}
public async Task<IEnumerable<Item>> GetItemsAsync()
{
return await itemsCollection.Find(new BsonDocument()).ToListAsync();
}
public async Task UpdateitemAsync(Item item)
{
var filter = filterBuilder.Eq(existingItem => existingItem.Id, item.Id);
await itemsCollection.ReplaceOneAsync(filter, item);
}
}
} | 32.576923 | 93 | 0.658205 | [
"MIT"
] | nolkasaur/.NET-REST-API | Catalog.Api/Repositories/MongoDbItemsRepository.cs | 1,694 | C# |
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Todo.Ports.Entities;
namespace Todo.Ports.UseCases;
public interface ITaskService
{
Task<Guid> Add(string description);
void Do(Guid taskId);
Task<IEnumerable<ITask>> List(int pageNumber = 1, int pageSize = 10);
void Remove(Guid taskId);
void Undo(Guid taskId);
}
| 23.1875 | 73 | 0.735849 | [
"MIT"
] | fractas/todo | Todo.Ports/UseCases/ITaskService.cs | 373 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FunBrainDomain;
namespace FunBrainInfrastructure.Models
{
public class UserCreate
{
public string Name { get; set; }
public string Email { get; set; }
public User ToUser(int nextId)
{
return new User
{
Id = nextId,
Name = Name,
Email = Email
};
}
}
} | 20.44 | 41 | 0.549902 | [
"MIT"
] | ralbu/FunBrain-DotNetCore | src/FunBrainInfrastructure/Models/UserCreate.cs | 513 | C# |
using PizzaBox.Domain.Models;
using PizzaBox.Domain.Singletons;
using Xunit;
namespace PizzaBox.Testing.Tests
{
public class PriceTests
{
[Theory]
[InlineData(3, CrustType.Pan)]
[InlineData(2.5, CrustType.Thick)]
[InlineData(2, CrustType.Thin)]
[InlineData(5, CrustType.Stuffed)]
public void Test_CrustTypePan(float expected, CrustType type)
{
// arrange
var sut = new Crust(type);
// var expected = 1.7F;
// act -- part that we want to test
// var actual = sut.getPrice(CrustType.Pan);
var actual = sut.Price;
// assert
Assert.Equal(expected, actual);
}
[Theory]
[InlineData(5.5, ToppingType.Chicken)]
[InlineData(6, ToppingType.Meat)]
[InlineData(3.5, ToppingType.Mozirilla)]
[InlineData(1, ToppingType.Onion)]
public void Test_ToppingType(float expected, ToppingType type)
{
// arrange
var sut = new Topping(type);
// var expected = 0.6F;
// act -- part that we want to test
var actual = sut.Price;
// assert
Assert.Equal(expected, actual);
}
[Theory]
[InlineData(10, SizeType.Large)]
[InlineData(7, SizeType.Medium)]
[InlineData(5, SizeType.Small)]
[InlineData(12.5, SizeType.Xlarge)]
public void Test_SizeType(float expected, SizeType type)
{
// arrange
var sut = new Size(type);
// var expected = 7.0F;
// act -- part that we want to test
var actual = sut.Price;
// assert
Assert.Equal(expected, actual);
}
}
} | 26.057971 | 70 | 0.537264 | [
"MIT"
] | 03012021-dotnet-uta/NoureldinKamel_p0 | PizzaBox.Testing/Tests/PriceTests.cs | 1,798 | C# |
using System.Globalization;
namespace Orckestra.Composer.Parameters
{
public class GetOrderUrlParameter: BaseUrlParameter
{
/// <summary>
/// Gets or sets the order identifier.
/// </summary>
/// <value>
/// The order identifier.
/// </value>
public string OrderId { get; set; }
}
} | 22 | 55 | 0.573864 | [
"MIT"
] | InnaBoitsun/BetterRetailGroceryTest | src/Orckestra.Composer/Parameters/GetOrderUrlParameter.cs | 352 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _01.House_Painting
{
class Program
{
static void Main(string[] args)
{
double x = double.Parse(Console.ReadLine());
double y = double.Parse(Console.ReadLine());
double h = double.Parse(Console.ReadLine());
double sideWallS = x * y;
double windowS = 1.5 * 1.5;
double allSideWallS = (2 * sideWallS) - (2 * windowS);
double backWall = x * x;
double entrance = 1.2 * 2;
double frontAndBackWalls = 2 * backWall - entrance;
double totalWallS = allSideWallS + frontAndBackWalls;
double greenPaintLiters = totalWallS / 3.4;
double roofSquares = 2 * x * y;
double roofTriangles = 2 * (x * h / 2);
double totalRoofS = roofSquares + roofTriangles;
double redPaintLiters = totalRoofS / 4.3;
Console.WriteLine($"{greenPaintLiters:f2}");
Console.WriteLine($"{redPaintLiters:f2}");
}
}
}
//15:56-16:09 | 35 | 66 | 0.577489 | [
"MIT"
] | bobo4aces/01.SoftUni-ProgramingBasics | 99. Exams/2017.03.19 - Morning/01. House Painting/01. House Painting.cs | 1,157 | C# |
/*******************************************************************************
* Copyright 2012-2019 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.
* *****************************************************************************
*
* AWS Tools for Windows (TM) PowerShell (TM)
*
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
using System.Text;
using Amazon.PowerShell.Common;
using Amazon.Runtime;
using Amazon.Personalize;
using Amazon.Personalize.Model;
namespace Amazon.PowerShell.Cmdlets.PERS
{
/// <summary>
/// Describes a solution. For more information on solutions, see <a>CreateSolution</a>.
/// </summary>
[Cmdlet("Get", "PERSSolution")]
[OutputType("Amazon.Personalize.Model.Solution")]
[AWSCmdlet("Calls the AWS Personalize DescribeSolution API operation.", Operation = new[] {"DescribeSolution"}, SelectReturnType = typeof(Amazon.Personalize.Model.DescribeSolutionResponse))]
[AWSCmdletOutput("Amazon.Personalize.Model.Solution or Amazon.Personalize.Model.DescribeSolutionResponse",
"This cmdlet returns an Amazon.Personalize.Model.Solution object.",
"The service call response (type Amazon.Personalize.Model.DescribeSolutionResponse) can also be referenced from properties attached to the cmdlet entry in the $AWSHistory stack."
)]
public partial class GetPERSSolutionCmdlet : AmazonPersonalizeClientCmdlet, IExecutor
{
#region Parameter SolutionArn
/// <summary>
/// <para>
/// <para>The Amazon Resource Name (ARN) of the solution to describe.</para>
/// </para>
/// </summary>
#if !MODULAR
[System.Management.Automation.Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true)]
#else
[System.Management.Automation.Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true, Mandatory = true)]
[System.Management.Automation.AllowEmptyString]
[System.Management.Automation.AllowNull]
#endif
[Amazon.PowerShell.Common.AWSRequiredParameter]
public System.String SolutionArn { get; set; }
#endregion
#region Parameter Select
/// <summary>
/// Use the -Select parameter to control the cmdlet output. The default value is 'Solution'.
/// Specifying -Select '*' will result in the cmdlet returning the whole service response (Amazon.Personalize.Model.DescribeSolutionResponse).
/// Specifying the name of a property of type Amazon.Personalize.Model.DescribeSolutionResponse will result in that property being returned.
/// Specifying -Select '^ParameterName' will result in the cmdlet returning the selected cmdlet parameter value.
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
public string Select { get; set; } = "Solution";
#endregion
#region Parameter PassThru
/// <summary>
/// Changes the cmdlet behavior to return the value passed to the SolutionArn parameter.
/// The -PassThru parameter is deprecated, use -Select '^SolutionArn' instead. This parameter will be removed in a future version.
/// </summary>
[System.Obsolete("The -PassThru parameter is deprecated, use -Select '^SolutionArn' instead. This parameter will be removed in a future version.")]
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
public SwitchParameter PassThru { get; set; }
#endregion
protected override void ProcessRecord()
{
base.ProcessRecord();
var context = new CmdletContext();
// allow for manipulation of parameters prior to loading into context
PreExecutionContextLoad(context);
#pragma warning disable CS0618, CS0612 //A class member was marked with the Obsolete attribute
if (ParameterWasBound(nameof(this.Select)))
{
context.Select = CreateSelectDelegate<Amazon.Personalize.Model.DescribeSolutionResponse, GetPERSSolutionCmdlet>(Select) ??
throw new System.ArgumentException("Invalid value for -Select parameter.", nameof(this.Select));
if (this.PassThru.IsPresent)
{
throw new System.ArgumentException("-PassThru cannot be used when -Select is specified.", nameof(this.Select));
}
}
else if (this.PassThru.IsPresent)
{
context.Select = (response, cmdlet) => this.SolutionArn;
}
#pragma warning restore CS0618, CS0612 //A class member was marked with the Obsolete attribute
context.SolutionArn = this.SolutionArn;
#if MODULAR
if (this.SolutionArn == null && ParameterWasBound(nameof(this.SolutionArn)))
{
WriteWarning("You are passing $null as a value for parameter SolutionArn which is marked as required. In case you believe this parameter was incorrectly marked as required, report this by opening an issue at https://github.com/aws/aws-tools-for-powershell/issues.");
}
#endif
// allow further manipulation of loaded context prior to processing
PostExecutionContextLoad(context);
var output = Execute(context) as CmdletOutput;
ProcessOutput(output);
}
#region IExecutor Members
public object Execute(ExecutorContext context)
{
var cmdletContext = context as CmdletContext;
// create request
var request = new Amazon.Personalize.Model.DescribeSolutionRequest();
if (cmdletContext.SolutionArn != null)
{
request.SolutionArn = cmdletContext.SolutionArn;
}
CmdletOutput output;
// issue call
var client = Client ?? CreateClient(_CurrentCredentials, _RegionEndpoint);
try
{
var response = CallAWSServiceOperation(client, request);
object pipelineOutput = null;
pipelineOutput = cmdletContext.Select(response, this);
output = new CmdletOutput
{
PipelineOutput = pipelineOutput,
ServiceResponse = response
};
}
catch (Exception e)
{
output = new CmdletOutput { ErrorResponse = e };
}
return output;
}
public ExecutorContext CreateContext()
{
return new CmdletContext();
}
#endregion
#region AWS Service Operation Call
private Amazon.Personalize.Model.DescribeSolutionResponse CallAWSServiceOperation(IAmazonPersonalize client, Amazon.Personalize.Model.DescribeSolutionRequest request)
{
Utils.Common.WriteVerboseEndpointMessage(this, client.Config, "AWS Personalize", "DescribeSolution");
try
{
#if DESKTOP
return client.DescribeSolution(request);
#elif CORECLR
return client.DescribeSolutionAsync(request).GetAwaiter().GetResult();
#else
#error "Unknown build edition"
#endif
}
catch (AmazonServiceException exc)
{
var webException = exc.InnerException as System.Net.WebException;
if (webException != null)
{
throw new Exception(Utils.Common.FormatNameResolutionFailureMessage(client.Config, webException.Message), webException);
}
throw;
}
}
#endregion
internal partial class CmdletContext : ExecutorContext
{
public System.String SolutionArn { get; set; }
public System.Func<Amazon.Personalize.Model.DescribeSolutionResponse, GetPERSSolutionCmdlet, object> Select { get; set; } =
(response, cmdlet) => response.Solution;
}
}
}
| 44.975 | 282 | 0.613118 | [
"Apache-2.0"
] | 5u5hma/aws-tools-for-powershell | modules/AWSPowerShell/Cmdlets/Personalize/Basic/Get-PERSSolution-Cmdlet.cs | 8,995 | C# |
using System;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Reflection;
using System.Runtime.Loader;
using System.Runtime.CompilerServices;
using System.Security.Cryptography;
using System.Collections.Generic;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.VisualBasic;
using Newtonsoft.Json;
using BladeEngine.Core;
using BladeEngine.Core.Exceptions;
using static BladeEngine.Core.Utils.LanguageConstructs;
using BladeEngine.Core.Utils.Logging;
using Newtonsoft.Json.Linq;
using System.Data.SqlClient;
using System.Data;
using System.Drawing;
using System.Globalization;
using System.Threading;
namespace BladeEngine.VisualBasic
{
public class BladeRunnerVisualBasic : BladeRunner<BladeEngineVisualBasic, BladeEngineConfigVisualBasic>
{
public BladeRunnerVisualBasic(ILogger logger) : base(logger)
{ }
bool GetModel(BladeRunnerOptions options, BladeRunnerRunResult runnerResult, Type modelType)
{
var result = false;
if (options.Model != null)
{
if (IsSomeString(StrongEngine.StrongConfig.StrongModelType, true))
{
var givenModelType = options.Model.GetType();
if (givenModelType == typeof(JObject) && modelType != typeof(JObject))
{
if (!Logger.Try($"Mapping deserialized JObject model to {givenModelType.Name} ...", () =>
{
options.Model = ((JObject)options.Model).ToObject(modelType);
return true;
}, out Exception ex))
{
runnerResult.TrySetStatus("MappingModelTypeFailed");
runnerResult.Exception = new BladeEngineException($"Converting deserialized model to '{StrongEngine.StrongConfig.StrongModelType}' failed.", ex);
}
}
else
{
if (!(givenModelType == modelType || givenModelType.DescendsFrom(modelType)))
{
runnerResult.SetStatus("InvalidModelType");
runnerResult.Exception = new BladeEngineException($"Expected a '{StrongEngine.StrongConfig.StrongModelType}', but a '{givenModelType.Name}' model is given.");
}
}
}
else
{
result = true;
}
}
else
{
Logger.Log("No model specified. 'null' will be used as model.", options.Debug);
result = true;
}
return result;
}
Assembly CompileOrLoadAssembly(BladeRunnerOptions options, BladeRunnerRunResult runnerResult, out Type modelType)
{
Assembly result = null;
var md5 = runnerResult.RenderedTemplate.ToMD5();
if (!Directory.Exists(options.CacheDir))
{
Logger.Try($"Creating cache directory '{options.CacheDir}' ...", options.Debug, () => Directory.CreateDirectory(options.CacheDir));
}
var existingCompiledAssembly = Path.Combine(options.CacheDir, md5 + ".dll");
var createAssembly = true;
if (File.Exists(existingCompiledAssembly))
{
result = Logger.Try($"Loading existing assembly at '" + existingCompiledAssembly + "'", options.Debug, () => Assembly.LoadFrom(existingCompiledAssembly));
createAssembly = result == null;
}
var refPaths = new List<string> {
typeof(object).GetTypeInfo().Assembly.Location,
typeof(DynamicAttribute).GetTypeInfo().Assembly.Location, // required due to the use of 'dynamic' in Render() method that BladeTemplateVisualBasic generates
typeof(WebUtility).GetTypeInfo().Assembly.Location, // used in the class that BladeTemplateVisualBasic generates
typeof(MD5CryptoServiceProvider).GetTypeInfo().Assembly.Location, // " " "
typeof(MD5).GetTypeInfo().Assembly.Location, // " " "
typeof(HashAlgorithm).GetTypeInfo().Assembly.Location, // " " "
typeof(WebClient).GetTypeInfo().Assembly.Location, // useful assembly
typeof(Bitmap).GetTypeInfo().Assembly.Location, // " "
typeof(Calendar).GetTypeInfo().Assembly.Location, // " "
typeof(IQueryable).GetTypeInfo().Assembly.Location, // " "
typeof(PropertyInfo).GetTypeInfo().Assembly.Location, // " "
typeof(Thread).GetTypeInfo().Assembly.Location, // " "
typeof(File).GetTypeInfo().Assembly.Location, // " "
typeof(FileSystemWatcher).GetTypeInfo().Assembly.Location, // " "
typeof(DataSet).GetTypeInfo().Assembly.Location, // " "
typeof(SqlConnection).GetTypeInfo().Assembly.Location, // " "
typeof(JsonConvert).GetTypeInfo().Assembly.Location, // " "
Assembly.Load(new AssemblyName("System.Security.Cryptography.Algorithms")).Location,
Assembly.Load(new AssemblyName("System.ComponentModel.Primitives")).Location,
Assembly.Load(new AssemblyName("Microsoft.VisualBasic")).Location,
Assembly.Load(new AssemblyName("System.Xml")).Location,
Assembly.Load(new AssemblyName("netstandard")).Location,
Path.Combine(Path.GetDirectoryName(typeof(System.Runtime.GCSettings).GetTypeInfo().Assembly.Location), "System.Runtime.dll")
};
if (StrongEngine.StrongConfig.References != null && StrongEngine.StrongConfig.References.Count > 0)
{
foreach (var reference in StrongEngine.StrongConfig.References.Where(r => IsSomeString(r, true)))
{
var toAdd = "";
if (reference.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) || reference.EndsWith(".exe", StringComparison.OrdinalIgnoreCase))
{
if (Path.IsPathRooted(reference))
{
toAdd = reference;
}
else
{
toAdd = Path.Combine(Environment.CurrentDirectory, reference);
}
}
else
{
toAdd = Assembly.Load(new AssemblyName(reference)).Location;
}
if (!refPaths.Contains(toAdd, StringComparer.OrdinalIgnoreCase))
{
refPaths.Add(toAdd);
}
}
}
if (createAssembly)
{
var syntaxTree = VisualBasicSyntaxTree.ParseText(runnerResult.RenderedTemplate);
var assemblyName = Path.GetRandomFileName();
var references = refPaths.Select(r => MetadataReference.CreateFromFile(r)).ToArray();
if (options.Debug)
{
Logger.Log("Adding references ...");
foreach (var r in refPaths)
{
Logger.Debug(r);
}
Logger.Log(Environment.NewLine + "Compiling ...");
}
var compilation = VisualBasicCompilation.Create(
assemblyName,
syntaxTrees: new[] { syntaxTree },
references: references,
options: new VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary));
using (var ms = new MemoryStream())
{
var er = compilation.Emit(ms);
if (!er.Success)
{
Logger.Danger("Failed!" + Environment.NewLine);
var failures = er.Diagnostics.Where(diagnostic => diagnostic.IsWarningAsError || diagnostic.Severity == DiagnosticSeverity.Error);
foreach (Diagnostic diagnostic in failures)
{
Logger.Danger($"\t{diagnostic.Id}: {diagnostic.GetMessage()}");
}
}
else
{
if (options.Debug)
{
Logger.Success("Succeeded");
}
ms.Seek(0, SeekOrigin.Begin);
result = AssemblyLoadContext.Default.LoadFromStream(ms);
Logger.Try($"Saving compiled assembly into cache '{existingCompiledAssembly}' ...", options.Debug, () =>
{
ms.Seek(0, SeekOrigin.Begin);
using (var file = new FileStream(existingCompiledAssembly, FileMode.Create, System.IO.FileAccess.Write))
{
var bytes = new byte[ms.Length];
ms.Read(bytes, 0, (int)ms.Length);
file.Write(bytes, 0, bytes.Length);
ms.Close();
}
});
}
}
}
modelType = null;
if (StrongEngine.StrongConfig.UseStrongModel)
{
if (IsSomeString(StrongEngine.StrongConfig.StrongModelType, true))
{
foreach (var reference in refPaths)
{
try
{
var asm = Assembly.LoadFrom(reference);
if (IsSomeString(StrongEngine.StrongConfig.StrongModelType, true) && modelType == null)
{
modelType = asm.GetType(StrongEngine.StrongConfig.StrongModelType);
if (modelType != null)
{
break;
}
}
}
catch (Exception e)
{
if (options.Debug)
{
Logger.Log($"Loading assembly {reference} failed.{Environment.NewLine + "\t"}{e.ToString("\t" + Environment.NewLine)}");
}
}
}
if (modelType == null)
{
result = null;
runnerResult.SetStatus("ModelTypeNotFound");
throw new BladeEngineException($"Model type '{StrongEngine.StrongConfig.StrongModelType}' was not found in references");
}
}
else
{
result = null;
runnerResult.SetStatus("ModelTypeNotSpecified");
throw new BladeEngineException($"'UseStrongModel' is requested, but no strong model type is specified");
}
}
return result;
}
protected override bool Execute(BladeRunnerOptions options, BladeRunnerRunResult runnerResult, out string result)
{
result = "";
if (string.IsNullOrEmpty(runnerResult.RenderedTemplate))
{
throw new BladeEngineException("No code is produced to be executed!");
}
else
{
var assembly = CompileOrLoadAssembly(options, runnerResult, out Type modelType);
if (assembly != null)
{
if (GetModel(options, runnerResult, modelType))
{
var templateMainClass = runnerResult.Template.GetFullMainClassName(); // StrongEngine.StrongConfig.Namespace + "." + runnerResult.Template.GetMainClassName();
var templateType = assembly.GetType(templateMainClass);
if (templateType != null)
{
var templateInstance = Logger.Try($"Instantiating from {templateMainClass} ...", options.Debug, () => assembly.CreateInstance(templateMainClass));
if (templateInstance != null)
{
var method = templateType.GetMethod("Render");
if (method != null)
{
Logger.Log($"Invoking Render() on {templateMainClass} instance ...", options.Debug);
var parameters = method.GetParameters();
if (parameters.Length == 0)
{
result = method.Invoke(templateInstance, new object[] { })?.ToString();
}
else if (parameters.Length == 1)
{
result = method.Invoke(templateInstance, new object[] { (object)options.Model })?.ToString();
}
else
{
throw new BladeEngineException($"Cannot execute {templateMainClass}.Render() since it requires more than one argument.");
}
}
else
{
throw new BladeEngineException("Generated class does not have a method named Render().");
}
}
}
else
{
throw new BladeEngineException($"Cannot access {templateMainClass} in generated assembly.");
}
}
}
}
return true;
}
}
}
| 45.032738 | 186 | 0.465072 | [
"MIT"
] | ironcodev/BladeEngine | BladeEngine.VisualBasic/BladeRunnerVisualBasic.cs | 15,133 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Threading.Tasks;
using Contoso.GameNetCore.Proto;
namespace Contoso.GameNetCore.Routing
{
public class RouteHandler : IRouteHandler, IRouter
{
private readonly RequestDelegate _requestDelegate;
public RouteHandler(RequestDelegate requestDelegate)
{
_requestDelegate = requestDelegate;
}
public RequestDelegate GetRequestHandler(ProtoContext httpContext, RouteData routeData)
{
return _requestDelegate;
}
public VirtualPathData GetVirtualPath(VirtualPathContext context)
{
// Nothing to do.
return null;
}
public Task RouteAsync(RouteContext context)
{
context.Handler = _requestDelegate;
return Task.CompletedTask;
}
}
}
| 28.611111 | 112 | 0.637864 | [
"Apache-2.0"
] | bclnet/GameNetCore | src/Proto/Routing/src/RouteHandler.cs | 1,030 | C# |
using System.Data.Entity;
using System.Threading.Tasks;
using Autofac.Extras.NLog;
using Wiz.Gringotts.UIWeb.Data;
using Wiz.Gringotts.UIWeb.Infrastructure.Commands;
using MediatR;
using NExtensions;
namespace Wiz.Gringotts.UIWeb.Models.Payees
{
public class TogglePayeeIsActiveCommand : IAsyncRequest<ICommandResult>
{
public int PayeeId { get; private set; }
public TogglePayeeIsActiveCommand(int payeeId)
{
this.PayeeId = payeeId;
}
}
public class TogglePayeeIsActiveCommandHandler : IAsyncRequestHandler<TogglePayeeIsActiveCommand, ICommandResult>
{
public ILogger Logger { get; set; }
private readonly ISearch<Payee> payees;
private readonly ApplicationDbContext context;
public TogglePayeeIsActiveCommandHandler(ISearch<Payee> payees, ApplicationDbContext context)
{
this.payees = payees;
this.context = context;
}
public async Task<ICommandResult> Handle(TogglePayeeIsActiveCommand command)
{
Logger.Trace("Handle::{0}", command.PayeeId);
var payee = await payees.GetById(command.PayeeId)
.FirstOrDefaultAsync();
if (payee != null)
{
payee.IsActive = !payee.IsActive;
await context.SaveChangesAsync();
Logger.Info("Handle::Success Id:{0} IsActive:{1}", payee.Id, payee.IsActive);
return new SuccessResult(payee.Id);
}
return new FailureResult("Payee {0} not found.".FormatWith(command.PayeeId));
}
}
} | 31.423077 | 117 | 0.640759 | [
"MIT"
] | NotMyself/Gringotts | src/UIWeb/Models/Payees/CommandTogglePayeeIsActive.cs | 1,636 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.TestUtilities;
using Microsoft.Extensions.DependencyInjection;
using Xunit;
// ReSharper disable InconsistentNaming
namespace Microsoft.EntityFrameworkCore
{
public abstract class EntityFrameworkServiceCollectionExtensionsTestBase
{
private readonly TestHelpers _testHelpers;
protected EntityFrameworkServiceCollectionExtensionsTestBase(TestHelpers testHelpers)
=> _testHelpers = testHelpers;
[ConditionalFact]
public void Calling_AddEntityFramework_explicitly_does_not_change_services()
{
var services1 = AddServices(new ServiceCollection());
var services2 = AddServices(new ServiceCollection());
new EntityFrameworkServicesBuilder(services2).TryAddCoreServices();
AssertServicesSame(services1, services2);
}
[ConditionalFact]
public virtual void Repeated_calls_to_add_do_not_modify_collection()
{
AssertServicesSame(
AddServices(new ServiceCollection()),
AddServices(AddServices(new ServiceCollection())));
}
[ConditionalFact]
public virtual void Required_services_are_registered_with_expected_lifetimes()
{
LifetimeTest(EntityFrameworkServicesBuilder.CoreServices);
}
protected virtual void LifetimeTest(
params IDictionary<Type, ServiceCharacteristics>[] serviceDefinitions)
{
var services = AddServices(new ServiceCollection());
foreach (var coreService in serviceDefinitions.SelectMany(e => e))
{
var registered = services.Where(s => s.ServiceType == coreService.Key).ToList();
if (coreService.Value.MultipleRegistrations)
{
Assert.All(registered, s => Assert.Equal(coreService.Value.Lifetime, s.Lifetime));
}
else
{
Assert.Single(registered);
Assert.Equal(coreService.Value.Lifetime, registered[0].Lifetime);
}
}
}
protected virtual void AssertServicesSame(IServiceCollection services1, IServiceCollection services2)
{
var sortedServices1 = services1
.OrderBy(s => s.ServiceType.GetHashCode())
.ToList();
var sortedServices2 = services2
.OrderBy(s => s.ServiceType.GetHashCode())
.ToList();
Assert.Equal(sortedServices1.Count, sortedServices2.Count);
for (var i = 0; i < sortedServices1.Count; i++)
{
Assert.Equal(sortedServices1[i].ServiceType, sortedServices2[i].ServiceType);
Assert.Equal(sortedServices1[i].ImplementationType, sortedServices2[i].ImplementationType);
Assert.Equal(sortedServices1[i].Lifetime, sortedServices2[i].Lifetime);
}
}
private IServiceCollection AddServices(IServiceCollection serviceCollection)
=> _testHelpers.AddProviderServices(serviceCollection);
}
}
| 37.206522 | 109 | 0.648846 | [
"MIT"
] | CameronAavik/efcore | test/EFCore.Specification.Tests/EntityFrameworkServiceCollectionExtensionsTestBase.cs | 3,423 | C# |
using Singer.Core.Helper;
using Singer.Core.Logging;
using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Text;
namespace ESignature.Business
{
public static class Const
{
public const string Version = "1.0.0";
public const string AppName = "esignatue";
/// <summary> 数据库版本 </summary>
internal static int DbVersion = 1;
#if DEBUG
internal static string DbPassword = string.Empty;
#else
internal static string DbPassword = $"k98djnc__{AppName}";
#endif
internal const string GlobalDb = AppName + "_global";
internal static string ConnectionString =
"Data Source={0};Pooling=true;FailIfMissing=false;Version=3;UTF8Encoding=True;Journal Mode=Off;";
internal static string Host => ConfigHelper.Read<string>(GlobalKeys.Host);
public static ILogger DefaultLogger => LogManager.Logger(AppName);
private const string DbPathFormat = "Contents\\data\\{0}.db";
internal static string DbPath(this string name)
{
#if DEBUG
name = $"{name}_debug";
#else
name = $"{name}_pro";
#endif
return Path.Combine(AppDomain.CurrentDomain.BaseDirectory, string.Format(DbPathFormat, name));
}
/// <summary> 获得当前应用软件的版本 </summary>
public static Version CurrentVersion
{
get
{
var location = (Assembly.GetEntryAssembly() ?? Assembly.GetExecutingAssembly()).Location;
var version = FileVersionInfo.GetVersionInfo(location).ProductVersion;
return !string.IsNullOrWhiteSpace(version) ? new Version(version) : new Version();
}
}
public static string UserAgent
{
get
{
var agent = new StringBuilder();
agent.AppendFormat("ESignature.Client/{0}/{1}/{2}", CurrentVersion, Environment.OSVersion,
Environment.MachineName);
return agent.ToString();
}
}
}
} | 30.691176 | 109 | 0.614279 | [
"MIT"
] | shoy160/Singer.Wpf | sample/Singer.Sample/Const.cs | 2,121 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Text;
using Xunit;
namespace System.Globalization.Tests
{
/// <summary>
/// Class to read data obtained from http://www.unicode.org/Public/idna. For more information read the information
/// contained in Data\6.0\IdnaTest.txt
///
/// The structure of the data set is a semicolon deliminated list with the following columns:
///
/// Column 1: type - T for transitional, N for nontransitional, B for both
/// Column 2: source - the source string to be tested
/// Column 3: toUnicode - the result of applying toUnicode to the source, using the specified type
/// Column 4: toASCII - the result of applying toASCII to the source, using nontransitional
///
/// If the value of toUnicode or toASCII is the same as source, the column will be blank.
/// </summary>
public class Unicode_6_0_IdnaTest : IConformanceIdnaTest
{
public IdnType Type { get; set; }
public string Source { get; set; }
public ConformanceIdnaTestResult GetUnicodeResult { get; set; }
public ConformanceIdnaTestResult GetASCIIResult { get; set; }
public int LineNumber { get; set; }
public Unicode_6_0_IdnaTest(string line, int lineNumber)
{
var split = line.Split(';');
Type = ConvertStringToType(split[0].Trim());
Source = EscapedToLiteralString(split[1], lineNumber);
GetUnicodeResult = new ConformanceIdnaTestResult(EscapedToLiteralString(split[2], lineNumber), Source);
GetASCIIResult = new ConformanceIdnaTestResult(EscapedToLiteralString(split[3], lineNumber), GetUnicodeResult.Value);
LineNumber = lineNumber;
}
private static IdnType ConvertStringToType(string idnType)
{
switch (idnType)
{
case "T":
return IdnType.Transitional;
case "N":
return IdnType.Nontransitional;
case "B":
return IdnType.Both;
default:
throw new ArgumentOutOfRangeException("idnType", "Unknown idnType");
}
}
/// <summary>
/// This will convert strings with escaped sequences to literal characters. The input string is
/// expected to have escaped sequences in the form of '\uXXXX'.
///
/// Example: "a\u0020b" will be converted to 'a b'.
/// </summary>
private static string EscapedToLiteralString(string escaped, int lineNumber)
{
var sb = new StringBuilder();
for (int i = 0; i < escaped.Length; i++)
{
if (i + 1 < escaped.Length && escaped[i] == '\\' && escaped[i + 1] == 'u')
{
// Verify that the escaped sequence is not malformed
Assert.True(i + 5 < escaped.Length, "There was a problem converting to literal string on Line " + lineNumber);
var codepoint = Convert.ToInt32(escaped.Substring(i + 2, 4), 16);
sb.Append((char)codepoint);
i += 5;
}
else
{
sb.Append(escaped[i]);
}
}
return sb.ToString().Trim();
}
}
}
| 40.218391 | 130 | 0.57988 | [
"MIT"
] | 690486439/corefx | src/System.Globalization.Extensions/tests/IdnMapping/Data/Unicode_6_0/Unicode_6_0_IdnaTest.cs | 3,501 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public enum GameManagerEvent
{
WIN,
LOSE
}
public class GameManager : BaseBehaviour
{
Observer observer;
private float playTime;
private static GameObject player;
public static GameObject Player
{
get { return player; }
}
void Awake()
{
observer = Observer.Instance;
}
void Start()
{
observer.AddListener(LevelBulderEvens.LOAD, this, StartAfterLoad);
observer.AddListener(PlayerEvents.DIE, this, LoseGameMenu);
observer.AddListener(EnemyManagerEvent.WIN, this, WinGameMenu);
player = GameObject.FindGameObjectWithTag("Player");
}
void StartAfterLoad(ObservParam obj)
{
player = GameObject.FindGameObjectWithTag("Player");
}
void Update()
{
playTime += Time.deltaTime;
}
private void LoseGameMenu(ObservParam obj)
{
observer.SendMessage(GameManagerEvent.LOSE);
}
private void WinGameMenu(ObservParam obj)
{
observer.SendMessage(GameManagerEvent.WIN, playTime);
}
private void OnDestroy()
{
observer.RemoveAllListeners(this);
}
}
| 19.640625 | 74 | 0.638823 | [
"MIT"
] | LunaryDog/TankHunter | Assets/Scripts/Game/Managers/GameManager.cs | 1,259 | C# |
using System.Collections;
using System.Collections.Generic;
using System;
using UnityEditor;
using UnityEngine;
using XNode;
using XNodeEditor;
namespace hiVN
{
[CustomNodeEditor(typeof(BaseNode))]
public class BaseNodeEditor : NodeEditor
{
public override Color GetTint()
{
BaseNode baseNode = (BaseNode)target;
DialogueGraph dialogueGraph = (DialogueGraph)baseNode.graph;
if (dialogueGraph.atNode == baseNode)
{
return Color.white;
}
else
{
return base.GetTint();
}
}
}
} | 20.83871 | 72 | 0.575851 | [
"MIT"
] | Hizuvi/hiVN | NodeSystem/Nodes/Editor/BaseNodeEditor.cs | 648 | C# |
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Dispenser")]
[assembly: AssemblyTrademark("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("28534864-2b0f-45bc-bd4e-0906e4a56993")]
| 42 | 85 | 0.759398 | [
"MIT"
] | lvermeulen/Dispenser | src/Dispenser/Properties/AssemblyInfo.cs | 800 | C# |
namespace HOSKYSWAP.Common;
public enum Status
{
Open,
Filled,
Cancelled,
Error,
Ignored,
Confirming,
Cancelling,
Staked,
Unstaking,
Unstaked
}
public record Order
{
public Guid Id { get; set; } = Guid.NewGuid();
public string OwnerAddress { get; set; } = string.Empty;
public string TxHash { get; set; } = string.Empty;
public List<long> TxIndexes { get; set; } = new();
public string Action { get; set; } = string.Empty;
public decimal Rate { get; set; } = 0;
public ulong Total { get; set; } = 0;
public Status Status { get; set; } = Status.Open;
public string ExecuteTxId { get; set; } = string.Empty;
public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
public DateTime UpdatedAt { get; set; } = DateTime.UtcNow;
} | 27.033333 | 62 | 0.628853 | [
"MIT"
] | joshjaypegman/HOSKYSWAP | src/HOSKYSWAP.Common/Order.cs | 811 | C# |
// The MIT License (MIT)
// Copyright (c) 2015 Ben Abelshausen
// 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 GTFS.Entities;
using System;
using System.Collections.Generic;
namespace GTFS.Filters
{
/// <summary>
/// Represents a GTFS feed filter that leaves only data related to the some filtered stops.
///
/// - Leaves only trips related to the filtered stops.
/// - Leaves trips intact, will add stops again to keep complete trips.
/// - Filters out all other data not related to any of the trips or stops.
/// </summary>
public class GTFSFeedStopsFilter : GTFSFeedFilter
{
/// <summary>
/// Holds the stop filter function.
/// </summary>
private Func<Stop, bool> _stopFilter;
/// <summary>
/// Creates a new stops filter.
/// </summary>
/// <param name="stopFilter"></param>
public GTFSFeedStopsFilter(Func<Stop, bool> stopFilter)
{
_stopFilter = stopFilter;
}
/// <summary>
/// Creates a new stops filter.
/// </summary>
/// <param name="stopIds"></param>
public GTFSFeedStopsFilter(HashSet<string> stopIds)
{
_stopFilter = (s) => stopIds.Contains(s.Id);
}
/// <summary>
/// Filters the given feed and returns a filtered version.
/// </summary>
/// <param name="feed"></param>
/// <returns></returns>
public override IGTFSFeed Filter(IGTFSFeed feed)
{
var filteredFeed = new GTFSFeed();
// collect stopids and tripids.
var stopIds = new HashSet<string>();
var tripIds = new HashSet<string>();
foreach (var stop in feed.Stops)
{
if (_stopFilter.Invoke(stop))
{ // stop has to be included.
stopIds.Add(stop.Id);
}
}
foreach (var stopTime in feed.StopTimes)
{
if (stopIds.Contains(stopTime.StopId))
{ // save the trip id's to keep.
tripIds.Add(stopTime.TripId);
}
}
foreach (var stopTime in feed.StopTimes)
{
if (tripIds.Contains(stopTime.TripId))
{ // stop is included, keep this stopTime.
stopIds.Add(stopTime.StopId);
}
}
// filter stop-times.
foreach (var stopTime in feed.StopTimes)
{
if (stopIds.Contains(stopTime.StopId) &&
tripIds.Contains(stopTime.TripId))
{ // save the trip id's to keep.
filteredFeed.StopTimes.Add(stopTime);
}
}
// filter stops.
foreach (var stop in feed.Stops)
{
if (stopIds.Contains(stop.Id))
{ // stop has to be included.
filteredFeed.Stops.Add(stop);
}
}
// filter trips.
var routeIds = new HashSet<string>();
var serviceIds = new HashSet<string>();
var shapeIds = new HashSet<string>();
foreach (var trip in feed.Trips)
{
if (tripIds.Contains(trip.Id))
{ // keep this trip, it is related to at least one stop-time.
filteredFeed.Trips.Add(trip);
// keep serviceId, routeId and shapeId.
routeIds.Add(trip.RouteId);
serviceIds.Add(trip.ServiceId);
if (!string.IsNullOrWhiteSpace(trip.ShapeId))
{
shapeIds.Add(trip.ShapeId);
}
}
}
// filter routes.
var agencyIds = new HashSet<string>();
foreach (var route in feed.Routes)
{
if (routeIds.Contains(route.Id))
{ // keep this route.
filteredFeed.Routes.Add(route);
// keep agency ids.
agencyIds.Add(route.AgencyId);
}
}
// filter agencies.
foreach (var agency in feed.Agencies)
{
if (agencyIds.Contains(agency.Id))
{ // keep this agency.
filteredFeed.Agencies.Add(agency);
}
}
// filter calendars.
foreach (var calendar in feed.Calendars)
{
if (serviceIds.Contains(calendar.ServiceId))
{ // keep this calendar.
filteredFeed.Calendars.Add(calendar);
}
}
// filter calendar-dates.
foreach (var calendarDate in feed.CalendarDates)
{
if (serviceIds.Contains(calendarDate.ServiceId))
{ // keep this calendarDate.
filteredFeed.CalendarDates.Add(calendarDate);
}
}
// filter fare rules.
var fareIds = new HashSet<string>();
foreach (var fareRule in feed.FareRules)
{
if (routeIds.Contains(fareRule.RouteId))
{ // keep this fare rule.
filteredFeed.FareRules.Add(fareRule);
// keep fare ids.
fareIds.Add(fareRule.FareId);
}
}
// filter fare attributes.
foreach (var fareAttribute in feed.FareAttributes)
{
if (fareIds.Contains(fareAttribute.FareId))
{ // keep this fare attribute.
filteredFeed.FareAttributes.Add(fareAttribute);
}
}
// filter frequencies.
foreach (var frequency in feed.Frequencies)
{
if (tripIds.Contains(frequency.TripId))
{ // keep this frequency.
filteredFeed.Frequencies.Add(frequency);
}
}
foreach (var transfer in feed.Transfers)
{
if (stopIds.Contains(transfer.FromStopId) &&
stopIds.Contains(transfer.ToStopId))
{
filteredFeed.Transfers.Add(transfer);
}
}
// filter shapes.
foreach(var shape in feed.Shapes)
{
if(shapeIds.Contains(shape.Id))
{
filteredFeed.Shapes.Add(shape);
}
}
return filteredFeed;
}
}
} | 34.70354 | 95 | 0.511411 | [
"MIT"
] | FleQ-inc/GTFS | src/GTFS/Filters/GTFSFeedStopsFilter.cs | 7,845 | C# |
namespace Fixie.Internal
{
public interface Handler<in TMessage> : Listener where TMessage : Message
{
void Handle(TMessage message);
}
} | 22.571429 | 77 | 0.677215 | [
"MIT"
] | Meberem/fixie | src/Fixie/Internal/Handler.cs | 160 | C# |
using System.Runtime.Caching;
using Orleans;
using Orleans.Concurrency;
namespace TicTacToe.Orleans.Grains;
[Reentrant]
public class PairingGrain : Grain, IPairingGrain
{
private readonly MemoryCache _cache = new("pairing");
public Task AddGame(Guid gameId, string name)
{
_cache.Add(gameId.ToString(), name, new DateTimeOffset(DateTime.UtcNow).AddHours(1));
return Task.CompletedTask;
}
public Task RemoveGame(Guid gameId)
{
_cache.Remove(gameId.ToString());
return Task.CompletedTask;
}
public Task<PairingSummary[]> GetGames() => Task.FromResult(_cache.Select(x => new PairingSummary { GameId = Guid.Parse(x.Key), Name = x.Value as string }).ToArray());
} | 28.038462 | 171 | 0.698217 | [
"Apache-2.0"
] | AhmedKhalil777/Orleans.Learning | src/TicTacToe.Orleans/TicTacToe.Orleans/Grains/PairingGrain.cs | 731 | C# |
using System;
#if UNITY_2020_2_OR_NEWER
using Unity.Profiling.LowLevel;
#endif
namespace MLAPI.Profiling
{
internal struct ProfilerCounterUtility
{
#if UNITY_2020_2_OR_NEWER && ENABLE_PROFILER
public static byte GetProfilerMarkerDataType<T>()
{
switch (Type.GetTypeCode(typeof(T)))
{
case TypeCode.Int32:
return (byte)ProfilerMarkerDataType.Int32;
case TypeCode.UInt32:
return (byte)ProfilerMarkerDataType.UInt32;
case TypeCode.Int64:
return (byte)ProfilerMarkerDataType.Int64;
case TypeCode.UInt64:
return (byte)ProfilerMarkerDataType.UInt64;
case TypeCode.Single:
return (byte)ProfilerMarkerDataType.Float;
case TypeCode.Double:
return (byte)ProfilerMarkerDataType.Double;
case TypeCode.String:
return (byte)ProfilerMarkerDataType.String16;
default:
throw new ArgumentException($"Type {typeof(T)} is unsupported by ProfilerCounter.");
}
}
#endif
}
} | 33.694444 | 104 | 0.577082 | [
"MIT"
] | 0vjm3wfw9gqm4j/com.unity.multiplayer.mlapi | com.unity.multiplayer.mlapi/Runtime/Profiling/ProfilerCounterUtility.cs | 1,213 | C# |
/*
* Copyright (C) 2019 - 2021, Fyfe Software Inc. and the SanteSuite Contributors (See NOTICE.md)
*
* 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.
*
* User: fyfej
* Date: 2021-2-9
*/
using SanteDB.Core.Diagnostics;
using SanteDB.Core.Mail;
using SanteDB.Core.Model.Query;
using SanteDB.Core.Security;
using SanteDB.Core.Services;
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
namespace SanteDB.DisconnectedClient.Mail
{
/// <summary>
/// Represents a local alerting service
/// </summary>
public class LocalMailService : IMailMessageRepositoryService, IRepositoryService<MailMessage>
{
/// <summary>
/// Get the service name
/// </summary>
public String ServiceName => "Local Mail Storage Service";
// Tracer
private Tracer m_tracer = Tracer.GetTracer(typeof(LocalMailService));
public event EventHandler<MailMessageEventArgs> Committed;
public event EventHandler<MailMessageEventArgs> Received;
/// <summary>
/// Broadcast alert
/// </summary>
public void Broadcast(MailMessage msg)
{
try
{
this.m_tracer.TraceVerbose("Broadcasting alert {0}", msg);
// Broadcast alert
// TODO: Fix this, this is bad
var args = new MailMessageEventArgs(msg);
this.Received?.Invoke(this, args);
if (args.Ignore)
return;
if (msg.Flags == MailMessageFlags.Transient)
ApplicationContext.Current.ShowToast(msg.Subject);
else
this.Save(msg);
// Committed
this.Committed?.BeginInvoke(this, args, null, null);
}
catch (Exception e)
{
this.m_tracer.TraceError("Error broadcasting alert: {0}", e);
}
}
/// <summary>
/// Get alerts matching
/// </summary>
/// <param name="predicate"></param>
/// <returns></returns>
public IEnumerable<MailMessage> Find(Expression<Func<MailMessage, bool>> predicate, int offset, int? count, out int totalCount, params ModelSort<MailMessage>[] orderBy)
{
var persistenceService = ApplicationContext.Current.GetService<IDataPersistenceService<MailMessage>>();
if (persistenceService == null)
throw new InvalidOperationException("Cannot find alert persistence service");
return persistenceService.Query(predicate, offset, count, out totalCount, AuthenticationContext.Current.Principal, orderBy);
}
/// <summary>
/// Get an alert from the storage
/// </summary>
public MailMessage Get(Guid id)
{
var persistenceService = ApplicationContext.Current.GetService<IDataPersistenceService<MailMessage>>();
if (persistenceService == null)
throw new InvalidOperationException("Cannot find alert persistence service");
return persistenceService.Get(id, null, false, AuthenticationContext.Current.Principal);
}
/// <summary>
/// Inserts an alert message.
/// </summary>
/// <param name="message">The alert message to be inserted.</param>
/// <returns>Returns the inserted alert.</returns>
public MailMessage Insert(MailMessage message)
{
var persistenceService = ApplicationContext.Current.GetService<IDataPersistenceService<MailMessage>>();
if (persistenceService == null)
{
throw new InvalidOperationException(string.Format("{0} not found", nameof(IDataPersistenceService<MailMessage>)));
}
MailMessage alert = persistenceService.Insert(message, TransactionMode.Commit, AuthenticationContext.Current.Principal);
this.Received?.Invoke(this, new MailMessageEventArgs(alert));
return alert;
}
/// <summary>
/// Save the alert without notifying anyone
/// </summary>
public MailMessage Save(MailMessage alert)
{
var persistenceService = ApplicationContext.Current.GetService<IDataPersistenceService<MailMessage>>();
if (persistenceService == null)
{
throw new InvalidOperationException(string.Format("{0} not found", nameof(IDataPersistenceService<MailMessage>)));
}
try
{
// Transient messages don't get saved
if (alert.Flags.HasFlag(MailMessageFlags.Transient))
{
return alert;
}
this.m_tracer.TraceVerbose("Saving alert {0}", alert);
var existingAlert = this.Get(alert.Key ?? Guid.Empty);
if (existingAlert == null)
{
persistenceService.Insert(alert, TransactionMode.Commit, AuthenticationContext.SystemPrincipal);
}
else
{
persistenceService.Update(alert, TransactionMode.Commit, AuthenticationContext.SystemPrincipal);
}
this.Committed?.Invoke(this, new MailMessageEventArgs(alert));
}
catch (Exception e)
{
this.m_tracer.TraceError("Error saving alert: {0}", e);
}
return alert;
}
/// <summary>
/// Gets the specified mail message
/// </summary>
public MailMessage Get(Guid key, Guid versionKey)
{
return this.Get(key);
}
/// <summary>
/// Find the specified mail message
/// </summary>
public IEnumerable<MailMessage> Find(Expression<Func<MailMessage, bool>> query)
{
return this.Find(query, 0, 100, out int tr);
}
/// <summary>
/// Obsolete the mail message
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public MailMessage Obsolete(Guid key)
{
var message = this.Get(key);
message.Flags = MailMessageFlags.Archived;
return this.Save(message);
}
}
} | 35.448454 | 176 | 0.590228 | [
"Apache-2.0"
] | santedb/santedb-dc-core | SanteDB.DisconnectedClient.Core/Mail/LocalMailService.cs | 6,879 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace QuanLyHocSinh.Properties
{
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
{
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default
{
get
{
return defaultInstance;
}
}
}
}
| 34.451613 | 151 | 0.582397 | [
"MIT"
] | duyndh/QuanLyHocSinh | PresentaionTier/Properties/Settings.Designer.cs | 1,070 | C# |
// Licensed to Elasticsearch B.V under one or more agreements.
// Elasticsearch B.V licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information
using System;
using System.Runtime.Serialization;
namespace Nest
{
public class DateRange
{
[DataMember(Name = "gt")]
public DateTimeOffset? GreaterThan { get; set; }
[DataMember(Name = "gte")]
public DateTimeOffset? GreaterThanOrEqualTo { get; set; }
[DataMember(Name = "lt")]
public DateTimeOffset? LessThan { get; set; }
[DataMember(Name = "lte")]
public DateTimeOffset? LessThanOrEqualTo { get; set; }
}
public class DoubleRange
{
[DataMember(Name = "gt")]
public double? GreaterThan { get; set; }
[DataMember(Name = "gte")]
public double? GreaterThanOrEqualTo { get; set; }
[DataMember(Name = "lt")]
public double? LessThan { get; set; }
[DataMember(Name = "lte")]
public double? LessThanOrEqualTo { get; set; }
}
public class FloatRange
{
[DataMember(Name = "gt")]
public float? GreaterThan { get; set; }
[DataMember(Name = "gte")]
public float? GreaterThanOrEqualTo { get; set; }
[DataMember(Name = "lt")]
public float? LessThan { get; set; }
[DataMember(Name = "lte")]
public float? LessThanOrEqualTo { get; set; }
}
public class IntegerRange
{
[DataMember(Name = "gt")]
public int? GreaterThan { get; set; }
[DataMember(Name = "gte")]
public int? GreaterThanOrEqualTo { get; set; }
[DataMember(Name = "lt")]
public int? LessThan { get; set; }
[DataMember(Name = "lte")]
public int? LessThanOrEqualTo { get; set; }
}
public class LongRange
{
[DataMember(Name = "gt")]
public long? GreaterThan { get; set; }
[DataMember(Name = "gte")]
public long? GreaterThanOrEqualTo { get; set; }
[DataMember(Name = "lt")]
public long? LessThan { get; set; }
[DataMember(Name = "lte")]
public long? LessThanOrEqualTo { get; set; }
}
public class IpAddressRange
{
[DataMember(Name = "gt")]
public string GreaterThan { get; set; }
[DataMember(Name = "gte")]
public string GreaterThanOrEqualTo { get; set; }
[DataMember(Name = "lt")]
public string LessThan { get; set; }
[DataMember(Name = "lte")]
public string LessThanOrEqualTo { get; set; }
}
}
| 22.83 | 76 | 0.664477 | [
"Apache-2.0"
] | Brightspace/elasticsearch-net | src/Nest/CommonOptions/Range/Ranges.cs | 2,285 | C# |
namespace FSS.Omnius.Modules.Migrations.MSSQL
{
using System;
using System.Data.Entity.Migrations;
public partial class userAttributes : DbMigration
{
public override void Up()
{
AddColumn("dbo.Persona_Users", "DisplayName", c => c.String(nullable: false, maxLength: 100));
AddColumn("dbo.Persona_Users", "Email", c => c.String(maxLength: 100));
AddColumn("dbo.Persona_Users", "Company", c => c.String(maxLength: 100));
AddColumn("dbo.Persona_Users", "Department", c => c.String(maxLength: 100));
AddColumn("dbo.Persona_Users", "Team", c => c.String(maxLength: 100));
AddColumn("dbo.Persona_Users", "WorkPhone", c => c.String(maxLength: 20));
AddColumn("dbo.Persona_Users", "MobilPhone", c => c.String(maxLength: 20));
AddColumn("dbo.Persona_Users", "Address", c => c.String(maxLength: 500));
AddColumn("dbo.Persona_Users", "Job", c => c.String(maxLength: 100));
AddColumn("dbo.Persona_Users", "LastLogin", c => c.DateTime(nullable: false));
AddColumn("dbo.Persona_Users", "localExpiresAt", c => c.DateTime(nullable: false));
DropColumn("dbo.Persona_Users", "passwordHash");
}
public override void Down()
{
AddColumn("dbo.Persona_Users", "passwordHash", c => c.String(nullable: false));
DropColumn("dbo.Persona_Users", "localExpiresAt");
DropColumn("dbo.Persona_Users", "LastLogin");
DropColumn("dbo.Persona_Users", "Job");
DropColumn("dbo.Persona_Users", "Address");
DropColumn("dbo.Persona_Users", "MobilPhone");
DropColumn("dbo.Persona_Users", "WorkPhone");
DropColumn("dbo.Persona_Users", "Team");
DropColumn("dbo.Persona_Users", "Department");
DropColumn("dbo.Persona_Users", "Company");
DropColumn("dbo.Persona_Users", "Email");
DropColumn("dbo.Persona_Users", "DisplayName");
}
}
}
| 50.219512 | 106 | 0.601748 | [
"MIT"
] | simplifate/omnius | application/FSS.Omnius.Modules/Migrations/MSSQL/201512041443397_userAttributes.cs | 2,059 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BEditor.Extensions.FFmpeg.Encoding;
using BEditor.Media;
using BEditor.Media.Encoding;
using AudioCodec = FFMediaToolkit.Encoding.AudioCodec;
using EncoderPreset = FFMediaToolkit.Encoding.EncoderPreset;
using ImagePixelFormat = FFMediaToolkit.Graphics.ImagePixelFormat;
using SampleFormat = FFMediaToolkit.Audio.SampleFormat;
using VideoCodec = FFMediaToolkit.Encoding.VideoCodec;
namespace BEditor.Extensions.FFmpeg
{
public sealed class RegisterdEncoding : ISupportEncodingSettings
{
public string Name => "FFmpeg";
public IOutputContainer? Create(string file)
{
return new OutputContainer(file);
}
public AudioEncoderSettings GetDefaultAudioSettings()
{
return new(44100, 2)
{
CodecOptions =
{
{ "Format", SampleFormat.SingleP },
{ "Codec", AudioCodec.Default },
}
};
}
public VideoEncoderSettings GetDefaultVideoSettings()
{
return new(1920, 1080)
{
CodecOptions =
{
{ "Format", ImagePixelFormat.Yuv420 },
{ "Preset", EncoderPreset.Medium },
{ "Codec", VideoCodec.Default },
}
};
}
public IEnumerable<string> SupportExtensions()
{
yield return ".mp4";
yield return ".wav";
yield return ".mp3";
yield return ".wmv";
yield return ".avi";
yield return ".webm";
yield return ".3gp";
yield return ".3g2";
yield return ".flv";
yield return ".mkv";
yield return ".mov";
yield return ".ogv";
}
}
} | 28.285714 | 68 | 0.557071 | [
"MIT"
] | b-editor/BEditor | extensions/BEditor.Extensions.FFmpeg/RegisterdEncoding.cs | 1,982 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Media;
using Windows.System.Display;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
namespace AllPlayMediaPlayer
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
AllPlay.Service s;
private bool isSingleWindowDevice;
public MainPage()
{
this.InitializeComponent();
//mediaElement.TransportControls = controls;
s = new AllPlay.Service(mediaElement);
s.Start();
isSingleWindowDevice =
Windows.System.Profile.AnalyticsInfo.VersionInfo.DeviceFamily == "Windows.IoT" ||
Windows.System.Profile.AnalyticsInfo.VersionInfo.DeviceFamily == "Windows.Mobile" ||
Windows.System.Profile.AnalyticsInfo.VersionInfo.DeviceFamily == "Windows.XBox";
var systemMediaControls = SystemMediaTransportControls.GetForCurrentView();
//mediaElement.TransportControls = systemMediaControls;
systemMediaControls.ButtonPressed += SystemControls_ButtonPressed;
mediaElement.CurrentStateChanged += MediaElement_CurrentStateChanged;
}
private void MediaElement_CurrentStateChanged(object sender, RoutedEventArgs e)
{
UpdateScreensaverSettings();
}
private DisplayRequest appDisplayRequest;
private void UpdateScreensaverSettings()
{
bool enableScreenSaver = false;
if (mediaElement.IsFullWindow)
{
enableScreenSaver = true;
}
else if (isSingleWindowDevice)
{
enableScreenSaver = true;
}
if (mediaElement.IsAudioOnly == false) //Disable system screensaver if playing video
{
if (mediaElement.CurrentState == Windows.UI.Xaml.Media.MediaElementState.Playing)
{
if (isSingleWindowDevice) mediaElement.IsFullWindow = true; //on single window devices, go full screen for video
if (appDisplayRequest == null)
{
// This call creates an instance of the DisplayRequest object.
appDisplayRequest = new DisplayRequest();
appDisplayRequest.RequestActive();
enableScreenSaver = false;
}
}
else // CurrentState is Buffering, Closed, Opening, Paused, or Stopped.
{
if (appDisplayRequest != null)
{
// Deactivate the display request and set the var to null.
appDisplayRequest.RequestRelease();
appDisplayRequest = null;
}
}
}
else
{
if (isSingleWindowDevice) mediaElement.IsFullWindow = false;
}
Screensaver.IsScreensaverEnabled = enableScreenSaver;
Screensaver.ScreensaverUri = Playlist.CurrentItem?.ThumbnailUrl;
}
public AllPlay.Playlist Playlist
{
get
{
return s.Playlist;
}
}
private void SystemControls_ButtonPressed(SystemMediaTransportControls sender, SystemMediaTransportControlsButtonPressedEventArgs args)
{
switch(args.Button)
{
case SystemMediaTransportControlsButton.Next:
s.Playlist.MoveNext();
break;
case SystemMediaTransportControlsButton.Previous:
s.Playlist.MovePrevious();
break;
default: break;
}
}
}
}
| 36.118644 | 143 | 0.583294 | [
"Apache-2.0"
] | AndreasGocht/AllPlayMediaPlayer | src/AllPlayMediaPlayer/MainPage.xaml.cs | 4,264 | C# |
using System;
using System.IO;
using System.Linq;
using OfficeOpenXml;
using OfficeOpenXml.Style.XmlAccess;
namespace HelloEPPlus
{
class Program
{
static void Main(string[] args)
{
using (var package = new ExcelPackage())
{
var worksheet = package.Workbook.Worksheets.Add("Sheet1");
worksheet.Cells.Style.Font.Name = "游ゴシック";
worksheet.Cells["C3"].Value = "Hello World!";
package.SaveAs(new FileInfo("Result.xlsx"));
}
}
}
}
| 24.521739 | 74 | 0.56383 | [
"MIT"
] | nuitsjp/DioDocsStudy | HelloForExcel/HelloEPPlus/Program.cs | 576 | C# |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Runtime.Remoting.Lifetime;
using System.Threading;
using System.Reflection;
using System.Collections;
using System.Collections.Generic;
using OpenSim.Region.ScriptEngine.Interfaces;
using OpenSim.Region.ScriptEngine.Shared.Api.Interfaces;
using LSL_Float = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLFloat;
using LSL_Integer = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLInteger;
using LSL_Key = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString;
using LSL_List = OpenSim.Region.ScriptEngine.Shared.LSL_Types.list;
using LSL_Rotation = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Quaternion;
using LSL_String = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString;
using LSL_Vector = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Vector3;
namespace OpenSim.Region.ScriptEngine.Shared.ScriptBase
{
public partial class ScriptBaseClass : MarshalByRefObject
{
public ILSL_Api m_LSL_Functions;
public void ApiTypeLSL(IScriptApi api)
{
if (!(api is ILSL_Api))
return;
m_LSL_Functions = (ILSL_Api)api;
}
public void state(string newState)
{
m_LSL_Functions.state(newState);
}
//
// Script functions
//
public LSL_Integer llAbs(int i)
{
return m_LSL_Functions.llAbs(i);
}
public LSL_Float llAcos(double val)
{
return m_LSL_Functions.llAcos(val);
}
public void llAddToLandBanList(string avatar, double hours)
{
m_LSL_Functions.llAddToLandBanList(avatar, hours);
}
public void llAddToLandPassList(string avatar, double hours)
{
m_LSL_Functions.llAddToLandPassList(avatar, hours);
}
public void llAdjustSoundVolume(double volume)
{
m_LSL_Functions.llAdjustSoundVolume(volume);
}
public void llAllowInventoryDrop(int add)
{
m_LSL_Functions.llAllowInventoryDrop(add);
}
public LSL_Float llAngleBetween(LSL_Rotation a, LSL_Rotation b)
{
return m_LSL_Functions.llAngleBetween(a, b);
}
public void llApplyImpulse(LSL_Vector force, int local)
{
m_LSL_Functions.llApplyImpulse(force, local);
}
public void llApplyRotationalImpulse(LSL_Vector force, int local)
{
m_LSL_Functions.llApplyRotationalImpulse(force, local);
}
public LSL_Float llAsin(double val)
{
return m_LSL_Functions.llAsin(val);
}
public LSL_Float llAtan2(double x, double y)
{
return m_LSL_Functions.llAtan2(x, y);
}
public void llAttachToAvatar(int attachment)
{
m_LSL_Functions.llAttachToAvatar(attachment);
}
public LSL_Key llAvatarOnSitTarget()
{
return m_LSL_Functions.llAvatarOnSitTarget();
}
public LSL_Key llAvatarOnLinkSitTarget(int linknum)
{
return m_LSL_Functions.llAvatarOnLinkSitTarget(linknum);
}
public LSL_Rotation llAxes2Rot(LSL_Vector fwd, LSL_Vector left, LSL_Vector up)
{
return m_LSL_Functions.llAxes2Rot(fwd, left, up);
}
public LSL_Rotation llAxisAngle2Rot(LSL_Vector axis, double angle)
{
return m_LSL_Functions.llAxisAngle2Rot(axis, angle);
}
public LSL_Integer llBase64ToInteger(string str)
{
return m_LSL_Functions.llBase64ToInteger(str);
}
public LSL_String llBase64ToString(string str)
{
return m_LSL_Functions.llBase64ToString(str);
}
public void llBreakAllLinks()
{
m_LSL_Functions.llBreakAllLinks();
}
public void llBreakLink(int linknum)
{
m_LSL_Functions.llBreakLink(linknum);
}
public LSL_Integer llCeil(double f)
{
return m_LSL_Functions.llCeil(f);
}
public void llClearCameraParams()
{
m_LSL_Functions.llClearCameraParams();
}
public void llCloseRemoteDataChannel(string channel)
{
m_LSL_Functions.llCloseRemoteDataChannel(channel);
}
public LSL_Float llCloud(LSL_Vector offset)
{
return m_LSL_Functions.llCloud(offset);
}
public void llCollisionFilter(string name, string id, int accept)
{
m_LSL_Functions.llCollisionFilter(name, id, accept);
}
public void llCollisionSound(string impact_sound, double impact_volume)
{
m_LSL_Functions.llCollisionSound(impact_sound, impact_volume);
}
public void llCollisionSprite(string impact_sprite)
{
m_LSL_Functions.llCollisionSprite(impact_sprite);
}
public LSL_Float llCos(double f)
{
return m_LSL_Functions.llCos(f);
}
public void llCreateLink(string target, int parent)
{
m_LSL_Functions.llCreateLink(target, parent);
}
public LSL_List llCSV2List(string src)
{
return m_LSL_Functions.llCSV2List(src);
}
public LSL_List llDeleteSubList(LSL_List src, int start, int end)
{
return m_LSL_Functions.llDeleteSubList(src, start, end);
}
public LSL_String llDeleteSubString(string src, int start, int end)
{
return m_LSL_Functions.llDeleteSubString(src, start, end);
}
public void llDetachFromAvatar()
{
m_LSL_Functions.llDetachFromAvatar();
}
public LSL_Vector llDetectedGrab(int number)
{
return m_LSL_Functions.llDetectedGrab(number);
}
public LSL_Integer llDetectedGroup(int number)
{
return m_LSL_Functions.llDetectedGroup(number);
}
public LSL_Key llDetectedKey(int number)
{
return m_LSL_Functions.llDetectedKey(number);
}
public LSL_Integer llDetectedLinkNumber(int number)
{
return m_LSL_Functions.llDetectedLinkNumber(number);
}
public LSL_String llDetectedName(int number)
{
return m_LSL_Functions.llDetectedName(number);
}
public LSL_Key llDetectedOwner(int number)
{
return m_LSL_Functions.llDetectedOwner(number);
}
public LSL_Vector llDetectedPos(int number)
{
return m_LSL_Functions.llDetectedPos(number);
}
public LSL_Rotation llDetectedRot(int number)
{
return m_LSL_Functions.llDetectedRot(number);
}
public LSL_Integer llDetectedType(int number)
{
return m_LSL_Functions.llDetectedType(number);
}
public LSL_Vector llDetectedTouchBinormal(int index)
{
return m_LSL_Functions.llDetectedTouchBinormal(index);
}
public LSL_Integer llDetectedTouchFace(int index)
{
return m_LSL_Functions.llDetectedTouchFace(index);
}
public LSL_Vector llDetectedTouchNormal(int index)
{
return m_LSL_Functions.llDetectedTouchNormal(index);
}
public LSL_Vector llDetectedTouchPos(int index)
{
return m_LSL_Functions.llDetectedTouchPos(index);
}
public LSL_Vector llDetectedTouchST(int index)
{
return m_LSL_Functions.llDetectedTouchST(index);
}
public LSL_Vector llDetectedTouchUV(int index)
{
return m_LSL_Functions.llDetectedTouchUV(index);
}
public LSL_Vector llDetectedVel(int number)
{
return m_LSL_Functions.llDetectedVel(number);
}
public void llDialog(string avatar, string message, LSL_List buttons, int chat_channel)
{
m_LSL_Functions.llDialog(avatar, message, buttons, chat_channel);
}
public void llDie()
{
m_LSL_Functions.llDie();
}
public LSL_String llDumpList2String(LSL_List src, string seperator)
{
return m_LSL_Functions.llDumpList2String(src, seperator);
}
public LSL_Integer llEdgeOfWorld(LSL_Vector pos, LSL_Vector dir)
{
return m_LSL_Functions.llEdgeOfWorld(pos, dir);
}
public void llEjectFromLand(string pest)
{
m_LSL_Functions.llEjectFromLand(pest);
}
public void llEmail(string address, string subject, string message)
{
m_LSL_Functions.llEmail(address, subject, message);
}
public LSL_String llEscapeURL(string url)
{
return m_LSL_Functions.llEscapeURL(url);
}
public LSL_Rotation llEuler2Rot(LSL_Vector v)
{
return m_LSL_Functions.llEuler2Rot(v);
}
public LSL_Float llFabs(double f)
{
return m_LSL_Functions.llFabs(f);
}
public LSL_Integer llFloor(double f)
{
return m_LSL_Functions.llFloor(f);
}
public void llForceMouselook(int mouselook)
{
m_LSL_Functions.llForceMouselook(mouselook);
}
public LSL_Float llFrand(double mag)
{
return m_LSL_Functions.llFrand(mag);
}
public LSL_Key llGenerateKey()
{
return m_LSL_Functions.llGenerateKey();
}
public LSL_Vector llGetAccel()
{
return m_LSL_Functions.llGetAccel();
}
public LSL_Integer llGetAgentInfo(string id)
{
return m_LSL_Functions.llGetAgentInfo(id);
}
public LSL_String llGetAgentLanguage(string id)
{
return m_LSL_Functions.llGetAgentLanguage(id);
}
public LSL_List llGetAgentList(LSL_Integer scope, LSL_List options)
{
return m_LSL_Functions.llGetAgentList(scope, options);
}
public LSL_Vector llGetAgentSize(string id)
{
return m_LSL_Functions.llGetAgentSize(id);
}
public LSL_Float llGetAlpha(int face)
{
return m_LSL_Functions.llGetAlpha(face);
}
public LSL_Float llGetAndResetTime()
{
return m_LSL_Functions.llGetAndResetTime();
}
public LSL_String llGetAnimation(string id)
{
return m_LSL_Functions.llGetAnimation(id);
}
public LSL_List llGetAnimationList(string id)
{
return m_LSL_Functions.llGetAnimationList(id);
}
public LSL_Integer llGetAttached()
{
return m_LSL_Functions.llGetAttached();
}
public LSL_List llGetBoundingBox(string obj)
{
return m_LSL_Functions.llGetBoundingBox(obj);
}
public LSL_Vector llGetCameraPos()
{
return m_LSL_Functions.llGetCameraPos();
}
public LSL_Rotation llGetCameraRot()
{
return m_LSL_Functions.llGetCameraRot();
}
public LSL_Vector llGetCenterOfMass()
{
return m_LSL_Functions.llGetCenterOfMass();
}
public LSL_Vector llGetColor(int face)
{
return m_LSL_Functions.llGetColor(face);
}
public LSL_String llGetCreator()
{
return m_LSL_Functions.llGetCreator();
}
public LSL_String llGetDate()
{
return m_LSL_Functions.llGetDate();
}
public LSL_Float llGetEnergy()
{
return m_LSL_Functions.llGetEnergy();
}
public LSL_Vector llGetForce()
{
return m_LSL_Functions.llGetForce();
}
public LSL_Integer llGetFreeMemory()
{
return m_LSL_Functions.llGetFreeMemory();
}
public LSL_Integer llGetFreeURLs()
{
return m_LSL_Functions.llGetFreeURLs();
}
public LSL_Vector llGetGeometricCenter()
{
return m_LSL_Functions.llGetGeometricCenter();
}
public LSL_Float llGetGMTclock()
{
return m_LSL_Functions.llGetGMTclock();
}
public LSL_String llGetHTTPHeader(LSL_Key request_id, string header)
{
return m_LSL_Functions.llGetHTTPHeader(request_id, header);
}
public LSL_Key llGetInventoryCreator(string item)
{
return m_LSL_Functions.llGetInventoryCreator(item);
}
public LSL_Key llGetInventoryKey(string name)
{
return m_LSL_Functions.llGetInventoryKey(name);
}
public LSL_String llGetInventoryName(int type, int number)
{
return m_LSL_Functions.llGetInventoryName(type, number);
}
public LSL_Integer llGetInventoryNumber(int type)
{
return m_LSL_Functions.llGetInventoryNumber(type);
}
public LSL_Integer llGetInventoryPermMask(string item, int mask)
{
return m_LSL_Functions.llGetInventoryPermMask(item, mask);
}
public LSL_Integer llGetInventoryType(string name)
{
return m_LSL_Functions.llGetInventoryType(name);
}
public LSL_Key llGetKey()
{
return m_LSL_Functions.llGetKey();
}
public LSL_Key llGetLandOwnerAt(LSL_Vector pos)
{
return m_LSL_Functions.llGetLandOwnerAt(pos);
}
public LSL_Key llGetLinkKey(int linknum)
{
return m_LSL_Functions.llGetLinkKey(linknum);
}
public LSL_String llGetLinkName(int linknum)
{
return m_LSL_Functions.llGetLinkName(linknum);
}
public LSL_Integer llGetLinkNumber()
{
return m_LSL_Functions.llGetLinkNumber();
}
public LSL_Integer llGetLinkNumberOfSides(int link)
{
return m_LSL_Functions.llGetLinkNumberOfSides(link);
}
public void llSetKeyframedMotion(LSL_List frames, LSL_List options)
{
m_LSL_Functions.llSetKeyframedMotion(frames, options);
}
public LSL_Integer llGetListEntryType(LSL_List src, int index)
{
return m_LSL_Functions.llGetListEntryType(src, index);
}
public LSL_Integer llGetListLength(LSL_List src)
{
return m_LSL_Functions.llGetListLength(src);
}
public LSL_Vector llGetLocalPos()
{
return m_LSL_Functions.llGetLocalPos();
}
public LSL_Rotation llGetLocalRot()
{
return m_LSL_Functions.llGetLocalRot();
}
public LSL_Float llGetMass()
{
return m_LSL_Functions.llGetMass();
}
public LSL_Float llGetMassMKS()
{
return m_LSL_Functions.llGetMassMKS();
}
public LSL_Integer llGetMemoryLimit()
{
return m_LSL_Functions.llGetMemoryLimit();
}
public void llGetNextEmail(string address, string subject)
{
m_LSL_Functions.llGetNextEmail(address, subject);
}
public LSL_String llGetNotecardLine(string name, int line)
{
return m_LSL_Functions.llGetNotecardLine(name, line);
}
public LSL_Key llGetNumberOfNotecardLines(string name)
{
return m_LSL_Functions.llGetNumberOfNotecardLines(name);
}
public LSL_Integer llGetNumberOfPrims()
{
return m_LSL_Functions.llGetNumberOfPrims();
}
public LSL_Integer llGetNumberOfSides()
{
return m_LSL_Functions.llGetNumberOfSides();
}
public LSL_String llGetObjectDesc()
{
return m_LSL_Functions.llGetObjectDesc();
}
public LSL_List llGetObjectDetails(string id, LSL_List args)
{
return m_LSL_Functions.llGetObjectDetails(id, args);
}
public LSL_Float llGetObjectMass(string id)
{
return m_LSL_Functions.llGetObjectMass(id);
}
public LSL_String llGetObjectName()
{
return m_LSL_Functions.llGetObjectName();
}
public LSL_Integer llGetObjectPermMask(int mask)
{
return m_LSL_Functions.llGetObjectPermMask(mask);
}
public LSL_Integer llGetObjectPrimCount(string object_id)
{
return m_LSL_Functions.llGetObjectPrimCount(object_id);
}
public LSL_Vector llGetOmega()
{
return m_LSL_Functions.llGetOmega();
}
public LSL_Key llGetOwner()
{
return m_LSL_Functions.llGetOwner();
}
public LSL_Key llGetOwnerKey(string id)
{
return m_LSL_Functions.llGetOwnerKey(id);
}
public LSL_List llGetParcelDetails(LSL_Vector pos, LSL_List param)
{
return m_LSL_Functions.llGetParcelDetails(pos, param);
}
public LSL_Integer llGetParcelFlags(LSL_Vector pos)
{
return m_LSL_Functions.llGetParcelFlags(pos);
}
public LSL_Integer llGetParcelMaxPrims(LSL_Vector pos, int sim_wide)
{
return m_LSL_Functions.llGetParcelMaxPrims(pos, sim_wide);
}
public LSL_String llGetParcelMusicURL()
{
return m_LSL_Functions.llGetParcelMusicURL();
}
public LSL_Integer llGetParcelPrimCount(LSL_Vector pos, int category, int sim_wide)
{
return m_LSL_Functions.llGetParcelPrimCount(pos, category, sim_wide);
}
public LSL_List llGetParcelPrimOwners(LSL_Vector pos)
{
return m_LSL_Functions.llGetParcelPrimOwners(pos);
}
public LSL_Integer llGetPermissions()
{
return m_LSL_Functions.llGetPermissions();
}
public LSL_Key llGetPermissionsKey()
{
return m_LSL_Functions.llGetPermissionsKey();
}
public LSL_Vector llGetPos()
{
return m_LSL_Functions.llGetPos();
}
public LSL_List llGetPrimitiveParams(LSL_List rules)
{
return m_LSL_Functions.llGetPrimitiveParams(rules);
}
public LSL_List llGetLinkPrimitiveParams(int linknum, LSL_List rules)
{
return m_LSL_Functions.llGetLinkPrimitiveParams(linknum, rules);
}
public LSL_Integer llGetRegionAgentCount()
{
return m_LSL_Functions.llGetRegionAgentCount();
}
public LSL_Vector llGetRegionCorner()
{
return m_LSL_Functions.llGetRegionCorner();
}
public LSL_Integer llGetRegionFlags()
{
return m_LSL_Functions.llGetRegionFlags();
}
public LSL_Float llGetRegionFPS()
{
return m_LSL_Functions.llGetRegionFPS();
}
public LSL_String llGetRegionName()
{
return m_LSL_Functions.llGetRegionName();
}
public LSL_Float llGetRegionTimeDilation()
{
return m_LSL_Functions.llGetRegionTimeDilation();
}
public LSL_Vector llGetRootPosition()
{
return m_LSL_Functions.llGetRootPosition();
}
public LSL_Rotation llGetRootRotation()
{
return m_LSL_Functions.llGetRootRotation();
}
public LSL_Rotation llGetRot()
{
return m_LSL_Functions.llGetRot();
}
public LSL_Vector llGetScale()
{
return m_LSL_Functions.llGetScale();
}
public LSL_String llGetScriptName()
{
return m_LSL_Functions.llGetScriptName();
}
public LSL_Integer llGetScriptState(string name)
{
return m_LSL_Functions.llGetScriptState(name);
}
public LSL_String llGetSimulatorHostname()
{
return m_LSL_Functions.llGetSimulatorHostname();
}
public LSL_Integer llGetSPMaxMemory()
{
return m_LSL_Functions.llGetSPMaxMemory();
}
public LSL_Integer llGetStartParameter()
{
return m_LSL_Functions.llGetStartParameter();
}
public LSL_Integer llGetStatus(int status)
{
return m_LSL_Functions.llGetStatus(status);
}
public LSL_String llGetSubString(string src, int start, int end)
{
return m_LSL_Functions.llGetSubString(src, start, end);
}
public LSL_Vector llGetSunDirection()
{
return m_LSL_Functions.llGetSunDirection();
}
public LSL_String llGetTexture(int face)
{
return m_LSL_Functions.llGetTexture(face);
}
public LSL_Vector llGetTextureOffset(int face)
{
return m_LSL_Functions.llGetTextureOffset(face);
}
public LSL_Float llGetTextureRot(int side)
{
return m_LSL_Functions.llGetTextureRot(side);
}
public LSL_Vector llGetTextureScale(int side)
{
return m_LSL_Functions.llGetTextureScale(side);
}
public LSL_Float llGetTime()
{
return m_LSL_Functions.llGetTime();
}
public LSL_Float llGetTimeOfDay()
{
return m_LSL_Functions.llGetTimeOfDay();
}
public LSL_String llGetTimestamp()
{
return m_LSL_Functions.llGetTimestamp();
}
public LSL_Vector llGetTorque()
{
return m_LSL_Functions.llGetTorque();
}
public LSL_Integer llGetUnixTime()
{
return m_LSL_Functions.llGetUnixTime();
}
public LSL_Integer llGetUsedMemory()
{
return m_LSL_Functions.llGetUsedMemory();
}
public LSL_Vector llGetVel()
{
return m_LSL_Functions.llGetVel();
}
public LSL_Float llGetWallclock()
{
return m_LSL_Functions.llGetWallclock();
}
public void llGiveInventory(string destination, string inventory)
{
m_LSL_Functions.llGiveInventory(destination, inventory);
}
public void llGiveInventoryList(string destination, string category, LSL_List inventory)
{
m_LSL_Functions.llGiveInventoryList(destination, category, inventory);
}
public void llGiveMoney(string destination, int amount)
{
m_LSL_Functions.llGiveMoney(destination, amount);
}
public LSL_String llTransferLindenDollars(string destination, int amount)
{
return m_LSL_Functions.llTransferLindenDollars(destination, amount);
}
public void llGodLikeRezObject(string inventory, LSL_Vector pos)
{
m_LSL_Functions.llGodLikeRezObject(inventory, pos);
}
public LSL_Float llGround(LSL_Vector offset)
{
return m_LSL_Functions.llGround(offset);
}
public LSL_Vector llGroundContour(LSL_Vector offset)
{
return m_LSL_Functions.llGroundContour(offset);
}
public LSL_Vector llGroundNormal(LSL_Vector offset)
{
return m_LSL_Functions.llGroundNormal(offset);
}
public void llGroundRepel(double height, int water, double tau)
{
m_LSL_Functions.llGroundRepel(height, water, tau);
}
public LSL_Vector llGroundSlope(LSL_Vector offset)
{
return m_LSL_Functions.llGroundSlope(offset);
}
public LSL_String llHTTPRequest(string url, LSL_List parameters, string body)
{
return m_LSL_Functions.llHTTPRequest(url, parameters, body);
}
public void llHTTPResponse(LSL_Key id, int status, string body)
{
m_LSL_Functions.llHTTPResponse(id, status, body);
}
public LSL_String llInsertString(string dst, int position, string src)
{
return m_LSL_Functions.llInsertString(dst, position, src);
}
public void llInstantMessage(string user, string message)
{
m_LSL_Functions.llInstantMessage(user, message);
}
public LSL_String llIntegerToBase64(int number)
{
return m_LSL_Functions.llIntegerToBase64(number);
}
public LSL_String llKey2Name(string id)
{
return m_LSL_Functions.llKey2Name(id);
}
public LSL_String llGetUsername(string id)
{
return m_LSL_Functions.llGetUsername(id);
}
public LSL_String llRequestUsername(string id)
{
return m_LSL_Functions.llRequestUsername(id);
}
public LSL_String llGetDisplayName(string id)
{
return m_LSL_Functions.llGetDisplayName(id);
}
public LSL_String llRequestDisplayName(string id)
{
return m_LSL_Functions.llRequestDisplayName(id);
}
public LSL_List llCastRay(LSL_Vector start, LSL_Vector end, LSL_List options)
{
return m_LSL_Functions.llCastRay(start, end, options);
}
public void llLinkParticleSystem(int linknum, LSL_List rules)
{
m_LSL_Functions.llLinkParticleSystem(linknum, rules);
}
public LSL_String llList2CSV(LSL_List src)
{
return m_LSL_Functions.llList2CSV(src);
}
public LSL_Float llList2Float(LSL_List src, int index)
{
return m_LSL_Functions.llList2Float(src, index);
}
public LSL_Integer llList2Integer(LSL_List src, int index)
{
return m_LSL_Functions.llList2Integer(src, index);
}
public LSL_Key llList2Key(LSL_List src, int index)
{
return m_LSL_Functions.llList2Key(src, index);
}
public LSL_List llList2List(LSL_List src, int start, int end)
{
return m_LSL_Functions.llList2List(src, start, end);
}
public LSL_List llList2ListStrided(LSL_List src, int start, int end, int stride)
{
return m_LSL_Functions.llList2ListStrided(src, start, end, stride);
}
public LSL_Rotation llList2Rot(LSL_List src, int index)
{
return m_LSL_Functions.llList2Rot(src, index);
}
public LSL_String llList2String(LSL_List src, int index)
{
return m_LSL_Functions.llList2String(src, index);
}
public LSL_Vector llList2Vector(LSL_List src, int index)
{
return m_LSL_Functions.llList2Vector(src, index);
}
public LSL_Integer llListen(int channelID, string name, string ID, string msg)
{
return m_LSL_Functions.llListen(channelID, name, ID, msg);
}
public void llListenControl(int number, int active)
{
m_LSL_Functions.llListenControl(number, active);
}
public void llListenRemove(int number)
{
m_LSL_Functions.llListenRemove(number);
}
public LSL_Integer llListFindList(LSL_List src, LSL_List test)
{
return m_LSL_Functions.llListFindList(src, test);
}
public LSL_List llListInsertList(LSL_List dest, LSL_List src, int start)
{
return m_LSL_Functions.llListInsertList(dest, src, start);
}
public LSL_List llListRandomize(LSL_List src, int stride)
{
return m_LSL_Functions.llListRandomize(src, stride);
}
public LSL_List llListReplaceList(LSL_List dest, LSL_List src, int start, int end)
{
return m_LSL_Functions.llListReplaceList(dest, src, start, end);
}
public LSL_List llListSort(LSL_List src, int stride, int ascending)
{
return m_LSL_Functions.llListSort(src, stride, ascending);
}
public LSL_Float llListStatistics(int operation, LSL_List src)
{
return m_LSL_Functions.llListStatistics(operation, src);
}
public void llLoadURL(string avatar_id, string message, string url)
{
m_LSL_Functions.llLoadURL(avatar_id, message, url);
}
public LSL_Float llLog(double val)
{
return m_LSL_Functions.llLog(val);
}
public LSL_Float llLog10(double val)
{
return m_LSL_Functions.llLog10(val);
}
public void llLookAt(LSL_Vector target, double strength, double damping)
{
m_LSL_Functions.llLookAt(target, strength, damping);
}
public void llLoopSound(string sound, double volume)
{
m_LSL_Functions.llLoopSound(sound, volume);
}
public void llLoopSoundMaster(string sound, double volume)
{
m_LSL_Functions.llLoopSoundMaster(sound, volume);
}
public void llLoopSoundSlave(string sound, double volume)
{
m_LSL_Functions.llLoopSoundSlave(sound, volume);
}
public LSL_Integer llManageEstateAccess(int action, string avatar)
{
return m_LSL_Functions.llManageEstateAccess(action, avatar);
}
public void llMakeExplosion(int particles, double scale, double vel, double lifetime, double arc, string texture, LSL_Vector offset)
{
m_LSL_Functions.llMakeExplosion(particles, scale, vel, lifetime, arc, texture, offset);
}
public void llMakeFire(int particles, double scale, double vel, double lifetime, double arc, string texture, LSL_Vector offset)
{
m_LSL_Functions.llMakeFire(particles, scale, vel, lifetime, arc, texture, offset);
}
public void llMakeFountain(int particles, double scale, double vel, double lifetime, double arc, int bounce, string texture, LSL_Vector offset, double bounce_offset)
{
m_LSL_Functions.llMakeFountain(particles, scale, vel, lifetime, arc, bounce, texture, offset, bounce_offset);
}
public void llMakeSmoke(int particles, double scale, double vel, double lifetime, double arc, string texture, LSL_Vector offset)
{
m_LSL_Functions.llMakeSmoke(particles, scale, vel, lifetime, arc, texture, offset);
}
public void llMapDestination(string simname, LSL_Vector pos, LSL_Vector look_at)
{
m_LSL_Functions.llMapDestination(simname, pos, look_at);
}
public LSL_String llMD5String(string src, int nonce)
{
return m_LSL_Functions.llMD5String(src, nonce);
}
public LSL_String llSHA1String(string src)
{
return m_LSL_Functions.llSHA1String(src);
}
public void llMessageLinked(int linknum, int num, string str, string id)
{
m_LSL_Functions.llMessageLinked(linknum, num, str, id);
}
public void llMinEventDelay(double delay)
{
m_LSL_Functions.llMinEventDelay(delay);
}
public void llModifyLand(int action, int brush)
{
m_LSL_Functions.llModifyLand(action, brush);
}
public LSL_Integer llModPow(int a, int b, int c)
{
return m_LSL_Functions.llModPow(a, b, c);
}
public void llMoveToTarget(LSL_Vector target, double tau)
{
m_LSL_Functions.llMoveToTarget(target, tau);
}
public void llOffsetTexture(double u, double v, int face)
{
m_LSL_Functions.llOffsetTexture(u, v, face);
}
public void llOpenRemoteDataChannel()
{
m_LSL_Functions.llOpenRemoteDataChannel();
}
public LSL_Integer llOverMyLand(string id)
{
return m_LSL_Functions.llOverMyLand(id);
}
public void llOwnerSay(string msg)
{
m_LSL_Functions.llOwnerSay(msg);
}
public void llParcelMediaCommandList(LSL_List commandList)
{
m_LSL_Functions.llParcelMediaCommandList(commandList);
}
public LSL_List llParcelMediaQuery(LSL_List aList)
{
return m_LSL_Functions.llParcelMediaQuery(aList);
}
public LSL_List llParseString2List(string str, LSL_List separators, LSL_List spacers)
{
return m_LSL_Functions.llParseString2List(str, separators, spacers);
}
public LSL_List llParseStringKeepNulls(string src, LSL_List seperators, LSL_List spacers)
{
return m_LSL_Functions.llParseStringKeepNulls(src, seperators, spacers);
}
public void llParticleSystem(LSL_List rules)
{
m_LSL_Functions.llParticleSystem(rules);
}
public void llPassCollisions(int pass)
{
m_LSL_Functions.llPassCollisions(pass);
}
public void llPassTouches(int pass)
{
m_LSL_Functions.llPassTouches(pass);
}
public void llPlaySound(string sound, double volume)
{
m_LSL_Functions.llPlaySound(sound, volume);
}
public void llPlaySoundSlave(string sound, double volume)
{
m_LSL_Functions.llPlaySoundSlave(sound, volume);
}
public void llPointAt(LSL_Vector pos)
{
m_LSL_Functions.llPointAt(pos);
}
public LSL_Float llPow(double fbase, double fexponent)
{
return m_LSL_Functions.llPow(fbase, fexponent);
}
public void llPreloadSound(string sound)
{
m_LSL_Functions.llPreloadSound(sound);
}
public void llPushObject(string target, LSL_Vector impulse, LSL_Vector ang_impulse, int local)
{
m_LSL_Functions.llPushObject(target, impulse, ang_impulse, local);
}
public void llRefreshPrimURL()
{
m_LSL_Functions.llRefreshPrimURL();
}
public void llRegionSay(int channelID, string text)
{
m_LSL_Functions.llRegionSay(channelID, text);
}
public void llRegionSayTo(string key, int channelID, string text)
{
m_LSL_Functions.llRegionSayTo(key, channelID, text);
}
public void llReleaseCamera(string avatar)
{
m_LSL_Functions.llReleaseCamera(avatar);
}
public void llReleaseURL(string url)
{
m_LSL_Functions.llReleaseURL(url);
}
public void llReleaseControls()
{
m_LSL_Functions.llReleaseControls();
}
public void llRemoteDataReply(string channel, string message_id, string sdata, int idata)
{
m_LSL_Functions.llRemoteDataReply(channel, message_id, sdata, idata);
}
public void llRemoteDataSetRegion()
{
m_LSL_Functions.llRemoteDataSetRegion();
}
public void llRemoteLoadScript(string target, string name, int running, int start_param)
{
m_LSL_Functions.llRemoteLoadScript(target, name, running, start_param);
}
public void llRemoteLoadScriptPin(string target, string name, int pin, int running, int start_param)
{
m_LSL_Functions.llRemoteLoadScriptPin(target, name, pin, running, start_param);
}
public void llRemoveFromLandBanList(string avatar)
{
m_LSL_Functions.llRemoveFromLandBanList(avatar);
}
public void llRemoveFromLandPassList(string avatar)
{
m_LSL_Functions.llRemoveFromLandPassList(avatar);
}
public void llRemoveInventory(string item)
{
m_LSL_Functions.llRemoveInventory(item);
}
public void llRemoveVehicleFlags(int flags)
{
m_LSL_Functions.llRemoveVehicleFlags(flags);
}
public LSL_Key llRequestAgentData(string id, int data)
{
return m_LSL_Functions.llRequestAgentData(id, data);
}
public LSL_Key llRequestInventoryData(string name)
{
return m_LSL_Functions.llRequestInventoryData(name);
}
public void llRequestPermissions(string agent, int perm)
{
m_LSL_Functions.llRequestPermissions(agent, perm);
}
public LSL_String llRequestSecureURL()
{
return m_LSL_Functions.llRequestSecureURL();
}
public LSL_Key llRequestSimulatorData(string simulator, int data)
{
return m_LSL_Functions.llRequestSimulatorData(simulator, data);
}
public LSL_Key llRequestURL()
{
return m_LSL_Functions.llRequestURL();
}
public void llResetLandBanList()
{
m_LSL_Functions.llResetLandBanList();
}
public void llResetLandPassList()
{
m_LSL_Functions.llResetLandPassList();
}
public void llResetOtherScript(string name)
{
m_LSL_Functions.llResetOtherScript(name);
}
public void llResetScript()
{
m_LSL_Functions.llResetScript();
}
public void llResetTime()
{
m_LSL_Functions.llResetTime();
}
public void llRezAtRoot(string inventory, LSL_Vector position, LSL_Vector velocity, LSL_Rotation rot, int param)
{
m_LSL_Functions.llRezAtRoot(inventory, position, velocity, rot, param);
}
public void llRezObject(string inventory, LSL_Vector pos, LSL_Vector vel, LSL_Rotation rot, int param)
{
m_LSL_Functions.llRezObject(inventory, pos, vel, rot, param);
}
public LSL_Float llRot2Angle(LSL_Rotation rot)
{
return m_LSL_Functions.llRot2Angle(rot);
}
public LSL_Vector llRot2Axis(LSL_Rotation rot)
{
return m_LSL_Functions.llRot2Axis(rot);
}
public LSL_Vector llRot2Euler(LSL_Rotation r)
{
return m_LSL_Functions.llRot2Euler(r);
}
public LSL_Vector llRot2Fwd(LSL_Rotation r)
{
return m_LSL_Functions.llRot2Fwd(r);
}
public LSL_Vector llRot2Left(LSL_Rotation r)
{
return m_LSL_Functions.llRot2Left(r);
}
public LSL_Vector llRot2Up(LSL_Rotation r)
{
return m_LSL_Functions.llRot2Up(r);
}
public void llRotateTexture(double rotation, int face)
{
m_LSL_Functions.llRotateTexture(rotation, face);
}
public LSL_Rotation llRotBetween(LSL_Vector start, LSL_Vector end)
{
return m_LSL_Functions.llRotBetween(start, end);
}
public void llRotLookAt(LSL_Rotation target, double strength, double damping)
{
m_LSL_Functions.llRotLookAt(target, strength, damping);
}
public LSL_Integer llRotTarget(LSL_Rotation rot, double error)
{
return m_LSL_Functions.llRotTarget(rot, error);
}
public void llRotTargetRemove(int number)
{
m_LSL_Functions.llRotTargetRemove(number);
}
public LSL_Integer llRound(double f)
{
return m_LSL_Functions.llRound(f);
}
public LSL_Integer llSameGroup(string agent)
{
return m_LSL_Functions.llSameGroup(agent);
}
public void llSay(int channelID, string text)
{
m_LSL_Functions.llSay(channelID, text);
}
public void llScaleTexture(double u, double v, int face)
{
m_LSL_Functions.llScaleTexture(u, v, face);
}
public LSL_Integer llScriptDanger(LSL_Vector pos)
{
return m_LSL_Functions.llScriptDanger(pos);
}
public void llScriptProfiler(LSL_Integer flags)
{
m_LSL_Functions.llScriptProfiler(flags);
}
public LSL_Key llSendRemoteData(string channel, string dest, int idata, string sdata)
{
return m_LSL_Functions.llSendRemoteData(channel, dest, idata, sdata);
}
public void llSensor(string name, string id, int type, double range, double arc)
{
m_LSL_Functions.llSensor(name, id, type, range, arc);
}
public void llSensorRemove()
{
m_LSL_Functions.llSensorRemove();
}
public void llSensorRepeat(string name, string id, int type, double range, double arc, double rate)
{
m_LSL_Functions.llSensorRepeat(name, id, type, range, arc, rate);
}
public void llSetAlpha(double alpha, int face)
{
m_LSL_Functions.llSetAlpha(alpha, face);
}
public void llSetBuoyancy(double buoyancy)
{
m_LSL_Functions.llSetBuoyancy(buoyancy);
}
public void llSetCameraAtOffset(LSL_Vector offset)
{
m_LSL_Functions.llSetCameraAtOffset(offset);
}
public void llSetCameraEyeOffset(LSL_Vector offset)
{
m_LSL_Functions.llSetCameraEyeOffset(offset);
}
public void llSetLinkCamera(LSL_Integer link, LSL_Vector eye, LSL_Vector at)
{
m_LSL_Functions.llSetLinkCamera(link, eye, at);
}
public void llSetCameraParams(LSL_List rules)
{
m_LSL_Functions.llSetCameraParams(rules);
}
public void llSetClickAction(int action)
{
m_LSL_Functions.llSetClickAction(action);
}
public void llSetColor(LSL_Vector color, int face)
{
m_LSL_Functions.llSetColor(color, face);
}
public void llSetContentType(LSL_Key id, LSL_Integer type)
{
m_LSL_Functions.llSetContentType(id, type);
}
public void llSetDamage(double damage)
{
m_LSL_Functions.llSetDamage(damage);
}
public void llSetForce(LSL_Vector force, int local)
{
m_LSL_Functions.llSetForce(force, local);
}
public void llSetForceAndTorque(LSL_Vector force, LSL_Vector torque, int local)
{
m_LSL_Functions.llSetForceAndTorque(force, torque, local);
}
public void llSetVelocity(LSL_Vector force, int local)
{
m_LSL_Functions.llSetVelocity(force, local);
}
public void llSetAngularVelocity(LSL_Vector force, int local)
{
m_LSL_Functions.llSetAngularVelocity(force, local);
}
public void llSetHoverHeight(double height, int water, double tau)
{
m_LSL_Functions.llSetHoverHeight(height, water, tau);
}
public void llSetInventoryPermMask(string item, int mask, int value)
{
m_LSL_Functions.llSetInventoryPermMask(item, mask, value);
}
public void llSetLinkAlpha(int linknumber, double alpha, int face)
{
m_LSL_Functions.llSetLinkAlpha(linknumber, alpha, face);
}
public void llSetLinkColor(int linknumber, LSL_Vector color, int face)
{
m_LSL_Functions.llSetLinkColor(linknumber, color, face);
}
public void llSetLinkPrimitiveParams(int linknumber, LSL_List rules)
{
m_LSL_Functions.llSetLinkPrimitiveParams(linknumber, rules);
}
public void llSetLinkTexture(int linknumber, string texture, int face)
{
m_LSL_Functions.llSetLinkTexture(linknumber, texture, face);
}
public void llSetLinkTextureAnim(int linknum, int mode, int face, int sizex, int sizey, double start, double length, double rate)
{
m_LSL_Functions.llSetLinkTextureAnim(linknum, mode, face, sizex, sizey, start, length, rate);
}
public void llSetLocalRot(LSL_Rotation rot)
{
m_LSL_Functions.llSetLocalRot(rot);
}
public LSL_Integer llSetMemoryLimit(LSL_Integer limit)
{
return m_LSL_Functions.llSetMemoryLimit(limit);
}
public void llSetObjectDesc(string desc)
{
m_LSL_Functions.llSetObjectDesc(desc);
}
public void llSetObjectName(string name)
{
m_LSL_Functions.llSetObjectName(name);
}
public void llSetObjectPermMask(int mask, int value)
{
m_LSL_Functions.llSetObjectPermMask(mask, value);
}
public void llSetParcelMusicURL(string url)
{
m_LSL_Functions.llSetParcelMusicURL(url);
}
public void llSetPayPrice(int price, LSL_List quick_pay_buttons)
{
m_LSL_Functions.llSetPayPrice(price, quick_pay_buttons);
}
public void llSetPos(LSL_Vector pos)
{
m_LSL_Functions.llSetPos(pos);
}
public void llSetPrimitiveParams(LSL_List rules)
{
m_LSL_Functions.llSetPrimitiveParams(rules);
}
public void llSetLinkPrimitiveParamsFast(int linknum, LSL_List rules)
{
m_LSL_Functions.llSetLinkPrimitiveParamsFast(linknum, rules);
}
public void llSetPrimURL(string url)
{
m_LSL_Functions.llSetPrimURL(url);
}
public LSL_Integer llSetRegionPos(LSL_Vector pos)
{
return m_LSL_Functions.llSetRegionPos(pos);
}
public void llSetRemoteScriptAccessPin(int pin)
{
m_LSL_Functions.llSetRemoteScriptAccessPin(pin);
}
public void llSetRot(LSL_Rotation rot)
{
m_LSL_Functions.llSetRot(rot);
}
public void llSetScale(LSL_Vector scale)
{
m_LSL_Functions.llSetScale(scale);
}
public void llSetScriptState(string name, int run)
{
m_LSL_Functions.llSetScriptState(name, run);
}
public void llSetSitText(string text)
{
m_LSL_Functions.llSetSitText(text);
}
public void llSetSoundQueueing(int queue)
{
m_LSL_Functions.llSetSoundQueueing(queue);
}
public void llSetSoundRadius(double radius)
{
m_LSL_Functions.llSetSoundRadius(radius);
}
public void llSetStatus(int status, int value)
{
m_LSL_Functions.llSetStatus(status, value);
}
public void llSetText(string text, LSL_Vector color, double alpha)
{
m_LSL_Functions.llSetText(text, color, alpha);
}
public void llSetTexture(string texture, int face)
{
m_LSL_Functions.llSetTexture(texture, face);
}
public void llSetTextureAnim(int mode, int face, int sizex, int sizey, double start, double length, double rate)
{
m_LSL_Functions.llSetTextureAnim(mode, face, sizex, sizey, start, length, rate);
}
public void llSetTimerEvent(double sec)
{
m_LSL_Functions.llSetTimerEvent(sec);
}
public void llSetTorque(LSL_Vector torque, int local)
{
m_LSL_Functions.llSetTorque(torque, local);
}
public void llSetTouchText(string text)
{
m_LSL_Functions.llSetTouchText(text);
}
public void llSetVehicleFlags(int flags)
{
m_LSL_Functions.llSetVehicleFlags(flags);
}
public void llSetVehicleFloatParam(int param, LSL_Float value)
{
m_LSL_Functions.llSetVehicleFloatParam(param, value);
}
public void llSetVehicleRotationParam(int param, LSL_Rotation rot)
{
m_LSL_Functions.llSetVehicleRotationParam(param, rot);
}
public void llSetVehicleType(int type)
{
m_LSL_Functions.llSetVehicleType(type);
}
public void llSetVehicleVectorParam(int param, LSL_Vector vec)
{
m_LSL_Functions.llSetVehicleVectorParam(param, vec);
}
public void llShout(int channelID, string text)
{
m_LSL_Functions.llShout(channelID, text);
}
public LSL_Float llSin(double f)
{
return m_LSL_Functions.llSin(f);
}
public void llSitTarget(LSL_Vector offset, LSL_Rotation rot)
{
m_LSL_Functions.llSitTarget(offset, rot);
}
public void llLinkSitTarget(LSL_Integer link, LSL_Vector offset, LSL_Rotation rot)
{
m_LSL_Functions.llLinkSitTarget(link, offset, rot);
}
public void llSleep(double sec)
{
m_LSL_Functions.llSleep(sec);
}
public void llSound(string sound, double volume, int queue, int loop)
{
m_LSL_Functions.llSound(sound, volume, queue, loop);
}
public void llSoundPreload(string sound)
{
m_LSL_Functions.llSoundPreload(sound);
}
public LSL_Float llSqrt(double f)
{
return m_LSL_Functions.llSqrt(f);
}
public void llStartAnimation(string anim)
{
m_LSL_Functions.llStartAnimation(anim);
}
public void llStopAnimation(string anim)
{
m_LSL_Functions.llStopAnimation(anim);
}
public void llStopHover()
{
m_LSL_Functions.llStopHover();
}
public void llStopLookAt()
{
m_LSL_Functions.llStopLookAt();
}
public void llStopMoveToTarget()
{
m_LSL_Functions.llStopMoveToTarget();
}
public void llStopPointAt()
{
m_LSL_Functions.llStopPointAt();
}
public void llStopSound()
{
m_LSL_Functions.llStopSound();
}
public LSL_Integer llStringLength(string str)
{
return m_LSL_Functions.llStringLength(str);
}
public LSL_String llStringToBase64(string str)
{
return m_LSL_Functions.llStringToBase64(str);
}
public LSL_String llStringTrim(string src, int type)
{
return m_LSL_Functions.llStringTrim(src, type);
}
public LSL_Integer llSubStringIndex(string source, string pattern)
{
return m_LSL_Functions.llSubStringIndex(source, pattern);
}
public void llTakeCamera(string avatar)
{
m_LSL_Functions.llTakeCamera(avatar);
}
public void llTakeControls(int controls, int accept, int pass_on)
{
m_LSL_Functions.llTakeControls(controls, accept, pass_on);
}
public LSL_Float llTan(double f)
{
return m_LSL_Functions.llTan(f);
}
public LSL_Integer llTarget(LSL_Vector position, double range)
{
return m_LSL_Functions.llTarget(position, range);
}
public void llTargetOmega(LSL_Vector axis, double spinrate, double gain)
{
m_LSL_Functions.llTargetOmega(axis, spinrate, gain);
}
public void llTargetRemove(int number)
{
m_LSL_Functions.llTargetRemove(number);
}
public void llTeleportAgent(string agent, string simname, LSL_Vector pos, LSL_Vector lookAt)
{
m_LSL_Functions.llTeleportAgent(agent, simname, pos, lookAt);
}
public void llTeleportAgentGlobalCoords(string agent, LSL_Vector global, LSL_Vector pos, LSL_Vector lookAt)
{
m_LSL_Functions.llTeleportAgentGlobalCoords(agent, global, pos, lookAt);
}
public void llTeleportAgentHome(string agent)
{
m_LSL_Functions.llTeleportAgentHome(agent);
}
public void llTextBox(string avatar, string message, int chat_channel)
{
m_LSL_Functions.llTextBox(avatar, message, chat_channel);
}
public LSL_String llToLower(string source)
{
return m_LSL_Functions.llToLower(source);
}
public LSL_String llToUpper(string source)
{
return m_LSL_Functions.llToUpper(source);
}
public void llTriggerSound(string sound, double volume)
{
m_LSL_Functions.llTriggerSound(sound, volume);
}
public void llTriggerSoundLimited(string sound, double volume, LSL_Vector top_north_east, LSL_Vector bottom_south_west)
{
m_LSL_Functions.llTriggerSoundLimited(sound, volume, top_north_east, bottom_south_west);
}
public LSL_String llUnescapeURL(string url)
{
return m_LSL_Functions.llUnescapeURL(url);
}
public void llUnSit(string id)
{
m_LSL_Functions.llUnSit(id);
}
public LSL_Float llVecDist(LSL_Vector a, LSL_Vector b)
{
return m_LSL_Functions.llVecDist(a, b);
}
public LSL_Float llVecMag(LSL_Vector v)
{
return m_LSL_Functions.llVecMag(v);
}
public LSL_Vector llVecNorm(LSL_Vector v)
{
return m_LSL_Functions.llVecNorm(v);
}
public void llVolumeDetect(int detect)
{
m_LSL_Functions.llVolumeDetect(detect);
}
public LSL_Float llWater(LSL_Vector offset)
{
return m_LSL_Functions.llWater(offset);
}
public void llWhisper(int channelID, string text)
{
m_LSL_Functions.llWhisper(channelID, text);
}
public LSL_Vector llWind(LSL_Vector offset)
{
return m_LSL_Functions.llWind(offset);
}
public LSL_String llXorBase64Strings(string str1, string str2)
{
return m_LSL_Functions.llXorBase64Strings(str1, str2);
}
public LSL_String llXorBase64StringsCorrect(string str1, string str2)
{
return m_LSL_Functions.llXorBase64StringsCorrect(str1, str2);
}
public LSL_List llGetPrimMediaParams(int face, LSL_List rules)
{
return m_LSL_Functions.llGetPrimMediaParams(face, rules);
}
public LSL_List llGetLinkMedia(LSL_Integer link, LSL_Integer face, LSL_List rules)
{
return m_LSL_Functions.llGetLinkMedia(link, face, rules);
}
public LSL_Integer llSetPrimMediaParams(int face, LSL_List rules)
{
return m_LSL_Functions.llSetPrimMediaParams(face, rules);
}
public LSL_Integer llSetLinkMedia(LSL_Integer link, LSL_Integer face, LSL_List rules)
{
return m_LSL_Functions.llSetLinkMedia(link, face, rules);
}
public LSL_Integer llClearPrimMedia(LSL_Integer face)
{
return m_LSL_Functions.llClearPrimMedia(face);
}
public LSL_Integer llClearLinkMedia(LSL_Integer link, LSL_Integer face)
{
return m_LSL_Functions.llClearLinkMedia(link, face);
}
public void print(string str)
{
m_LSL_Functions.print(str);
}
}
}
| 28.57505 | 173 | 0.6095 | [
"BSD-3-Clause"
] | AlericInglewood/opensimulator | OpenSim/Region/ScriptEngine/Shared/Api/Runtime/LSL_Stub.cs | 57,493 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PickUpVolume : MonoBehaviour
{
[SerializeField] GameObject holder;
private List<GameObject> pickupObjects = new List<GameObject>();
private void OnTriggerEnter(Collider other)
{
if(pickupObjects.Contains(other.gameObject))
{
return;
}
PickUpItem pickupItem = other.GetComponent<PickUpItem>();
if(pickupItem != null)
{
pickupObjects.Add(other.gameObject);
}
}
private void OnTriggerExit(Collider other)
{
PickUpItem pickUpItem = other.GetComponent<PickUpItem>();
if(pickUpItem != null)
{
pickupObjects.Remove(other.gameObject);
}
}
public GameObject PickupItem()
{
// Clear dead references and test size
pickupObjects.RemoveAll(item => item == null || item.GetComponent<PickUpItem>().isPickedUp == true);
if(pickupObjects.Count <= 0)
{
return null;
}
KeyValuePair<float, GameObject> closestObj = new KeyValuePair<float, GameObject>(99999, null);
foreach(GameObject obj in pickupObjects)
{
if(closestObj.Value == null)
{
closestObj = new KeyValuePair<float, GameObject>(Vector3.Distance(holder.gameObject.transform.position, obj.transform.position), obj);
continue;
}
if(Vector3.Distance(holder.gameObject.transform.position, obj.transform.position) < closestObj.Key)
{
closestObj = new KeyValuePair<float, GameObject>(Vector3.Distance(holder.gameObject.transform.position, obj.transform.position), obj);
}
}
return closestObj.Value;
}
}
| 29.33871 | 150 | 0.616273 | [
"Apache-2.0"
] | Karamu98/GamesJam2019 | GamesJam2019/Assets/PickUpVolume.cs | 1,821 | C# |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="MaterialControl.xaml.cs" company="Helix Toolkit">
// Copyright (c) 2014 Helix Toolkit contributors
// </copyright>
// <summary>
// Interaction logic for MaterialControl.xaml
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace EnvironmentMapDemo
{
using System;
using System.Windows.Controls;
using System.Windows.Data;
using HelixToolkit.Wpf.SharpDX;
/// <summary>
/// Interaction logic for MaterialControl.xaml
/// </summary>
public partial class MaterialControl : UserControl
{
public MaterialControl()
{
InitializeComponent();
}
}
public class ColorConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
var c = (global::SharpDX.Color4)value;
return c.ToColor();
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
var c = (System.Windows.Media.Color)value;
return c.ToColor4();
}
}
} | 33.325581 | 125 | 0.506629 | [
"MIT"
] | B3zaleel/helix-toolkit | Source/Examples/WPF.SharpDX/EnvironmentMapDemo/MaterialControl.xaml.cs | 1,435 | C# |
using System.ComponentModel.DataAnnotations;
namespace AspNetZeroOrganisationUnitClone.Users.Dto
{
public class ChangePasswordDto
{
[Required]
public string CurrentPassword { get; set; }
[Required]
public string NewPassword { get; set; }
}
}
| 20.642857 | 51 | 0.67128 | [
"MIT"
] | CiscoNinja/AspNetZeroOrganisationUnitClone | aspnet-core/src/AspNetZeroOrganisationUnitClone.Application/Users/Dto/ChangePasswordDto.cs | 291 | C# |
#region copyright
/*
* Copyright (c) 2018 Sveriges Radio AB, Stockholm, Sweden
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#endregion
namespace CodecControl.Web.Models.Requests
{
public class SetInputEnabledRequest : RequestBase
{
public int Input { get; set; }
public bool Enabled { get; set; }
}
} | 47.027778 | 76 | 0.75251 | [
"BSD-3-Clause"
] | IrisBroadcast/CodecControl | src/CodecControl.Web/Models/Requests/SetInputEnabledRequest.cs | 1,695 | C# |
namespace p02.AnonymousVox
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
public class StartUp
{
public static void Main()
{
string text = Console.ReadLine();
//string[] placeholders = Console.ReadLine()
// .Split("{}"
// .ToCharArray(), StringSplitOptions.RemoveEmptyEntries); -> different way
//string[] placeholders = Console.ReadLine()
//.Split(new char[] { '{', '}' }
//, StringSplitOptions.RemoveEmptyEntries); -> the same thing, different way
string[] placeholders = Regex.Split(Console.ReadLine(), "[{}]")
.Where(e => e != "")
.ToArray();
string pattern = @"([a-zA-Z]+)(.*)(\1)";
MatchCollection matches = Regex.Matches(text, pattern);
int count = 0;
foreach (Match item in matches)
{
string newValue = item.Groups[1] + placeholders[count++] + item.Groups[3];
text = text.Replace(item.Value, newValue);
}
Console.WriteLine(text);
}
}
}
| 29.340909 | 100 | 0.523625 | [
"MIT"
] | GitHarr/SoftUni | Homework/TechModule/ProgramingFundamentals-Extended/3.Strings, Regular Expressions and Text Processing/Exercises/p02.AnonymousVox/STartUp.cs | 1,293 | C# |
using System;
using System.Xml.Serialization;
namespace Alipay.AopSdk.Domain
{
/// <summary>
/// KoubeiMarketingCampaignRetailDmSetModel Data Structure.
/// </summary>
[Serializable]
public class KoubeiMarketingCampaignRetailDmSetModel : AopObject
{
/// <summary>
/// 下架时间,仅上架操作时使用,必须晚于当前时间
/// </summary>
[XmlElement("campaign_end_time")]
public string CampaignEndTime { get; set; }
/// <summary>
/// 内容ID,调用koubei.marketing.campaign.retail.dm.create创建内容时返回的内容ID
/// </summary>
[XmlElement("content_id")]
public string ContentId { get; set; }
/// <summary>
/// 上下架操作类型,上架:ONLINE,下架:OFFLINE,注意:请先调用创建内容接口再进行上架操作,下架内容不得再上架。
/// </summary>
[XmlElement("operate_type")]
public string OperateType { get; set; }
}
}
| 27.806452 | 73 | 0.613689 | [
"MIT"
] | ArcherTrister/LeXun.Alipay.AopSdk | src/Alipay.AopSdk/Domain/KoubeiMarketingCampaignRetailDmSetModel.cs | 1,030 | C# |
namespace AlephVault.Unity.Binary
{
namespace Wrappers
{
/// <summary>
/// A serializable wrapper around a <see cref="char"/> value.
/// </summary>
public class Char : Wrapper<char>
{
public Char(char wrapped) : base(wrapped) { }
public Char() : base() { }
/// <summary>
/// The serialization is done by doing it over the internal
/// delta value member.
/// </summary>
/// <param name="serializer">The serializer to use</param>
public override void Serialize(Serializer serializer)
{
serializer.Serialize(ref Wrapped);
}
public static explicit operator Char(char value) => new Char(value);
}
}
}
| 29.071429 | 80 | 0.519656 | [
"MIT"
] | AlephVault/unity-binary | Runtime/Wrappers/Char.cs | 814 | C# |
/* WinUSBNet library
* (C) 2010 Thomas Bleeker (www.madwizard.org)
*
* Licensed under the MIT license, see license.txt or:
* http://www.opensource.org/licenses/mit-license.php
*/
using System;
namespace MadWizard.WinUSBNet
{
/// <summary>
/// USB device details
/// </summary>
public class USBDeviceDescriptor
{
/// <summary>
/// Windows path name for the USB device
/// </summary>
public string PathName { get; private set; }
/// <summary>
/// USB vendor ID (VID) of the device
/// </summary>
public int VID { get; private set; }
/// <summary>
/// USB product ID (PID) of the device
/// </summary>
public int PID { get; private set; }
/// <summary>
/// Manufacturer name, or null if not available
/// </summary>
public string Manufacturer { get; private set; }
/// <summary>
/// Product name, or null if not available
/// </summary>
public string Product { get; private set; }
/// <summary>
/// Device serial number, or null if not available
/// </summary>
public string SerialNumber { get; private set; }
/// <summary>
/// Friendly device name, or path name when no
/// further device information is available
/// </summary>
public string FullName
{
get
{
if (Manufacturer != null && Product != null)
return Product + " - " + Manufacturer;
else if (Product != null)
return Product;
else if (SerialNumber != null)
return SerialNumber;
else
return PathName;
}
}
/// <summary>
/// Device class code as defined in the interface descriptor
/// This property can be used if the class type is not defined
/// int the USBBaseClass enumeration
/// </summary>
public byte ClassValue
{
get;
private set;
}
/// <summary>
/// Device subclass code
/// </summary>
public byte SubClass
{
get;
private set;
}
/// <summary>
/// Device protocol code
/// </summary>
public byte Protocol
{
get;
private set;
}
/// <summary>
/// Device class code. If the device class does
/// not match any of the USBBaseClass enumeration values
/// the value will be USBBaseClass.Unknown
/// </summary>
public USBBaseClass BaseClass
{
get;
private set;
}
internal USBDeviceDescriptor(string path, API.USB_DEVICE_DESCRIPTOR deviceDesc, string manufacturer, string product, string serialNumber)
{
PathName = path;
VID = deviceDesc.idVendor;
PID = deviceDesc.idProduct;
Manufacturer = manufacturer;
Product = product;
SerialNumber = serialNumber;
ClassValue = deviceDesc.bDeviceClass;
SubClass = deviceDesc.bDeviceSubClass;
Protocol = deviceDesc.bDeviceProtocol;
// If interface class is of a known type (USBBaseeClass enum), use this
// for the InterfaceClass property.
BaseClass = USBBaseClass.Unknown;
if (Enum.IsDefined(typeof(USBBaseClass), (int)deviceDesc.bDeviceClass))
{
BaseClass = (USBBaseClass)(int)deviceDesc.bDeviceClass;
}
}
}
}
| 29.412214 | 146 | 0.50584 | [
"MIT"
] | CasperGuo/winusbnet | WinUSBNet/USBDeviceDescriptor.cs | 3,853 | C# |
using System;
using System.Web;
namespace yumaster.Tools.Net
{
/// <summary>
/// Cookie操作辅助类
/// </summary>
public static class CookieHelper
{
/// <summary>
/// 清除指定Cookie
/// </summary>
/// <param name="cookiename">cookiename</param>
public static void Clear(string cookiename)
{
var cookie = HttpContext.Current.Request.Cookies[cookiename];
if (cookie != null)
{
cookie.Expires = DateTime.Now.AddYears(-3);
HttpContext.Current.Response.Cookies.Add(cookie);
}
}
/// <summary>
/// 删除所有cookie值
/// </summary>
public static void ClearAll()
{
int n = HttpContext.Current.Response.Cookies.Count;
for (int i = 0; i < n; i++)
{
var myCookie = HttpContext.Current.Response.Cookies[i];
myCookie.Expires = DateTime.Now.AddDays(-1);
HttpContext.Current.Response.Cookies.Add(myCookie);
}
}
/// <summary>
/// 获取指定Cookie值
/// </summary>
/// <param name="cookiename">cookiename</param>
/// <returns>Cookie值</returns>
public static string GetCookieValue(string cookiename)
{
var cookie = HttpContext.Current.Request.Cookies[cookiename];
string str = null;
if (cookie != null)
{
str = cookie.Value;
}
return str;
}
/// <summary>
/// 添加一个Cookie
/// </summary>
/// <param name="cookiename">cookie名</param>
/// <param name="cookievalue">cookie值</param>
/// <param name="expires">过期时间 DateTime</param>
public static void SetCookie(string cookiename, string cookievalue, DateTime expires)
{
HttpContext.Current.Response.Cookies.Add(new HttpCookie(cookiename)
{
Value = cookievalue,
Expires = expires
});
}
}
} | 29.450704 | 93 | 0.512195 | [
"MIT"
] | yumaster/Tools | yumaster.Tools/Net/CookieHelper.cs | 2,153 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo("Azure.Messaging.EventHubs, PublicKey=0024000004800000940000000602000000240000525341310004000001000100097ad52abbeaa2e1a1982747cc0106534f65cfea6707eaed696a3a63daea80de2512746801a7e47f88e7781e71af960d89ba2e25561f70b0e2dbc93319e0af1961a719ccf5a4d28709b2b57a5d29b7c09dc8d269a490ebe2651c4b6e6738c27c5fb2c02469fe9757f0a3479ac310d6588a50a28d7dd431b907fd325e18b9e8ed")]
[assembly: InternalsVisibleTo("Azure.Messaging.EventHubs.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100d15ddcb29688295338af4b7686603fe614abd555e09efba8fb88ee09e1f7b1ccaeed2e8f823fa9eef3fdd60217fc012ea67d2479751a0b8c087a4185541b851bd8b16f8d91b840e51b1cb0ba6fe647997e57429265e85ef62d565db50a69ae1647d54d7bd855e4db3d8a91510e5bcbd0edfbbecaa20a7bd9ae74593daa7b11b4")]
| 109.333333 | 397 | 0.926829 | [
"MIT"
] | AzureMentor/azure-sdk-for-net | sdk/eventhub/Azure.Messaging.EventHubs/src/TrackOneClient/Properties/AssemblyInfo.cs | 986 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace YOpenGL
{
public class Timer : IDisposable
{
public Timer(Action callBack)
{
_isfirst = false;
_isRunning = false;
_isDisposed = false;
_callBack = callBack;
_stopwatch = new Stopwatch();
_resetEvent = new AutoResetEvent(false);
}
private Action _callBack;
private Thread _thread;
private int _dueTime;
private int _period;
private bool _isRunning;
private bool _isfirst;
private bool _isDisposed;
private long _lastTick;
private Stopwatch _stopwatch;
private AutoResetEvent _resetEvent;
private void _InitThread()
{
_thread = new Thread(_ThreadLoop);
_thread.SetApartmentState(ApartmentState.STA);
_thread.IsBackground = true;
_thread.Priority = ThreadPriority.Normal;
}
private void _DisposeThread()
{
if (_thread == null) return;
if (_thread.IsAlive)
_thread.Abort();
_thread = null;
}
private void _ThreadLoop()
{
while (_isRunning)
{
if (_isfirst)
{
_isfirst = false;
if (_dueTime > 0)
Thread.Sleep(_dueTime);
if (_dueTime < 0)
continue;
_callBack();
continue;
}
var now = _stopwatch.ElapsedMilliseconds;
if (_period < 0 || now - _lastTick < _period)
{
if (_period < 0)
_resetEvent.WaitOne();
continue;
}
else
{
_lastTick = now;
_callBack();
}
}
}
public void Start(int dueTime, int period)
{
if (_isDisposed || _isRunning) return;
_dueTime = dueTime;
_period = period;
_DisposeThread();
_InitThread();
_isfirst = true;
_isRunning = true;
_stopwatch.Start();
_thread.Start();
}
public void Change(int dueTime, int period)
{
if (_isDisposed) return;
if (!_isRunning)
Start(Timeout.Infinite, Timeout.Infinite);
while ((_thread.ThreadState & System.Threading.ThreadState.Unstarted) != 0)
Thread.Sleep(1);
_dueTime = dueTime;
_period = period;
_isfirst = true;
_lastTick = 0;
_resetEvent.Set();
_stopwatch.Restart();
}
public void Stop()
{
if (_isDisposed) return;
_isfirst = false;
_isRunning = false;
_stopwatch.Stop();
_DisposeThread();
}
public void Dispose()
{
if (_isDisposed) return;
_isDisposed = true;
_DisposeThread();
_resetEvent.Dispose();
_resetEvent = null;
_stopwatch = null;
_callBack = null;
}
}
} | 26.338346 | 87 | 0.472738 | [
"MIT"
] | yzylovepmn/YDrawing2D | YOpenGL/Internel/Timer.cs | 3,505 | C# |
using Xunit;
namespace Pantry.InMemory.Tests
{
[CollectionDefinition(CollectionName)]
public class ConcurrentDictionaryStandardTestsFixtureCollection : ICollectionFixture<ConcurrentDictionaryStandardTestsFixture>
{
public const string CollectionName = nameof(ConcurrentDictionaryStandardTestsFixtureCollection);
}
}
| 31.090909 | 130 | 0.812865 | [
"Apache-2.0"
] | nventive/Pantry | src/Pantry.InMemory.Tests/ConcurrentDictionaryStandardTestsFixtureCollection.cs | 344 | C# |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using NUnit.Framework;
using QuantConnect.Indicators;
namespace QuantConnect.Tests.Indicators
{
[TestFixture]
public class BollingerBandsTests
{
[Test]
public void ComparesWithExternalDataMiddleBand()
{
var bb = new BollingerBands(20, 2.0m, MovingAverageType.Simple);
TestHelper.TestIndicator(bb, "spy_bollinger_bands.txt", "Moving Average 20", (BollingerBands ind) => (double)ind.MiddleBand.Current.Value);
}
[Test]
public void ComparesWithExternalDataUpperBand()
{
var bb = new BollingerBands(20, 2.0m, MovingAverageType.Simple);
TestHelper.TestIndicator(bb, "spy_bollinger_bands.txt", "Bollinger Bands® 20 2 Top", (BollingerBands ind) => (double)ind.UpperBand.Current.Value);
}
[Test]
public void ComparesWithExternalDataLowerBand()
{
var bb = new BollingerBands(20, 2.0m, MovingAverageType.Simple);
TestHelper.TestIndicator(bb, "spy_bollinger_bands.txt", "Bollinger Bands® 20 2 Bottom", (BollingerBands ind) => (double)ind.LowerBand.Current.Value);
}
[Test]
public void ResetsProperly()
{
var bb = new BollingerBands(2, 2m);
bb.Update(DateTime.Today, 1m);
Assert.IsFalse(bb.IsReady);
bb.Update(DateTime.Today.AddSeconds(1), 2m);
Assert.IsTrue(bb.IsReady);
Assert.IsTrue(bb.StandardDeviation.IsReady);
Assert.IsTrue(bb.LowerBand.IsReady);
Assert.IsTrue(bb.MiddleBand.IsReady);
Assert.IsTrue(bb.UpperBand.IsReady);
bb.Reset();
TestHelper.AssertIndicatorIsInDefaultState(bb);
TestHelper.AssertIndicatorIsInDefaultState(bb.StandardDeviation);
TestHelper.AssertIndicatorIsInDefaultState(bb.LowerBand);
TestHelper.AssertIndicatorIsInDefaultState(bb.MiddleBand);
TestHelper.AssertIndicatorIsInDefaultState(bb.UpperBand);
}
}
}
| 40.057971 | 161 | 0.671129 | [
"Apache-2.0"
] | Bimble/Lean | Tests/Indicators/BollingerBandsTests.cs | 2,768 | C# |
////////////////////////////////////////////////////////////////////////////
// <copyright file="YesNoScanner2Narrow.cs" company="Intel Corporation">
//
// Copyright (c) 2013-2015 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// </copyright>
////////////////////////////////////////////////////////////////////////////
using System;
using System.Diagnostics.CodeAnalysis;
using System.Security.Permissions;
using System.Windows.Forms;
using ACAT.Lib.Core.ActuatorManagement;
using ACAT.Lib.Core.AgentManagement;
using ACAT.Lib.Core.Extensions;
using ACAT.Lib.Core.InputActuators;
using ACAT.Lib.Core.PanelManagement;
using ACAT.Lib.Core.PanelManagement.CommandDispatcher;
using ACAT.Lib.Core.Utility;
using ACAT.Lib.Core.WidgetManagement;
using ACAT.Lib.Extension;
#region SupressStyleCopWarnings
[module: SuppressMessage(
"StyleCop.CSharp.ReadabilityRules",
"SA1126:PrefixCallsCorrectly",
Scope = "namespace",
Justification = "Not needed. ACAT naming conventions takes care of this")]
[module: SuppressMessage(
"StyleCop.CSharp.ReadabilityRules",
"SA1101:PrefixLocalCallsWithThis",
Scope = "namespace",
Justification = "Not needed. ACAT naming conventions takes care of this")]
[module: SuppressMessage(
"StyleCop.CSharp.ReadabilityRules",
"SA1121:UseBuiltInTypeAlias",
Scope = "namespace",
Justification = "Since they are just aliases, it doesn't really matter")]
[module: SuppressMessage(
"StyleCop.CSharp.DocumentationRules",
"SA1200:UsingDirectivesMustBePlacedWithinNamespace",
Scope = "namespace",
Justification = "ACAT guidelines")]
[module: SuppressMessage(
"StyleCop.CSharp.NamingRules",
"SA1309:FieldNamesMustNotBeginWithUnderscore",
Scope = "namespace",
Justification = "ACAT guidelines. Private fields begin with an underscore")]
[module: SuppressMessage(
"StyleCop.CSharp.NamingRules",
"SA1300:ElementMustBeginWithUpperCaseLetter",
Scope = "namespace",
Justification = "ACAT guidelines. Private/Protected methods begin with lowercase")]
#endregion SupressStyleCopWarnings
namespace ACAT.Extensions.Default.UI.ContextMenus
{
/// <summary>
/// Variation of the YesNoScannerNarrow.
/// Narrow version of the yes/no scanner. Useful if
/// the prompt is a short string. Displays yes and no and
/// lets the user make the choice
/// This scanner has a blank line between the yes and
/// the no to give the user time to make the choice
/// </summary>
[DescriptorAttribute("056E5553-66C7-4B60-A931-D7FED719DAF2", "YesNoScanner2Narrow", "Yes No Scanner")]
public partial class YesNoScanner2Narrow : Form, IScannerPanel, IExtension
{
/// <summary>
/// Root widget that represents this form
/// </summary>
protected Widget rootWidget;
/// <summary>
/// The scannerCommon object
/// </summary>
protected ScannerCommon scannerCommon;
/// <summary>
/// Startup args
/// </summary>
protected StartupArg startupArg;
/// <summary>
/// Startup command arguments
/// </summary>
protected object startupCommandArg;
/// <summary>
/// The command dispatcher object
/// </summary>
private readonly Dispatcher _dispatcher;
/// <summary>
/// Provdes access to methods/properties in this class
/// </summary>
private readonly ExtensionInvoker _invoker;
/// <summary>
/// The keyboard actuator object
/// </summary>
private readonly KeyboardActuator _keyboardActuator;
/// <summary>
/// The scannerHelper object
/// </summary>
private ScannerHelper _scannerHelper;
/// <summary>
/// Title of this scanner
/// </summary>
private String _title = String.Empty;
/// <summary>
/// Initializes a new instance of the class.
/// </summary>
/// <param name="panelClass">Panel class of the scanner</param>
/// <param name="panelTitle">Title of the scanner</param>
public YesNoScanner2Narrow(String panelClass, String panelTitle)
{
InitializeComponent();
Load += ContextMenu_Load;
FormClosing += ContextMenu_FormClosing;
Choice = false;
_title = panelTitle;
PanelClass = panelClass;
Caption = String.Empty;
_invoker = new ExtensionInvoker(this);
_dispatcher = new Dispatcher(this);
var actuator = ActuatorManager.Instance.GetActuator(typeof(KeyboardActuator));
if (actuator is KeyboardActuator)
{
_keyboardActuator = actuator as KeyboardActuator;
_keyboardActuator.EvtKeyPress += _keyboardActuator_EvtKeyPress;
}
}
/// <summary>
/// Gets or sets the prompt to display
/// </summary>
public String Caption { get; set; }
/// <summary>
/// Gets the user choice (true on yes)
/// </summary>
public bool Choice { get; set; }
/// <summary>
/// Gets the command dispatcher for the scanner
/// </summary>
public RunCommandDispatcher CommandDispatcher
{
get { return _dispatcher; }
}
/// <summary>
/// Gets the descriptor for this class
/// </summary>
public IDescriptor Descriptor
{
get { return DescriptorAttribute.GetDescriptor(GetType()); }
}
/// <summary>
/// Gets this form object
/// </summary>
public Form Form
{
get { return this; }
}
/// <summary>
/// Gets the panel class
/// </summary>
public String PanelClass { get; protected set; }
/// <summary>
/// Gets the scanner common object
/// </summary>
public ScannerCommon ScannerCommon
{
get { return scannerCommon; }
}
/// <summary>
/// Gets the sync object
/// </summary>
public SyncLock SyncObj
{
get { return scannerCommon.SyncObj; }
}
/// <summary>
/// Gets the text controller object
/// </summary>
public ITextController TextController
{
get { return scannerCommon.TextController; }
}
/// <summary>
/// Sets the form styles
/// </summary>
protected override CreateParams CreateParams
{
get
{
Log.Debug();
return Windows.SetFormStyles(base.CreateParams);
}
}
protected override bool ShowWithoutActivation
{
get { return true; }
}
/// <summary>
/// Invoked to check if a scanner button should be enabled. Uses context
/// to determine the 'enabled' state.
/// </summary>
/// <param name="arg">info about the scanner button</param>
public bool CheckWidgetEnabled(CheckEnabledArgs arg)
{
return _scannerHelper.CheckWidgetEnabled(arg);
}
/// <summary>
/// Gets the extension invoker
/// </summary>
/// <returns></returns>
public ExtensionInvoker GetInvoker()
{
return _invoker;
}
/// <summary>
/// Initializes the class
/// </summary>
/// <param name="startupArg">startup parameter</param>
/// <returns></returns>
public bool Initialize(StartupArg startupArg)
{
Log.Debug();
PanelClass = startupArg.PanelClass;
startupCommandArg = startupArg.Arg;
this.startupArg = startupArg;
_scannerHelper = new ScannerHelper(this, startupArg);
scannerCommon = new ScannerCommon(this);
if (!scannerCommon.Initialize(startupArg))
{
return false;
}
rootWidget = scannerCommon.GetRootWidget();
return true;
}
/// <summary>
/// Invoked when focus changes in the active foreground window
/// </summary>
/// <param name="monitorInfo">foreground window focused element information</param>
public void OnFocusChanged(WindowActivityMonitorInfo monitorInfo)
{
scannerCommon.OnFocusChanged(monitorInfo);
}
/// <summary>
/// Pauses the animation and hides the scanner
/// </summary>
public virtual void OnPause()
{
Log.Debug();
scannerCommon.GetAnimationManager().Pause();
scannerCommon.HideScanner();
scannerCommon.OnPause();
}
/// <summary>
/// Not used
/// </summary>
/// <param name="arg"></param>
/// <returns></returns>
public bool OnQueryPanelChange(PanelRequestEventArgs arg)
{
return true;
}
/// <summary>
/// Resumes animation and shows the scanner
/// </summary>
public virtual void OnResume()
{
Log.Debug();
scannerCommon.GetAnimationManager().Resume();
scannerCommon.ShowScanner();
scannerCommon.OnResume();
}
/// <summary>
/// Invoked when a widget is actuated
/// </summary>
/// <param name="widget">widget</param>
/// <param name="handled">was this handled</param>
public virtual void OnWidgetActuated(Widget widget, ref bool handled)
{
handled = false;
}
/// <summary>
/// Not used
/// </summary>
/// <param name="parent"></param>
/// <param name="widget"></param>
public void SetTargetControl(Form parent, Widget widget)
{
}
/// <summary>
/// Release resources
/// </summary>
/// <param name="e">closing arg</param>
protected override void OnFormClosing(FormClosingEventArgs e)
{
_scannerHelper.OnFormClosing(e);
scannerCommon.OnFormClosing(e);
_keyboardActuator.EvtKeyPress -= _keyboardActuator_EvtKeyPress;
base.OnFormClosing(e);
}
/// <summary>
/// Window proc
/// </summary>
/// <param name="m"></param>
[EnvironmentPermissionAttribute(SecurityAction.LinkDemand, Unrestricted = true)]
protected override void WndProc(ref Message m)
{
if (scannerCommon != null)
{
scannerCommon.HandleWndProc(m);
}
base.WndProc(ref m);
}
/// <summary>
/// Keypress handler
/// </summary>
/// <param name="sender">event sender</param>
/// <param name="e">event args</param>
private void _keyboardActuator_EvtKeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == 27 || e.KeyChar == 'n' || e.KeyChar == 'N')
{
e.Handled = true;
Choice = false;
Close();
}
else if (e.KeyChar == 'y' || e.KeyChar == 'Y')
{
e.Handled = true;
Choice = true;
Close();
}
}
/// <summary>
/// Form is closing. Dispose resources
/// </summary>
/// <param name="sender">event sender</param>
/// <param name="e">event args</param>
private void ContextMenu_FormClosing(object sender, FormClosingEventArgs e)
{
scannerCommon.OnClosing();
scannerCommon.Dispose();
}
/// <summary>
/// Form loader. Initialize.
/// </summary>
/// <param name="sender">event sender</param>
/// <param name="e">event args</param>
private void ContextMenu_Load(object sender, EventArgs e)
{
Log.Debug();
scannerCommon.OnLoad(false);
Widget widget = scannerCommon.GetRootWidget().Finder.FindChild("ContextMenuTitle");
if (widget != null)
{
widget.SetText(_title);
}
widget = scannerCommon.GetRootWidget().Finder.FindChild("Prompt");
if (widget != null && !String.IsNullOrEmpty(Caption))
{
widget.SetText(Caption);
}
scannerCommon.GetAnimationManager().Start(rootWidget);
}
/// <summary>
/// Handles yes/no command, sets the choice and then
/// closes the scanner
/// </summary>
private class CommandHandler : RunCommandHandler
{
/// <summary>
/// Initializes a new instance of the class.
/// </summary>
/// <param name="cmd">command to execute</param>
public CommandHandler(String cmd)
: base(cmd)
{
}
/// <summary>
/// Executes the command
/// </summary>
/// <param name="handled">was this handled</param>
/// <returns>true on success</returns>
public override bool Execute(ref bool handled)
{
handled = true;
var form = Dispatcher.Scanner.Form as YesNoScanner2Narrow;
switch (Command)
{
case "CmdYes":
form.Choice = true;
break;
case "CmdNo":
form.Choice = false;
break;
}
Windows.CloseForm(form);
return true;
}
}
/// <summary>
/// Dispatcher that holds the commands to be processed
/// </summary>
private class Dispatcher : RunCommandDispatcher
{
/// <summary>
/// Initializes a new instance of the class
/// </summary>
/// <param name="panel">the scanner object</param>
public Dispatcher(IScannerPanel panel)
: base(panel)
{
Commands.Add(new CommandHandler("CmdYes"));
Commands.Add(new CommandHandler("CmdNo"));
}
}
}
} | 30.942857 | 106 | 0.547883 | [
"Apache-2.0"
] | devlato/acat | src/Extensions/Default/UI/ContextMenus/YesNoScanner2Narrow.cs | 15,237 | C# |
using System;
using System.Threading.Tasks;
using Amazon.DynamoDBv2.DataModel;
using FluentAssertions;
using Paramore.Brighter.Inbox.DynamoDB;
using Paramore.Brighter.Tests.CommandProcessors.TestDoubles;
using Xunit;
namespace Paramore.Brighter.Tests.Inbox.DynamoDB
{
[Trait("Category", "DynamoDB")]
public class DynamoDbCommandExistsAsyncTests : BaseImboxDyamoDBBaseTest
{
private readonly MyCommand _command;
private readonly DynamoDbInbox _dynamoDbInbox;
private readonly Guid _guid = Guid.NewGuid();
private readonly string _contextKey;
public DynamoDbCommandExistsAsyncTests()
{
_command = new MyCommand { Id = _guid, Value = "Test Earliest"};
_contextKey = "test-context-key";
var createTableRequest = new DynamoDbInboxBuilder(DynamoDbTestHelper.DynamoDbInboxTestConfiguration.TableName).CreateInboxTableRequest();
DynamoDbTestHelper.CreateInboxTable(createTableRequest);
_dynamoDbInbox = new DynamoDbInbox(DynamoDbTestHelper.DynamoDbContext, DynamoDbTestHelper.DynamoDbInboxTestConfiguration);
var config = new DynamoDBOperationConfig
{
OverrideTableName = DynamoDbTestHelper.DynamoDbInboxTestConfiguration.TableName,
ConsistentRead = false
};
var dbContext = DynamoDbTestHelper.DynamoDbContext;
dbContext.SaveAsync(ConstructCommand(_command, DateTime.UtcNow, _contextKey), config).GetAwaiter().GetResult();
}
[Fact]
public async Task When_checking_a_command_exist()
{
var commandExists = await _dynamoDbInbox.ExistsAsync<MyCommand>(_command.Id, _contextKey);
commandExists.Should().BeTrue("because the command exists.", commandExists);
}
[Fact]
public async Task When_checking_a_command_exist_for_a_different_context()
{
var commandExists = await _dynamoDbInbox.ExistsAsync<MyCommand>(_command.Id, "some other context");
commandExists.Should().BeFalse("because the command exists for a different context.", commandExists);
}
[Fact]
public async Task When_checking_a_command_does_not_exist()
{
var commandExists = await _dynamoDbInbox.ExistsAsync<MyCommand>(Guid.Empty, _contextKey);
commandExists.Should().BeFalse("because the command doesn't exists.", commandExists);
}
}
}
| 39.671875 | 149 | 0.682946 | [
"MIT"
] | SVemulapalli/Brighter | tests/Paramore.Brighter.Tests/Inbox/DynamoDB/When_checking_for_existing_command_async.cs | 2,541 | C# |
namespace MassTransit.DocumentDbIntegration
{
using System;
using Configuration;
using Configurators;
public static class DocumentDbRepositoryConfigurationExtensions
{
/// <summary>
/// Configures the DocumentDb Saga Repository
/// </summary>
/// <param name="configurator"></param>
/// <param name="configure"></param>
/// <typeparam name="TSaga"></typeparam>
/// <returns></returns>
public static ISagaRegistrationConfigurator<TSaga> DocumentDbRepository<TSaga>(this ISagaRegistrationConfigurator<TSaga> configurator,
Action<IDocumentDbSagaRepositoryConfigurator<TSaga>> configure)
where TSaga : class, IVersionedSaga
{
var repositoryConfigurator = new DocumentDbSagaRepositoryConfigurator<TSaga>();
configure?.Invoke(repositoryConfigurator);
BusConfigurationResult.CompileResults(repositoryConfigurator.Validate());
configurator.Repository(x => repositoryConfigurator.Register(x));
return configurator;
}
/// <summary>
/// Configures the DocumentDb Saga Repository.
/// </summary>
/// <param name="configurator"></param>
/// <param name="endpointUri">The endpointUri of the database</param>
/// <param name="key">The authentication key of the database</param>
/// <param name="configure"></param>
/// <typeparam name="TSaga"></typeparam>
/// <returns></returns>
public static ISagaRegistrationConfigurator<TSaga> DocumentDbRepository<TSaga>(this ISagaRegistrationConfigurator<TSaga> configurator,
Uri endpointUri, string key, Action<IDocumentDbSagaRepositoryConfigurator<TSaga>> configure)
where TSaga : class, IVersionedSaga
{
var repositoryConfigurator = new DocumentDbSagaRepositoryConfigurator<TSaga>
{
EndpointUri = endpointUri,
Key = key
};
configure?.Invoke(repositoryConfigurator);
BusConfigurationResult.CompileResults(repositoryConfigurator.Validate());
configurator.Repository(x => repositoryConfigurator.Register(x));
return configurator;
}
}
}
| 37.622951 | 142 | 0.647059 | [
"ECL-2.0",
"Apache-2.0"
] | ChipsetSV/MassTransit | src/Persistence/MassTransit.DocumentDbIntegration/Configuration/DocumentDbRepositoryConfigurationExtensions.cs | 2,295 | C# |
/*
* Copyright (C) 2016 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
namespace com.opengamma.strata.product.credit.type
{
//JAVA TO C# CONVERTER TODO TASK: This Java 'import static' statement cannot be converted to C#:
// import static com.opengamma.strata.basics.currency.Currency.EUR;
//JAVA TO C# CONVERTER TODO TASK: This Java 'import static' statement cannot be converted to C#:
// import static com.opengamma.strata.basics.currency.Currency.GBP;
//JAVA TO C# CONVERTER TODO TASK: This Java 'import static' statement cannot be converted to C#:
// import static com.opengamma.strata.basics.currency.Currency.JPY;
//JAVA TO C# CONVERTER TODO TASK: This Java 'import static' statement cannot be converted to C#:
// import static com.opengamma.strata.basics.currency.Currency.USD;
//JAVA TO C# CONVERTER TODO TASK: This Java 'import static' statement cannot be converted to C#:
// import static com.opengamma.strata.basics.date.BusinessDayConventions.FOLLOWING;
//JAVA TO C# CONVERTER TODO TASK: This Java 'import static' statement cannot be converted to C#:
// import static com.opengamma.strata.basics.date.DayCounts.ACT_360;
//JAVA TO C# CONVERTER TODO TASK: This Java 'import static' statement cannot be converted to C#:
// import static com.opengamma.strata.basics.date.HolidayCalendarIds.EUTA;
//JAVA TO C# CONVERTER TODO TASK: This Java 'import static' statement cannot be converted to C#:
// import static com.opengamma.strata.basics.date.HolidayCalendarIds.GBLO;
//JAVA TO C# CONVERTER TODO TASK: This Java 'import static' statement cannot be converted to C#:
// import static com.opengamma.strata.basics.date.HolidayCalendarIds.JPTO;
//JAVA TO C# CONVERTER TODO TASK: This Java 'import static' statement cannot be converted to C#:
// import static com.opengamma.strata.basics.date.HolidayCalendarIds.USNY;
//JAVA TO C# CONVERTER TODO TASK: This Java 'import static' statement cannot be converted to C#:
// import static com.opengamma.strata.basics.schedule.Frequency.P3M;
using BusinessDayAdjustment = com.opengamma.strata.basics.date.BusinessDayAdjustment;
using DaysAdjustment = com.opengamma.strata.basics.date.DaysAdjustment;
using HolidayCalendarId = com.opengamma.strata.basics.date.HolidayCalendarId;
/// <summary>
/// Standardized credit default swap conventions.
/// </summary>
internal sealed class StandardCdsConventions
{
private static readonly HolidayCalendarId GBLO_USNY = GBLO.combinedWith(USNY);
private static readonly HolidayCalendarId GBLO_USNY_JPTO = JPTO.combinedWith(GBLO_USNY);
private static readonly HolidayCalendarId GBLO_EUTA = GBLO.combinedWith(EUTA);
/// <summary>
/// USD-dominated standardized credit default swap.
/// <para>
/// The payment dates are calculated with 'USNY'.
/// </para>
/// </summary>
public static readonly ImmutableCdsConvention USD_STANDARD = ImmutableCdsConvention.of("USD-STANDARD", USD, ACT_360, P3M, BusinessDayAdjustment.of(FOLLOWING, USNY), DaysAdjustment.ofBusinessDays(3, USNY));
/// <summary>
/// EUR-dominated standardized credit default swap.
/// <para>
/// The payment dates are calculated with 'EUTA'.
/// </para>
/// </summary>
public static readonly ImmutableCdsConvention EUR_STANDARD = ImmutableCdsConvention.of("EUR-STANDARD", EUR, ACT_360, P3M, BusinessDayAdjustment.of(FOLLOWING, EUTA), DaysAdjustment.ofBusinessDays(3, EUTA));
/// <summary>
/// EUR-dominated standardized credit default swap.
/// <para>
/// The payment dates are calculated with 'EUTA' and 'GBLO'.
/// </para>
/// </summary>
public static readonly ImmutableCdsConvention EUR_GB_STANDARD = ImmutableCdsConvention.of("EUR-GB-STANDARD", EUR, ACT_360, P3M, BusinessDayAdjustment.of(FOLLOWING, GBLO_EUTA), DaysAdjustment.ofBusinessDays(3, GBLO_EUTA));
/// <summary>
/// GBP-dominated standardized credit default swap.
/// <para>
/// The payment dates are calculated with 'GBLO'.
/// </para>
/// </summary>
public static readonly ImmutableCdsConvention GBP_STANDARD = ImmutableCdsConvention.of("GBP-STANDARD", GBP, ACT_360, P3M, BusinessDayAdjustment.of(FOLLOWING, GBLO), DaysAdjustment.ofBusinessDays(3, GBLO));
/// <summary>
/// GBP-dominated standardized credit default swap.
/// <para>
/// The payment dates are calculated with 'GBLO' and 'USNY'.
/// </para>
/// </summary>
public static readonly ImmutableCdsConvention GBP_US_STANDARD = ImmutableCdsConvention.of("GBP-US-STANDARD", GBP, ACT_360, P3M, BusinessDayAdjustment.of(FOLLOWING, GBLO_USNY), DaysAdjustment.ofBusinessDays(3, GBLO_USNY));
/// <summary>
/// JPY-dominated standardized credit default swap.
/// <para>
/// The payment dates are calculated with 'JPTO'.
/// </para>
/// </summary>
public static readonly ImmutableCdsConvention JPY_STANDARD = ImmutableCdsConvention.of("JPY-STANDARD", JPY, ACT_360, P3M, BusinessDayAdjustment.of(FOLLOWING, JPTO), DaysAdjustment.ofBusinessDays(3, JPTO));
/// <summary>
/// JPY-dominated standardized credit default swap.
/// <para>
/// The payment dates are calculated with 'JPTO', 'USNY' and 'GBLO'.
/// </para>
/// </summary>
public static readonly ImmutableCdsConvention JPY_US_GB_STANDARD = ImmutableCdsConvention.of("JPY-US-GB-STANDARD", JPY, ACT_360, P3M, BusinessDayAdjustment.of(FOLLOWING, GBLO_USNY_JPTO), DaysAdjustment.ofBusinessDays(3, GBLO_USNY_JPTO));
//-------------------------------------------------------------------------
/// <summary>
/// Restricted constructor.
/// </summary>
private StandardCdsConventions()
{
}
}
} | 50.972973 | 240 | 0.732238 | [
"Apache-2.0"
] | ckarcz/Strata.ConvertedToCSharp | modules/product/src/main/java/com/opengamma/strata/product/credit/type/StandardCdsConventions.cs | 5,660 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.