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 Syncfusion.Windows.Forms;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using HASSAgent.Models.Config;
using HASSAgent.Mqtt;
using HASSAgent.Sensors;
using HASSAgent.Settings;
using Serilog;
using Syncfusion.Windows.Forms.Grid;
namespace HASSAgent.Forms.Sensors
{
public partial class SensorsConfig : MetroForm
{
private List<ConfiguredSensor> _sensors = new List<ConfiguredSensor>();
private readonly List<ConfiguredSensor> _toBeDeletedSensors = new List<ConfiguredSensor>();
private int _heightDiff;
public SensorsConfig()
{
InitializeComponent();
}
private void SensorsConfig_Load(object sender, EventArgs e)
{
// set the initial height difference for resizing
_heightDiff = Height - LcSensors.Height;
// pause the sensor manager
SensorsManager.Pause();
// catch all key presses
KeyPreview = true;
// load stored sensors
PrepareSensorsList();
// set all flags to 'max one row'
LcSensors.Grid.AllowDragSelectedCols = false;
LcSensors.Grid.AllowSelection = GridSelectionFlags.Row;
LcSensors.Grid.AllowDragSelectedRows = false;
LcSensors.Grid.ListBoxSelectionMode = SelectionMode.One;
LcSensors.SelectionMode = SelectionMode.One;
// we have to refresh after selecting, otherwise a bunch of rows stay highlighted :\
LcSensors.Grid.SelectionChanged += (o, args) => LcSensors.Grid.Refresh();
LcSensors.Grid.SelectionChanging += (o, args) => LcSensors.Grid.Refresh();
}
/// <summary>
/// Load the stored sensors into the grid
/// </summary>
private void PrepareSensorsList()
{
// make a copy of the current sensors
_sensors = Variables.SingleValueSensors.Select(StoredSensors.ConvertAbstractSingleValueToConfigured).Where(configuredSensor => configuredSensor != null).ToList();
_sensors = _sensors.Concat(Variables.MultiValueSensors.Select(StoredSensors.ConvertAbstractMultiValueToConfigured).Where(configuredSensor => configuredSensor != null)).ToList();
// bind to the list
LcSensors.DataSource = _sensors;
// hide id column
LcSensors.Grid.HideCols["Id"] = true;
// hide query column
LcSensors.Grid.HideCols["Query"] = true;
// hide windowname column
LcSensors.Grid.HideCols["WindowName"] = true;
// hide updateinterval column
LcSensors.Grid.HideCols["UpdateInterval"] = true;
// force column resize
LcSensors.Grid.ColWidths.ResizeToFit(GridRangeInfo.Table(), GridResizeToFitOptions.IncludeHeaders);
// set header height
LcSensors.Grid.RowHeights[0] = 25;
// add extra space
for (var i = 1; i <= LcSensors.Grid.ColCount; i++) LcSensors.Grid.ColWidths[i] += 15;
// redraw
LcSensors.Refresh();
}
/// <summary>
/// Reload the sensors
/// </summary>
private void UpdateSensorsList()
{
// reload data
LcSensors.Grid.ResetVolatileData();
// force column resize
LcSensors.Grid.ColWidths.ResizeToFit(GridRangeInfo.Table(), GridResizeToFitOptions.IncludeHeaders);
// add extra space
for (var i = 1; i <= LcSensors.Grid.ColCount; i++) LcSensors.Grid.ColWidths[i] += 15;
// redraw
LcSensors.Refresh();
}
/// <summary>
/// Open a new form to modify the selected sensor
/// </summary>
private void ModifySelectedSensor()
{
// find all (if any) selected rows
var selectedRows = LcSensors.Grid.Selections.GetSelectedRows(true, true);
if (selectedRows.Count == 0) return;
// we can just modify one, so the first
var selectedRow = selectedRows[0];
var selectedSensor = (ConfiguredSensor)LcSensors.Items[selectedRow.Top - 1];
// show modding form
using (var sensor = new SensorsMod(selectedSensor))
{
var res = sensor.ShowDialog();
if (res != DialogResult.OK) return;
// update in temp list
_sensors[_sensors.FindIndex(x => x.Id == sensor.Sensor.Id)] = sensor.Sensor;
// reload the gui list
UpdateSensorsList();
}
}
/// <summary>
/// Delete all selected sensors
/// <para>Note: doesn't actually execute deletion, that's done after the user clicks 'store'</para>
/// </summary>
private void DeleteSelectedSensors()
{
// check for selected rows
var selectedRows = LcSensors.Grid.Selections.GetSelectedRows(true, true);
if (selectedRows.Count == 0) return;
// get selected row indexes
var rowList = new List<int>();
for (var i = LcSensors.Grid.Model.SelectedRanges.ActiveRange.Top; i <= LcSensors.Grid.Model.SelectedRanges.ActiveRange.Bottom; i++)
{
rowList.Add(i - 1);
}
// make descending
rowList.Sort();
rowList.Reverse();
foreach (var row in rowList)
{
// get object
var qA = (ConfiguredSensor)LcSensors.Items[row];
// add to to-be-deleted list
_toBeDeletedSensors.Add(qA);
// remove from the list
_sensors.RemoveAt(_sensors.FindIndex(x => x.Id == qA.Id));
}
// reload the gui list
UpdateSensorsList();
}
/// <summary>
/// Show a form to add a new sensor
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void BtnAdd_Click(object sender, EventArgs e)
{
using (var sensor = new SensorsMod())
{
var res = sensor.ShowDialog();
if (res != DialogResult.OK) return;
// add to the temp list
_sensors.Add(sensor.Sensor);
// reload the gui list
UpdateSensorsList();
}
}
/// <summary>
/// Stores our temporary list, and syncs it to HASS through MQTT
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private async void BtnStore_Click(object sender, EventArgs e)
{
// lock interface
LcSensors.Enabled = false;
BtnRemove.Enabled = false;
BtnModify.Enabled = false;
BtnAdd.Enabled = false;
BtnStore.Enabled = false;
BtnStore.Text = "storing and registering, please wait .. ";
await Task.Run(async delegate
{
try
{
// process the to-be-removed
// todo: code smell
if (_toBeDeletedSensors.Any())
{
foreach (var sensor in _toBeDeletedSensors)
{
if (sensor == null) continue;
if (sensor.IsSingleValue())
{
var abstractSensor = StoredSensors.ConvertConfiguredToAbstractSingleValue(sensor);
// remove and unregister
await abstractSensor.UnPublishAutoDiscoveryConfigAsync();
Variables.SingleValueSensors.RemoveAt(Variables.SingleValueSensors.FindIndex(x => x.Id == abstractSensor.Id));
Log.Information("[SENSORS] Removed single-value sensor: {sensor}", abstractSensor.Name);
}
else
{
var abstractSensor = StoredSensors.ConvertConfiguredToAbstractMultiValue(sensor);
// remove and unregister
await abstractSensor.UnPublishAutoDiscoveryConfigAsync();
Variables.MultiValueSensors.RemoveAt(Variables.MultiValueSensors.FindIndex(x => x.Id == abstractSensor.Id));
Log.Information("[SENSORS] Removed multi-value sensor: {sensor}", abstractSensor.Name);
}
}
}
// copy our list to the main one
// todo: code smell
foreach (var sensor in _sensors)
{
if (sensor == null) continue;
if (sensor.IsSingleValue())
{
var abstractSensor = StoredSensors.ConvertConfiguredToAbstractSingleValue(sensor);
if (Variables.SingleValueSensors.All(x => x.Id != abstractSensor.Id))
{
// new, add and register
Variables.SingleValueSensors.Add(abstractSensor);
await abstractSensor.PublishAutoDiscoveryConfigAsync();
await abstractSensor.PublishStateAsync(false);
Log.Information("[SENSORS] Added single-value sensor: {sensor}", abstractSensor.Name);
continue;
}
// existing, update and re-register
var currentSensorIndex = Variables.SingleValueSensors.FindIndex(x => x.Id == abstractSensor.Id);
if (Variables.SingleValueSensors[currentSensorIndex].Name != abstractSensor.Name)
{
// name changed, unregister
Log.Information("[SENSORS] Single-value sensor changed name, re-registering as new entity: {old} to {new}", Variables.SingleValueSensors[currentSensorIndex].Name, abstractSensor.Name);
await Variables.SingleValueSensors[currentSensorIndex].UnPublishAutoDiscoveryConfigAsync();
}
Variables.SingleValueSensors[currentSensorIndex] = abstractSensor;
await abstractSensor.PublishAutoDiscoveryConfigAsync();
await abstractSensor.PublishStateAsync(false);
Log.Information("[SENSORS] Modified single-value sensor: {sensor}", abstractSensor.Name);
}
else
{
var abstractSensor = StoredSensors.ConvertConfiguredToAbstractMultiValue(sensor);
if (Variables.MultiValueSensors.All(x => x.Id != abstractSensor.Id))
{
// new, add and register
Variables.MultiValueSensors.Add(abstractSensor);
await abstractSensor.PublishAutoDiscoveryConfigAsync();
await abstractSensor.PublishStatesAsync(false);
Log.Information("[SENSORS] Added multi-value sensor: {sensor}", abstractSensor.Name);
continue;
}
// existing, update and re-register
var currentSensorIndex = Variables.MultiValueSensors.FindIndex(x => x.Id == abstractSensor.Id);
if (Variables.MultiValueSensors[currentSensorIndex].Name != abstractSensor.Name)
{
// name changed, unregister
Log.Information("[SENSORS] Multi-value sensor changed name, re-registering as new entity: {old} to {new}", Variables.MultiValueSensors[currentSensorIndex].Name, abstractSensor.Name);
await Variables.MultiValueSensors[currentSensorIndex].UnPublishAutoDiscoveryConfigAsync();
}
Variables.MultiValueSensors[currentSensorIndex] = abstractSensor;
await abstractSensor.PublishAutoDiscoveryConfigAsync();
await abstractSensor.PublishStatesAsync(false);
Log.Information("[SENSORS] Modified multi-value sensor: {sensor}", abstractSensor.Name);
}
}
// annouce ourselves
await MqttManager.AnnounceAvailabilityAsync();
// store to file
StoredSensors.Store();
}
catch (Exception ex)
{
Log.Fatal(ex, "[SENSORS] Error while saving: {err}", ex.Message);
Variables.MainForm?.ShowMessageBox("An error occured while saving the sensors, check the logs for more info.", true);
}
});
// done
DialogResult = DialogResult.OK;
}
private void BtnModify_Click(object sender, EventArgs e) => ModifySelectedSensor();
private void BtnRemove_Click(object sender, EventArgs e) => DeleteSelectedSensors();
private void SensorsConfig_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode != Keys.Escape) return;
Close();
}
private void SensorsConfig_FormClosing(object sender, FormClosingEventArgs e)
{
// unpause the sensors manager
SensorsManager.Unpause();
}
private void LcSensors_DoubleClick(object sender, EventArgs e) => ModifySelectedSensor();
private void SensorsConfig_Resize(object sender, EventArgs e)
{
LcSensors.Height = Height - _heightDiff;
}
}
}
| 42.151429 | 217 | 0.521792 | [
"MIT"
] | Syntoxr/HASS.Agent | src/HASS.Agent/HASSAgent/Forms/Sensors/SensorsConfig.cs | 14,755 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNextGen.Network.V20170601
{
public static class GetLocalNetworkGateway
{
/// <summary>
/// A common class for general resource information
/// </summary>
public static Task<GetLocalNetworkGatewayResult> InvokeAsync(GetLocalNetworkGatewayArgs args, InvokeOptions? options = null)
=> Pulumi.Deployment.Instance.InvokeAsync<GetLocalNetworkGatewayResult>("azure-nextgen:network/v20170601:getLocalNetworkGateway", args ?? new GetLocalNetworkGatewayArgs(), options.WithVersion());
}
public sealed class GetLocalNetworkGatewayArgs : Pulumi.InvokeArgs
{
/// <summary>
/// The name of the local network gateway.
/// </summary>
[Input("localNetworkGatewayName", required: true)]
public string LocalNetworkGatewayName { get; set; } = null!;
/// <summary>
/// The name of the resource group.
/// </summary>
[Input("resourceGroupName", required: true)]
public string ResourceGroupName { get; set; } = null!;
public GetLocalNetworkGatewayArgs()
{
}
}
[OutputType]
public sealed class GetLocalNetworkGatewayResult
{
/// <summary>
/// Local network gateway's BGP speaker settings.
/// </summary>
public readonly Outputs.BgpSettingsResponse? BgpSettings;
/// <summary>
/// A unique read-only string that changes whenever the resource is updated.
/// </summary>
public readonly string? Etag;
/// <summary>
/// IP address of local network gateway.
/// </summary>
public readonly string? GatewayIpAddress;
/// <summary>
/// Resource ID.
/// </summary>
public readonly string? Id;
/// <summary>
/// Local network site address space.
/// </summary>
public readonly Outputs.AddressSpaceResponse? LocalNetworkAddressSpace;
/// <summary>
/// Resource location.
/// </summary>
public readonly string? Location;
/// <summary>
/// Resource name.
/// </summary>
public readonly string Name;
/// <summary>
/// The provisioning state of the LocalNetworkGateway resource. Possible values are: 'Updating', 'Deleting', and 'Failed'.
/// </summary>
public readonly string ProvisioningState;
/// <summary>
/// The resource GUID property of the LocalNetworkGateway resource.
/// </summary>
public readonly string? ResourceGuid;
/// <summary>
/// Resource tags.
/// </summary>
public readonly ImmutableDictionary<string, string>? Tags;
/// <summary>
/// Resource type.
/// </summary>
public readonly string Type;
[OutputConstructor]
private GetLocalNetworkGatewayResult(
Outputs.BgpSettingsResponse? bgpSettings,
string? etag,
string? gatewayIpAddress,
string? id,
Outputs.AddressSpaceResponse? localNetworkAddressSpace,
string? location,
string name,
string provisioningState,
string? resourceGuid,
ImmutableDictionary<string, string>? tags,
string type)
{
BgpSettings = bgpSettings;
Etag = etag;
GatewayIpAddress = gatewayIpAddress;
Id = id;
LocalNetworkAddressSpace = localNetworkAddressSpace;
Location = location;
Name = name;
ProvisioningState = provisioningState;
ResourceGuid = resourceGuid;
Tags = tags;
Type = type;
}
}
}
| 31.773438 | 207 | 0.599459 | [
"Apache-2.0"
] | pulumi/pulumi-azure-nextgen | sdk/dotnet/Network/V20170601/GetLocalNetworkGateway.cs | 4,067 | C# |
using EmptyFiles;
using VerifyTests;
static class FileComparer
{
public static async Task<EqualityResult> DoCompare(VerifySettings settings, FilePair file, bool previousTextHasFailed)
{
if (!File.Exists(file.Verified))
{
return Equality.MissingVerified;
}
if (AllFiles.IsEmptyFile(file.Verified))
{
return Equality.NotEqual;
}
var result = await FilesEqual(settings, file, previousTextHasFailed);
if (result.IsEqual)
{
return Equality.Equal;
}
return new(Equality.NotEqual, result.Message);
}
static Task<CompareResult> FilesEqual(VerifySettings settings, FilePair filePair, bool previousTextHasFailed)
{
if (!previousTextHasFailed &&
settings.TryFindStreamComparer(filePair.Extension, out var compare))
{
return DoCompare(settings, compare!, filePair);
}
if (FilesAreSameSize(filePair))
{
return DefaultCompare(settings, filePair);
}
return Task.FromResult(CompareResult.NotEqual());
}
public static Task<CompareResult> DefaultCompare(VerifySettings settings, FilePair filePair)
{
return DoCompare(
settings,
(stream1, stream2, _) => StreamsAreEqual(stream1, stream2),
filePair);
}
static bool FilesAreSameSize(in FilePair file)
{
FileInfo first = new(file.Received);
FileInfo second = new(file.Verified);
return first.Length == second.Length;
}
static async Task<CompareResult> DoCompare(VerifySettings settings, StreamCompare compare, FilePair filePair)
{
#if NETSTANDARD2_0 || NETFRAMEWORK
using var fs1 = FileHelpers.OpenRead(filePair.Received);
using var fs2 = FileHelpers.OpenRead(filePair.Verified);
#else
await using var fs1 = FileHelpers.OpenRead(filePair.Received);
await using var fs2 = FileHelpers.OpenRead(filePair.Verified);
#endif
return await compare(fs1, fs2, settings.Context);
}
#region DefualtCompare
static async Task<CompareResult> StreamsAreEqual(Stream stream1, Stream stream2)
{
const int bufferSize = 1024 * sizeof(long);
var buffer1 = new byte[bufferSize];
var buffer2 = new byte[bufferSize];
while (true)
{
var count = await ReadBufferAsync(stream1, buffer1);
//no need to compare size here since only enter on files being same size
if (count == 0)
{
return CompareResult.Equal;
}
await ReadBufferAsync(stream2, buffer2);
for (var i = 0; i < count; i += sizeof(long))
{
if (BitConverter.ToInt64(buffer1, i) != BitConverter.ToInt64(buffer2, i))
{
return CompareResult.NotEqual();
}
}
}
}
static async Task<int> ReadBufferAsync(Stream stream, byte[] buffer)
{
var bytesRead = 0;
while (bytesRead < buffer.Length)
{
var read = await stream.ReadAsync(buffer, bytesRead, buffer.Length - bytesRead);
if (read == 0)
{
// Reached end of stream.
return bytesRead;
}
bytesRead += read;
}
return bytesRead;
}
#endregion
} | 29.733333 | 123 | 0.574832 | [
"MIT"
] | JordanMarr/Verify | src/Verify/Compare/FileComparer.cs | 3,451 | C# |
//using Glimpse.Core.Extensibility;
//namespace MvcMusicStore.Framework
//{
// public class QueryClientScript : IStaticClientScript
// {
// public ScriptOrder Order
// {
// get { return ScriptOrder.IncludeAfterClientInterfaceScript; }
// }
// public string GetUri(string version)
// {
// return "/Framework/QueryScript.js";
// }
// }
//} | 24.294118 | 75 | 0.583535 | [
"Apache-2.0"
] | Alexandre-Busarello/Glimpse | source/Glimpse.Mvc3.MusicStore.Sample/Framework/QueryClientScript.cs | 415 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using until.develop;
namespace until.utils.algorithm
{
public class DijkstraResolver
{
private class Node
{
public bool Open = false;
public bool Close = false;
public float Cost = float.MaxValue;
public int Index = 0;
public Node(int index)
{
Index = index;
}
public override string ToString()
{
return $"{base.ToString()} ({Index}, {Cost})";
}
}
private class Context
{
public Node[] Nodes = null;
public Node[] WipList = null;
public int WipCount = 0;
public bool hasSearchNode => WipCount > 0;
public Context(int count)
{
Nodes = new Node[count];
WipList = new Node[count];
for (int index = 0; index < count; ++index)
{
Nodes[index] = new Node(index);
}
}
public Node enqueue(int index)
{
var node = Nodes[index];
return enqueue(node);
}
public Node enqueue(Node node)
{
if (node.Open | node.Close)
{
return node;
}
node.Open = true;
WipList[WipCount] = node;
++WipCount;
return node;
}
public Node dequeue()
{
int min_index = -1;
float min_cost = float.MaxValue;
for (int index = 0; index < WipCount; ++index)
{
var test = WipList[index];
if (test.Cost <= min_cost)
{
min_cost = test.Cost;
min_index = index;
}
}
if (min_index < 0)
{
return null;
}
var node = WipList[min_index];
node.Close = true;
WipCount = Math.Max(WipCount - 1, 0);
WipList[min_index] = WipList[WipCount];
return node;
}
}
#region Methods
public static int[] resolvePath(DijkstraCondition condition)
{
// 探査
var context = new Context(condition.EntityCount);
var start_node = context.enqueue(condition.Goal);
var found = false;
start_node.Cost = 0.0f;
while (context.hasSearchNode)
{
var search_node = context.dequeue();
if (search_node.Index == condition.Start)
{
found = true;
break;
}
var neighbours = condition.getNeighbours(search_node.Index);
foreach (var neighbour_index in neighbours)
{
var neighbour_node = context.enqueue(neighbour_index);
var neighbour_cost = search_node.Cost + condition.getLinkCost(search_node.Index, neighbour_index);
if (neighbour_node.Cost > neighbour_cost)
{
neighbour_node.Cost = neighbour_cost;
}
}
}
// 結果を戻す
if (!found)
{
return null;
}
var answer = new List<int>();
var node = context.Nodes[condition.Start];
while (node != null)
{
answer.Add(node.Index);
var cost_min = node.Cost;
var neighbours = condition.getNeighbours(node.Index);
node = null;
if (neighbours != null)
{
foreach (var neighbour_index in neighbours)
{
var neighbour = context.Nodes[neighbour_index];
if (neighbour.Cost <= cost_min)
{
node = neighbour;
cost_min = neighbour.Cost;
}
}
}
}
return answer.ToArray();
}
private static Context resolveAllCostSearch(DijkstraCondition condition)
{
// 探査
var context = new Context(condition.EntityCount);
var start_node = context.enqueue(condition.Start);
start_node.Cost = 0.0f;
while (context.hasSearchNode)
{
var search_node = context.dequeue();
var neighbours = condition.getNeighbours(search_node.Index);
foreach (var neighbour_index in neighbours)
{
var neighbour_node = context.enqueue(neighbour_index);
var neighbour_cost = search_node.Cost + condition.getLinkCost(search_node.Index, neighbour_index);
if (neighbour_node.Cost > neighbour_cost)
{
neighbour_node.Cost = neighbour_cost;
}
}
}
return context;
}
public static float[] resolveAllCost(DijkstraCondition condition)
{
var context = resolveAllCostSearch(condition);
var cost_list = new float[condition.EntityCount];
for (int index = 0; index < condition.EntityCount; ++index)
{
cost_list[index] = context.Nodes[index].Cost;
}
return cost_list;
}
public static int[] resolveNearestIndexList(DijkstraCondition condition)
{
var context = resolveAllCostSearch(condition);
var list = new List<Node>(context.Nodes);
list.Sort((a, b) => Math.Sign(a.Cost - b.Cost));
var indecies = new int[list.Count];
for (int index = 0; index < list.Count; ++index)
{
indecies[index] = list[index].Index;
}
return indecies;
}
#endregion
}
public interface DijkstraCondition
{
public int Start { get; }
public int Goal { get; }
public int EntityCount { get; }
public float getLinkCost(int start, int end);
public int[] getNeighbours(int start);
}
}
| 31.403756 | 118 | 0.458962 | [
"MIT"
] | fullmoonhalf/until | Assets/Until/Scripts/Utils/Dijkstra.cs | 6,709 | C# |
#pragma checksum "F:\DotNetSelfPractise_Home\source\Class10and11\AutofacTrying\Trying2\Views\Shared\_Layout.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "5c0d780952970826bd192b3ddb169589ba277088"
// <auto-generated/>
#pragma warning disable 1591
[assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCore.Views_Shared__Layout), @"mvc.1.0.view", @"/Views/Shared/_Layout.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 "F:\DotNetSelfPractise_Home\source\Class10and11\AutofacTrying\Trying2\Views\_ViewImports.cshtml"
using Trying2;
#line default
#line hidden
#nullable disable
#nullable restore
#line 2 "F:\DotNetSelfPractise_Home\source\Class10and11\AutofacTrying\Trying2\Views\_ViewImports.cshtml"
using Trying2.Models;
#line default
#line hidden
#nullable disable
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"5c0d780952970826bd192b3ddb169589ba277088", @"/Views/Shared/_Layout.cshtml")]
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"b2840dd170dc9f6687156bfa6ae1a88ec7f3f601", @"/Views/_ViewImports.cshtml")]
public class Views_Shared__Layout : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<dynamic>
{
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_0 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("rel", new global::Microsoft.AspNetCore.Html.HtmlString("stylesheet"), 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("href", new global::Microsoft.AspNetCore.Html.HtmlString("~/lib/bootstrap/dist/css/bootstrap.min.css"), 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("href", new global::Microsoft.AspNetCore.Html.HtmlString("~/css/site.css"), 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("class", new global::Microsoft.AspNetCore.Html.HtmlString("navbar-brand"), 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("asp-area", "", 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("asp-controller", "Home", 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", "Index", 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("name", "_LoginPartial", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_8 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("class", new global::Microsoft.AspNetCore.Html.HtmlString("nav-link text-dark"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_9 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-action", "Privacy", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_10 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("src", new global::Microsoft.AspNetCore.Html.HtmlString("~/lib/jquery/dist/jquery.min.js"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_11 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("src", new global::Microsoft.AspNetCore.Html.HtmlString("~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_12 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("src", "~/js/site.js", 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.Razor.TagHelpers.HeadTagHelper __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_HeadTagHelper;
private global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper;
private global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.BodyTagHelper __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_BodyTagHelper;
private global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper;
private global::Microsoft.AspNetCore.Mvc.TagHelpers.PartialTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_PartialTagHelper;
private global::Microsoft.AspNetCore.Mvc.TagHelpers.ScriptTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper;
#pragma warning disable 1998
public async override global::System.Threading.Tasks.Task ExecuteAsync()
{
WriteLiteral("<!DOCTYPE html>\r\n<html lang=\"en\">\r\n");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("head", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "5c0d780952970826bd192b3ddb169589ba2770888210", async() => {
WriteLiteral("\r\n <meta charset=\"utf-8\" />\r\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\r\n <title>");
#nullable restore
#line 6 "F:\DotNetSelfPractise_Home\source\Class10and11\AutofacTrying\Trying2\Views\Shared\_Layout.cshtml"
Write(ViewData["Title"]);
#line default
#line hidden
#nullable disable
WriteLiteral(" - Trying2</title>\r\n ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("link", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "5c0d780952970826bd192b3ddb169589ba2770888868", async() => {
}
);
__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_1);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\r\n ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("link", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "5c0d780952970826bd192b3ddb169589ba27708810046", async() => {
}
);
__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_2);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\r\n");
}
);
__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_HeadTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.HeadTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_HeadTagHelper);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\r\n");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("body", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "5c0d780952970826bd192b3ddb169589ba27708811929", async() => {
WriteLiteral("\r\n <header>\r\n <nav class=\"navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3\">\r\n <div class=\"container\">\r\n ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("a", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "5c0d780952970826bd192b3ddb169589ba27708812385", async() => {
WriteLiteral("Trying2");
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_3);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Area = (string)__tagHelperAttribute_4.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_4);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Controller = (string)__tagHelperAttribute_5.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_5);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Action = (string)__tagHelperAttribute_6.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_6);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral(@"
<button class=""navbar-toggler"" type=""button"" data-toggle=""collapse"" data-target="".navbar-collapse"" aria-controls=""navbarSupportedContent""
aria-expanded=""false"" aria-label=""Toggle navigation"">
<span class=""navbar-toggler-icon""></span>
</button>
<div class=""navbar-collapse collapse d-sm-inline-flex flex-sm-row-reverse"">
");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("partial", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "5c0d780952970826bd192b3ddb169589ba27708814569", async() => {
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_PartialTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.PartialTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_PartialTagHelper);
__Microsoft_AspNetCore_Mvc_TagHelpers_PartialTagHelper.Name = (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("\r\n <ul class=\"navbar-nav flex-grow-1\">\r\n <li class=\"nav-item\">\r\n ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("a", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "5c0d780952970826bd192b3ddb169589ba27708815886", async() => {
WriteLiteral("Home");
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_8);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Area = (string)__tagHelperAttribute_4.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_4);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Controller = (string)__tagHelperAttribute_5.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_5);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Action = (string)__tagHelperAttribute_6.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_6);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\r\n </li>\r\n <li class=\"nav-item\">\r\n ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("a", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "5c0d780952970826bd192b3ddb169589ba27708817725", async() => {
WriteLiteral("Privacy");
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_8);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Area = (string)__tagHelperAttribute_4.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_4);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Controller = (string)__tagHelperAttribute_5.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_5);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Action = (string)__tagHelperAttribute_9.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_9);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\r\n </li>\r\n </ul>\r\n </div>\r\n </div>\r\n </nav>\r\n </header>\r\n <div class=\"container\">\r\n <main role=\"main\" class=\"pb-3\">\r\n ");
#nullable restore
#line 35 "F:\DotNetSelfPractise_Home\source\Class10and11\AutofacTrying\Trying2\Views\Shared\_Layout.cshtml"
Write(RenderBody());
#line default
#line hidden
#nullable disable
WriteLiteral("\r\n </main>\r\n </div>\r\n\r\n <footer class=\"border-top footer text-muted\">\r\n <div class=\"container\">\r\n © 2020 - Trying2 - ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("a", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "5c0d780952970826bd192b3ddb169589ba27708820103", async() => {
WriteLiteral("Privacy");
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Area = (string)__tagHelperAttribute_4.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_4);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Controller = (string)__tagHelperAttribute_5.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_5);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Action = (string)__tagHelperAttribute_9.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_9);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\r\n </div>\r\n </footer>\r\n ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("script", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "5c0d780952970826bd192b3ddb169589ba27708821785", async() => {
}
);
__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_10);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\r\n ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("script", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "5c0d780952970826bd192b3ddb169589ba27708822886", async() => {
}
);
__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_11);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\r\n ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("script", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "5c0d780952970826bd192b3ddb169589ba27708823987", async() => {
}
);
__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper);
__Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.ScriptTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper);
__Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper.Src = (string)__tagHelperAttribute_12.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_12);
#nullable restore
#line 46 "F:\DotNetSelfPractise_Home\source\Class10and11\AutofacTrying\Trying2\Views\Shared\_Layout.cshtml"
__Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper.AppendVersion = true;
#line default
#line hidden
#nullable disable
__tagHelperExecutionContext.AddTagHelperAttribute("asp-append-version", __Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper.AppendVersion, 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("\r\n ");
#nullable restore
#line 47 "F:\DotNetSelfPractise_Home\source\Class10and11\AutofacTrying\Trying2\Views\Shared\_Layout.cshtml"
Write(RenderSection("Scripts", required: false));
#line default
#line hidden
#nullable disable
WriteLiteral("\r\n");
}
);
__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_BodyTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.BodyTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_BodyTagHelper);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\r\n</html>\r\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<dynamic> Html { get; private set; }
}
}
#pragma warning restore 1591
| 83.533333 | 384 | 0.725749 | [
"MIT"
] | Amphibian007/DotNetSelfPractise_Home | source/Class10and11/AutofacTrying/Trying2/obj/Debug/netcoreapp3.1/Razor/Views/Shared/_Layout.cshtml.g.cs | 27,566 | C# |
using System;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
using System.Threading.Tasks;
using ARSoft.Tools.Net;
using McMaster.Extensions.CommandLineUtils;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Server.Kestrel.Core;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using static Arashi.AoiConfig;
using Timer = System.Timers.Timer;
namespace Arashi.Aoi
{
class Program
{
static void Main(string[] args)
{
var cmd = new CommandLineApplication
{
Name = "Arashi.Aoi",
Description = "ArashiDNS.Aoi - Lightweight DNS over HTTPS Server" +
Environment.NewLine +
$"Copyright (c) {DateTime.Now.Year} Milkey Tan. Code released under the Mozilla Public License 2.0" +
Environment.NewLine +
"https://github.com/mili-tan/ArashiDNS.Aoi/blob/master/CREDITS.md"
};
cmd.HelpOption("-?|-h|--help");
var ipOption = cmd.Option<string>("-l|--listen <IPEndPoint>", "Set server listening address and port <127.0.0.1:2020>",
CommandOptionType.SingleValue);
var upOption = cmd.Option<string>("-u|--upstream <IPAddress>", "Set upstream origin DNS server IP address <8.8.8.8>",
CommandOptionType.SingleValue);
var buOption = cmd.Option<string>("-b|--backupstream <IPAddress>", "Set backup upstream DNS server IP address <8.8.8.8>",
CommandOptionType.SingleValue);
var timeoutOption = cmd.Option<int>("-t|--timeout <Timeout(ms)>", "Set timeout for query to upstream DNS server <500>",
CommandOptionType.SingleValue);
var retriesOption = cmd.Option<int>("-r|--retries <Int>", "Set number of retries for query to upstream DNS server <5>",
CommandOptionType.SingleValue);
var perfixOption = cmd.Option<string>("-p|--perfix <PerfixString>", "Set your DNS over HTTPS server query prefix </dns-query>",
CommandOptionType.SingleValue);
var cacheOption = cmd.Option("-c|--cache:<Type>", "Local query cache settings [full/flexible/none]", CommandOptionType.SingleOrNoValue);
var logOption = cmd.Option("--log:<Type>", "Console log output settings [full/dns/none]", CommandOptionType.SingleOrNoValue);
var chinaListOption = cmd.Option("-cn|--chinalist", "Set enable ChinaList", CommandOptionType.NoValue);
var tcpOption = cmd.Option("--tcp", "Set enable upstream DNS query using TCP only", CommandOptionType.NoValue);
var httpsOption = cmd.Option("-s|--https", "Set enable HTTPS", CommandOptionType.NoValue);
var pfxOption = cmd.Option<string>("-pfx|--pfxfile <FilePath>", "Set your pfx certificate file path <./cert.pfx>",
CommandOptionType.SingleOrNoValue);
var pfxPassOption = cmd.Option<string>("-pass|--pfxpass <Password>", "Set your pfx certificate password <password>",
CommandOptionType.SingleOrNoValue);
var pemOption = cmd.Option<string>("-pem|--pemfile <FilePath>", "Set your pem certificate file path <./cert.pem>",
CommandOptionType.SingleOrNoValue);
var keyOption = cmd.Option<string>("-key|--keyfile <FilePath>", "Set your pem certificate key file path <./cert.key>",
CommandOptionType.SingleOrNoValue);
var syncmmdbOption = cmd.Option<string>("--syncmmdb", "Sync MaxMind GeoLite2 DB", CommandOptionType.NoValue);
var synccnlsOption = cmd.Option<string>("--synccnls", "Sync China White List", CommandOptionType.NoValue);
var noecsOption = cmd.Option("--noecs", "Set force disable active EDNS Client Subnet", CommandOptionType.NoValue);
var transidOption = cmd.Option("--transid", "Set enable DNS Transaction ID", CommandOptionType.NoValue);
var showOption = cmd.Option("--show", "Show current active configuration", CommandOptionType.NoValue);
var saveOption = cmd.Option("--save", "Save active configuration to config.json file", CommandOptionType.NoValue);
var loadOption = cmd.Option<string>("--load:<FilePath>", "Load existing configuration from config.json file [./config.json]",
CommandOptionType.SingleOrNoValue);
var loadcnOption = cmd.Option<string>("--loadcn:<FilePath>", "Load existing configuration from cnlist.json file [./cnlist.json]",
CommandOptionType.SingleOrNoValue);
var testOption = cmd.Option("-e|--test", "Exit after passing the test", CommandOptionType.NoValue);
var ipipOption = cmd.Option("--ipip", string.Empty, CommandOptionType.NoValue);
var rankOption = cmd.Option("--rank", string.Empty, CommandOptionType.NoValue);
var adminOption = cmd.Option("--admin", string.Empty, CommandOptionType.NoValue);
var noUpdateOption = cmd.Option("-nu|--noupdate", string.Empty, CommandOptionType.NoValue);
ipipOption.ShowInHelpText = false;
adminOption.ShowInHelpText = false;
synccnlsOption.ShowInHelpText = false;
noUpdateOption.ShowInHelpText = false;
chinaListOption.ShowInHelpText = false;
loadcnOption.ShowInHelpText = false;
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
pemOption.ShowInHelpText = false;
keyOption.ShowInHelpText = false;
}
cmd.OnExecute(() =>
{
if (loadOption.HasValue())
Config = JsonConvert.DeserializeObject<AoiConfig>(
string.IsNullOrWhiteSpace(loadOption.Value())
? File.ReadAllText("config.json")
: File.ReadAllText(loadOption.Value()));
if (loadcnOption.HasValue())
DNSChinaConfig.Config = JsonConvert.DeserializeObject<DNSChinaConfig>(
string.IsNullOrWhiteSpace(loadcnOption.Value())
? File.ReadAllText("cnlist.json")
: File.ReadAllText(loadcnOption.Value()));
Console.WriteLine(cmd.Description);
var ipEndPoint = ipOption.HasValue()
? IPEndPoint.Parse(ipOption.Value())
: httpsOption.HasValue()
? new IPEndPoint(IPAddress.Loopback, 443)
: new IPEndPoint(IPAddress.Loopback, 2020);
if ((File.Exists("/.dockerenv") ||
Environment.GetEnvironmentVariables().Contains("ARASHI_RUNNING_IN_CONTAINER") ||
Environment.GetEnvironmentVariables().Contains("ARASHI_ANY")) &&
!ipOption.HasValue()) ipEndPoint.Address = IPAddress.Any;
if (Environment.GetEnvironmentVariables().Contains("PORT") && !ipOption.HasValue())
try
{
if (string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("PORT")))
throw new Exception();
ipEndPoint.Port = Convert.ToInt32(Environment.GetEnvironmentVariable("PORT"));
}
catch (Exception)
{
Console.WriteLine("Failed to get $PORT Environment Variable");
}
if (Dns.GetHostAddresses(Dns.GetHostName()).All(ip =>
IPAddress.IsLoopback(ip) || ip.AddressFamily == AddressFamily.InterNetworkV6))
{
Config.UpStream = "2001:4860:4860::8888";
Config.BackUpStream = "2001:4860:4860::8844";
Console.WriteLine("May run on IPv6 single stack network");
}
if (PortIsUse(53) && !upOption.HasValue())
{
Config.UpStream = IPAddress.Loopback.ToString();
Console.WriteLine("Use localhost:53 dns server as upstream");
}
if (upOption.HasValue()) Config.UpStream = upOption.Value();
if (buOption.HasValue()) Config.BackUpStream = buOption.Value();
if (timeoutOption.HasValue()) Config.TimeOut = timeoutOption.ParsedValue;
if (retriesOption.HasValue()) Config.Retries = retriesOption.ParsedValue;
if (perfixOption.HasValue()) Config.QueryPerfix = "/" + perfixOption.Value().Trim('/').Trim('\\');
Config.CacheEnable = cacheOption.HasValue();
Config.ChinaListEnable = chinaListOption.HasValue();
Config.RankEnable = rankOption.HasValue();
Config.LogEnable = logOption.HasValue();
Config.OnlyTcpEnable = tcpOption.HasValue();
Config.EcsEnable = !noecsOption.HasValue();
Config.UseAdminRoute = adminOption.HasValue();
Config.UseIpRoute = ipipOption.HasValue();
Config.TransIdEnable = transidOption.HasValue();
if (logOption.HasValue() && !string.IsNullOrWhiteSpace(logOption.Value()))
{
var val = logOption.Value().ToLower().Trim();
if (val == "full") Config.FullLogEnable = true;
if (val == "none" || val == "null" || val == "off") Config.LogEnable = false;
}
if (cacheOption.HasValue() && !string.IsNullOrWhiteSpace(cacheOption.Value()))
{
var val = cacheOption.Value().ToLower().Trim();
if (val == "full") Config.GeoCacheEnable = false;
if (val == "none" || val == "null" || val == "off") Config.CacheEnable = false;
}
if (Config.CacheEnable && Config.GeoCacheEnable || syncmmdbOption.HasValue() || Config.RankEnable)
{
var setupBasePath = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
Console.WriteLine(
"This product includes GeoLite2 data created by MaxMind, available from https://www.maxmind.com");
if (syncmmdbOption.HasValue())
{
if (File.Exists(setupBasePath + "GeoLite2-ASN.mmdb"))
File.Delete(setupBasePath + "GeoLite2-ASN.mmdb");
if (File.Exists(setupBasePath + "GeoLite2-City.mmdb"))
File.Delete(setupBasePath + "GeoLite2-City.mmdb");
}
if (!noUpdateOption.HasValue())
{
var timer = new Timer(100) {Enabled = true, AutoReset = true};
timer.Elapsed += (_, _) =>
{
timer.Interval = 3600000 * 24;
GetFileUpdate("GeoLite2-ASN.mmdb", Config.MaxmindAsnDbUrl);
GetFileUpdate("GeoLite2-City.mmdb", Config.MaxmindCityDbUrl);
};
}
}
if (synccnlsOption.HasValue())
{
if (File.Exists(AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "China_WhiteList.List"))
File.Delete(AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "China_WhiteList.List");
var timer = new Timer(100) {Enabled = true, AutoReset = true};
timer.Elapsed += (_, _) =>
{
timer.Interval = 3600000 * 24;
GetFileUpdate("China_WhiteList.List", DNSChinaConfig.Config.ChinaListUrl);
Task.Run(() =>
{
while (true)
{
if (File.Exists(DNSChinaConfig.Config.ChinaListPath))
{
File.ReadAllLines(DNSChinaConfig.Config.ChinaListPath).ToList()
.ConvertAll(DomainName.Parse);
break;
}
Thread.Sleep(1000);
}
});
};
}
else if (File.Exists(DNSChinaConfig.Config.ChinaListPath))
GetFileUpdate("China_WhiteList.List", DNSChinaConfig.Config.ChinaListUrl);
if (Config.UseAdminRoute)
Console.WriteLine(
$"Access Get AdminToken : /dns-admin/set-token?t={Config.AdminToken}");
var host = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(AppDomain.CurrentDomain.SetupInformation.ApplicationBase)
.ConfigureLogging(configureLogging =>
{
if (Config.LogEnable && Config.FullLogEnable) configureLogging.AddConsole();
})
.ConfigureServices(services => services.AddRouting())
.ConfigureKestrel(options =>
{
options.Limits.MaxRequestBodySize = 1024;
options.Listen(ipEndPoint, listenOptions =>
{
listenOptions.Protocols = HttpProtocols.Http1AndHttp2;
if (!httpsOption.HasValue()) return;
if (!pfxOption.HasValue() && !pemOption.HasValue()) listenOptions.UseHttps();
if (pfxOption.HasValue())
if (pfxPassOption.HasValue())
listenOptions.UseHttps(pfxOption.Value(), pfxPassOption.Value());
else listenOptions.UseHttps(pfxOption.Value());
if (pemOption.HasValue() && keyOption.HasValue())
listenOptions.UseHttps(X509Certificate2.CreateFromPem(
File.ReadAllText(pemOption.Value()), File.ReadAllText(keyOption.Value())));
});
})
.UseStartup<Startup>()
.Build();
if (testOption.HasValue())
Task.Run(() =>
{
for (int i = 0; i < 100; i++)
if (PortIsUse(ipEndPoint.Port))
host.StopAsync().Wait(5000);
Environment.Exit(0);
});
if (saveOption.HasValue())
{
File.WriteAllText("config.json", JsonConvert.SerializeObject(Config, Formatting.Indented));
if (Config.ChinaListEnable)
File.WriteAllText("cnlist.json",
JsonConvert.SerializeObject(DNSChinaConfig.Config, Formatting.Indented));
}
if (showOption.HasValue()) Console.WriteLine(JsonConvert.SerializeObject(Config, Formatting.Indented));
host.Run();
});
try
{
if (File.Exists("/.dockerenv") ||
Environment.GetEnvironmentVariables().Contains("DOTNET_RUNNING_IN_CONTAINER") ||
Environment.GetEnvironmentVariables().Contains("ARASHI_RUNNING_IN_CONTAINER"))
Console.WriteLine("ArashiDNS Running in Docker Container");
if (Environment.GetEnvironmentVariables().Contains("ARASHI_VAR"))
{
if (string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("ARASHI_VAR")))
throw new Exception();
cmd.Execute(Environment.GetEnvironmentVariable("ARASHI_VAR").Split(' '));
}
else
cmd.Execute(args);
}
catch (Exception e)
{
Console.WriteLine(e);
cmd.Execute();
}
}
public static bool PortIsUse(int port)
{
var ipEndPointsTcp = IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpListeners();
var ipEndPointsUdp = IPGlobalProperties.GetIPGlobalProperties().GetActiveUdpListeners();
return ipEndPointsTcp.Any(endPoint => endPoint.Port == port)
|| ipEndPointsUdp.Any(endPoint => endPoint.Port == port);
}
public static void GetFileUpdate(string file, string url)
{
var setupBasePath = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
if (File.Exists(setupBasePath + file))
Console.Write(file + " Last updated: " + new FileInfo(setupBasePath + file).LastWriteTimeUtc);
else Console.Write(file + " Not Exist or being Updating");
if (File.Exists(setupBasePath + file) &&
(DateTime.UtcNow - new FileInfo(setupBasePath + file).LastWriteTimeUtc)
.TotalDays > 7)
{
Console.WriteLine(
$" : Expired {(DateTime.UtcNow - new FileInfo(setupBasePath + file).LastWriteTimeUtc).TotalDays:0} days");
File.Delete(setupBasePath + file);
}
else Console.WriteLine();
if (!File.Exists(setupBasePath + file))
Task.Run(() =>
{
Console.WriteLine($"Downloading {file}...");
File.WriteAllBytes(setupBasePath + file, new HttpClient().GetByteArrayAsync(url).Result);
Console.WriteLine(file + " Download Done");
});
}
}
}
| 55.078313 | 148 | 0.545773 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | DreamLayer/Arashi.Azure.P | Arashi.Shimbashi/Program.cs | 18,288 | C# |
using System.Collections.Generic;
using System.IO;
using UnityEngine;
namespace Lasm.Continuum.Humility
{
public static partial class HUMIO
{
/// <summary>
/// Quick building of a file path, based on the persistant data path.
/// </summary>
internal static string PersistantPath(string fileName)
{
return Application.persistentDataPath + "/data/" + fileName;
}
/// <summary>
/// Quick building of a path, based on the persistant data path.
/// </summary>
public static string PersistantPath()
{
return Application.persistentDataPath + "/data/";
}
/// <summary>
/// Starts the saving operation of this value.
/// </summary>
public static Data.Save Save(this object value)
{
return new Data.Save(value);
}
/// <summary>
/// Starts a loading process.
/// </summary>
public static Data.Load Load()
{
return new Data.Load();
}
public static Data.Remove Remove(this string path)
{
return new Data.Remove(path);
}
#if UNITY_EDITOR
/// <summary>
/// Searches for a filename in the editor project, and returns its path.
/// </summary>
public static string PathOf(string fileName)
{
var files = UnityEditor.AssetDatabase.FindAssets(fileName);
if (files.Length == 0) return string.Empty;
var assetPath = UnityEditor.AssetDatabase.GUIDToAssetPath(files[0]).Replace(fileName, string.Empty);
return assetPath;
}
public static List<T> AssetsAtPathOf<T>(string fileName) where T : UnityEngine.Object
{
var files = UnityEditor.AssetDatabase.FindAssets(fileName);
if (files.Length == 0) return new List<T>();
List<T> assets = new List<T>();
for (int i = 0; i < files.Length; i++)
{
var assetPath = UnityEditor.AssetDatabase.GUIDToAssetPath(files[i]);
var asset = UnityEditor.AssetDatabase.LoadAssetAtPath<T>(assetPath);
if (asset != null) assets.Add(asset);
}
return assets;
}
#endif
/// <summary>
/// Deletes a folder.
/// </summary>
public static void Delete(string path)
{
if (File.Exists(path))
{
File.Delete(path);
}
}
/// <summary>
/// Begins a Copy operation.
/// </summary>
public static Data.Copy Copy()
{
return new Data.Copy();
}
/// <summary>
/// Begins an operation to ensure the path has, is, or does something.
/// </summary>
public static Data.Ensure Ensure(this string path)
{
return new Data.Ensure(path);
}
}
}
| 29.534653 | 112 | 0.536708 | [
"MIT"
] | stuksgens/Continuum | Runtime/Humility/IO/HUMIO_Root.cs | 2,985 | C# |
using System;
namespace Bing.Date
{
/// <summary>
/// Bing <see cref="DateTimeSpan"/> 扩展
/// </summary>
public static class DateTimeSpanExtensions
{
#region Before
/// <summary>
/// 之前
/// </summary>
/// <param name="ts">日期时间间隔</param>
public static DateTime Before(this DateTimeSpan ts) => ts.Before(DateTime.Now);
/// <summary>
/// 之前
/// </summary>
/// <param name="ts">日期时间间隔</param>
/// <param name="originalValue">原值</param>
public static DateTime Before(this DateTimeSpan ts, DateTime originalValue) => originalValue.AddMonths(-ts.Months).AddYears(-ts.Years).Add(-ts.TimeSpan);
/// <summary>
/// 之前
/// </summary>
/// <param name="ts">日期时间间隔</param>
public static DateTimeOffset OffsetBefore(this DateTimeSpan ts) => ts.Before(DateTimeOffset.Now);
/// <summary>
/// 之前
/// </summary>
/// <param name="ts">日期时间间隔</param>
/// <param name="originalValue">原值</param>
public static DateTimeOffset Before(this DateTimeSpan ts, DateTimeOffset originalValue) => originalValue.AddMonths(-ts.Months).AddYears(-ts.Years).Add(-ts.TimeSpan);
#endregion
#region From
/// <summary>
/// 从现在开始
/// </summary>
/// <param name="ts">日期时间间隔</param>
public static DateTime FromNow(this DateTimeSpan ts) => ts.From(DateTime.Now);
/// <summary>
/// 从当前时间开始的之后一段日期时间间隔
/// </summary>
/// <param name="ts">日期时间间隔</param>
/// <param name="originalValue">原值</param>
public static DateTime From(this DateTimeSpan ts, DateTime originalValue) => originalValue.AddMonths(ts.Months).AddYears(ts.Years).Add(ts.TimeSpan);
/// <summary>
/// 从现在开始
/// </summary>
/// <param name="ts">日期时间间隔</param>
public static DateTimeOffset OffsetFromNow(this DateTimeSpan ts) => ts.From(DateTimeOffset.Now);
/// <summary>
/// 从当前时间开始的之后一段日期时间间隔
/// </summary>
/// <param name="ts">日期时间间隔</param>
/// <param name="originalValue">原值</param>
public static DateTimeOffset From(this DateTimeSpan ts, DateTimeOffset originalValue) => originalValue.AddMonths(ts.Months).AddYears(ts.Years).Add(ts.TimeSpan);
#endregion
#region Number
/// <summary>
/// 创建指定年数的日期时间间隔
/// </summary>
/// <param name="years">年数</param>
public static DateTimeSpan Years(this int years) => new DateTimeSpan {Years = years};
/// <summary>
/// 创建指定季度数的日期时间间隔
/// </summary>
/// <param name="quarters">季度数</param>
public static DateTimeSpan Quarters(this int quarters) => new DateTimeSpan { Months = quarters*3 };
/// <summary>
/// 创建指定月数的日期时间间隔
/// </summary>
/// <param name="months">月数</param>
public static DateTimeSpan Months(this int months) => new DateTimeSpan { Months = months };
/// <summary>
/// 创建指定周数的日期时间间隔
/// </summary>
/// <param name="weeks">周数</param>
public static DateTimeSpan Weeks(this int weeks) => new DateTimeSpan { TimeSpan = TimeSpan.FromDays(weeks*7) };
/// <summary>
/// 创建指定周数的日期时间间隔
/// </summary>
/// <param name="weeks">周数</param>
public static DateTimeSpan Weeks(this double weeks) => new DateTimeSpan { TimeSpan = TimeSpan.FromDays(weeks * 7) };
/// <summary>
/// 创建指定天数的日期时间间隔
/// </summary>
/// <param name="days">天数</param>
public static DateTimeSpan Days(this int days) => new DateTimeSpan { TimeSpan = TimeSpan.FromDays(days) };
/// <summary>
/// 创建指定天数的日期时间间隔
/// </summary>
/// <param name="days">天数</param>
public static DateTimeSpan Days(this double days) => new DateTimeSpan { TimeSpan = TimeSpan.FromDays(days) };
/// <summary>
/// 创建指定小时数的日期时间间隔
/// </summary>
/// <param name="hours">小时数</param>
public static DateTimeSpan Hours(this int hours) => new DateTimeSpan { TimeSpan = TimeSpan.FromHours(hours) };
/// <summary>
/// 创建指定小时数的日期时间间隔
/// </summary>
/// <param name="hours">小时数</param>
public static DateTimeSpan Hours(this double hours) => new DateTimeSpan { TimeSpan = TimeSpan.FromHours(hours) };
/// <summary>
/// 创建指定分钟数的日期时间间隔
/// </summary>
/// <param name="minutes">分钟数</param>
public static DateTimeSpan Minutes(this int minutes) => new DateTimeSpan { TimeSpan = TimeSpan.FromMinutes(minutes) };
/// <summary>
/// 创建指定分钟数的日期时间间隔
/// </summary>
/// <param name="minutes">分钟数</param>
public static DateTimeSpan Minutes(this double minutes) => new DateTimeSpan { TimeSpan = TimeSpan.FromMinutes(minutes) };
/// <summary>
/// 创建指定秒数的日期时间间隔
/// </summary>
/// <param name="seconds">秒数</param>
public static DateTimeSpan Seconds(this int seconds) => new DateTimeSpan { TimeSpan = TimeSpan.FromSeconds(seconds) };
/// <summary>
/// 创建指定秒数的日期时间间隔
/// </summary>
/// <param name="seconds">秒数</param>
public static DateTimeSpan Seconds(this double seconds) => new DateTimeSpan { TimeSpan = TimeSpan.FromSeconds(seconds) };
/// <summary>
/// 创建指定毫秒数的日期时间间隔
/// </summary>
/// <param name="milliseconds">毫秒数</param>
public static DateTimeSpan Milliseconds(this int milliseconds) => new DateTimeSpan { TimeSpan = TimeSpan.FromMilliseconds(milliseconds) };
/// <summary>
/// 创建指定毫秒数的日期时间间隔
/// </summary>
/// <param name="milliseconds">毫秒数</param>
public static DateTimeSpan Milliseconds(this double milliseconds) => new DateTimeSpan { TimeSpan = TimeSpan.FromMilliseconds(milliseconds) };
/// <summary>
/// 创建指定刻度数的日期时间间隔
/// </summary>
/// <param name="ticks">刻度数</param>
public static DateTimeSpan Ticks(this int ticks) => new DateTimeSpan { TimeSpan = TimeSpan.FromTicks(ticks) };
/// <summary>
/// 创建指定刻度数的日期时间间隔
/// </summary>
/// <param name="ticks">刻度数</param>
public static DateTimeSpan Ticks(this long ticks) => new DateTimeSpan { TimeSpan = TimeSpan.FromTicks(ticks) };
#endregion
}
}
| 36.55618 | 173 | 0.583525 | [
"MIT"
] | bing-framework/Bing.Utils | src/Bing.Utils.DateTime/Bing/Date/DateTimeSpanExtensions.cs | 7,279 | C# |
//-----------------------------------------------------------------------
// <copyright company="CoApp Project">
// ResourceLib Original Code from http://resourcelib.codeplex.com
// Original Copyright (c) 2008-2009 Vestris Inc.
// Changes Copyright (c) 2011 Garrett Serack . All rights reserved.
// </copyright>
// <license>
// MIT License
// You may freely use and distribute this software under the terms of the following license agreement.
//
// 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
// </license>
//-----------------------------------------------------------------------
namespace CoApp.Developer.Toolkit.ResourceLib {
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using CoApp.Toolkit.Win32;
/// <summary>
/// A font directory, RT_FONTDIR resource.
/// </summary>
public class FontDirectoryResource : Resource {
private List<FontDirectoryEntry> _fonts = new List<FontDirectoryEntry>();
private byte[] _reserved;
/// <summary>
/// A new font resource.
/// </summary>
public FontDirectoryResource() : base(IntPtr.Zero, IntPtr.Zero, new ResourceId(ResourceTypes.RT_FONTDIR), null, ResourceUtil.NEUTRALLANGID, 0) {
}
/// <summary>
/// An existing font resource.
/// </summary>
/// <param name = "hModule">Module handle.</param>
/// <param name = "hResource">Resource ID.</param>
/// <param name = "type">Resource type.</param>
/// <param name = "name">Resource name.</param>
/// <param name = "language">Language ID.</param>
/// <param name = "size">Resource size.</param>
public FontDirectoryResource(IntPtr hModule, IntPtr hResource, ResourceId type, ResourceId name, UInt16 language, int size)
: base(hModule, hResource, type, name, language, size) {
}
/// <summary>
/// Number of fonts in this directory.
/// </summary>
public List<FontDirectoryEntry> Fonts {
get { return _fonts; }
set { _fonts = value; }
}
/// <summary>
/// Read the font resource.
/// </summary>
/// <param name = "hModule">Handle to a module.</param>
/// <param name = "lpRes">Pointer to the beginning of the font structure.</param>
/// <returns>Address of the end of the font structure.</returns>
internal override IntPtr Read(IntPtr hModule, IntPtr lpRes) {
var lpHead = lpRes;
var count = (UInt16) Marshal.ReadInt16(lpRes);
lpRes = new IntPtr(lpRes.ToInt32() + 2);
for (var i = 0; i < count; i++) {
var fontEntry = new FontDirectoryEntry();
lpRes = fontEntry.Read(lpRes);
_fonts.Add(fontEntry);
}
var reservedLen = _size - (lpRes.ToInt32() - lpHead.ToInt32() - 1);
_reserved = new byte[reservedLen];
Marshal.Copy(lpRes, _reserved, 0, reservedLen);
return lpRes;
}
/// <summary>
/// Write the font directory to a binary stream.
/// </summary>
/// <param name = "w">Binary stream.</param>
internal override void Write(BinaryWriter w) {
w.Write((UInt16) _fonts.Count);
foreach (var fontEntry in _fonts) {
fontEntry.Write(w);
}
w.Write(_reserved);
}
}
} | 44.615385 | 153 | 0.592241 | [
"Apache-2.0"
] | riverar/devtools | toolkit/ResourceLib/FontDirectoryResource.cs | 4,642 | C# |
using Microsoft.AspNetCore.Mvc;
namespace FALKR_SubstitutionCipher.Controllers
{
public class AboutController : Controller
{
public IActionResult Index()
{
return View();
}
}
}
| 15.266667 | 46 | 0.615721 | [
"MIT"
] | SamArmand/FALKR-SubstitutionCipher | src/FALKR-SubstitutionCipher/Controllers/AboutController.cs | 231 | C# |
using System;
using System.Reflection;
namespace Natasha.CSharp.Reverser
{
/// <summary>
/// 访问级别反解器
/// </summary>
public static class AccessReverser
{
/// <summary>
/// 根据枚举获取访问级别
/// </summary>
/// <param name="enumAccess">访问级别枚举</param>
/// <returns></returns>
public static string GetAccess(AccessFlags enumAccess)
{
switch (enumAccess)
{
case AccessFlags.Public:
return "public ";
case AccessFlags.Private:
return "private ";
case AccessFlags.Protected:
return "protected ";
case AccessFlags.Internal:
return "internal ";
case AccessFlags.InternalAndProtected:
return "internal protected ";
default:
return "internal ";
}
}
/// <summary>
/// 获取方法的访问级别
/// </summary>
/// <param name="reflectMethodInfo">反射出的方法成员</param>
/// <returns></returns>
public static string GetAccess(MethodInfo reflectMethodInfo)
{
if (reflectMethodInfo.IsPublic)
{
return "public ";
}
else if (reflectMethodInfo.IsPrivate)
{
return "private ";
}
else if (reflectMethodInfo.IsAssembly)
{
return "internal ";
}
else if (reflectMethodInfo.IsFamily)
{
return "protected ";
}
else if (reflectMethodInfo.IsFamilyOrAssembly)
{
return "internal protected ";
}
return "internal ";
}
/// <summary>
/// 获取字段的访问级别
/// </summary>
/// <param name="reflectFieldInfo">反射出的字段成员</param>
/// <returns></returns>
public static string GetAccess(FieldInfo reflectFieldInfo)
{
if (reflectFieldInfo.IsPublic)
{
return "public ";
}
else if (reflectFieldInfo.IsPrivate)
{
return "private ";
}
else if (reflectFieldInfo.IsFamily)
{
return "protected ";
}
else if (reflectFieldInfo.IsAssembly)
{
return "internal ";
}
else if (reflectFieldInfo.IsFamilyOrAssembly)
{
return "internal protected ";
}
return "internal ";
}
/// <summary>
/// 获取类型的访问级别
/// </summary>
/// <param name="type">类型</param>
/// <returns></returns>
public static string GetAccess<T>()
{
return GetAccess(typeof(T));
}
public static string GetAccess(Type type)
{
if (type.IsPublic)
{
return "public ";
}
else if (type.IsNotPublic)
{
return "internal ";
}
return "internal ";
}
}
}
| 18.243094 | 68 | 0.438522 | [
"MIT"
] | alexinea/Natasha | src/Natasha.CSharp/Natasha.CSharp.Reverser/Reverser/AccessReverser.cs | 3,440 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using System.Transactions;
using Newtonsoft.Json;
namespace Data
{
public class Ballpark
{
public string name { get; set; }
public string type { get; set; }
public List<Feature> features { get; set; }
public static async Task<Ballpark> GetParks(){
using (StreamReader r = new StreamReader("ballparks.json"))
{
return JsonConvert.DeserializeObject<Ballpark>(await r.ReadToEndAsync());
}
}
}
} | 24.44 | 89 | 0.608838 | [
"MIT"
] | zoidfarb204/sport-trip-api | Data/Models/Ballpark.cs | 613 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using PlexRequests.Core.Helpers;
using PlexRequests.Core.Settings;
using PlexRequests.Plex;
using PlexRequests.Sync.SyncProcessors;
namespace PlexRequests.Sync
{
public class ProcessorProvider : IProcessorProvider
{
private readonly List<ISyncProcessor> _processors;
public ProcessorProvider(
IPlexApi plexApi,
IPlexService plexService,
IMediaItemProcessor mediaItemProcessor,
IAgentGuidParser agentGuidParser,
IOptionsSnapshot<PlexSettings> plexSettings,
ILoggerFactory loggerFactory
)
{
_processors = new List<ISyncProcessor>
{
new MovieProcessor(plexService, mediaItemProcessor, plexSettings.Value, loggerFactory),
new TvProcessor(plexApi, plexService, mediaItemProcessor, plexSettings.Value, agentGuidParser, loggerFactory)
};
}
public ISyncProcessor GetProcessor(string type)
{
var processor = _processors.FirstOrDefault(x => x.Type.ToString().Equals(type, StringComparison.InvariantCultureIgnoreCase));
return processor;
}
}
}
| 32.219512 | 137 | 0.68433 | [
"MIT"
] | Jbond312/PlexRequestsApi | src/PlexRequests.Sync/ProcessorProvider.cs | 1,323 | C# |
/*
* 本文代码来自网上,请参考
* http://blog.csdn.net/sqqyq/article/details/50920261
* https://docs.microsoft.com/en-us/aspnet/web-api/overview/advanced/http-message-handlers
* 有关 HttpClient 的使用注意事项,请参考链接:
*/
using PWMIS.OAuth2.Tools;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
namespace PWMIS.OAuth2.Tools
{
/// <summary>
/// HTTP代理请求消息拦截器
/// </summary>
public class ProxyRequestHandler : DelegatingHandler
{
ProxyConfig _config;
private static object sync_obj = new object();
private Dictionary<string, HttpClient> dictHttpClient;
public ProxyRequestHandler()
{
//注意:整个应用程序周期,ProxyRequestHandler 是一个单例,所以本类不能随意使用全局变量。
dictHttpClient = new Dictionary<string, HttpClient>();
Logger.Instance.LogFilePath = this.Config.LogFilePath;
}
static ProxyRequestHandler()
{
ServicePointManager.DefaultConnectionLimit = 512;
}
private HttpClient GetHttpClient(Uri baseAddress, HttpRequestMessage request, bool sessionRequired)
{
if (sessionRequired)
{
//注意:应该每个浏览器客户端一个HttpClient 实例,这样才可以保证各自的会话不冲突
var client = getSessionHttpClient(request, baseAddress.Host);
setHttpClientHeader(client, baseAddress, request);
return client;
}
else
{
string key = baseAddress.ToString();
if (dictHttpClient.ContainsKey(key))
{
return dictHttpClient[key];
}
else
{
lock (sync_obj)
{
if (dictHttpClient.ContainsKey(key))
{
return dictHttpClient[key];
}
else
{
var client = getNoneSessionHttpClient(request, baseAddress.Host);
setHttpClientHeader(client, baseAddress, request);
dictHttpClient.Add(key, client);
//定期清除DNS缓存
var sp = ServicePointManager.FindServicePoint(baseAddress);
sp.ConnectionLeaseTimeout = 60 * 1000; // 1 分钟
return client;
}
}
}
}
}
private HttpClient getSessionHttpClient(HttpRequestMessage request, string host)
{
CookieContainer cc = new CookieContainer();
HttpClientHandler handler = new HttpClientHandler();
handler.CookieContainer = cc;
handler.UseCookies = true;
HttpClient client = new HttpClient(handler);
//client.DefaultRequestHeaders.Connection.Add("keep-alive");
//dictHttpClient.Add(key, client);
//复制Cookies
var headerCookies = request.Headers.GetCookies();
foreach (var chv in headerCookies)
{
foreach (var item in chv.Cookies)
{
Cookie cookie = new Cookie(item.Name, item.Value);
cookie.Domain = host;
cc.Add(cookie);
}
}
return client;
}
private HttpClient getNoneSessionHttpClient(HttpRequestMessage request, string host)
{
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Connection.Add("keep-alive");
return client;
}
private void setHttpClientHeader(HttpClient client, Uri baseAddress, HttpRequestMessage request)
{
client.Timeout = new TimeSpan(0, 2, 0); //Token会在资源服务器刚被请求的时候使用,跟Token失效时间无关
client.BaseAddress = baseAddress;
//复制请求头,转发请求
foreach (var item in request.Headers)
{
client.DefaultRequestHeaders.Add(item.Key, item.Value);
}
client.DefaultRequestHeaders.Add("Proxy-Server", this.Config.ServerName);
client.DefaultRequestHeaders.Host = baseAddress.Host;
}
/// <summary>
/// 获取或者设置代理服务配置
/// </summary>
public ProxyConfig Config
{
get
{
if (_config == null)
{
string filePath = HttpContext.Current.Server.MapPath("/ProxyServer.config");
if (!System.IO.File.Exists(filePath))
throw new Exception("当前站点根目录下没有发现代理配置文件:ProxyServer.config");
//每行 # 开头,表示注释内容,忽略
string[] configArr = System.IO.File.ReadAllLines(filePath);
string[] configArr1 = configArr.Where(p => !p.TrimStart(' ', '\t').StartsWith("#")).ToArray();
string configStr = string.Concat(configArr1);
//string configStr = System.IO.File.ReadAllText(filePath);
_config = Newtonsoft.Json.JsonConvert.DeserializeObject<ProxyConfig>(configStr);
}
return _config;
}
set { _config = value; }
}
/// <summary>
/// 拦截请求
/// </summary>
/// <param name="request">请求</param>
/// <param name="cancellationToken">用于发送取消操作信号</param>
/// <returns></returns>
protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
//获取URL参数
//NameValueCollection query = HttpUtility.ParseQueryString(request.RequestUri.Query);
//获取Post正文数据,比如json文本
//string fRequesContent = request.Content.ReadAsStringAsync().Result;
//可以做一些其他安全验证工作,比如Token验证,签名验证。
//可以在需要时自定义HTTP响应消息
//return SendError("自定义的HTTP响应消息", HttpStatusCode.OK);
////请求处理耗时跟踪
//Stopwatch sw = new Stopwatch();
//sw.Start();
////调用内部处理接口,并获取HTTP响应消息
////HttpResponseMessage response = await base.SendAsync(request, cancellationToken);
////篡改HTTP响应消息正文
////response.Content = new StringContent(response.Content.ReadAsStringAsync().Result.Replace(@"\\", @"\"));
//HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
//response.Content = new StringContent("被拦截了,哈哈");
//sw.Stop();
////记录处理耗时
//long exeMs = sw.ElapsedMilliseconds;
//代理服务
bool matched = false;
bool sessionRequired = false;
bool isAuthenticated = false;
string url = request.RequestUri.PathAndQuery;
Uri baseAddress = null;
//处理代理规则
foreach (var route in this.Config.RouteMaps)
{
if (url.StartsWith(route.Prefix))
{
baseAddress = new Uri("http://" + route.Host + "/");
if (!string.IsNullOrEmpty(route.Match))
{
if (route.Map == null) route.Map = "";
url = url.Replace(route.Match, route.Map);
}
matched = true;
if (route.SessionRequired)
sessionRequired = true;
if (route.IsAuthenticated)
isAuthenticated = true;
//break;
//只要不替换前缀,还可以继续匹配并且替换剩余部分
}
}
//未匹配到代理,返回本机请求响应结果
if (!matched)
{
return await base.SendAsync(request, cancellationToken);
}
//处理代理URL地址中的服务器变量,变量名使用[]中括号表示:
//注意:在这里无法使用HttpContext.Current.Session,所以下面的方法出错
//url = url.Replace("[SessionID]", HttpContext.Current.Session.SessionID);
//如果缓存没有,将继续处理
if (request.Headers.CacheControl != null &&
request.Headers.CacheControl.Public &&
this.Config.EnableCache && ProxyCacheProcess != null)
{
var response = ProxyCacheProcess(this, request);
if (response == null)
{
response = await GetNewResponseMessage(request, url, baseAddress, sessionRequired, isAuthenticated);
SetRequestCache(url, response);
}
return response;
}
return await GetNewResponseMessage(request, url, baseAddress, sessionRequired, isAuthenticated);
}
#region 缓存相关
/*
* 缓存相关资料:
* Http头介绍:Expires,Cache-Control,Last-Modified,ETag http://www.51testing.com/html/28/116228-238337.html
* 带缓存的HTTP代理服务器(五) http://blog.csdn.net/sakeven/article/details/37611967
* 缓存 HTTP POST请求和响应 http://www.oschina.net/question/82993_74342
*/
/// <summary>
/// 代理服务器缓存处理程序,如果代理配置设置了允许使用缓存,那么将调用此方法。
/// 该方法将根据HttpRequestMessage 决定如何使用缓存,如果缓存已经过期,返回空响应
/// </summary>
public Func<ProxyRequestHandler, HttpRequestMessage, HttpResponseMessage> ProxyCacheProcess;
public void SetRequestCache(string url, HttpResponseMessage value)
{
throw new NotSupportedException("当前版本不支持代理缓存");
}
public HttpResponseMessage GetRequestCache(string url)
{
throw new NotSupportedException("当前版本不支持代理缓存");
}
#endregion
/// <summary>
/// 请求目标服务器,获取响应结果
/// </summary>
/// <param name="request"></param>
/// <param name="url"></param>
/// <param name="baseAddress"></param>
/// <param name="sessionRequired">是否需要会话支持</param>
/// <param name="isAuthenticated">当前请求必须是登录验证过的,默认不要求</param>
/// <returns></returns>
private async Task<HttpResponseMessage> GetNewResponseMessage(HttpRequestMessage request, string url, Uri baseAddress, bool sessionRequired,bool isAuthenticated=false)
{
string userHostAddress = HttpContext.Current.Request.UserHostAddress;
HttpClient client = GetHttpClient(baseAddress, request, sessionRequired);
var identity = HttpContext.Current.User.Identity;
if (identity == null || identity.IsAuthenticated == false)
{
if (isAuthenticated)
{
if (this.Config.EnableRequestLog)
{
string logTxt = string.Format("Begin Time:{0} ,\r\n {1} Request-Url:{2} {3} ,\r\n Map-Url:{4} {5} ,\r\n []:{6} Statue:{7} \r\n ExctionMessage:{8}",
DateTime.Now.ToLongTimeString(),
userHostAddress,
request.Method.ToString(), request.RequestUri.ToString(),
client.BaseAddress.ToString(), url,
"[N/A]",
"Unauthorized",
"this url request need is authenticated."
);
WriteLogFile(logTxt);
}
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
response.Headers.Add("Proxy-Server", this.Config.ServerName);
return response;
}
else
{
return await ProxyReuqest(request, url, client, "[NULL]");
}
}
//处理代理的服务器变量:
//url = url.Replace("[UserName]", identity.Name);
//请求结果无权限,重新获取令牌,尝试3次
int unauthorizedCount = 0;
string errorMessage = "";
for (int i = 0; i < 3; i++)
{
using (TokenManager tm = new TokenManager(identity.Name, null))
{
//重试的时候,强制刷新令牌
if(i>0) tm.NeedRefresh = true;
TokenResponse token = tm.TakeToken();
//存在客户端登录,但是服务器重启会话丢失的情况,这时候将无法取到令牌,
//这种情况下视为客户未登录,由资源服务器来决定该访问是否需要验证授权
//所以代理服务不直接抛出错误请求。
if (token == null)
{
if (this.Config.EnableRequestLog)
{
string logTxt = string.Format("Begin Time:{0} ,\r\n {1} Request-Url:{2} {3} ,\r\n Map-Url:{4} {5} ,\r\n Old-Token:{6}\r\n Statue:{7} \r\n ExctionMessage:{8}",
DateTime.Now.ToLongTimeString(),
userHostAddress,
request.Method.ToString(), request.RequestUri.ToString(),
client.BaseAddress.ToString(), url,
tm.OldToken == null ? "[OldToken=null]" : tm.OldToken.AccessToken,
"TokenGainFailure",
tm.TokenExctionMessage
);
WriteLogFile(logTxt);
}
if (tm.TokenExctionMessage == "UserNoToken")
return await ProxyReuqest(request, url, client,tm.UserName);
else
return SendError("代理请求刷新令牌失败:" + tm.TokenExctionMessage, HttpStatusCode.Unauthorized);
}
else
{
try
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.AccessToken);
var result = await ProxyReuqest(request, url, client,tm.UserName);
if (result.StatusCode == HttpStatusCode.Unauthorized)
{
WriteLogFile(string.Format("----未授权,尝试第{0}次访问----", i + 1));
unauthorizedCount++;
client = GetHttpClient(baseAddress, request, true);
}
else
{
return result;
}
}
catch (Exception ex)
{
errorMessage = string.Format("----{0} Proxy Request Error:{1},Request Url:{2} ----",
DateTime.Now.ToString("HH:mm:ss.fff"), ex.Message, url);
if (ex.InnerException != null)
errorMessage += ex.InnerException.Message;
WriteLogFile(errorMessage);
WriteLogFile(ex.StackTrace);
break;
}
}
}
}//end for
if (unauthorizedCount >= 3)
return SendError("已经3次尝试使用令牌访问资源服务器,仍然被拒绝授权访问。", HttpStatusCode.Unauthorized);
else
return SendError("访问资源服务器发生错误:"+errorMessage, HttpStatusCode.InternalServerError);
}
private async Task<HttpResponseMessage> ProxyReuqest(HttpRequestMessage request, string url, HttpClient client,string userName)
{
HttpResponseMessage result = null;
string allLogText = "";
if (this.Config.EnableRequestLog)
{
string userHostAddress = HttpContext.Current.Request.UserHostAddress;
string token = client.DefaultRequestHeaders.Authorization == null ? "" : client.DefaultRequestHeaders.Authorization.ToString();
string logTxt = string.Format("Begin Time:{0} ,\r\n {1} Request-Url:{2} {3} ,\r\n Map-Url:{4} {5} ,\r\n User:{6} Token:{7}\r\n ",
DateTime.Now.ToString("HH:mm:ss.fff"),
userHostAddress,
request.Method.ToString(), request.RequestUri.ToString(),
client.BaseAddress.ToString(), url,
userName, token
);
//WriteLogFile(logTxt);
allLogText = logTxt;
}
Stopwatch sw = new Stopwatch();
sw.Start();
if (request.Method == HttpMethod.Get)
{
result = await client.GetAsync(url);
}
else if (request.Method == HttpMethod.Post)
{
result = await client.PostAsync(url, request.Content);
}
else if (request.Method == HttpMethod.Put)
{
result = await client.PutAsync(url, request.Content);
}
else if (request.Method == HttpMethod.Delete)
{
result = await client.DeleteAsync(url);
}
else
{
result = SendError("PWMIS ASP.NET Proxy 不支持这种 Method:" + request.Method.ToString(), HttpStatusCode.BadRequest);
}
sw.Stop();
result.Headers.Add("Proxy-Server", this.Config.ServerName);
if (this.Config.EnableRequestLog)
{
string logTxt = string.Format("End Time:{0} ,\r\n Statue:{1} ,\r\n Elapsed(ms):{2} ",
DateTime.Now.ToString("HH:mm:ss.fff"),
//request.Method.ToString(), request.RequestUri.ToString(),
//client.BaseAddress.ToString(), url,
result.StatusCode.ToString(),
sw.Elapsed.TotalMilliseconds
);
if (result.StatusCode != HttpStatusCode.OK)
{
string contentMsg = result.StatusCode == HttpStatusCode.Unauthorized ? "HTTP Error 401.0 - Unauthorized" : result.Content.ReadAsStringAsync().Result;
logTxt += "\r\n Error Text:" + contentMsg;
logTxt += "\r\n Request Headers:" + client.DefaultRequestHeaders.ToString() + "---------End Error Messages-----------";
}
allLogText += logTxt;
WriteLogFile(allLogText);
}
//
if (string.IsNullOrEmpty(this.Config.OAuthRedirUrl))
{
return result;
}
else
{
if (result.StatusCode == HttpStatusCode.Unauthorized && this.Config.UnauthorizedRedir)
{
//如果未登录,禁止访问API,跳转到相应的页面
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.Redirect);
response.Headers.Location = new Uri(this.Config.OAuthRedirUrl);
return response;
}
else
{
return result;
}
}
}
private void WriteLogFile(string logTxt)
{
Logger.Instance.WriteLine(logTxt);
}
/// <summary>
/// 构造自定义HTTP响应消息
/// </summary>
/// <param name="error"></param>
/// <param name="code"></param>
/// <returns></returns>
private HttpResponseMessage SendError(string error, HttpStatusCode code)
{
var response = new HttpResponseMessage();
response.Content = new StringContent(error);
response.StatusCode = code;
return response;
}
}
} | 41.325956 | 192 | 0.491261 | [
"Apache-2.0"
] | bluedoctor/PWMIS.OAuth2.0 | PWMIS.OAuth2.Tools/RequestHandler.cs | 22,141 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using SeoSchema;
using SeoSchema.Enumerations;
using SuperStructs;
namespace SeoSchema.Entities
{
/// <summary>
/// For a given health insurance plan, the specification for costs and coverage of prescription drugs.
/// <see cref="https://schema.org/HealthPlanFormulary"/>
/// </summary>
public class HealthPlanFormulary : IEntity
{
/// Whether The costs to the patient for services under this network or formulary.
public Or<bool>? HealthPlanCostSharing { get; set; }
/// The tier(s) of drugs offered by this formulary or insurance plan.
public Or<string>? HealthPlanDrugTier { get; set; }
/// Whether prescriptions can be delivered by mail.
public Or<bool>? OffersPrescriptionByMail { get; set; }
/// An additional type for the item, typically used for adding more specific types from external vocabularies in microdata syntax. This is a relationship between something and a class that the thing is in. In RDFa syntax, it is better to use the native RDFa syntax - the 'typeof' attribute - for multiple types. Schema.org tools may have only weaker understanding of extra types, in particular those defined externally.
public Or<Uri>? AdditionalType { get; set; }
/// An alias for the item.
public Or<string>? AlternateName { get; set; }
/// A description of the item.
public Or<string>? Description { get; set; }
/// A sub property of description. A short description of the item used to disambiguate from other, similar items. Information from other properties (in particular, name) may be necessary for the description to be useful for disambiguation.
public Or<string>? DisambiguatingDescription { get; set; }
/// The identifier property represents any kind of identifier for any kind of Thing, such as ISBNs, GTIN codes, UUIDs etc. Schema.org provides dedicated properties for representing many of these, either as textual strings or as URL (URI) links. See background notes for more details.
public Or<PropertyValue, string, Uri>? Identifier { get; set; }
/// An image of the item. This can be a URL or a fully described ImageObject.
public Or<ImageObject, Uri>? Image { get; set; }
/// Indicates a page (or other CreativeWork) for which this thing is the main entity being described. See background notes for details. Inverse property: mainEntity.
public Or<CreativeWork, Uri>? MainEntityOfPage { get; set; }
/// The name of the item.
public Or<string>? Name { get; set; }
/// Indicates a potential Action, which describes an idealized action in which this thing would play an 'object' role.
public Or<Action>? PotentialAction { get; set; }
/// URL of a reference Web page that unambiguously indicates the item's identity. E.g. the URL of the item's Wikipedia page, Wikidata entry, or official website.
public Or<Uri>? SameAs { get; set; }
/// A CreativeWork or Event about this Thing.. Inverse property: about.
public Or<CreativeWork, Event>? SubjectOf { get; set; }
/// URL of the item.
public Or<Uri>? Url { get; set; }
}
}
| 52.412698 | 427 | 0.693822 | [
"MIT"
] | jefersonsv/SeoSchema | src/SeoSchema/Entities/HealthPlanFormulary.cs | 3,302 | C# |
// Copyright 2014 The Rector & Visitors of the University of Virginia
//
// 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 Xamarin.Forms;
namespace Sensus.UI.Inputs
{
public class ButtonWithValue : Button
{
public string Value { get; set; }
}
}
| 31.833333 | 75 | 0.740838 | [
"Apache-2.0"
] | bzd3y/sensus | Sensus.Shared/UI/Inputs/ButtonWithValue.cs | 766 | C# |
// Copyright (c) Microsoft Corporation
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO.Abstractions;
using System.Linq;
using Microsoft.Plugin.Folder.Sources.Result;
namespace Microsoft.Plugin.Folder.Sources
{
public class QueryEnvironmentVariable : IQueryEnvironmentVariable
{
private readonly IDirectory _directory;
private readonly IEnvironmentHelper _environmentHelper;
public QueryEnvironmentVariable(IDirectory directory, IEnvironmentHelper environmentHelper)
{
_directory = directory;
_environmentHelper = environmentHelper;
}
public IEnumerable<IItemResult> Query(string querySearch)
{
if (querySearch == null)
{
throw new ArgumentNullException(nameof(querySearch));
}
return GetEnvironmentVariables(querySearch)
.OrderBy(v => v.Title)
.Where(v => v.Title.StartsWith(querySearch, StringComparison.InvariantCultureIgnoreCase));
}
public IEnumerable<EnvironmentVariableResult> GetEnvironmentVariables(string querySearch)
{
foreach (DictionaryEntry variable in _environmentHelper.GetEnvironmentVariables())
{
if (variable.Value == null)
{
continue;
}
var name = "%" + (string)variable.Key + "%";
var path = (string)variable.Value;
if (_directory.Exists(path))
{
yield return new EnvironmentVariableResult(querySearch, name, path);
}
}
}
}
}
| 33.701754 | 107 | 0.603332 | [
"MIT"
] | 10088/PowerToys | src/modules/launcher/Plugins/Microsoft.Plugin.Folder/Sources/QueryEnvironmentVariable.cs | 1,867 | C# |
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using SaintCoinach.Imaging;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Saint = SaintCoinach.Xiv;
namespace Garland.Data.Modules
{
public class FishingSpots : Module
{
Dictionary<string, dynamic> _baitByName = new Dictionary<string, dynamic>();
Dictionary<string, dynamic> _fishingSpotsByName = new Dictionary<string, dynamic>();
List<dynamic> _fishItems = new List<dynamic>();
Dictionary<string, Tuple<int, int, int>> _hackFishingSpotLocations = new Dictionary<string, Tuple<int, int, int>>()
{
// Diadem fishing spots have no set coordinates.
["Diadem Grotto"] = Tuple.Create(1647, 14, 34), // 158
["Southern Diadem Lake"] = Tuple.Create(1647, 8, 30), // 149
["Northern Diadem Lake"] = Tuple.Create(1647, 10, 9), // 151
["Blustery Cloudtop"] = Tuple.Create(1647, 31, 11), // 152
["Calm Cloudtop"] = Tuple.Create(1647, 28, 33), // 153
["Swirling Cloudtop"] = Tuple.Create(1647, 13, 24), // 154
};
HashSet<int> _hackExcludedFishingSpots = new HashSet<int>() {
// Legacy Diadem fishing spots.
147, 150
};
public override string Name => "Fish";
public override void Start()
{
BuildFishingSpots();
BuildFish();
BuildSupplementalFishData();
BuildBaitChains();
}
dynamic BuildBait(string baitName)
{
if (_baitByName.TryGetValue(baitName, out var bait))
return bait;
var item = GarlandDatabase.Instance.ItemsByName[baitName];
bait = new JObject();
bait.name = baitName;
bait.id = item.id;
bait.icon = item.icon;
if (item.category == 47) // Seafood
bait.mooch = 1;
else if (item.category != 33) // Fishing tackle
throw new InvalidOperationException("Bad bait.");
_builder.Db.Baits.Add(bait);
_baitByName[baitName] = bait;
return bait;
}
void BuildFish()
{
foreach (var sFishParameter in _builder.Sheet<Saint.FishParameter>())
{
var guideText = sFishParameter.Text.ToString();
if (string.IsNullOrEmpty(guideText))
continue;
var item = GarlandDatabase.Instance.ItemsById[sFishParameter.Item.Key];
item.fish = new JObject();
item.fish.guide = guideText;
item.fish.icon = GetFishIcon((UInt16)sFishParameter.Item.GetRaw("Icon"));
if (sFishParameter.WeatherRestricted)
item.fish.weatherRestricted = 1;
if (sFishParameter.TimeRestricted)
item.fish.timeRestricted = 1;
var sGatheringSubCategory = (Saint.GatheringSubCategory)sFishParameter["GatheringSubCategory"];
if (sGatheringSubCategory != null && sGatheringSubCategory.Key > 0)
{
item.fish.folklore = sGatheringSubCategory.Item.Key;
_builder.Db.AddReference(item, "item", (int)item.fish.folklore, false);
var folkloreItem = _builder.Db.ItemsById[sGatheringSubCategory.Item.Key];
if (folkloreItem.unlocks == null)
folkloreItem.unlocks = new JArray();
folkloreItem.unlocks.Add(sFishParameter.Item.Key);
_builder.Db.AddReference(folkloreItem, "item", sFishParameter.Item.Key, false);
}
}
foreach (var sSpearfishingItem in _builder.Sheet<Saint.SpearfishingItem>())
{
var guideText = sSpearfishingItem["Description"]?.ToString();
if (string.IsNullOrEmpty(guideText))
continue;
var sItem = (Saint.Item)sSpearfishingItem["Item"];
var item = GarlandDatabase.Instance.ItemsById[sItem.Key];
item.fish = new JObject();
item.fish.guide = guideText;
item.fish.icon = GetFishIcon((UInt16)sItem.GetRaw("Icon"));
}
}
int GetFishIcon(UInt16 itemIconIndex)
{
// Replace 02 icon id with 07, eg. 029046 -> 079046 for fish rubbing image
var fishIconIndex = itemIconIndex - 20000 + 70000;
var icon = IconHelper.GetIcon(_builder.Realm.Packs, fishIconIndex);
return IconDatabase.EnsureEntry("fish", icon);
}
void BuildSupplementalFishData()
{
var comma = new string[] { ", " };
dynamic currentFishingSpot = null;
JArray currentFishingSpotItems = null;
dynamic currentNode = null;
JArray currentNodeItems = null;
var lines = Utils.Tsv("Supplemental\\FFXIV Data - Fishing.tsv");
foreach (var rLine in lines.Skip(1))
{
// Line data
var name = rLine[0];
// Name may reference either fishing spot, spearfishing node, or fish - check here.
if (_builder.Db.SpearfishingNodesByName.TryGetValue(name, out var node))
{
currentFishingSpot = null;
currentFishingSpotItems = null;
currentNode = node;
currentNodeItems = node.items;
continue;
}
if (_fishingSpotsByName.TryGetValue(name, out var fishingSpot))
{
currentNode = null;
currentNodeItems = null;
currentFishingSpot = fishingSpot;
currentFishingSpotItems = fishingSpot.items;
continue;
}
// Fish info
var bait = rLine[1];
var start = rLine[2];
var end = rLine[3];
var transition = rLine[4];
var weather = rLine[5];
var predator = rLine[6];
var tug = rLine[7];
var hookset = rLine[8];
var gathering = rLine[9];
var snagging = rLine[10];
var fishEyes = rLine[11];
var ff14anglerId = rLine[12];
// Fill item fishing information.
var item = GarlandDatabase.Instance.ItemsByName[name];
_fishItems.Add(item);
// Some quest fish may not have been previously recognized as a fish.
if (item.fish == null)
item.fish = new JObject();
if (item.fish.spots == null)
item.fish.spots = new JArray();
dynamic spot = new JObject();
if (currentFishingSpot != null)
spot.spot = currentFishingSpot.id;
else if (currentNode != null)
spot.node = currentNode.id;
// Sanity check weather and time restrictions.
// Sanity check only applies to normal fishing spots. The
// fields aren't available for spearfishing yet.
if (currentFishingSpot != null)
CheckConditions(name, item.fish, ref weather, ref transition, ref start, ref end);
// Baits & Gigs
if (bait.Contains("Gig Head"))
{
if (spot.gig == null)
spot.gig = new JArray();
spot.gig.Add(bait);
}
else if (!string.IsNullOrEmpty(bait))
{
spot.tmpBait = bait;
// If not otherwise specified, fish should inherit the time
// and weather restrictions of restricted bait (like predators).
var baitItem = _builder.Db.ItemsByName[bait];
if (baitItem.fish != null)
{
dynamic baitSpotView = ((JArray)baitItem.fish.spots).FirstOrDefault(s => s["spot"] == spot.spot && s["node"] == spot.node);
if (baitSpotView == null)
throw new InvalidOperationException($"Can't find bait view for {name} bait {bait}.");
InheritConditions(spot, baitSpotView, weather, transition, start, end);
}
}
// Time restrictions
if (start != "" || end != "")
{
spot.during = new JObject();
if (start != "")
spot.during.start = int.Parse(start);
if (end != "")
spot.during.end = int.Parse(end);
}
// Weather restrictions
if (transition != "")
{
var transitionList = transition.Split(comma, StringSplitOptions.None);
CheckWeather(transitionList);
spot.transition = new JArray(transitionList);
}
if (weather != "")
{
var weatherList = weather.Split(comma, StringSplitOptions.None);
CheckWeather(weatherList);
spot.weather = new JArray(weatherList);
}
// Predators
if (predator != "")
{
var tokens = predator.Split(comma, StringSplitOptions.None);
spot.predator = new JArray();
for (var i = 0; i < tokens.Length; i += 2)
{
var predatorName = tokens[i];
spot.predator.Add(BuildPredator(predatorName, tokens[i + 1]));
// If not otherwise specified, fish should inherit the time
// and weather restrictions of restricted predators (like bait).
var predatorItem = _builder.Db.ItemsByName[predatorName];
if (predatorItem.fish != null)
{
var predatorSpots = (JArray)predatorItem.fish.spots;
dynamic predatorSpotView = predatorSpots.FirstOrDefault(s => s["spot"] == spot.spot && s["node"] == spot.node);
if (predatorSpotView == null)
{
// Predators for spearfishing nodes may not exist on this spot/node.
// Fallback to any available spot.
predatorSpotView = predatorSpots.FirstOrDefault();
if (predatorSpotView == null)
throw new InvalidOperationException($"Can't find predator view for {name} predator {predatorName}.");
}
InheritConditions(spot, predatorSpotView, weather, transition, start, end);
}
}
}
// Other properties.
if (hookset != "")
spot.hookset = hookset + " Hookset";
if (gathering != "")
spot.gatheringReq = int.Parse(gathering);
if (snagging != "")
spot.snagging = 1;
if (fishEyes == "Y")
spot.fishEyes = 1;
// Add the fish to this gathering point if it's not otherwise there.
if (currentFishingSpot != null && !currentFishingSpotItems.Any(i => (int)i["id"] == (int)item.id))
{
if (item.fishingSpots == null)
item.fishingSpots = new JArray();
item.fishingSpots.Add(currentFishingSpot.id);
dynamic obj = new JObject();
obj.id = item.id;
obj.lvl = item.ilvl;
currentFishingSpot.items.Add(obj);
_builder.Db.AddReference(currentFishingSpot, "item", (int)item.id, false);
_builder.Db.AddReference(item, "fishing", (int)currentFishingSpot.id, true);
}
if (currentNode != null && !currentNodeItems.Any(i => (int)i["id"] == (int)item.id))
{
if (item.nodes == null)
item.nodes = new JArray();
item.nodes.Add(currentNode.id);
dynamic obj = new JObject();
obj.id = item.id;
currentNodeItems.Add(obj);
_builder.Db.AddReference(currentNode, "item", (int)item.id, false);
_builder.Db.AddReference(item, "node", (int)currentNode.id, true);
}
item.fish.spots.Add(spot);
}
}
void InheritConditions(dynamic spot, dynamic inheritSpot, string weather, string transition, string start, string end)
{
if (weather == "" && inheritSpot.weather != null)
spot.weather = new JArray(inheritSpot.weather);
if (transition == "" && inheritSpot.transition != null)
spot.transition = new JArray(inheritSpot.transition);
if (start == "" && end == "" && inheritSpot.during != null)
spot.during = new JObject(inheritSpot.during);
}
void CheckConditions(string name, dynamic fish, ref string weather, ref string transition, ref string start, ref string end)
{
bool isTimeRestricted = fish.timeRestricted == 1;
bool isWeatherRestricted = fish.weatherRestricted == 1;
if (start == "N/A")
{
if (isTimeRestricted)
DatabaseBuilder.PrintLine($"{name} has time restrictions but N/A for start time.");
else
start = "";
}
if (end == "N/A")
{
if (isTimeRestricted)
DatabaseBuilder.PrintLine($"{name} has time restrictions but N/A for end time.");
else
end = "";
}
if (weather == "N/A")
{
if (isWeatherRestricted)
DatabaseBuilder.PrintLine($"{name} has weather restrictions but N/A for weather.");
else
weather = "";
}
if (transition == "N/A")
{
if (isWeatherRestricted)
DatabaseBuilder.PrintLine($"{name} has weather restrictions but N/A for transition.");
else
transition = "";
}
if (!isTimeRestricted && start != "")
{
DatabaseBuilder.PrintLine($"{name} has no time restrictions, but start is {start}.");
start = "";
}
if (!isTimeRestricted && end != "")
{
DatabaseBuilder.PrintLine($"{name} has no time restrictions, but end is {end}.");
end = "";
}
if (!isWeatherRestricted && transition != "")
{
DatabaseBuilder.PrintLine($"{name} has no weather restrictions, but transition is {transition}.");
transition = "";
}
if (!isWeatherRestricted && weather != "")
{
DatabaseBuilder.PrintLine($"{name} has no weather restrictions, but weather is {weather}.");
weather = "";
}
}
void BuildBaitChains()
{
foreach (var item in _fishItems)
{
foreach (var spot in item.fish.spots)
{
if (spot.tmpBait == null)
continue;
List<string> baitNames = new List<string>();
var baitObj = BuildBait((string)spot.tmpBait);
spot.bait = new JArray();
foreach (var baitChain in GetBaitChains(spot, baitObj))
{
baitNames.Add((string)baitChain.name);
spot.bait.Add((int)baitChain.id);
_builder.Db.AddReference(item, "item", (int)baitChain.id, false);
}
var fishingSpot = _builder.Db.FishingSpotsById[(int)spot.spot];
_builder.Db.Fish.Add(BuildFishView(item, spot, fishingSpot, baitNames.ToArray()));
spot.Remove("tmpBait");
}
}
}
IEnumerable<dynamic> GetBaitChains(dynamic spot, dynamic baitObj)
{
if (baitObj.mooch != null)
{
var baitFishItem = _builder.Db.ItemsById[(int)baitObj.id];
foreach (var baitSpot in baitFishItem.fish.spots)
{
if (baitSpot.spot != spot.spot || baitSpot.node != baitSpot.node)
continue;
if (baitSpot.tmpBait != null)
{
var subBait = BuildBait((string)baitSpot.tmpBait);
foreach (var subBaitChain in GetBaitChains(baitSpot, subBait))
yield return subBaitChain;
}
else
{
foreach (var subBaitId in baitSpot.bait)
{
var subBaitFishItem = _builder.Db.ItemsById[(int)subBaitId];
yield return BuildBait((string)subBaitFishItem.en.name);
}
}
}
}
yield return baitObj;
}
void CheckWeather(string[] weatherList)
{
if (!weatherList.All(w => _builder.Db.Weather.Contains(w)))
throw new InvalidOperationException($"Bad weather list: {string.Join(", ", weatherList)}");
}
dynamic BuildPredator(string name, string amount)
{
dynamic obj = new JObject();
obj.id = (int)GarlandDatabase.Instance.ItemsByName[name].id;
obj.amount = int.Parse(amount);
return obj;
}
dynamic BuildPredatorView(dynamic fishItem, dynamic spotView, dynamic predator)
{
var predatorItem = GarlandDatabase.Instance.ItemsById[(int)predator.id];
if (predatorItem.fish == null)
throw new InvalidOperationException("Predator " + predatorItem.en.name + " has no fishing data.");
dynamic view = new JObject();
view.name = predatorItem.en.name;
view.predatorAmount = predator.amount;
// Find the fishing spot for this predator that matches the current spot.
dynamic predatorSpot = ((JArray)predatorItem.fish.spots).First(s => s["spot"] == spotView.spot);
view.bait = new JArray();
foreach (var baitId in predatorSpot.bait)
{
var bait = GarlandDatabase.Instance.ItemsById[(int)baitId];
view.bait.Add(bait.en.name);
GarlandDatabase.Instance.AddReference(fishItem, "item", (int)baitId, false);
}
view.id = predatorItem.id;
view.icon = predatorItem.icon;
GarlandDatabase.Instance.AddReference(fishItem, "item", (int)predatorItem.id, false);
return view;
}
dynamic BuildFishView(dynamic item, dynamic spotView, dynamic fishingSpot, string[] baits)
{
// Convert item fish data into a view for Bell/ffxivfisher.
dynamic view = new JObject();
view.name = item.en.name;
view.patch = item.patch;
if (spotView.snagging != null)
view.snagging = 1;
if (item.fish.folklore != null)
view.folklore = 1;
if (spotView.fishEyes != null)
view.fishEyes = 1;
view.bait = new JArray(baits);
if (spotView.during != null)
view.during = spotView.during;
if (spotView.predator != null)
{
view.predator = new JArray();
foreach (var predator in spotView.predator)
{
view.predator.Add(BuildPredatorView(item, spotView, predator));
}
}
if (spotView.weather != null)
view.weather = spotView.weather;
if (spotView.transition != null)
view.transition = spotView.transition;
if (spotView.hookset != null)
view.hookset = spotView.hookset;
view.id = item.id;
view.icon = item.icon;
view.func = "fish";
view.rarity = item.rarity;
view.title = fishingSpot.en.name;
view.category = GetFishingSpotCategoryName((int)fishingSpot.category);
view.lvl = fishingSpot.lvl;
if (fishingSpot.x != null)
{
var x = (double)fishingSpot.x;
var y = (double)fishingSpot.y;
view.coords = new JArray(x, y);
view.radius = fishingSpot.radius;
}
var location = GarlandDatabase.Instance.LocationsById[(int)fishingSpot.zoneid];
view.zone = MapZoneName((string)location.name);
return view;
}
string MapZoneName(string name)
{
switch (name)
{
case "Old Gridania":
case "New Gridania":
return "Gridania";
case "Limsa Lominsa Lower Decks":
case "Limsa Lominsa Upper Decks":
return "Limsa Lominsa";
}
return name;
}
void BuildFishingSpots()
{
foreach (var sFishingSpot in _builder.Sheet<Saint.FishingSpot>())
{
if (sFishingSpot.Key <= 1 || sFishingSpot.GatheringLevel == 0)
continue; // Skip
if (_hackExcludedFishingSpots.Contains(sFishingSpot.Key))
continue;
var name = sFishingSpot.PlaceName.Name.ToString();
dynamic spot = new JObject();
spot.id = sFishingSpot.Key;
_builder.Localize.Column(spot, sFishingSpot, "PlaceName", "name");
spot.patch = PatchDatabase.Get("fishing", sFishingSpot.Key);
spot.category = sFishingSpot.FishingSpotCategory - 1;
spot.lvl = sFishingSpot.GatheringLevel;
spot.radius = sFishingSpot.Radius;
if (sFishingSpot.TerritoryType != null)
{
var locationInfo = _builder.LocationInfoByMapId[sFishingSpot.TerritoryType.Map.Key];
spot.x = Math.Round(sFishingSpot.MapX, 2);
spot.y = Math.Round(sFishingSpot.MapY, 2);
spot.zoneid = sFishingSpot.TerritoryType.Map.PlaceName.Key;
_builder.Db.AddLocationReference(sFishingSpot.TerritoryType.Map.PlaceName.Key);
}
else if (_hackFishingSpotLocations.TryGetValue(name, out var locationInfo))
{
spot.zoneid = locationInfo.Item1;
spot.x = locationInfo.Item2;
spot.y = locationInfo.Item3;
spot.approx = 1;
if (sFishingSpot.Radius == 0)
spot.radius = 300; // estimate
_builder.Db.AddLocationReference(locationInfo.Item1);
}
else
DatabaseBuilder.PrintLine($"No location for fishing spot [{sFishingSpot.Key}] {name}");
spot.areaid = sFishingSpot.PlaceName.Key;
_builder.Db.AddLocationReference(sFishingSpot.PlaceName.Key);
JArray items = new JArray();
foreach (var sItem in sFishingSpot.Items)
{
var item = _builder.Db.ItemsById[sItem.Key];
if (item.fishingSpots == null)
item.fishingSpots = new JArray();
item.fishingSpots.Add(sFishingSpot.Key);
dynamic obj = new JObject();
obj.id = sItem.Key;
obj.lvl = sItem.ItemLevel.Key;
items.Add(obj);
_builder.Db.AddReference(spot, "item", sItem.Key, false);
_builder.Db.AddReference(item, "fishing", sFishingSpot.Key, true);
}
spot.items = items;
_builder.Db.FishingSpots.Add(spot);
_builder.Db.FishingSpotsById[sFishingSpot.Key] = spot;
_fishingSpotsByName[name] = spot;
}
}
static string GetFishingSpotCategoryName(int key)
{
switch (key)
{
case 0: return "Ocean Fishing";
case 1: return "Freshwater Fishing";
case 2: return "Dunefishing";
case 3: return "Skyfishing";
case 4: return "Cloudfishing";
case 5: return "Hellfishing";
case 6: return "Aetherfishing";
case 7: return "Saltfishing";
default: throw new NotImplementedException();
}
}
}
}
| 39.689602 | 147 | 0.498286 | [
"MIT"
] | CatStarwind/GarlandTools | Garland.Data/Modules/FishingSpots.cs | 25,959 | C# |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// <auto-generated/>
// Template Source: ComplexType.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.Json.Serialization;
/// <summary>
/// The type ClassificationResult.
/// </summary>
[JsonConverter(typeof(DerivedTypeConverter<ClassificationResult>))]
public partial class ClassificationResult
{
/// <summary>
/// Gets or sets confidenceLevel.
/// The confidence level, 0 to 100, of the result.
/// </summary>
[JsonPropertyName("confidenceLevel")]
public Int32? ConfidenceLevel { get; set; }
/// <summary>
/// Gets or sets count.
/// The number of instances of the specific information type in the input.
/// </summary>
[JsonPropertyName("count")]
public Int32? Count { get; set; }
/// <summary>
/// Gets or sets sensitiveTypeId.
/// The GUID of the discovered sensitive information type.
/// </summary>
[JsonPropertyName("sensitiveTypeId")]
public Guid? SensitiveTypeId { get; set; }
/// <summary>
/// Gets or sets additional data.
/// </summary>
[JsonExtensionData]
public IDictionary<string, object> AdditionalData { get; set; }
/// <summary>
/// Gets or sets @odata.type.
/// </summary>
[JsonPropertyName("@odata.type")]
public string ODataType { get; set; }
}
}
| 32.745763 | 153 | 0.554865 | [
"MIT"
] | microsoftgraph/msgraph-beta-sdk-dotnet | src/Microsoft.Graph/Generated/model/ClassificationResult.cs | 1,932 | C# |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Text;
using DotNetty.Common.Utilities;
using DotNetty.Transport.Channels;
using Surging.Cloud.Protocol.Mqtt.Internal.Channel;
using Surging.Cloud.Protocol.Mqtt.Internal.Enums;
using Surging.Cloud.Protocol.Mqtt.Internal.Messages;
using System.Collections;
using System.Linq;
using DotNetty.Codecs.Mqtt.Packets;
using System.Threading.Tasks;
using Surging.Cloud.Protocol.Mqtt.Internal.Runtime;
using System.Net;
using Surging.Cloud.CPlatform.Address;
using Surging.Cloud.CPlatform;
using Surging.Cloud.CPlatform.Utilities;
using Surging.Cloud.CPlatform.Messages;
using Surging.Cloud.CPlatform.Ids;
namespace Surging.Cloud.Protocol.Mqtt.Internal.Services
{
public abstract class AbstractChannelService : IChannelService
{
private readonly AttributeKey<string> _loginAttrKey = AttributeKey<string>.ValueOf("login");
private readonly AttributeKey<string> _deviceIdAttrKey = AttributeKey<string>.ValueOf("deviceId");
private readonly IMessagePushService _messagePushService;
private readonly ConcurrentDictionary<string, IEnumerable<MqttChannel>> _topics = new ConcurrentDictionary<string, IEnumerable<MqttChannel>>();
private readonly ConcurrentDictionary<string, MqttChannel> _mqttChannels = new ConcurrentDictionary<String, MqttChannel>();
protected readonly ConcurrentDictionary<String, ConcurrentQueue<RetainMessage>> _retain = new ConcurrentDictionary<String, ConcurrentQueue<RetainMessage>>();
private readonly IMqttBrokerEntryManger _mqttBrokerEntryManger;
private readonly IMqttRemoteInvokeService _mqttRemoteInvokeService;
private readonly string _publishServiceId;
public AbstractChannelService(IMessagePushService messagePushService,
IMqttBrokerEntryManger mqttBrokerEntryManger,
IMqttRemoteInvokeService mqttRemoteInvokeService,
IServiceIdGenerator serviceIdGenerator
)
{
_messagePushService = messagePushService;
_mqttBrokerEntryManger = mqttBrokerEntryManger;
_mqttRemoteInvokeService = mqttRemoteInvokeService;
_publishServiceId= serviceIdGenerator.GenerateServiceId(typeof(IMqttRomtePublishService).GetMethod("Publish"));
}
public ConcurrentDictionary<string, MqttChannel> MqttChannels { get {
return _mqttChannels;
}
}
public AttributeKey<string> DeviceIdAttrKey
{
get
{
return _deviceIdAttrKey;
}
}
public AttributeKey<string> LoginAttrKey
{
get
{
return _loginAttrKey;
}
}
public ConcurrentDictionary<string, IEnumerable<MqttChannel>> Topics
{
get
{
return _topics;
}
}
public ConcurrentDictionary<String, ConcurrentQueue<RetainMessage>> Retain
{
get
{
return _retain;
}
}
public abstract Task Close(string deviceId, bool isDisconnect);
public abstract Task<bool> Connect(string deviceId, MqttChannel build);
public bool RemoveChannel(string topic, MqttChannel mqttChannel)
{
var result = false;
if (!string.IsNullOrEmpty(topic) && mqttChannel != null)
{
_topics.TryGetValue(topic, out IEnumerable<MqttChannel> mqttChannels);
var channels = mqttChannels == null ? new List<MqttChannel>() : mqttChannels.ToList();
channels.Remove(mqttChannel);
_topics.AddOrUpdate(topic, channels, (key, value) => channels);
result = true;
}
return result;
}
public async ValueTask<string> GetDeviceId(IChannel channel)
{
string deviceId = null;
if (channel != null)
{
deviceId = channel.GetAttribute<string>(DeviceIdAttrKey).Get();
}
return await new ValueTask<string>(deviceId);
}
public bool AddChannel(string topic, MqttChannel mqttChannel)
{
var result = false;
if (!string.IsNullOrEmpty(topic) && mqttChannel != null)
{
_topics.TryGetValue(topic, out IEnumerable<MqttChannel> mqttChannels);
var channels = mqttChannels==null ? new List<MqttChannel>(): mqttChannels.ToList();
channels.Add(mqttChannel);
_topics.AddOrUpdate(topic, channels, (key, value) => channels);
result = true;
}
return result;
}
public MqttChannel GetMqttChannel(string deviceId)
{
MqttChannel channel = null;
if (!string.IsNullOrEmpty(deviceId))
{
_mqttChannels.TryGetValue(deviceId, out channel);
}
return channel;
}
protected async Task RegisterMqttBroker(string topic)
{
var addresses = await _mqttBrokerEntryManger.GetMqttBrokerAddress(topic);
var host = NetUtils.GetHostAddress();
if (addresses==null || !addresses.Any(p => p.ToString() == host.ToString()))
await _mqttBrokerEntryManger.Register(topic, host);
}
protected async Task BrokerCancellationReg(string topic)
{
if (Topics.ContainsKey(topic))
{
if (Topics[topic].Count() == 0)
await _mqttBrokerEntryManger.CancellationReg(topic, NetUtils.GetHostAddress());
}
else
{
await _mqttBrokerEntryManger.CancellationReg(topic, NetUtils.GetHostAddress());
}
}
public async Task RemotePublishMessage(string deviceId, MqttWillMessage willMessage)
{
await _mqttRemoteInvokeService.InvokeAsync(new MqttRemoteInvokeContext
{
topic = willMessage.Topic,
InvokeMessage = new RemoteInvokeMessage
{
ServiceId = _publishServiceId,
Parameters = new Dictionary<string, object>() {
{"deviceId",deviceId},
{ "message",willMessage}
}
},
}, AppConfig.ServerOptions.ExecutionTimeoutInMilliseconds);
}
public abstract Task Login(IChannel channel, string deviceId, ConnectMessage mqttConnectMessage);
public abstract Task Publish(IChannel channel, PublishPacket mqttPublishMessage);
public abstract Task Pubrec(MqttChannel channel, int messageId);
public abstract ValueTask PingReq(IChannel channel);
public abstract Task Pubrel(IChannel channel, int messageId);
public abstract Task SendWillMsg(MqttWillMessage willMeaasge);
public abstract Task Suscribe(string deviceId, params string[] topics);
public abstract Task UnSubscribe(string deviceId, params string[] topics);
public abstract Task Publish(string deviceId, MqttWillMessage willMessage);
public async ValueTask<bool> GetDeviceIsOnine(string deviceId)
{
bool result = false;
if (!string.IsNullOrEmpty(deviceId))
{
MqttChannels.TryGetValue(deviceId, out MqttChannel mqttChannel);
result = mqttChannel==null?false: await mqttChannel.IsOnine();
}
return result;
}
}
}
| 37.79902 | 166 | 0.628842 | [
"MIT"
] | microserviceframe/surging.cloud-new | src/Surging.Cloud/Surging.Cloud.Protocol.Mqtt/Internal/Services/AbstractChannelService.cs | 7,713 | C# |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
using System.Collections.Generic;
using Aliyun.Acs.Core;
using Aliyun.Acs.Core.Http;
using Aliyun.Acs.Core.Transform;
using Aliyun.Acs.Core.Utils;
using Aliyun.Acs.vs;
using Aliyun.Acs.vs.Transform;
using Aliyun.Acs.vs.Transform.V20181212;
namespace Aliyun.Acs.vs.Model.V20181212
{
public class AddRenderingDeviceInternetPortsRequest : RpcAcsRequest<AddRenderingDeviceInternetPortsResponse>
{
public AddRenderingDeviceInternetPortsRequest()
: base("vs", "2018-12-12", "AddRenderingDeviceInternetPorts")
{
if (this.GetType().GetProperty("ProductEndpointMap") != null && this.GetType().GetProperty("ProductEndpointType") != null)
{
this.GetType().GetProperty("ProductEndpointMap").SetValue(this, Aliyun.Acs.vs.Endpoint.endpointMap, null);
this.GetType().GetProperty("ProductEndpointType").SetValue(this, Aliyun.Acs.vs.Endpoint.endpointRegionalType, null);
}
Method = MethodType.POST;
}
private string iSP;
private string ipProtocol;
private long? ownerId;
private string instanceIds;
private string internalPort;
public string ISP
{
get
{
return iSP;
}
set
{
iSP = value;
DictionaryUtil.Add(QueryParameters, "ISP", value);
}
}
public string IpProtocol
{
get
{
return ipProtocol;
}
set
{
ipProtocol = value;
DictionaryUtil.Add(QueryParameters, "IpProtocol", value);
}
}
public long? OwnerId
{
get
{
return ownerId;
}
set
{
ownerId = value;
DictionaryUtil.Add(QueryParameters, "OwnerId", value.ToString());
}
}
public string InstanceIds
{
get
{
return instanceIds;
}
set
{
instanceIds = value;
DictionaryUtil.Add(QueryParameters, "InstanceIds", value);
}
}
public string InternalPort
{
get
{
return internalPort;
}
set
{
internalPort = value;
DictionaryUtil.Add(QueryParameters, "InternalPort", value);
}
}
public override bool CheckShowJsonItemName()
{
return false;
}
public override AddRenderingDeviceInternetPortsResponse GetResponse(UnmarshallerContext unmarshallerContext)
{
return AddRenderingDeviceInternetPortsResponseUnmarshaller.Unmarshall(unmarshallerContext);
}
}
}
| 24.915385 | 134 | 0.66996 | [
"Apache-2.0"
] | aliyun/aliyun-openapi-net-sdk | aliyun-net-sdk-vs/Vs/Model/V20181212/AddRenderingDeviceInternetPortsRequest.cs | 3,239 | C# |
using System.Threading.Tasks;
using Nethereum.JsonRpc.Client;
public interface IIbftGetValidatorsByBlockHash
{
Task<string[]> SendRequestAsync(string blockHash, object id = null);
RpcRequest BuildRequest(string blockHash, object id = null);
} | 31.375 | 72 | 0.788845 | [
"MIT"
] | avtokey/Nethereum | src/Nethereum.Pantheon/RPC/IBFT/IIbftGetValidatorsByBlockHash.cs | 251 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Windows;
using Macad.Common;
using Macad.Core;
using Macad.Core.Topology;
namespace Macad.Interaction
{
public sealed class SelectionManager : IDisposable
{
public List<InteractiveEntity> SelectedEntities
{
get
{
for (var i = _SelectionContexts.Count - 1; i >= 0; i--)
{
var sel = _SelectionContexts[i].SelectedEntities;
if (sel != null)
return sel;
}
return _BaseContext.SelectedEntities;
}
}
//--------------------------------------------------------------------------------------------------
readonly WorkspaceController _WorkspaceController;
//--------------------------------------------------------------------------------------------------
public SelectionManager(WorkspaceController workspaceController)
{
_WorkspaceController = workspaceController;
_BaseContext = new SelectionContext(workspaceController, SelectionContext.Options.IncludeAll | SelectionContext.Options.NewSelectedList);
_BaseContext.Activate();
Entity.EntityRemoved += _Entity_EntityRemoved;
}
//--------------------------------------------------------------------------------------------------
public void Dispose()
{
Entity.EntityRemoved -= _Entity_EntityRemoved;
_BaseContext.Dispose();
SelectedEntities.Clear();
}
//--------------------------------------------------------------------------------------------------
#region Selection
void ClearSelection(bool suppressEvent = false)
{
if (!suppressEvent && _RaiseSelectionChanging(null, SelectedEntities))
return;
SelectedEntities.Clear();
}
//--------------------------------------------------------------------------------------------------
public void SelectEntity(InteractiveEntity entity, bool exclusiveSelection = true)
{
if (_RaiseSelectionChanging(
entity != null ? new List<InteractiveEntity>() { entity } : new List<InteractiveEntity>(),
exclusiveSelection ? SelectedEntities : null))
return;
if (exclusiveSelection)
{
ClearSelection(true);
}
if (entity != null)
{
_AddEntityToSelectionList(entity);
_SyncToAisSelection();
}
else
{
_WorkspaceController.Workspace.AisContext.ClearSelected(false);
}
_RaiseSelectionChanged();
}
//--------------------------------------------------------------------------------------------------
public void SelectEntities(IEnumerable<InteractiveEntity> entities, bool exclusiveSelection = true)
{
var entityList = entities?.ToList() ?? new List<InteractiveEntity>();
if (_RaiseSelectionChanging(entityList,
exclusiveSelection ? SelectedEntities : null))
return;
if (exclusiveSelection)
{
ClearSelection(true);
}
if (entities != null)
{
foreach (var entity in entityList)
{
_AddEntityToSelectionList(entity);
}
_SyncToAisSelection();
}
else
{
_WorkspaceController.Workspace.AisContext.ClearSelected(false);
}
_RaiseSelectionChanged();
}
//--------------------------------------------------------------------------------------------------
[SuppressMessage("ReSharper", "PossibleMultipleEnumeration")]
public void ChangeEntitySelection(IEnumerable<InteractiveEntity> entitiesToSelect, IEnumerable<InteractiveEntity> entitiesToUnSelect)
{
if (_RaiseSelectionChanging(entitiesToSelect, entitiesToUnSelect))
return;
foreach (var entity in entitiesToUnSelect)
{
_RemoveEntityFromSelectionList(entity);
}
foreach (var entity in entitiesToSelect)
{
_AddEntityToSelectionList(entity);
}
_SyncToAisSelection();
_RaiseSelectionChanged();
}
//--------------------------------------------------------------------------------------------------
void _AddEntityToSelectionList(InteractiveEntity entity)
{
if (entity == null)
return;
SelectedEntities.Add(entity);
}
//--------------------------------------------------------------------------------------------------
void _RemoveEntityFromSelectionList(InteractiveEntity entity)
{
if (entity == null)
return;
SelectedEntities.Remove(entity);
}
//--------------------------------------------------------------------------------------------------
void _SyncFromAisSelection()
{
var aisContext = _WorkspaceController.Workspace.AisContext;
var aisSelected = new List<InteractiveEntity>();
aisContext.InitSelected();
while (aisContext.MoreSelected())
{
var selected = _WorkspaceController.VisualObjects.GetVisibleEntity(aisContext.SelectedInteractive());
if (selected != null)
aisSelected.Add(selected);
aisContext.NextSelected();
}
var toSelect = aisSelected.Except(SelectedEntities).ToArray();
var toDeselect = SelectedEntities.Except(aisSelected).ToArray();
if (_RaiseSelectionChanging(toSelect, toDeselect))
return;
foreach (var entity in toDeselect)
{
_RemoveEntityFromSelectionList(entity);
}
foreach (var entity in toSelect)
{
_AddEntityToSelectionList(entity);
}
_RaiseSelectionChanged();
}
//--------------------------------------------------------------------------------------------------
void _SyncToAisSelection()
{
var aisContext = _WorkspaceController.Workspace.AisContext;
_WorkspaceController.VisualObjects.UpdateInvalidatedEntities();
aisContext.ClearSelected(false);
foreach (var entity in SelectedEntities)
{
var visualShape = _WorkspaceController.VisualObjects.Get(entity);
if (visualShape != null)
{
aisContext.AddOrRemoveSelected(visualShape.AisObject, false);
}
}
}
//--------------------------------------------------------------------------------------------------
public class SelectionChangingCancelEventArgs : CancelEventArgs
{
public IEnumerable<InteractiveEntity> EntitiesToUnSelect { get; }
public IEnumerable<InteractiveEntity> EntitiesToSelect { get; }
public SelectionChangingCancelEventArgs(IEnumerable<InteractiveEntity> entitiesToSelect, IEnumerable<InteractiveEntity> entitiesToUnSelect)
{
EntitiesToSelect = entitiesToSelect ?? new List<InteractiveEntity>();
EntitiesToUnSelect = entitiesToUnSelect ?? new List<InteractiveEntity>();
}
}
//--------------------------------------------------------------------------------------------------
public delegate void SelectionChangingEventHandler(SelectionManager selectionManager, SelectionChangingCancelEventArgs eventArgs);
//--------------------------------------------------------------------------------------------------
public event SelectionChangingEventHandler SelectionChanging;
//--------------------------------------------------------------------------------------------------
bool _RaiseSelectionChanging(IEnumerable<InteractiveEntity> entitiesToSelect, IEnumerable<InteractiveEntity> entitiesToUnSelect)
{
if (SelectionChanging != null)
{
var eventArgs = new SelectionChangingCancelEventArgs(entitiesToSelect, entitiesToUnSelect);
SelectionChanging.Invoke(this, eventArgs);
return eventArgs.Cancel;
}
return false;
}
//--------------------------------------------------------------------------------------------------
public delegate void SelectionChangedEventHandler(SelectionManager selectionManager);
//--------------------------------------------------------------------------------------------------
public event SelectionChangedEventHandler SelectionChanged;
//--------------------------------------------------------------------------------------------------
void _RaiseSelectionChanged()
{
SelectionChanged?.Invoke(this);
}
//--------------------------------------------------------------------------------------------------
void _Entity_EntityRemoved(Entity entity)
{
if (!(entity is InteractiveEntity interactiveEntity))
return;
// Deselect
_RemoveEntityFromSelectionList(interactiveEntity);
_RaiseSelectionChanged();
}
//--------------------------------------------------------------------------------------------------
#endregion
#region SelectionContext
readonly SelectionContext _BaseContext;
readonly List<SelectionContext> _SelectionContexts = new List<SelectionContext>();
public SelectionContext CurrentContext { get { return _SelectionContexts.LastOrDefault(); } }
bool _ContextUpdatePending = false;
//--------------------------------------------------------------------------------------------------
public SelectionContext OpenContext(SelectionContext.Options options = SelectionContext.Options.None)
{
(CurrentContext ?? _BaseContext).DeActivate();
var context = new SelectionContext(_WorkspaceController, options);
context.ParametersChanged += _Context_ParametersChanged;
_SelectionContexts.Add(context);
context.Activate();
_SyncToAisSelection();
Invalidate();
return context;
}
//--------------------------------------------------------------------------------------------------
public void CloseContext(SelectionContext context)
{
if (_SelectionContexts.Contains(context))
{
context.DeActivate();
context.ParametersChanged -= _Context_ParametersChanged;
_SelectionContexts.Remove(context);
_SyncToAisSelection();
(CurrentContext ?? _BaseContext).Activate();
}
Invalidate();
}
//--------------------------------------------------------------------------------------------------
void _Context_ParametersChanged(SelectionContext selectionContext)
{
Invalidate();
}
//--------------------------------------------------------------------------------------------------
public void Invalidate()
{
_ContextUpdatePending = true;
}
//--------------------------------------------------------------------------------------------------
public void Update()
{
if (!_ContextUpdatePending)
return;
var ctx = CurrentContext ?? _BaseContext;
ctx.UpdateAis();
_ContextUpdatePending = false;
}
//--------------------------------------------------------------------------------------------------
#endregion
}
} | 36.29096 | 152 | 0.438702 | [
"MIT"
] | Macad3D/Macad3D | Source/Macad.Interaction/Workspace/Selection/SelectionManager.cs | 12,849 | C# |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class StoreRoomFiller : CelluarRoomFiller {
public StoreRoomFiller(Vector2 pos, int x, int y, Room r, List<Vector2> ds) : base(pos,x,y,r,ds) {}
public override Room FillRoom()
{
randomFillChance = 90;
Ceullar();
MakeStoreSpotsAndDestructables();
RoomGenerator generator = new RoomGenerator(transform.position, grid, room, true);
MakeDoors(false);
return room;
}
public void MakeStoreSpotsAndDestructables()
{
for (int i = 3; i < grid.GetLength(0) - 3; i++)
{
for (int j = 3; j < grid.GetLength(1) - 3; j++)
{
if(j == (sizeY / 2) + 2 && i == (sizeX / 2) + 1)
{
grid[i, j] = "ST";
}
if(j == sizeY/2 && i % 3 == 0)
{
grid[i,j] = "S";
}
//else if(Random.Range (0,100) < 5)
//{
// grid[i,j] = "D";
//}
}
}
}
}
| 23.682927 | 100 | 0.530381 | [
"MIT"
] | brandio/spellLike | dungeons of spell/Assets/Scripts/MapGen/RoomFiller/StoreRoomFiller.cs | 973 | C# |
/*
This class is from this article in stackoverflow:
https://stackoverflow.com/questions/202011/encrypt-and-decrypt-a-string-in-c
Code taken from StackOverflow posts are covered by the MIT or Creative Commons license. Here is more detail:
https://meta.stackexchange.com/questions/271080/the-mit-license-clarity-on-using-code-on-stack-overflow-and-stack-exchange
*/
using System;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.IO;
namespace PinCushion.Library
{
public static class EncryptDecrypt
{
// This constant is used to determine the keysize of the encryption algorithm in bits.
// We divide this by 8 within the code below to get the equivalent number of bytes.
private const int Keysize = 256;
// This constant determines the number of iterations for the password bytes generation function.
private const int DerivationIterations = 1000;
public static string Encrypt(string plainText, string passPhrase)
{
// Salt and IV is randomly generated each time, but is preprended to encrypted cipher text
// so that the same Salt and IV values can be used when decrypting.
var saltStringBytes = Generate256BitsOfRandomEntropy();
var ivStringBytes = Generate256BitsOfRandomEntropy();
var plainTextBytes = Encoding.UTF8.GetBytes(plainText);
using (var password = new Rfc2898DeriveBytes(passPhrase, saltStringBytes, DerivationIterations))
{
var keyBytes = password.GetBytes(Keysize / 8);
using (var symmetricKey = new RijndaelManaged())
{
symmetricKey.BlockSize = 256;
symmetricKey.Mode = CipherMode.CBC;
symmetricKey.Padding = PaddingMode.PKCS7;
using (var encryptor = symmetricKey.CreateEncryptor(keyBytes, ivStringBytes))
{
using (var memoryStream = new MemoryStream())
{
using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
{
cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
cryptoStream.FlushFinalBlock();
// Create the final bytes as a concatenation of the random salt bytes, the random iv bytes and the cipher bytes.
var cipherTextBytes = saltStringBytes;
cipherTextBytes = cipherTextBytes.Concat(ivStringBytes).ToArray();
cipherTextBytes = cipherTextBytes.Concat(memoryStream.ToArray()).ToArray();
memoryStream.Close();
cryptoStream.Close();
return Convert.ToBase64String(cipherTextBytes);
}
}
}
}
}
}
public static string Decrypt(string cipherText, string passPhrase)
{
// Get the complete stream of bytes that represent:
// [32 bytes of Salt] + [32 bytes of IV] + [n bytes of CipherText]
var cipherTextBytesWithSaltAndIv = Convert.FromBase64String(cipherText);
// Get the saltbytes by extracting the first 32 bytes from the supplied cipherText bytes.
var saltStringBytes = cipherTextBytesWithSaltAndIv.Take(Keysize / 8).ToArray();
// Get the IV bytes by extracting the next 32 bytes from the supplied cipherText bytes.
var ivStringBytes = cipherTextBytesWithSaltAndIv.Skip(Keysize / 8).Take(Keysize / 8).ToArray();
// Get the actual cipher text bytes by removing the first 64 bytes from the cipherText string.
var cipherTextBytes = cipherTextBytesWithSaltAndIv.Skip((Keysize / 8) * 2).Take(cipherTextBytesWithSaltAndIv.Length - ((Keysize / 8) * 2)).ToArray();
using (var password = new Rfc2898DeriveBytes(passPhrase, saltStringBytes, DerivationIterations))
{
var keyBytes = password.GetBytes(Keysize / 8);
using (var symmetricKey = new RijndaelManaged())
{
symmetricKey.BlockSize = 256;
symmetricKey.Mode = CipherMode.CBC;
symmetricKey.Padding = PaddingMode.PKCS7;
using (var decryptor = symmetricKey.CreateDecryptor(keyBytes, ivStringBytes))
{
using (var memoryStream = new MemoryStream(cipherTextBytes))
{
using (var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
{
var plainTextBytes = new byte[cipherTextBytes.Length];
var decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
memoryStream.Close();
cryptoStream.Close();
return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);
}
}
}
}
}
}
private static byte[] Generate256BitsOfRandomEntropy()
{
var randomBytes = new byte[32]; // 32 Bytes will give us 256 bits.
using (var rngCsp = new RNGCryptoServiceProvider())
{
// Fill the array with cryptographically secure random bytes.
rngCsp.GetBytes(randomBytes);
}
return randomBytes;
}
}
}
| 50.319328 | 162 | 0.566299 | [
"MIT"
] | bhochgurtel/PinCusion | src/Pincushion.Library/EncryptDecrypt.cs | 5,990 | C# |
/*<FILE_LICENSE>
* Azos (A to Z Application Operating System) Framework
* The A to Z Foundation (a.k.a. Azist) licenses this file to you under the MIT license.
* See the LICENSE file in the project root for more information.
</FILE_LICENSE>*/
using System;
using System.Collections.Generic;
using Azos.Data;
using Azos.Scripting;
using Azos.Serialization.JSON;
namespace Azos.Tests.Nub.ScriptingAndTesting
{
[Runnable]
public class DocLogicalComparerBasicTests
{
[Run]
public void TwoEmpty()
{
var comparer = new DocLogicalComparer();
var d1 = new Doc1() {};
var d2 = new Doc1(){};
var diff = comparer.Compare(d1, d2);
diff.See();
Aver.IsTrue(diff.AreSame);
Aver.IsFalse(diff.AreDifferent);
}
[Run]
public void OneField_d1_Different()
{
var comparer = new DocLogicalComparer();
var d1 = new Doc1() { S1 = "aaa" };
var d2 = new Doc1() { };
var diff = comparer.Compare(d1, d2);
diff.See();
Aver.IsFalse(diff.AreSame);
Aver.IsTrue(diff.AreDifferent);
}
[Run]
public void OneField_d2_Different()
{
var comparer = new DocLogicalComparer();
var d1 = new Doc1() { };
var d2 = new Doc1() { S1 = "abc"};
var diff = comparer.Compare(d1, d2);
diff.See();
Aver.IsFalse(diff.AreSame);
Aver.IsTrue(diff.AreDifferent);
}
[Run]
public void OneField_d1d2_Different()
{
var comparer = new DocLogicalComparer();
var d1 = new Doc1() { S1 = "in d1"};
var d2 = new Doc1() { S1 = "this is in d2" };
var diff = comparer.Compare(d1, d2);
diff.See();
Aver.IsFalse(diff.AreSame);
Aver.IsTrue(diff.AreDifferent);
}
[Run]
public void FullCycle_doc1()
{
var comparer = new DocLogicalComparer();
var d1 = new Doc1() { S1 = "in d1" };
var json = d1.ToJson(JsonWritingOptions.PrettyPrintRowsAsMap);
var d2 = JsonReader.ToDoc<Doc1>(json);
d1.See("d1");
json.See("JSON");
d2.See("d2");
var diff = comparer.Compare(d1, d2);
diff.See();
Aver.IsTrue(diff.AreSame);
}
[Run]
public void FullCycle_doc2()
{
var comparer = new DocLogicalComparer();
var d1 = new Doc2() { S1 = "in d1", B1 = true, I1 = 1234, DT1 =new DateTime(1980, 09, 15, 0,0,0,DateTimeKind.Utc), NI1 = null, NL1 = 9_000_000_000L, S2 = null, NDT1 = null };
var json = d1.ToJson(JsonWritingOptions.PrettyPrintRowsAsMap);
var d2 = JsonReader.ToDoc<Doc2>(json);
json.See("JSON");
var diff = comparer.Compare(d1, d2);
diff.See();
Aver.IsTrue(diff.AreSame);
}
[Run]
public void FullCycle_doc3()
{
var comparer = new DocLogicalComparer();
var d1 = new Doc3
{
D1 = new Doc1{ S1 = "asdf"},
D2 = new Doc2() { S1 = "in d1", B1 = true, I1 = 1234, DT1 = new DateTime(1980, 09, 15, 0, 0, 0, DateTimeKind.Utc), NI1 = null, NL1 = 9_000_000_000L, S2 = null, NDT1 = null }
};
var json = d1.ToJson(JsonWritingOptions.PrettyPrintRowsAsMap);
var d2 = JsonReader.ToDoc<Doc3>(json);
json.See("JSON");
var diff = comparer.Compare(d1, d2);
diff.See();
Aver.IsTrue(diff.AreSame);
}
[Run]
public void FullCycle_doc4()
{
var comparer = new DocLogicalComparer();
var d1 = new Doc4
{
COL1 = new[]{ null, null, new Doc1 { S1 = "asdf" }, new Doc1 { S1 = "forgfoot" }, new Doc1 { S1 = "eat borsch!" } },
COL2 = new[]{ new Doc2() { S1 = "in d1", B1 = true, I1 = 1234, DT1 = new DateTime(1980, 09, 15, 0, 0, 0, DateTimeKind.Utc), NI1 = null, NL1 = 9_000_000_000L, S2 = null, NDT1 = null }}
};
var json = d1.ToJson(JsonWritingOptions.PrettyPrintRowsAsMap);
var d2 = JsonReader.ToDoc<Doc4>(json);
json.WriteLine();
var diff = comparer.Compare(d1, d2);
diff.See();
Aver.IsTrue(diff.AreSame);
}
[Run]
public void FullCycle_doc5()
{
var comparer = new DocLogicalComparer();
var d1 = new Doc5
{
COL1 = new List<Doc1> { null, null, new Doc1 { S1 = "asdf" }, new Doc1 { S1 = "forgfoot" }, new Doc1 { S1 = "eat borsch!" } },
COL2 = new List<Doc2> { new Doc2() { S1 = "in d1", B1 = true, I1 = 1234, DT1 = new DateTime(1980, 09, 15, 0, 0, 0, DateTimeKind.Utc), NI1 = null, NL1 = 9_000_000_000L, S2 = null, NDT1 = null } }
};
var json = d1.ToJson(JsonWritingOptions.PrettyPrintRowsAsMap);
var d2 = JsonReader.ToDoc<Doc5>(json);
json.WriteLine();
var diff = comparer.Compare(d1, d2);
diff.See();
Aver.IsTrue(diff.AreSame);
}
[Run]
public void FullCycle_doc5_into_doc4()
{
var comparer = new DocLogicalComparer();
var d1 = new Doc5
{
COL1 = new List<Doc1> { null, null, new Doc1 { S1 = "asdf" }, new Doc1 { S1 = "forgfoot" }, new Doc1 { S1 = "eat borsch!" } },
COL2 = new List<Doc2> { new Doc2() { S1 = "in d1", B1 = true, I1 = 1234, DT1 = new DateTime(1980, 09, 15, 0, 0, 0, DateTimeKind.Utc), NI1 = null, NL1 = 9_000_000_000L, S2 = null, NDT1 = null } }
};
var json = d1.ToJson(JsonWritingOptions.PrettyPrintRowsAsMap);
//Notice how we round-trip LIST into []
var d2 = JsonReader.ToDoc<Doc4>(json);
json.WriteLine();
var diff = comparer.Compare(d1, d2);
diff.See();
Aver.IsTrue(diff.AreSame);
}
public class Doc1 : TypedDoc
{
[Field]
public string S1{ get; set;}
}
public class Doc2 : TypedDoc
{
[Field] public string S1 { get; set; }
[Field] public string S2 { get; set; }
[Field] public int I1 { get; set; }
[Field] public bool B1 { get; set; }
[Field] public int? NI1 { get; set; }
[Field] public long? NL1 { get; set; }
[Field] public DateTime DT1 { get; set; }
[Field] public DateTime? NDT1 { get; set; }
}
public class Doc3 : TypedDoc//composite
{
[Field] public Doc1 D1 { get; set; }
[Field] public Doc2 D2 { get; set; }
}
public class Doc4 : TypedDoc//composite
{
[Field] public Doc1[] COL1 { get; set; }
[Field] public Doc2[] COL2 { get; set; }
}
public class Doc5 : TypedDoc//composite
{
[Field] public List<Doc1> COL1 { get; set; }
[Field] public List<Doc2> COL2 { get; set; }
}
}
}
| 25.329412 | 202 | 0.575941 | [
"MIT"
] | JohnPKosh/azos | src/testing/Azos.Tests.Nub/ScriptingAndTesting/DocLogicalComparerBasicTests.cs | 6,461 | C# |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// <auto-generated/>
// Template Source: Templates\CSharp\Requests\IEntityRequest.cs.tt
namespace Microsoft.Graph
{
using System;
using System.IO;
using System.Net.Http;
using System.Threading;
using System.Linq.Expressions;
/// <summary>
/// The interface IApprovalWorkflowProviderRequest.
/// </summary>
public partial interface IApprovalWorkflowProviderRequest : IBaseRequest
{
/// <summary>
/// Creates the specified ApprovalWorkflowProvider using POST.
/// </summary>
/// <param name="approvalWorkflowProviderToCreate">The ApprovalWorkflowProvider to create.</param>
/// <returns>The created ApprovalWorkflowProvider.</returns>
System.Threading.Tasks.Task<ApprovalWorkflowProvider> CreateAsync(ApprovalWorkflowProvider approvalWorkflowProviderToCreate); /// <summary>
/// Creates the specified ApprovalWorkflowProvider using POST.
/// </summary>
/// <param name="approvalWorkflowProviderToCreate">The ApprovalWorkflowProvider to create.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The created ApprovalWorkflowProvider.</returns>
System.Threading.Tasks.Task<ApprovalWorkflowProvider> CreateAsync(ApprovalWorkflowProvider approvalWorkflowProviderToCreate, CancellationToken cancellationToken);
/// <summary>
/// Deletes the specified ApprovalWorkflowProvider.
/// </summary>
/// <returns>The task to await.</returns>
System.Threading.Tasks.Task DeleteAsync();
/// <summary>
/// Deletes the specified ApprovalWorkflowProvider.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The task to await.</returns>
System.Threading.Tasks.Task DeleteAsync(CancellationToken cancellationToken);
/// <summary>
/// Gets the specified ApprovalWorkflowProvider.
/// </summary>
/// <returns>The ApprovalWorkflowProvider.</returns>
System.Threading.Tasks.Task<ApprovalWorkflowProvider> GetAsync();
/// <summary>
/// Gets the specified ApprovalWorkflowProvider.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The ApprovalWorkflowProvider.</returns>
System.Threading.Tasks.Task<ApprovalWorkflowProvider> GetAsync(CancellationToken cancellationToken);
/// <summary>
/// Updates the specified ApprovalWorkflowProvider using PATCH.
/// </summary>
/// <param name="approvalWorkflowProviderToUpdate">The ApprovalWorkflowProvider to update.</param>
/// <returns>The updated ApprovalWorkflowProvider.</returns>
System.Threading.Tasks.Task<ApprovalWorkflowProvider> UpdateAsync(ApprovalWorkflowProvider approvalWorkflowProviderToUpdate);
/// <summary>
/// Updates the specified ApprovalWorkflowProvider using PATCH.
/// </summary>
/// <param name="approvalWorkflowProviderToUpdate">The ApprovalWorkflowProvider to update.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <exception cref="ClientException">Thrown when an object returned in a response is used for updating an object in Microsoft Graph.</exception>
/// <returns>The updated ApprovalWorkflowProvider.</returns>
System.Threading.Tasks.Task<ApprovalWorkflowProvider> UpdateAsync(ApprovalWorkflowProvider approvalWorkflowProviderToUpdate, CancellationToken cancellationToken);
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="value">The expand value.</param>
/// <returns>The request object to send.</returns>
IApprovalWorkflowProviderRequest Expand(string value);
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="expandExpression">The expression from which to calculate the expand value.</param>
/// <returns>The request object to send.</returns>
IApprovalWorkflowProviderRequest Expand(Expression<Func<ApprovalWorkflowProvider, object>> expandExpression);
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="value">The select value.</param>
/// <returns>The request object to send.</returns>
IApprovalWorkflowProviderRequest Select(string value);
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="selectExpression">The expression from which to calculate the select value.</param>
/// <returns>The request object to send.</returns>
IApprovalWorkflowProviderRequest Select(Expression<Func<ApprovalWorkflowProvider, object>> selectExpression);
}
}
| 50.962963 | 170 | 0.667333 | [
"MIT"
] | OfficeGlobal/msgraph-beta-sdk-dotnet | src/Microsoft.Graph/Requests/Generated/IApprovalWorkflowProviderRequest.cs | 5,504 | C# |
namespace PogBot
{
class Search
{
public static async Task<(string, string)> GetImage(string additionalSearch)
{
var search = "";
if (additionalSearch.Equals(""))
{
var rand = new Random().Next(0, 2);
switch (rand)
{
case 0: search = Global.qOW + " " + Global.RandomSearchQuery(Global.queriesOW); break;
case 1: search = Global.qLOL + " " + Global.RandomSearchQuery(Global.queriesLOL); break;
}
}
else
search = additionalSearch;
if (Global.googleSearch)
{
return (search, await GoogleSearch.GetImage(Global.Instance.Client, search));
}
return (search, Global.noImageMessage);
}
public static async Task<bool> SaveImageRef(string imageURL)
{
var found = Global.IsInSaved(imageURL);
if (!found)
{
File.AppendAllText(Global.saveFile, imageURL + "\n");
}
return found;
}
}
}
| 21.928571 | 93 | 0.611292 | [
"MIT"
] | noasoder/PogBot | PogBot/Search.cs | 923 | 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.Diagnostics;
using System.IO;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;
namespace System.Net.Http
{
internal sealed class HttpProxyConnectionHandler : HttpMessageHandler
{
private readonly HttpMessageHandler _innerHandler;
private readonly IWebProxy _proxy;
private readonly ICredentials _defaultCredentials;
private readonly HttpConnectionPools _connectionPools;
private bool _disposed;
public HttpProxyConnectionHandler(HttpConnectionSettings settings, HttpMessageHandler innerHandler)
{
Debug.Assert(innerHandler != null);
_innerHandler = innerHandler;
_proxy = settings._useProxy ? settings._proxy : new PassthroughWebProxy(s_proxyFromEnvironment.Value);
_defaultCredentials = settings._defaultProxyCredentials;
_connectionPools = new HttpConnectionPools(settings._maxConnectionsPerServer);
}
protected internal override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
Uri proxyUri = null;
try
{
if (!_proxy.IsBypassed(request.RequestUri))
{
proxyUri = _proxy.GetProxy(request.RequestUri);
}
}
catch (Exception)
{
// Eat any exception from the IWebProxy and just treat it as no proxy.
// TODO #21452: This seems a bit questionable, but it's what the tests expect
}
return proxyUri == null ?
_innerHandler.SendAsync(request, cancellationToken) :
SendWithProxyAsync(proxyUri, request, cancellationToken);
}
private async Task<HttpResponseMessage> SendWithProxyAsync(
Uri proxyUri, HttpRequestMessage request, CancellationToken cancellationToken)
{
if (proxyUri.Scheme != UriScheme.Http)
{
throw new InvalidOperationException($"invalid scheme {proxyUri.Scheme} for proxy");
}
if (request.RequestUri.Scheme == UriScheme.Https)
{
// TODO #21452: Implement SSL tunneling through proxy
throw new NotImplementedException("no support for SSL tunneling through proxy");
}
HttpConnection connection = await GetOrCreateConnection(request, proxyUri).ConfigureAwait(false);
HttpResponseMessage response = await connection.SendAsync(request, cancellationToken).ConfigureAwait(false);
// Handle proxy authentication
if (response.StatusCode == HttpStatusCode.ProxyAuthenticationRequired)
{
foreach (AuthenticationHeaderValue h in response.Headers.ProxyAuthenticate)
{
// We only support Basic auth, ignore others
const string Basic = "Basic";
if (h.Scheme == Basic)
{
NetworkCredential credential =
_proxy.Credentials?.GetCredential(proxyUri, Basic) ??
_defaultCredentials?.GetCredential(proxyUri, Basic);
if (credential != null)
{
response.Dispose();
request.Headers.ProxyAuthorization = new AuthenticationHeaderValue(Basic,
AuthenticationHelper.GetBasicTokenForCredential(credential));
connection = await GetOrCreateConnection(request, proxyUri).ConfigureAwait(false);
response = await connection.SendAsync(request, cancellationToken).ConfigureAwait(false);
}
break;
}
}
}
return response;
}
private ValueTask<HttpConnection> GetOrCreateConnection(HttpRequestMessage request, Uri proxyUri)
{
var key = new HttpConnectionKey(proxyUri);
HttpConnectionPool pool = _connectionPools.GetOrAddPool(key);
return pool.GetConnectionAsync(async state =>
{
Stream stream = await ConnectHelper.ConnectAsync(state.proxyUri.IdnHost, state.proxyUri.Port).ConfigureAwait(false);
return new HttpConnection(state.pool, state.key, null, stream, null, true);
}, (pool: pool, key: key, request: request, proxyUri: proxyUri));
}
protected override void Dispose(bool disposing)
{
if (disposing && !_disposed)
{
_disposed = true;
_connectionPools.Dispose();
}
base.Dispose(disposing);
}
public static bool EnvironmentProxyConfigured => s_proxyFromEnvironment.Value != null;
private static readonly Lazy<Uri> s_proxyFromEnvironment = new Lazy<Uri>(() =>
{
// http_proxy is standard on Unix, used e.g. by libcurl.
// TODO #21452: We should support the full array of environment variables here,
// including no_proxy, all_proxy, etc.
string proxyString = Environment.GetEnvironmentVariable("http_proxy");
if (!string.IsNullOrWhiteSpace(proxyString))
{
Uri proxyFromEnvironment;
if (Uri.TryCreate(proxyString, UriKind.Absolute, out proxyFromEnvironment) ||
Uri.TryCreate(Uri.UriSchemeHttp + Uri.SchemeDelimiter + proxyString, UriKind.Absolute, out proxyFromEnvironment))
{
return proxyFromEnvironment;
}
}
return null;
});
private sealed class PassthroughWebProxy : IWebProxy
{
private readonly Uri _proxyUri;
public PassthroughWebProxy(Uri proxyUri) => _proxyUri = proxyUri;
public ICredentials Credentials { get => null; set { } }
public Uri GetProxy(Uri destination) => _proxyUri;
public bool IsBypassed(Uri host) => false;
}
}
}
| 41.416667 | 136 | 0.600681 | [
"MIT"
] | harunpehlivan/corefx | src/System.Net.Http/src/System/Net/Http/Managed/HttpProxyConnectionHandler.cs | 6,463 | C# |
#if __ANDROID_28__
using System;
using System.ComponentModel;
using Android.Content;
using Android.Support.V4.View;
using Android.Views;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android.FastRenderers;
using Xamarin.Forms.Material.Android;
using AView = Android.Views.View;
using MaterialCardView = Android.Support.Design.Card.MaterialCardView;
using Xamarin.Forms.Platform.Android;
[assembly: ExportRenderer(typeof(Xamarin.Forms.Frame), typeof(MaterialFrameRenderer), new[] { typeof(VisualMarker.MaterialVisual) })]
namespace Xamarin.Forms.Material.Android
{
public class MaterialFrameRenderer : MaterialCardView,
IVisualElementRenderer, IEffectControlProvider, IViewRenderer, ITabStop
{
float _defaultElevation = -1f;
float _defaultCornerRadius = -1f;
int _defaultStrokeWidth = -1;
int? _defaultBackgroundColor;
int? _defaultStrokeColor;
int? _defaultLabelFor;
bool _disposed;
Frame _element;
VisualElementTracker _visualElementTracker;
VisualElementPackager _visualElementPackager;
readonly GestureManager _gestureManager;
readonly EffectControlProvider _effectControlProvider;
readonly MotionEventHelper _motionEventHelper;
public MaterialFrameRenderer(Context context)
: base(new ContextThemeWrapper(context, Resource.Style.XamarinFormsMaterialTheme))
{
_gestureManager = new GestureManager(this);
_effectControlProvider = new EffectControlProvider(this);
_motionEventHelper = new MotionEventHelper();
}
public event EventHandler<VisualElementChangedEventArgs> ElementChanged;
public event EventHandler<PropertyChangedEventArgs> ElementPropertyChanged;
public override bool OnTouchEvent(MotionEvent e)
{
if (_gestureManager.OnTouchEvent(e) || base.OnTouchEvent(e))
return true;
return _motionEventHelper.HandleMotionEvent(Parent, e);
}
protected MaterialCardView Control => this;
protected Frame Element
{
get { return _element; }
set
{
if (_element == value)
return;
var oldElement = _element;
_element = value;
OnElementChanged(new ElementChangedEventArgs<Frame>(oldElement, _element));
_element?.SendViewInitialized(this);
_motionEventHelper.UpdateElement(_element);
if (!string.IsNullOrEmpty(Element.AutomationId))
ContentDescription = Element.AutomationId;
}
}
protected override void Dispose(bool disposing)
{
if (_disposed)
return;
_disposed = true;
if (disposing)
{
_gestureManager?.Dispose();
_visualElementTracker?.Dispose();
_visualElementTracker = null;
_visualElementPackager?.Dispose();
_visualElementPackager = null;
var count = ChildCount;
for (var i = 0; i < count; i++)
{
var child = GetChildAt(i);
child.Dispose();
}
if (Element != null)
{
Element.PropertyChanged -= OnElementPropertyChanged;
if (Platform.Android.Platform.GetRenderer(Element) == this)
Element.ClearValue(Platform.Android.Platform.RendererProperty);
}
}
base.Dispose(disposing);
}
protected virtual void OnElementChanged(ElementChangedEventArgs<Frame> e)
{
ElementChanged?.Invoke(this, new VisualElementChangedEventArgs(e.OldElement, e.NewElement));
if (e.OldElement != null)
{
e.OldElement.PropertyChanged -= OnElementPropertyChanged;
}
if (e.NewElement != null)
{
this.EnsureId();
if (_visualElementTracker == null)
{
_visualElementTracker = new VisualElementTracker(this);
_visualElementPackager = new VisualElementPackager(this);
_visualElementPackager.Load();
}
e.NewElement.PropertyChanged += OnElementPropertyChanged;
UpdateShadow();
UpdateCornerRadius();
UpdateBorder();
UpdateBackgroundColor();
ElevationHelper.SetElevation(this, e.NewElement);
}
}
protected virtual void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
ElementPropertyChanged?.Invoke(this, e);
if (e.PropertyName == Frame.HasShadowProperty.PropertyName)
UpdateShadow();
else if (e.PropertyName == Frame.CornerRadiusProperty.PropertyName)
UpdateCornerRadius();
else if (e.PropertyName == Frame.BorderColorProperty.PropertyName)
UpdateBorder();
else if (e.PropertyName == VisualElement.BackgroundColorProperty.PropertyName)
UpdateBackgroundColor();
}
protected override void OnLayout(bool changed, int left, int top, int right, int bottom)
{
if (Element == null)
return;
var children = Element.LogicalChildren;
for (var i = 0; i < children.Count; i++)
{
if (children[i] is VisualElement visualElement)
{
var renderer = Platform.Android.Platform.GetRenderer(visualElement);
renderer?.UpdateLayout();
}
}
}
void UpdateShadow()
{
if (_disposed || Element == null)
return;
// set the default elevation on the first time
if (_defaultElevation < 0)
_defaultElevation = CardElevation;
if (Element.HasShadow)
CardElevation = _defaultElevation;
else
CardElevation = 0f;
}
void UpdateCornerRadius()
{
if (_disposed || Element == null)
return;
var cornerRadius = Element.CornerRadius;
if (cornerRadius < 0f && _defaultCornerRadius < 0f)
return;
if (_defaultCornerRadius < 0f)
_defaultCornerRadius = Radius;
if (cornerRadius < 0f)
Radius = _defaultCornerRadius;
else
Radius = (int)Context.ToPixels(cornerRadius);
UpdateBorder();
}
void UpdateBorder()
{
if (_disposed || Element == null)
return;
var borderColor = Element.BorderColor;
if (borderColor.IsDefault && _defaultStrokeColor == null && _defaultStrokeWidth < 0f)
return;
if (_defaultStrokeColor == null)
_defaultStrokeColor = StrokeColor;
if (_defaultStrokeWidth < 0)
_defaultStrokeWidth = StrokeWidth;
if (borderColor.IsDefault)
{
StrokeColor = _defaultStrokeColor.Value;
StrokeWidth = _defaultStrokeWidth;
}
else
{
StrokeColor = borderColor.ToAndroid();
StrokeWidth = (int)Context.ToPixels(1);
}
// update the native and forms view with the border
SetContentPadding(0, 0, 0, 0);
}
void UpdateBackgroundColor()
{
if (_disposed || Element == null)
return;
var bgColor = Element.BackgroundColor;
if (bgColor.IsDefault && _defaultBackgroundColor == null)
return;
if (_defaultBackgroundColor == null)
_defaultBackgroundColor = CardBackgroundColor.DefaultColor;
SetCardBackgroundColor(bgColor.IsDefault ? _defaultBackgroundColor.Value : bgColor.ToAndroid());
}
// IVisualElementRenderer
VisualElement IVisualElementRenderer.Element => Element;
VisualElementTracker IVisualElementRenderer.Tracker => _visualElementTracker;
ViewGroup IVisualElementRenderer.ViewGroup => this;
AView IVisualElementRenderer.View => this;
void IVisualElementRenderer.SetElement(VisualElement element) =>
Element = (element as Frame) ?? throw new ArgumentException("Element must be of type Frame.");
void IVisualElementRenderer.UpdateLayout() =>
_visualElementTracker?.UpdateLayout();
SizeRequest IVisualElementRenderer.GetDesiredSize(int widthConstraint, int heightConstraint)
{
var context = Context;
return new SizeRequest(new Size(context.ToPixels(20), context.ToPixels(20)));
}
void IVisualElementRenderer.SetLabelFor(int? id)
{
if (_defaultLabelFor == null)
_defaultLabelFor = ViewCompat.GetLabelFor(this);
ViewCompat.SetLabelFor(this, (int)(id ?? _defaultLabelFor));
}
// IEffectControlProvider
void IEffectControlProvider.RegisterEffect(Effect effect) =>
_effectControlProvider?.RegisterEffect(effect);
// IViewRenderer
void IViewRenderer.MeasureExactly() =>
ViewRenderer.MeasureExactly(this, Element, Context);
// ITabStop
AView ITabStop.TabStop => this;
}
}
#endif | 27 | 133 | 0.731001 | [
"MIT"
] | P3PPP/Xamarin.Forms | Xamarin.Forms.Material.Android/MaterialFrameRenderer.cs | 7,805 | C# |
// --------------------------------------------------------------------------------------------
// Copyright (c) 2019 The CefNet Authors. All rights reserved.
// Licensed under the MIT license.
// See the licence file in the project root for full license information.
// --------------------------------------------------------------------------------------------
// Generated by CefGen
// Source: Generated/Native/Types/cef_cookie_visitor_t.cs
// --------------------------------------------------------------------------------------------
// DO NOT MODIFY! THIS IS AUTOGENERATED FILE!
// --------------------------------------------------------------------------------------------
#pragma warning disable 0169, 1591, 1573
using System;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using CefNet.WinApi;
using CefNet.CApi;
using CefNet.Internal;
namespace CefNet
{
/// <summary>
/// Structure to implement for visiting cookie values. The functions of this
/// structure will always be called on the UI thread.
/// </summary>
/// <remarks>
/// Role: Handler
/// </remarks>
public unsafe partial class CefCookieVisitor : CefBaseRefCounted<cef_cookie_visitor_t>, ICefCookieVisitorPrivate
{
#if NET_LESS_5_0
private static readonly VisitDelegate fnVisit = VisitImpl;
#endif // NET_LESS_5_0
internal static unsafe CefCookieVisitor Create(IntPtr instance)
{
return new CefCookieVisitor((cef_cookie_visitor_t*)instance);
}
public CefCookieVisitor()
{
cef_cookie_visitor_t* self = this.NativeInstance;
#if NET_LESS_5_0
self->visit = (void*)Marshal.GetFunctionPointerForDelegate(fnVisit);
#else
self->visit = (delegate* unmanaged[Stdcall]<cef_cookie_visitor_t*, cef_cookie_t*, int, int, int*, int>)&VisitImpl;
#endif
}
public CefCookieVisitor(cef_cookie_visitor_t* instance)
: base((cef_base_ref_counted_t*)instance)
{
}
[MethodImpl(MethodImplOptions.ForwardRef)]
extern bool ICefCookieVisitorPrivate.AvoidVisit();
/// <summary>
/// Method that will be called once for each cookie. |count| is the 0-based
/// index for the current cookie. |total| is the total number of cookies. Set
/// |deleteCookie| to true (1) to delete the cookie currently being visited.
/// Return false (0) to stop visiting cookies. This function may never be
/// called if no cookies are found.
/// </summary>
protected internal unsafe virtual bool Visit(CefCookie cookie, int count, int total, ref int deleteCookie)
{
return default;
}
#if NET_LESS_5_0
[UnmanagedFunctionPointer(CallingConvention.Winapi)]
private unsafe delegate int VisitDelegate(cef_cookie_visitor_t* self, cef_cookie_t* cookie, int count, int total, int* deleteCookie);
#endif // NET_LESS_5_0
// int (*)(_cef_cookie_visitor_t* self, const const _cef_cookie_t* cookie, int count, int total, int* deleteCookie)*
#if !NET_LESS_5_0
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })]
#endif
private static unsafe int VisitImpl(cef_cookie_visitor_t* self, cef_cookie_t* cookie, int count, int total, int* deleteCookie)
{
var instance = GetInstance((IntPtr)self) as CefCookieVisitor;
if (instance == null || ((ICefCookieVisitorPrivate)instance).AvoidVisit())
{
return default;
}
return instance.Visit(*(CefCookie*)cookie, count, total, ref *deleteCookie) ? 1 : 0;
}
}
}
| 37.10989 | 135 | 0.659461 | [
"MIT"
] | AigioL/CefNet | CefNet/Generated/Managed/Types/CefCookieVisitor.cs | 3,381 | C# |
namespace DriverSolutions.ModuleSystem
{
partial class XF_UserNewEdit
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(XF_UserNewEdit));
this.layoutControl1 = new DevExpress.XtraLayout.LayoutControl();
this.btnSave = new DevExpress.XtraEditors.SimpleButton();
this.btnCancel = new DevExpress.XtraEditors.SimpleButton();
this.IsAdmin = new DevExpress.XtraEditors.CheckEdit();
this.IsEnabled = new DevExpress.XtraEditors.CheckEdit();
this.LastName = new DevExpress.XtraEditors.TextEdit();
this.SecondName = new DevExpress.XtraEditors.TextEdit();
this.FirstName = new DevExpress.XtraEditors.TextEdit();
this.Password = new DevExpress.XtraEditors.TextEdit();
this.Username = new DevExpress.XtraEditors.TextEdit();
this.layoutControlGroup1 = new DevExpress.XtraLayout.LayoutControlGroup();
this.layoutControlGroup2 = new DevExpress.XtraLayout.LayoutControlGroup();
this.layoutControlItem1 = new DevExpress.XtraLayout.LayoutControlItem();
this.layoutControlItem2 = new DevExpress.XtraLayout.LayoutControlItem();
this.layoutControlGroup3 = new DevExpress.XtraLayout.LayoutControlGroup();
this.layoutControlItem5 = new DevExpress.XtraLayout.LayoutControlItem();
this.layoutControlItem4 = new DevExpress.XtraLayout.LayoutControlItem();
this.layoutControlItem3 = new DevExpress.XtraLayout.LayoutControlItem();
this.layoutControlItem6 = new DevExpress.XtraLayout.LayoutControlItem();
this.layoutControlGroup4 = new DevExpress.XtraLayout.LayoutControlGroup();
this.layoutControlItem7 = new DevExpress.XtraLayout.LayoutControlItem();
this.layoutControlItem8 = new DevExpress.XtraLayout.LayoutControlItem();
this.layoutControlItem9 = new DevExpress.XtraLayout.LayoutControlItem();
this.emptySpaceItem1 = new DevExpress.XtraLayout.EmptySpaceItem();
((System.ComponentModel.ISupportInitialize)(this.layoutControl1)).BeginInit();
this.layoutControl1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.IsAdmin.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.IsEnabled.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.LastName.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.SecondName.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.FirstName.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.Password.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.Username.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlGroup1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlGroup2)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem2)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlGroup3)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem5)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem4)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem3)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem6)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlGroup4)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem7)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem8)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem9)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.emptySpaceItem1)).BeginInit();
this.SuspendLayout();
//
// layoutControl1
//
this.layoutControl1.Controls.Add(this.btnSave);
this.layoutControl1.Controls.Add(this.btnCancel);
this.layoutControl1.Controls.Add(this.IsAdmin);
this.layoutControl1.Controls.Add(this.IsEnabled);
this.layoutControl1.Controls.Add(this.LastName);
this.layoutControl1.Controls.Add(this.SecondName);
this.layoutControl1.Controls.Add(this.FirstName);
this.layoutControl1.Controls.Add(this.Password);
this.layoutControl1.Controls.Add(this.Username);
this.layoutControl1.Dock = System.Windows.Forms.DockStyle.Fill;
this.layoutControl1.Location = new System.Drawing.Point(0, 0);
this.layoutControl1.Name = "layoutControl1";
this.layoutControl1.OptionsCustomizationForm.DesignTimeCustomizationFormPositionAndSize = new System.Drawing.Rectangle(798, 279, 250, 350);
this.layoutControl1.Root = this.layoutControlGroup1;
this.layoutControl1.Size = new System.Drawing.Size(540, 310);
this.layoutControl1.TabIndex = 0;
this.layoutControl1.Text = "layoutControl1";
//
// btnSave
//
this.btnSave.Image = ((System.Drawing.Image)(resources.GetObject("btnSave.Image")));
this.btnSave.Location = new System.Drawing.Point(235, 264);
this.btnSave.Name = "btnSave";
this.btnSave.Size = new System.Drawing.Size(141, 41);
this.btnSave.StyleController = this.layoutControl1;
this.btnSave.TabIndex = 12;
this.btnSave.Text = "Save";
this.btnSave.Click += new System.EventHandler(this.btnSave_Click);
//
// btnCancel
//
this.btnCancel.Image = ((System.Drawing.Image)(resources.GetObject("btnCancel.Image")));
this.btnCancel.Location = new System.Drawing.Point(380, 264);
this.btnCancel.Name = "btnCancel";
this.btnCancel.Size = new System.Drawing.Size(155, 41);
this.btnCancel.StyleController = this.layoutControl1;
this.btnCancel.TabIndex = 11;
this.btnCancel.Text = "Cancel";
this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click);
//
// IsAdmin
//
this.IsAdmin.Location = new System.Drawing.Point(11, 235);
this.IsAdmin.Name = "IsAdmin";
this.IsAdmin.Properties.Caption = "Is Admin";
this.IsAdmin.Size = new System.Drawing.Size(518, 19);
this.IsAdmin.StyleController = this.layoutControl1;
this.IsAdmin.TabIndex = 10;
//
// IsEnabled
//
this.IsEnabled.Location = new System.Drawing.Point(11, 181);
this.IsEnabled.Name = "IsEnabled";
this.IsEnabled.Properties.Caption = "IsEnabled";
this.IsEnabled.Size = new System.Drawing.Size(518, 19);
this.IsEnabled.StyleController = this.layoutControl1;
this.IsEnabled.TabIndex = 9;
//
// LastName
//
this.LastName.Location = new System.Drawing.Point(83, 157);
this.LastName.Name = "LastName";
this.LastName.Size = new System.Drawing.Size(446, 20);
this.LastName.StyleController = this.layoutControl1;
this.LastName.TabIndex = 8;
//
// SecondName
//
this.SecondName.Location = new System.Drawing.Point(83, 133);
this.SecondName.Name = "SecondName";
this.SecondName.Size = new System.Drawing.Size(446, 20);
this.SecondName.StyleController = this.layoutControl1;
this.SecondName.TabIndex = 7;
//
// FirstName
//
this.FirstName.Location = new System.Drawing.Point(83, 109);
this.FirstName.Name = "FirstName";
this.FirstName.Size = new System.Drawing.Size(446, 20);
this.FirstName.StyleController = this.layoutControl1;
this.FirstName.TabIndex = 6;
//
// Password
//
this.Password.Location = new System.Drawing.Point(83, 54);
this.Password.Name = "Password";
this.Password.Properties.PasswordChar = '*';
this.Password.Size = new System.Drawing.Size(446, 20);
this.Password.StyleController = this.layoutControl1;
this.Password.TabIndex = 5;
//
// Username
//
this.Username.Location = new System.Drawing.Point(83, 30);
this.Username.Name = "Username";
this.Username.Size = new System.Drawing.Size(446, 20);
this.Username.StyleController = this.layoutControl1;
this.Username.TabIndex = 4;
//
// layoutControlGroup1
//
this.layoutControlGroup1.CustomizationFormText = "Root";
this.layoutControlGroup1.EnableIndentsWithoutBorders = DevExpress.Utils.DefaultBoolean.True;
this.layoutControlGroup1.GroupBordersVisible = false;
this.layoutControlGroup1.Items.AddRange(new DevExpress.XtraLayout.BaseLayoutItem[] {
this.layoutControlGroup2,
this.layoutControlGroup3,
this.layoutControlGroup4,
this.layoutControlItem8,
this.layoutControlItem9,
this.emptySpaceItem1});
this.layoutControlGroup1.Location = new System.Drawing.Point(0, 0);
this.layoutControlGroup1.Name = "Root";
this.layoutControlGroup1.Padding = new DevExpress.XtraLayout.Utils.Padding(3, 3, 3, 3);
this.layoutControlGroup1.Size = new System.Drawing.Size(540, 310);
this.layoutControlGroup1.Text = "Root";
this.layoutControlGroup1.TextVisible = false;
//
// layoutControlGroup2
//
this.layoutControlGroup2.CustomizationFormText = "Login";
this.layoutControlGroup2.Items.AddRange(new DevExpress.XtraLayout.BaseLayoutItem[] {
this.layoutControlItem1,
this.layoutControlItem2});
this.layoutControlGroup2.Location = new System.Drawing.Point(0, 0);
this.layoutControlGroup2.Name = "layoutControlGroup2";
this.layoutControlGroup2.Padding = new DevExpress.XtraLayout.Utils.Padding(3, 3, 3, 3);
this.layoutControlGroup2.Size = new System.Drawing.Size(534, 79);
this.layoutControlGroup2.Text = "Login";
//
// layoutControlItem1
//
this.layoutControlItem1.Control = this.Username;
this.layoutControlItem1.CustomizationFormText = "Username:";
this.layoutControlItem1.Location = new System.Drawing.Point(0, 0);
this.layoutControlItem1.Name = "layoutControlItem1";
this.layoutControlItem1.Size = new System.Drawing.Size(522, 24);
this.layoutControlItem1.Text = "Username:";
this.layoutControlItem1.TextSize = new System.Drawing.Size(69, 13);
//
// layoutControlItem2
//
this.layoutControlItem2.Control = this.Password;
this.layoutControlItem2.CustomizationFormText = "Password:";
this.layoutControlItem2.Location = new System.Drawing.Point(0, 24);
this.layoutControlItem2.Name = "layoutControlItem2";
this.layoutControlItem2.Size = new System.Drawing.Size(522, 24);
this.layoutControlItem2.Text = "Password:";
this.layoutControlItem2.TextSize = new System.Drawing.Size(69, 13);
//
// layoutControlGroup3
//
this.layoutControlGroup3.CustomizationFormText = "Identification";
this.layoutControlGroup3.Items.AddRange(new DevExpress.XtraLayout.BaseLayoutItem[] {
this.layoutControlItem5,
this.layoutControlItem4,
this.layoutControlItem3,
this.layoutControlItem6});
this.layoutControlGroup3.Location = new System.Drawing.Point(0, 79);
this.layoutControlGroup3.Name = "layoutControlGroup3";
this.layoutControlGroup3.Padding = new DevExpress.XtraLayout.Utils.Padding(3, 3, 3, 3);
this.layoutControlGroup3.Size = new System.Drawing.Size(534, 126);
this.layoutControlGroup3.Text = "Identification";
//
// layoutControlItem5
//
this.layoutControlItem5.Control = this.LastName;
this.layoutControlItem5.CustomizationFormText = "Last Name:";
this.layoutControlItem5.Location = new System.Drawing.Point(0, 48);
this.layoutControlItem5.Name = "layoutControlItem5";
this.layoutControlItem5.Size = new System.Drawing.Size(522, 24);
this.layoutControlItem5.Text = "Last Name:";
this.layoutControlItem5.TextSize = new System.Drawing.Size(69, 13);
//
// layoutControlItem4
//
this.layoutControlItem4.Control = this.SecondName;
this.layoutControlItem4.CustomizationFormText = "Second Name:";
this.layoutControlItem4.Location = new System.Drawing.Point(0, 24);
this.layoutControlItem4.Name = "layoutControlItem4";
this.layoutControlItem4.Size = new System.Drawing.Size(522, 24);
this.layoutControlItem4.Text = "Second Name:";
this.layoutControlItem4.TextSize = new System.Drawing.Size(69, 13);
//
// layoutControlItem3
//
this.layoutControlItem3.Control = this.FirstName;
this.layoutControlItem3.CustomizationFormText = "First Name:";
this.layoutControlItem3.Location = new System.Drawing.Point(0, 0);
this.layoutControlItem3.Name = "layoutControlItem3";
this.layoutControlItem3.Size = new System.Drawing.Size(522, 24);
this.layoutControlItem3.Text = "First Name:";
this.layoutControlItem3.TextSize = new System.Drawing.Size(69, 13);
//
// layoutControlItem6
//
this.layoutControlItem6.Control = this.IsEnabled;
this.layoutControlItem6.CustomizationFormText = "layoutControlItem6";
this.layoutControlItem6.Location = new System.Drawing.Point(0, 72);
this.layoutControlItem6.Name = "layoutControlItem6";
this.layoutControlItem6.Size = new System.Drawing.Size(522, 23);
this.layoutControlItem6.Text = "layoutControlItem6";
this.layoutControlItem6.TextSize = new System.Drawing.Size(0, 0);
this.layoutControlItem6.TextToControlDistance = 0;
this.layoutControlItem6.TextVisible = false;
//
// layoutControlGroup4
//
this.layoutControlGroup4.CustomizationFormText = "Rights";
this.layoutControlGroup4.Items.AddRange(new DevExpress.XtraLayout.BaseLayoutItem[] {
this.layoutControlItem7});
this.layoutControlGroup4.Location = new System.Drawing.Point(0, 205);
this.layoutControlGroup4.Name = "layoutControlGroup4";
this.layoutControlGroup4.Padding = new DevExpress.XtraLayout.Utils.Padding(3, 3, 3, 3);
this.layoutControlGroup4.Size = new System.Drawing.Size(534, 54);
this.layoutControlGroup4.Text = "Rights";
//
// layoutControlItem7
//
this.layoutControlItem7.Control = this.IsAdmin;
this.layoutControlItem7.CustomizationFormText = "layoutControlItem7";
this.layoutControlItem7.Location = new System.Drawing.Point(0, 0);
this.layoutControlItem7.Name = "layoutControlItem7";
this.layoutControlItem7.Size = new System.Drawing.Size(522, 23);
this.layoutControlItem7.Text = "layoutControlItem7";
this.layoutControlItem7.TextSize = new System.Drawing.Size(0, 0);
this.layoutControlItem7.TextToControlDistance = 0;
this.layoutControlItem7.TextVisible = false;
//
// layoutControlItem8
//
this.layoutControlItem8.Control = this.btnCancel;
this.layoutControlItem8.CustomizationFormText = "layoutControlItem8";
this.layoutControlItem8.Location = new System.Drawing.Point(375, 259);
this.layoutControlItem8.MaxSize = new System.Drawing.Size(0, 45);
this.layoutControlItem8.MinSize = new System.Drawing.Size(82, 45);
this.layoutControlItem8.Name = "layoutControlItem8";
this.layoutControlItem8.Size = new System.Drawing.Size(159, 45);
this.layoutControlItem8.SizeConstraintsType = DevExpress.XtraLayout.SizeConstraintsType.Custom;
this.layoutControlItem8.Text = "layoutControlItem8";
this.layoutControlItem8.TextSize = new System.Drawing.Size(0, 0);
this.layoutControlItem8.TextToControlDistance = 0;
this.layoutControlItem8.TextVisible = false;
//
// layoutControlItem9
//
this.layoutControlItem9.Control = this.btnSave;
this.layoutControlItem9.CustomizationFormText = "layoutControlItem9";
this.layoutControlItem9.Location = new System.Drawing.Point(230, 259);
this.layoutControlItem9.MaxSize = new System.Drawing.Size(0, 45);
this.layoutControlItem9.MinSize = new System.Drawing.Size(82, 45);
this.layoutControlItem9.Name = "layoutControlItem9";
this.layoutControlItem9.Size = new System.Drawing.Size(145, 45);
this.layoutControlItem9.SizeConstraintsType = DevExpress.XtraLayout.SizeConstraintsType.Custom;
this.layoutControlItem9.Text = "layoutControlItem9";
this.layoutControlItem9.TextSize = new System.Drawing.Size(0, 0);
this.layoutControlItem9.TextToControlDistance = 0;
this.layoutControlItem9.TextVisible = false;
//
// emptySpaceItem1
//
this.emptySpaceItem1.AllowHotTrack = false;
this.emptySpaceItem1.CustomizationFormText = "emptySpaceItem1";
this.emptySpaceItem1.Location = new System.Drawing.Point(0, 259);
this.emptySpaceItem1.Name = "emptySpaceItem1";
this.emptySpaceItem1.Size = new System.Drawing.Size(230, 45);
this.emptySpaceItem1.Text = "emptySpaceItem1";
this.emptySpaceItem1.TextSize = new System.Drawing.Size(0, 0);
//
// XF_UserNewEdit
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(540, 310);
this.Controls.Add(this.layoutControl1);
this.Name = "XF_UserNewEdit";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Edit user";
((System.ComponentModel.ISupportInitialize)(this.layoutControl1)).EndInit();
this.layoutControl1.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.IsAdmin.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.IsEnabled.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.LastName.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.SecondName.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.FirstName.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.Password.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.Username.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlGroup1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlGroup2)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem2)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlGroup3)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem5)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem4)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem3)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem6)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlGroup4)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem7)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem8)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem9)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.emptySpaceItem1)).EndInit();
this.ResumeLayout(false);
}
#endregion
private DevExpress.XtraLayout.LayoutControl layoutControl1;
private DevExpress.XtraLayout.LayoutControlGroup layoutControlGroup1;
private DevExpress.XtraEditors.SimpleButton btnSave;
private DevExpress.XtraEditors.SimpleButton btnCancel;
private DevExpress.XtraEditors.CheckEdit IsAdmin;
private DevExpress.XtraEditors.CheckEdit IsEnabled;
private DevExpress.XtraEditors.TextEdit LastName;
private DevExpress.XtraEditors.TextEdit SecondName;
private DevExpress.XtraEditors.TextEdit FirstName;
private DevExpress.XtraEditors.TextEdit Password;
private DevExpress.XtraEditors.TextEdit Username;
private DevExpress.XtraLayout.LayoutControlGroup layoutControlGroup2;
private DevExpress.XtraLayout.LayoutControlItem layoutControlItem1;
private DevExpress.XtraLayout.LayoutControlItem layoutControlItem2;
private DevExpress.XtraLayout.LayoutControlGroup layoutControlGroup3;
private DevExpress.XtraLayout.LayoutControlItem layoutControlItem5;
private DevExpress.XtraLayout.LayoutControlItem layoutControlItem4;
private DevExpress.XtraLayout.LayoutControlItem layoutControlItem3;
private DevExpress.XtraLayout.LayoutControlItem layoutControlItem6;
private DevExpress.XtraLayout.LayoutControlGroup layoutControlGroup4;
private DevExpress.XtraLayout.LayoutControlItem layoutControlItem7;
private DevExpress.XtraLayout.LayoutControlItem layoutControlItem8;
private DevExpress.XtraLayout.LayoutControlItem layoutControlItem9;
private DevExpress.XtraLayout.EmptySpaceItem emptySpaceItem1;
}
} | 58.539759 | 151 | 0.65403 | [
"MIT"
] | Ravenheart/driversolutions | DriverSolutions/ModuleSystem/XF_UserNewEdit.Designer.cs | 24,296 | C# |
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using TMPro;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class TelephoneListener : MonoBehaviour, IObjectListener
{
private InteractiveSprite interactiveSprite;
private IEnumerator getMoneyRoutine;
private IEnumerator checkPlantRoutine;
private IEnumerator coolDownRoutine;
private ILevelManager manager;
private void Start()
{
manager = SetLevelManager();
interactiveSprite = GetComponent<InteractiveSprite>();
}
private ILevelManager SetLevelManager()
{
ILevelManager iManager;
if (SceneManager.GetActiveScene().buildIndex == StaticDb.level1SceneIndex)
iManager = FindObjectOfType<Level1Manager>();
else
iManager = FindObjectOfType<Level2Manager>();
return iManager;
}
public void SetListeners()
{
List<Button> buttons;
if (manager.GetGameData().hasThreatDeployed)
{
buttons = interactiveSprite.actionButtonManager.GetActiveCanvasGroup(3);
buttons[0].GetComponentInChildren<TextMeshProUGUI>().text = "Richiedi fondi";
buttons[0].onClick.RemoveAllListeners();
buttons[0].onClick.AddListener(delegate
{
StartGetMoney();
interactiveSprite.ToggleMenu();
});
buttons[1].GetComponentInChildren<TextMeshProUGUI>().text = "Vai alle lezioni";
buttons[1].onClick.RemoveAllListeners();
buttons[1].onClick.AddListener(delegate
{
ClassDb.notebookManager.ToggleNoteBook();
interactiveSprite.ToggleMenu();
});
buttons[2].GetComponentInChildren<TextMeshProUGUI>().text = "Check dell'impianto";
buttons[2].onClick.RemoveAllListeners();
buttons[2].onClick.AddListener(delegate
{
StartCheckPlant();
interactiveSprite.ToggleMenu();
});
}
else
{
buttons = interactiveSprite.actionButtonManager.GetActiveCanvasGroup(2);
buttons[0].GetComponentInChildren<TextMeshProUGUI>().text = "Richiedi fondi";
buttons[0].onClick.RemoveAllListeners();
buttons[0].onClick.AddListener(delegate
{
StartGetMoney();
interactiveSprite.ToggleMenu();
});
buttons[1].GetComponentInChildren<TextMeshProUGUI>().text = "Vai alle lezioni";
buttons[1].onClick.RemoveAllListeners();
buttons[1].onClick.AddListener(delegate
{
ClassDb.notebookManager.ToggleNoteBook();
interactiveSprite.ToggleMenu();
});
}
foreach (Button button in buttons)
{
button.interactable = true;
}
}
private void StartGetMoney()
{
interactiveSprite.SetInteraction(false);
TimeEvent progressEvent = ClassDb.timeEventManager.NewTimeEvent(
manager.GetGameData().telephoneMoneyTime, interactiveSprite.gameObject, true, true,
StaticDb.getMoneyRoutine);
manager.GetGameData().timeEventList.Add(progressEvent);
getMoneyRoutine = GetMoney(progressEvent);
StartCoroutine(getMoneyRoutine);
}
public void RestartGetMoney(TimeEvent progressEvent)
{
interactiveSprite.SetInteraction(false);
getMoneyRoutine = GetMoney(progressEvent);
StartCoroutine(getMoneyRoutine);
}
private IEnumerator GetMoney(TimeEvent progressEvent)
{
//WRITE LOG
ClassDb.logManager.StartWritePlayerLogRoutine(StaticDb.player, StaticDb.logEvent.UserEvent, "STARTED MONEY REQUEST");
yield return new WaitWhile(() => manager.GetGameData().timeEventList.Contains(progressEvent));
int successRate = Random.Range(0, 1);
if (!(successRate >= manager.GetGameData().reputation))
{
float deltaMoney = Random.Range(0f, 5f) * manager.GetGameData().money / 100;
manager.GetGameData().money += deltaMoney;
ClassDb.levelMessageManager.StartMoneyEarnTrue(deltaMoney);
//WRITE LOG
ClassDb.logManager.StartWritePlayerLogRoutine(StaticDb.player, StaticDb.logEvent.GameEvent, "MONEY REQUEST FINE");
}
else
{
//Debug.Log("NO MONEY");
ClassDb.levelMessageManager.StartMoneyEarnFalse();
//WRITE LOG
ClassDb.logManager.StartWritePlayerLogRoutine(StaticDb.player, StaticDb.logEvent.GameEvent, "MONEY REQUEST NOT FINE");
}
StartCoolDown();
}
private void StartCoolDown()
{
TimeEvent progressEvent = ClassDb.timeEventManager.NewTimeEvent(
manager.GetGameData().telephoneMoneyCoolDown * 60, interactiveSprite.gameObject, true, false,
StaticDb.coolDownRoutine);
manager.GetGameData().timeEventList.Add(progressEvent);
coolDownRoutine = CoolDown(progressEvent);
StartCoroutine(coolDownRoutine);
}
public void RestartCoolDown(TimeEvent progressEvent)
{
interactiveSprite.SetInteraction(false);
coolDownRoutine = CoolDown(progressEvent);
StartCoroutine(coolDownRoutine);
}
private IEnumerator CoolDown(TimeEvent progressEvent)
{
//WRITE LOG
ClassDb.logManager.StartWritePlayerLogRoutine(StaticDb.player, StaticDb.logEvent.GameEvent, "STARTED MONEY REQUEST COOL DOWN");
yield return new WaitWhile(() => manager.GetGameData().timeEventList.Contains(progressEvent));
interactiveSprite.SetInteraction(true);
}
private void StartCheckPlant()
{
interactiveSprite.SetInteraction(false);
//REGISTER THE USER ACTION AND CHECK IF THE ACTION IS CORRECT OR WRONG RELATIVELY TO THE THREAT DEPLOYED
ClassDb.userActionManager.RegisterThreatSolution(new UserAction(StaticDb.ThreatSolution.plantCheck), manager.GetGameData().lastThreatDeployed, false);
TimeEvent progressEvent = ClassDb.timeEventManager.NewTimeEvent(
manager.GetGameData().telephoneCheckPlantTime, interactiveSprite.gameObject, true, true,
StaticDb.checkPlantRoutine);
manager.GetGameData().timeEventList.Add(progressEvent);
checkPlantRoutine = CheckPlant(progressEvent);
StartCoroutine(checkPlantRoutine);
}
public void RestartCheckPlant(TimeEvent progressEvent)
{
interactiveSprite.SetInteraction(false);
checkPlantRoutine = CheckPlant(progressEvent);
StartCoroutine(checkPlantRoutine);
}
private IEnumerator CheckPlant(TimeEvent progressEvent)
{
//WRITE LOG
ClassDb.logManager.StartWritePlayerLogRoutine(StaticDb.player, StaticDb.logEvent.UserEvent, "STARTED CHECK PLANT");
yield return new WaitWhile(() => manager.GetGameData().timeEventList.Contains(progressEvent));
interactiveSprite.SetInteraction(true);
float success = Random.Range(0, 100);
float moneyLoss;
if (!manager.GetGameData().hasThreatDeployed) yield break;
if (manager.GetGameData().lastThreatDeployed.threatAttack != StaticDb.ThreatAttack.replay &&
manager.GetGameData().lastThreatDeployed.threatAttack != StaticDb.ThreatAttack.stuxnet)
{
moneyLoss = 0;
ClassDb.levelMessageManager.StartPlantReport(true, moneyLoss);
yield break;
}
if (!(success > manager.GetGameData().defensePlantResistance))
{
moneyLoss = 0;
ClassDb.levelMessageManager.StartPlantReport(true, moneyLoss);
}
else
{
//Inform how much money has been lost
moneyLoss = manager.GetGameData().lastThreatDeployed.moneyLossPerMinute * 60 *
manager.GetGameData().lastThreatDeployed.deployTime;
ClassDb.levelMessageManager.StartPlantReport(false, moneyLoss);
}
//wait for closing dialog box
yield return new WaitWhile(() => manager.GetGameData().dialogEnabled);
manager.GetGameData().money -= moneyLoss;
manager.GetGameData().hasPlantChecked = true;
}
} | 33.472 | 158 | 0.65631 | [
"Apache-2.0"
] | serranda/SecuritySeriousGame | SIMSCADA/Assets/Script/SceneItemScript/TelephoneListener.cs | 8,370 | C# |
using DigitalPlatform.Marc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace dp2Circulation
{
/// <summary>
/// 书目记录合并策略
/// </summary>
public class MergeRegistry
{
// 数据库名顺序列表
public List<string> DbNames = new List<string>();
// 要求 ListViewItem 的 .Tag 为 ItemTag 类型
public void Sort(ref List<ListViewItem> items)
{
items.Sort((item1, item2) =>
{
ItemTag info1 = (ItemTag)item1.Tag;
ItemTag info2 = (ItemTag)item2.Tag;
if (info1.RecPath == info2.RecPath)
return 0;
// 先按照数据库名字排序
if (this.DbNames.Count > 0)
{
int index1 = this.DbNames.IndexOf(Global.GetDbName(info1.RecPath));
if (index1 == -1)
index1 = this.DbNames.Count + 1;
int index2 = this.DbNames.IndexOf(Global.GetDbName(info2.RecPath));
if (index2 == -1)
index2 = this.DbNames.Count + 1;
if (index1 != index2)
return index1 - index2;
}
// 再观察 606 690 丰富程度
int nRet = Compare6XX(info1.Xml, info2.Xml);
if (nRet != 0)
return nRet;
// 再观察 MARC 记录长度
nRet = CompareMarcLength(info1.Xml, info2.Xml);
if (nRet != 0)
return nRet;
return nRet;
});
}
// 比较 606 690 丰富程度。数值小于 0 表示 strXml1 比 strXml2 丰富
static int Compare6XX(string strXml1, string strXml2)
{
int nCount1 = Count6XX(strXml1);
int nCount2 = Count6XX(strXml2);
return nCount2 - nCount1;
}
static int CompareMarcLength(string strXml1, string strXml2)
{
return GetMarcLength(strXml2) - GetMarcLength(strXml1);
}
static int Count6XX(string strXml)
{
// 将MARCXML格式的xml记录转换为marc机内格式字符串
// parameters:
// bWarning ==true, 警告后继续转换,不严格对待错误; = false, 非常严格对待错误,遇到错误后不继续转换
// strMarcSyntax 指示marc语法,如果=="",则自动识别
// strOutMarcSyntax out参数,返回marc,如果strMarcSyntax == "",返回找到marc语法,否则返回与输入参数strMarcSyntax相同的值
int nRet = MarcUtil.Xml2Marc(strXml,
true, // 2013/1/12 修改为true
"", // strMarcSyntax
out string strOutMarcSyntax,
out string strMarc,
out string strError);
if (nRet == -1)
return 0;
int nCount = 0;
if (strOutMarcSyntax == "unimarc")
{
MarcRecord record = new MarcRecord(strMarc);
nCount += record.select("field[@name='606']").count;
nCount += record.select("field[@name='690']").count;
return nCount;
}
if (strOutMarcSyntax == "usmarc")
{
MarcRecord record = new MarcRecord(strMarc);
nCount += record.select("field[@name='600' or @name='610' or @name='630' or @name='650' or @name='651']").count;
nCount += record.select("field[@name='093']").count;
return nCount;
}
return 0;
}
static int GetMarcLength(string strXml)
{
// 将MARCXML格式的xml记录转换为marc机内格式字符串
// parameters:
// bWarning ==true, 警告后继续转换,不严格对待错误; = false, 非常严格对待错误,遇到错误后不继续转换
// strMarcSyntax 指示marc语法,如果=="",则自动识别
// strOutMarcSyntax out参数,返回marc,如果strMarcSyntax == "",返回找到marc语法,否则返回与输入参数strMarcSyntax相同的值
int nRet = MarcUtil.Xml2Marc(strXml,
true, // 2013/1/12 修改为true
"", // strMarcSyntax
out string strOutMarcSyntax,
out string strMarc,
out string strError);
if (nRet == -1)
return 0;
MarcRecord record = new MarcRecord(strMarc);
return record.Text.Length;
}
}
}
| 33.785714 | 128 | 0.501527 | [
"Apache-2.0"
] | DigitalPlatform/dp2 | dp2Circulation/IO/MergeRegistry.cs | 4,751 | C# |
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace EasyDesk.CleanArchitecture.Web.DependencyInjection;
public interface IServiceInstaller
{
void InstallServices(IServiceCollection services, IConfiguration configuration, IWebHostEnvironment environment);
}
| 32.545455 | 118 | 0.840782 | [
"MIT"
] | EasyDesk/easydesk-clean-architecture | src/EasyDesk.CleanArchitecture.Web/DependencyInjection/IServiceInstaller.cs | 360 | C# |
using System.Collections.Generic;
using System.Threading.Tasks;
using IEXSharp.Model;
using IEXSharp.Model.CoreData.StockResearch.Response;
using IEXSharp.Model.Shared.Request;
namespace IEXSharp.Service.Cloud.CoreData.StockResearch
{
public interface IStockResearchService
{
/// <summary>
/// <see cref="https://iexcloud.io/docs/api/#advanced-stats"/>
/// </summary>
/// <param name="symbol"></param>
/// <returns></returns>
Task<IEXResponse<AdvancedStatsResponse>> AdvancedStatsAsync(string symbol);
/// <summary>
/// <see cref="https://iexcloud.io/docs/api/#analyst-recommendations"/>
/// (previously called Recommendation Trends, but renamed by IEX. Endpoint URL is still the same though.
/// </summary>
/// <param name="symbol"></param>
/// <returns></returns>
Task<IEXResponse<IEnumerable<AnalystRecommendationsResponse>>> AnalystRecommendationsAsync(string symbol);
/// <summary>
/// <see cref="https://iexcloud.io/docs/api/#estimates"/>
/// </summary>
/// <param name="symbol"></param>
/// <param name="period"></param>
/// <param name="last"></param>
/// <returns></returns>
Task<IEXResponse<EstimatesResponse>> EstimatesAsync(string symbol, Period period = Period.Quarter, int last = 1);
/// <summary>
/// <see cref="https://iexcloud.io/docs/api/#estimates"/>
/// </summary>
/// <param name="symbol"></param>
/// <param name="field"></param>
/// <param name="period"></param>
/// <param name="last"></param>
/// <returns></returns>
Task<IEXResponse<string>> EstimateFieldAsync(string symbol, string field, Period period = Period.Quarter, int last = 1);
/// <summary>
/// <see cref="https://iexcloud.io/docs/api/#fund-ownership"/>
/// </summary>
/// <param name="symbol"></param>
/// <returns></returns>
Task<IEXResponse<IEnumerable<FundOwnershipResponse>>> FundOwnershipAsync(string symbol);
/// <summary>
/// <see cref="https://iexcloud.io/docs/api/#institutional-ownership"/>
/// </summary>
/// <param name="symbol"></param>
/// <returns></returns>
Task<IEXResponse<IEnumerable<InstitutionalOwnershipResponse>>> InstitutionalOwnerShipAsync(string symbol);
/// <summary>
/// <see cref="https://iexcloud.io/docs/api/#key-stats"/>
/// </summary>
/// <param name="symbol"></param>
/// <returns></returns>
Task<IEXResponse<KeyStatsResponse>> KeyStatsAsync(string symbol);
/// <summary>
/// <see cref="https://iexcloud.io/docs/api/#key-stats"/>
/// </summary>
/// <param name="symbol"></param>
/// <param name="stat"></param>
/// <returns></returns>
Task<IEXResponse<string>> KeyStatsStatAsync(string symbol, string stat);
/// <summary>
/// <see cref="https://iexcloud.io/docs/api/#price-target"/>
/// </summary>
/// <param name="symbol"></param>
/// <returns></returns>
Task<IEXResponse<PriceTargetResponse>> PriceTargetAsync(string symbol);
/// <summary>
/// <see cref="https://iexcloud.io/docs/api/#technical-indicators"/>
/// </summary>
/// <param name="symbol"></param>
/// <param name="indicator"></param>
/// <returns></returns>
Task<IEXResponse<TechnicalIndicatorsResponse>> TechnicalIndicatorsAsync(string symbol, string indicator);
}
}
| 35.566667 | 122 | 0.67104 | [
"MIT"
] | SelfXFighter/IEXSharp | IEXSharp/Service/Cloud/CoreData/StockResearch/IStockResearchService.cs | 3,201 | C# |
using GraphControl.Core.Interfaces.Views;
namespace GraphControl.Core.Interfaces.Models
{
public interface ICanvasSizeChanged
{
/// <summary>
/// Canvas size changed event
/// </summary>
/// <param name="options"></param>
void CanvasSizeChanged(IDrawOptions options);
}
}
| 23.285714 | 53 | 0.634969 | [
"MIT"
] | serge4k/GraphControl | GraphControl.Core/Interfaces/ICanvasSizeChanged.cs | 328 | C# |
using System.ComponentModel.DataAnnotations;
using SpyStore.Hol.Models.Entities.Base;
namespace SpyStore.Hol.Models.ViewModels
{
public class CartRecordWithProductInfo : ShoppingCartRecordBase
{
public new int Id { get; set; }
public string Description { get; set; }
[Display(Name = "Model Number")]
public string ModelNumber { get; set; }
[Display(Name = "Name")]
public string ModelName { get; set; }
public string ProductImage { get; set; }
public string ProductImageLarge { get; set; }
public string ProductImageThumb { get; set; }
[Display(Name = "In Stock")]
public int UnitsInStock { get; set; }
[Display(Name = "Price"), DataType(DataType.Currency)]
public decimal CurrentPrice { get; set; }
public int CategoryId { get; set; }
[Display(Name = "Category")]
public string CategoryName { get; set; }
}
}
| 36.615385 | 67 | 0.630252 | [
"BSD-3-Clause",
"MIT"
] | MalikWaseemJaved/presentations | .NETCore/ASP.NETCore/v3.1/SpyStore/SpyStore.Hol.Models/ViewModels/CartRecordWithProductInfo.cs | 954 | C# |
using System;
using UnityEngine;
using UnityEngine.Internal;
namespace LDtkUnity
{
[Serializable]
[ExcludeFromDocs]
public abstract class LDtkSceneDrawerBase
{
[SerializeField] private string _identifier;
[SerializeField] private bool _enabled = true;
[SerializeField] private Color _gizmoColor;
public string Identifier => _identifier;
public bool Enabled => _enabled;
public Color GizmoColor => _gizmoColor;
protected LDtkSceneDrawerBase(string identifier, Color gizmoColor)
{
_identifier = identifier;
_gizmoColor = gizmoColor;
AdjustGizmoColor();
}
private void AdjustGizmoColor()
{
_gizmoColor.a = 0.66f;
const float incrementDifference = -0.1f;
_gizmoColor.r += incrementDifference;
_gizmoColor.g += incrementDifference;
_gizmoColor.b += incrementDifference;
}
}
} | 27.666667 | 74 | 0.623494 | [
"MIT"
] | Cammin/LDtkToUnity | Assets/LDtkUnity/Runtime/Tools/SceneDrawer/LDtkSceneDrawerBase.cs | 998 | C# |
using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;
using System.Threading;
using System.Windows.Forms;
using System.Xml;
using Microsoft.Win32;
using System.Runtime.InteropServices;
namespace TDHelper
{
// The SplashScreen class definition. AKO Form
public partial class SplashScreen : Form
{
#region Member Variables
// Threading
private static SplashScreen ms_frmSplash = null;
private static Thread ms_oThread = null;
// Fade in and out.
private double m_dblOpacityIncrement = .05;
private double m_dblOpacityDecrement = .08;
private const int TIMER_INTERVAL = 50;
// Status and progress bar
private string m_sVersion;
private string m_sStatus;
private string m_sTimeRemaining;
private double m_dblCompletionFraction = 0.0;
private Rectangle m_rProgress;
// Progress smoothing
private double m_dblLastCompletionFraction = 0.0;
private double m_dblPBIncrementPerTimerInterval = .015;
// Self-calibration support
private int m_iIndex = 1;
private int m_iActualTicks = 0;
private ArrayList m_alPreviousCompletionFraction;
private ArrayList m_alActualTimes = new ArrayList();
private DateTime m_dtStart;
private bool m_bFirstLaunch = false;
private bool m_bDTSet = false;
#endregion Member Variables
/// <summary>
/// Constructor
/// </summary>
public SplashScreen()
{
InitializeComponent();
this.Opacity = 0.0;
UpdateTimer.Interval = TIMER_INTERVAL;
UpdateTimer.Start();
this.ClientSize = this.BackgroundImage.Size;
}
#region Public Static Methods
// A static method to create the thread and
// launch the SplashScreen.
static public void ShowSplashScreen()
{
// Make sure it's only launched once.
if (ms_frmSplash != null)
{
return;
}
ms_oThread = new Thread(new ThreadStart(SplashScreen.ShowForm))
{
IsBackground = true,
};
ms_oThread.SetApartmentState(ApartmentState.STA);
ms_oThread.Start();
while (ms_frmSplash == null || ms_frmSplash.IsHandleCreated == false)
{
System.Threading.Thread.Sleep(TIMER_INTERVAL);
}
}
// Close the form without setting the parent.
static public void CloseForm()
{
if (ms_frmSplash != null && ms_frmSplash.IsDisposed == false)
{
// Make it start going away.
ms_frmSplash.m_dblOpacityIncrement = -ms_frmSplash.m_dblOpacityDecrement;
}
ms_oThread = null; // we don't need these any more.
ms_frmSplash = null;
}
// A static method to set the status and update the reference.
static public void SetStatus(string newStatus)
{
SetStatus(newStatus, true);
}
// A static method to set the status and optionally update the reference.
// This is useful if you are in a section of code that has a variable
// set of status string updates. In that case, don't set the reference.
static public void SetStatus(string newStatus, bool setReference)
{
if (ms_frmSplash == null)
{
return;
}
ms_frmSplash.m_sStatus = newStatus;
if (setReference)
{
ms_frmSplash.SetReferenceInternal();
}
}
static public void SetVersion(string version)
{
if (ms_frmSplash != null)
{
ms_frmSplash.m_sVersion = version;
}
}
// Static method called from the initializing application to
// give the splash screen reference points. Not needed if
// you are using a lot of status strings.
static public void SetReferencePoint()
{
if (ms_frmSplash == null)
{
return;
}
ms_frmSplash.SetReferenceInternal();
}
#endregion Public Static Methods
#region Private Methods
// A private entry point for the thread.
static private void ShowForm()
{
ms_frmSplash = new SplashScreen();
Application.Run(ms_frmSplash);
}
// Internal method for setting reference points.
private void SetReferenceInternal()
{
if (m_bDTSet == false)
{
m_bDTSet = true;
m_dtStart = DateTime.Now;
ReadIncrements();
}
double dblMilliseconds = ElapsedMilliSeconds();
m_alActualTimes.Add(dblMilliseconds);
m_dblLastCompletionFraction = m_dblCompletionFraction;
if (m_alPreviousCompletionFraction != null && m_iIndex < m_alPreviousCompletionFraction.Count)
{
m_dblCompletionFraction = (double)m_alPreviousCompletionFraction[m_iIndex++];
}
else
{
m_dblCompletionFraction = (m_iIndex > 0) ? 1 : 0;
}
}
// Utility function to return elapsed Milliseconds since the
// SplashScreen was launched.
private double ElapsedMilliSeconds()
{
TimeSpan ts = DateTime.Now - m_dtStart;
return ts.TotalMilliseconds;
}
// Function to read the checkpoint intervals from the previous invocation of the
// splashscreen from the XML file.
private void ReadIncrements()
{
string sPBIncrementPerTimerInterval = SplashScreenXMLStorage.Interval;
if (Double.TryParse(sPBIncrementPerTimerInterval, System.Globalization.NumberStyles.Float, System.Globalization.NumberFormatInfo.InvariantInfo, out double dblResult))
{
m_dblPBIncrementPerTimerInterval = dblResult;
}
else
{
m_dblPBIncrementPerTimerInterval = .0015;
}
string sPBPreviousPctComplete = SplashScreenXMLStorage.Percents;
if (sPBPreviousPctComplete != string.Empty)
{
string[] aTimes = sPBPreviousPctComplete.Split(null);
m_alPreviousCompletionFraction = new ArrayList();
for (int i = 0; i < aTimes.Length; i++)
{
if (Double.TryParse(aTimes[i], System.Globalization.NumberStyles.Float, System.Globalization.NumberFormatInfo.InvariantInfo, out double dblVal))
{
m_alPreviousCompletionFraction.Add(dblVal);
}
else
{
m_alPreviousCompletionFraction.Add(1.0);
}
}
}
else
{
m_bFirstLaunch = true;
m_sTimeRemaining = string.Empty;
}
}
// Method to store the intervals (in percent complete) from the current invocation of
// the splash screen to XML storage.
private void StoreIncrements()
{
string sPercent = string.Empty;
double dblElapsedMilliseconds = ElapsedMilliSeconds();
for (int i = 0; i < m_alActualTimes.Count; i++)
{
sPercent += ((double)m_alActualTimes[i] / dblElapsedMilliseconds).ToString("0.####", System.Globalization.NumberFormatInfo.InvariantInfo) + " ";
}
SplashScreenXMLStorage.Percents = sPercent;
m_dblPBIncrementPerTimerInterval = 1.0 / (double)m_iActualTicks;
SplashScreenXMLStorage.Interval = m_dblPBIncrementPerTimerInterval.ToString("#.000000", System.Globalization.NumberFormatInfo.InvariantInfo);
}
public static SplashScreen GetSplashScreen()
{
return ms_frmSplash;
}
#endregion Private Methods
#region Event Handlers
// Tick Event handler for the Timer control. Handle fade in and fade out and paint progress bar.
private void UpdateTimer_Tick(object sender, System.EventArgs e)
{
lblStatus.Text = m_sStatus;
lblVersion.Text = m_sVersion;
// Calculate opacity
if (m_dblOpacityIncrement > 0) // Starting up splash screen
{
m_iActualTicks++;
if (this.Opacity < 1)
{
this.Opacity += m_dblOpacityIncrement;
}
}
else // Closing down splash screen
{
if (this.Opacity > 0)
{
this.Opacity += m_dblOpacityIncrement;
}
else
{
StoreIncrements();
UpdateTimer.Stop();
this.Close();
}
}
// Paint progress bar
if (m_bFirstLaunch == false && m_dblLastCompletionFraction < m_dblCompletionFraction)
{
m_dblLastCompletionFraction += m_dblPBIncrementPerTimerInterval;
int width = (int)Math.Floor(pnlStatus.ClientRectangle.Width * m_dblLastCompletionFraction);
int height = pnlStatus.ClientRectangle.Height;
int x = pnlStatus.ClientRectangle.X;
int y = pnlStatus.ClientRectangle.Y;
if (width > 0 && height > 0)
{
m_rProgress = new Rectangle(x, y, width, height);
if (!pnlStatus.IsDisposed)
{
Graphics g = pnlStatus.CreateGraphics();
LinearGradientBrush brBackground = new LinearGradientBrush(m_rProgress, Color.FromArgb(58, 96, 151), Color.FromArgb(181, 237, 254), LinearGradientMode.Horizontal);
g.FillRectangle(brBackground, m_rProgress);
g.Dispose();
}
int iSecondsLeft = 1 + (int)(TIMER_INTERVAL * ((1.0 - m_dblLastCompletionFraction) / m_dblPBIncrementPerTimerInterval)) / 1000;
m_sTimeRemaining = (iSecondsLeft == 1) ? string.Format("1 second remaining") : string.Format("{0} seconds remaining", iSecondsLeft);
}
}
lblTimeRemaining.Text = m_sTimeRemaining;
}
// Close the form if they double click on it.
private void SplashScreen_DoubleClick(object sender, System.EventArgs e)
{
// Use the overload that doesn't set the parent form to this very window.
CloseForm();
}
#endregion Event Handlers
}
#region Auxiliary Classes
/// <summary>
/// A specialized class for managing XML storage for the splash screen.
/// </summary>
internal class SplashScreenXMLStorage
{
private static readonly string ms_StoredValues = "SplashScreen.xml";
private static readonly string ms_DefaultPercents = string.Empty;
private static readonly string ms_DefaultIncrement = ".015";
// Get or set the string storing the percentage complete at each checkpoint.
static public string Percents
{
get { return GetValue("Percents", ms_DefaultPercents); }
set { SetValue("Percents", value); }
}
// Get or set how much time passes between updates.
static public string Interval
{
get { return GetValue("Interval", ms_DefaultIncrement); }
set { SetValue("Interval", value); }
}
// Store the file in a location where it can be written with only User rights. (Don't use install directory).
static private string StoragePath
{
get {return Path.Combine(Application.UserAppDataPath, ms_StoredValues);}
}
// Helper method for getting inner text of named element.
static private string GetValue(string name, string defaultValue)
{
if (!File.Exists(StoragePath))
{
return defaultValue;
}
try
{
XmlDocument docXML = new XmlDocument();
docXML.Load(StoragePath);
return (!(docXML.DocumentElement.SelectSingleNode(name) is XmlElement elValue))
? defaultValue
: elValue.InnerText;
}
catch
{
return defaultValue;
}
}
// Helper method for setting inner text of named element. Creates document if it doesn't exist.
static public void SetValue(
string name,
string stringValue)
{
XmlDocument docXML = new XmlDocument();
XmlElement elRoot = null;
if (!File.Exists(StoragePath))
{
elRoot = docXML.CreateElement("root");
docXML.AppendChild(elRoot);
}
else
{
docXML.Load(StoragePath);
elRoot = docXML.DocumentElement;
}
if (!(docXML.DocumentElement.SelectSingleNode(name) is XmlElement value))
{
value = docXML.CreateElement(name);
elRoot.AppendChild(value);
}
value.InnerText = stringValue;
docXML.Save(StoragePath);
}
}
#endregion Auxiliary Classes
}
| 29.170316 | 178 | 0.651264 | [
"MIT"
] | eyeonus/TDHelper | TradeDangerousGUI/SplashScreen.cs | 11,991 | C# |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Forms;
using System.Windows.Interop;
using System.Windows.Media.Animation;
using Cartogram.Properties;
using Cartogram.SQL;
using MessageBox = System.Windows.MessageBox;
namespace Cartogram
{
/// <summary>
/// Interaction logic for NewMap.xaml
/// </summary>
public partial class NewMap : Window
{
#region DLL Import
[DllImport("User32.dll")]
protected static extern int
SetClipboardViewer(int hWndNewViewer);
[DllImport("User32.dll", CharSet = CharSet.Auto)]
public static extern bool
ChangeClipboardChain(IntPtr hWndRemove, IntPtr hWndNewNext);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern int SendMessage(IntPtr hwnd, int wMsg, IntPtr wParam, IntPtr lParam);
#endregion
private HwndSource _source;
private static MainWindow _main;
private IntPtr _handle, _nextClipboardViewer;
public bool Cancelled { get; set; }
public Map CurrentMap { get; set; }
public NewMap()
{
InitializeComponent();
_main = MainWindow.GetSingleton();
PopulateLeagues();
ComboBoxName.DataContext = Sqlite.CharactersList();
ComboLeague.Text = Settings.Default.SelectedLeague;
ComboBoxName.Text = Settings.Default.CharacterName;
ZanaInt.Content = Settings.Default.ZanaQuantity.ToString();
ZanaValue.Value = Settings.Default.ZanaQuantity;
}
protected override void OnSourceInitialized(EventArgs e)
{
base.OnSourceInitialized(e);
var source = PresentationSource.FromVisual(this) as HwndSource;
if (source != null) _handle = source.Handle;
_nextClipboardViewer = (IntPtr)SetClipboardViewer((int)source.Handle);
source.AddHook(WndProc);
}
protected override void OnClosed(EventArgs e)
{
if (_source != null)
{
_source.RemoveHook(WndProc);
_source = null;
_main._newMap = null;
}
base.OnClosed(e);
}
private void PopulateLeagues()
{
var leagueList = new ObservableCollection<League>();
foreach (var entry in _main.LeagueObject)
{
dynamic values = entry.Value;
var league = new League
{
Active = values["active"].ToString() == "1",
PrettyName = values["prettyName"].ToString(),
};
leagueList.Add(league);
}
foreach (var league in leagueList.Where(league => league.Active))
{
switch (league.PrettyName)
{
case "Standard":
ComboLeague.Items.Insert(0, league.PrettyName);
continue;
case "Hardcore":
ComboLeague.Items.Insert(1, league.PrettyName);
continue;
}
ComboLeague.Items.Add(league.PrettyName);
}
}
private void TextBoxName_LostFocus(object sender, RoutedEventArgs e)
{
if (ComboBoxName.Text == string.Empty) return;
var currentCharacters = Sqlite.CharactersList();
if (!currentCharacters.Contains(ComboBoxName.Text))
{
Sqlite.InsertCharacter(ComboBoxName.Text);
currentCharacters.Add(ComboBoxName.Text);
ComboBoxName.DataContext = currentCharacters;
}
Settings.Default.CharacterName = ComboBoxName.Text;
Settings.Default.Save();
}
private void ComboLeague_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
Settings.Default.SelectedLeague = ComboLeague.Text;
Settings.Default.Save();
}
private void NameRemove_Click(object sender, RoutedEventArgs e)
{
if (ComboBoxName.Text == string.Empty) return;
if (Sqlite.DeleteCharacter(ComboBoxName.Text))
{
_main.ExtendedStatusStrip.AddStatus($"Removed {ComboBoxName.Text} from saved names.");
if (Settings.Default.CharacterName == ComboBoxName.Text)
Settings.Default.CharacterName = string.Empty;
ComboBoxName.Text = string.Empty;
ComboBoxName.IsDropDownOpen = false;
ComboBoxName.DataContext = Sqlite.CharactersList();
}
else
{
_main.ExtendedStatusStrip.AddStatus($"Failed to remove {ComboBoxName.Text} from saved names.");
}
}
private void ZanaValue_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
ZanaInt.Content = ZanaValue.Value.ToString("0");
}
private void ButtonStart_Click(object sender, RoutedEventArgs e)
{
if (ComboLeague.Text == string.Empty) MessageBox.Show(@"Please select a league", @"No league selected");
if (ComboBoxName.Text == string.Empty) MessageBox.Show(@"Please enter your characters name", @"No character selected");
int zanaQuantity, fragmentQuantity;
Settings.Default.ZanaQuantity = int.TryParse(ZanaInt.Content.ToString(), out zanaQuantity) ? zanaQuantity : 0;
Settings.Default.SelectedLeague = ComboLeague.Text;
//if (publicOpt)
//{
// _mySqlId = _mySql.AddMap(_main.CurrentMap);
// labelMySqlId.Text = _mySqlId.ToString(CultureInfo.InvariantCulture);
//}
//_main.CurrentMap.SqlId = _mySqlId;
if (_main.CurrentMap != null || CurrentMap == null) return;
CurrentMap.Quantity = CurrentMap.Quantity;
if (ComboZanaMod.SelectionBoxItem != null && ComboZanaMod.SelectionBoxItem.ToString().Length > 1)
{
CurrentMap.ZanaMod = ComboZanaMod.SelectionBoxItem.ToString();
}
else
{
CurrentMap.ZanaMod = string.Empty;
CurrentMap.Quantity += Settings.Default.ZanaQuantity;
}
if (int.TryParse(FragmentValue.Content.ToString(), out fragmentQuantity) && (string) FragmentValue.Content != "0")
CurrentMap.Quantity += (fragmentQuantity * 5);
CurrentMap.OwnMap = radioButtonOwn.IsChecked == true;
CurrentMap.League = ComboLeague.Text;
CurrentMap.Character = ComboBoxName.Text;
CurrentMap.Id = Sqlite.AddMap(CurrentMap);
if (CurrentMap.Id > 0)
{
CurrentMap.StartAt = DateTime.Now;
_main.CurrentMap = CurrentMap;
Settings.Default.Save();
try
{
System.Windows.Forms.Clipboard.SetDataObject(string.Empty, false, 5, 200);
}
catch
{
_main.ExtendedStatusStrip.AddStatus("Failed to clear clipboard");
}
Close();
}
else
{
MessageBox.Show(@"Failed inserting Map into database, please try again",
@"Failed inserting into database", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
private void ButtonCancel_Click(object sender, RoutedEventArgs e)
{
CurrentMap = null;
Cancelled = true;
Close();
}
#region WndProc
private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
const int WM_DRAWCLIPBOARD = 0x308;
switch (msg)
{
case WM_DRAWCLIPBOARD:
if (ParseHandler.CheckClipboard())
{
CurrentMap = ParseHandler.ParseClipboard();
//CurrentMap.ExpBefore = ExpValue();
if (CurrentMap == null) break;
PopulateMapInformation();
MapInformation.IsExpanded = true;
break;
}
SendMessage(_nextClipboardViewer, msg, wParam, lParam);
break;
}
return IntPtr.Zero;
}
#endregion
#region Custom Methods
private void PopulateMapInformation()
{
var mapInformation = Sqlite.MapInformation(CurrentMap.Name);
if (mapInformation == null) return;
LabelMapValue.Text = mapInformation.Zone;
LabelBossValue.Text = mapInformation.Boss;
LabelDescription.Text = mapInformation.BossDetails;
}
private string GetExperience()
{
Thread.Sleep(500);
System.Windows.Forms.Cursor.Position = new System.Drawing.Point((Screen.PrimaryScreen.Bounds.Width / 2) - 200, Screen.PrimaryScreen.Bounds.Height);
SendKeys.SendWait("^c");
var clipboardContents = System.Windows.Clipboard.GetText();
if (!clipboardContents.Contains("Current Exp:"))
{
MessageBox.Show(@"Failed capturing experience, please try again.", @"Experience Error");
return string.Empty;
}
return clipboardContents;
}
/// <summary>
/// Parses the captured experience into the Experience object
/// </summary>
/// <returns>Experience object containing all the details</returns>
internal Experience ExpValue()
{
var exp = GetExperience();
if (exp == string.Empty) return null;
var currentPercent = Regex.Match(exp, @"(?<=\().+?(?=\%)");
var currentLevel = Regex.Match(exp, @"(?<=el ).+?(?=\ )");
var currentExperience = Regex.Match(exp, @"(?<=p: ).+?(?=\ )");
var nextLevel = Regex.Match(exp, @"(?<=l: ).+?(?=\n)");
int level, percent;
long currentExp, expToLevel;
var expObj = new Experience
{
Level = currentLevel.Success ? int.TryParse(currentLevel.Groups[0].ToString(), out level) ? level : 0 : 0,
Percentage = currentPercent.Success ? int.TryParse(currentPercent.Groups[0].ToString(), out percent) ? percent : 0 : 0,
CurrentExperience = currentExperience.Success ? long.TryParse(currentExperience.Groups[0].ToString().Replace(",", ""), out currentExp) ? currentExp : 0 : 0,
NextLevelExperience = nextLevel.Success ? long.TryParse(nextLevel.Groups[0].ToString().Replace(",", ""), out expToLevel) ? expToLevel : 0 : 0
};
return expObj;
}
#endregion
private void MapInformation_Expanded(object sender, RoutedEventArgs e)
{
var growAnimation = new DoubleAnimation
{
From = 180,
To = 310,
FillBehavior = FillBehavior.Stop,
BeginTime = TimeSpan.FromSeconds(0.1),
Duration = TimeSpan.FromSeconds(0.2)
};
var growForm = new Storyboard()
{
Name = "ExpandForm"
};
growForm.Children.Add(growAnimation);
Storyboard.SetTarget(growAnimation, this);
Storyboard.SetTargetProperty(growAnimation, new PropertyPath(HeightProperty));
growForm.Begin(this, true);
}
private void MapInformation_Collapsed(object sender, RoutedEventArgs e)
{
var shrinkAnimation = new DoubleAnimation
{
From = 310,
To = 180,
FillBehavior = FillBehavior.Stop,
BeginTime = TimeSpan.FromSeconds(0.1),
Duration = TimeSpan.FromSeconds(0.2)
};
var growForm = new Storyboard
{
Name = "ShrinkForm"
};
growForm.Children.Add(shrinkAnimation);
Storyboard.SetTarget(shrinkAnimation, this);
Storyboard.SetTargetProperty(shrinkAnimation, new PropertyPath(HeightProperty));
growForm.Begin(this, true);
}
private void LabelDescription_MouseEnter(object sender, System.Windows.Input.MouseEventArgs e)
{
}
private void Fragments_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
FragmentValue.Content = Fragments.Value.ToString("0");
}
private void LabelDescription_MouseLeave(object sender, System.Windows.Input.MouseEventArgs e)
{
}
}
}
| 37.874286 | 172 | 0.565103 | [
"MIT"
] | M1nistry/Cartogram | src/Cartogram/NewMap.xaml.cs | 13,258 | C# |
using System.Collections.Concurrent;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
namespace HotChocolate.Utilities
{
public class Cache<TValue>
{
private const int _defaultCacheSize = 10;
private readonly object _sync = new object();
private readonly LinkedList<string> _ranking = new LinkedList<string>();
private readonly ConcurrentDictionary<string, CacheEntry> _cache =
new ConcurrentDictionary<string, CacheEntry>();
private LinkedListNode<string>? _first;
public event EventHandler<CacheEntryEventArgs<TValue>>? RemovedEntry;
public Cache(int size)
{
Size = size < _defaultCacheSize ? _defaultCacheSize : size;
}
public int Size { get; }
public int Usage => _cache.Count;
public bool TryGet(string key, [MaybeNull]out TValue value)
{
if (_cache.TryGetValue(key, out CacheEntry? entry))
{
TouchEntry(entry.Rank);
value = entry.Value;
return true;
}
value = default;
return false;
}
public TValue GetOrCreate(string key, Func<TValue> create)
{
if (_cache.TryGetValue(key, out CacheEntry? entry))
{
TouchEntry(entry.Rank);
}
else
{
entry = new CacheEntry(key, create());
AddNewEntry(entry);
}
return entry.Value;
}
private void TouchEntry(LinkedListNode<string> rank)
{
if (_first != rank)
{
lock (_sync)
{
if (_ranking.First != rank)
{
_ranking.Remove(rank);
_ranking.AddFirst(rank);
_first = rank;
}
}
}
}
private void AddNewEntry(CacheEntry entry)
{
if (!_cache.ContainsKey(entry.Key))
{
lock (_sync)
{
if (!_cache.ContainsKey(entry.Key))
{
ClearSpaceForNewEntry();
_ranking.AddFirst(entry.Rank);
_cache[entry.Key] = entry;
_first = entry.Rank;
}
}
}
}
private void ClearSpaceForNewEntry()
{
if (_cache.Count >= Size)
{
LinkedListNode<string>? rank = _ranking.Last;
if (rank is { } && _cache.TryRemove(rank.Value, out CacheEntry? entry))
{
_ranking.Remove(rank);
RemovedEntry?.Invoke(this, new CacheEntryEventArgs<TValue>(entry.Key, entry.Value));
}
}
}
private class CacheEntry
{
public CacheEntry(string key, TValue value)
{
Key = key ?? throw new ArgumentNullException(nameof(key));
Rank = new LinkedListNode<string>(key);
Value = value;
}
public string Key { get; }
public LinkedListNode<string> Rank { get; }
public TValue Value { get; }
}
}
}
| 29.367521 | 104 | 0.480501 | [
"MIT"
] | GraemeF/hotchocolate | src/HotChocolate/Utilities/src/Utilities/Cache.cs | 3,438 | C# |
//------------------------------------------------------------------------------
// <copyright file="ImportOpenInVSActionCmd.cs" company="Aras Corporation">
// © 2017-2021 Aras Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
using System;
using System.ComponentModel.Design;
using Aras.Method.Libs;
using Aras.Method.Libs.Code;
using Aras.Method.Libs.Configurations.ProjectConfigurations;
using Aras.VS.MethodPlugin.Authentication;
using Aras.VS.MethodPlugin.Dialogs;
using Aras.VS.MethodPlugin.Dialogs.Views;
using Aras.VS.MethodPlugin.SolutionManagement;
using Microsoft.VisualStudio.Shell;
namespace Aras.VS.MethodPlugin.Commands
{
/// <summary>
/// Command handler
/// </summary>
public sealed class ImportOpenInVSActionCmd : AuthenticationCommandBase
{
/// <summary>
/// Command ID.
/// </summary>
public const int CommandId = 0x106;
/// <summary>
/// Command menu group (command set GUID).
/// </summary>
public static readonly Guid CommandSet = CommandIds.ImportOpenInVSAction;
/// <summary>
/// Initializes a new instance of the <see cref="ImportOpenInVSActionCmd"/> class.
/// Adds our command handlers for menu (commands must exist in the command table file)
/// </summary>
/// <param name="package">Owner package, not null.</param>
public ImportOpenInVSActionCmd(IProjectManager projectManager, IAuthenticationManager authManager, IDialogFactory dialogFactory, IProjectConfigurationManager projectConfigurationManager, ICodeProviderFactory codeProviderFactory, MessageManager messageManager) :
base(authManager, dialogFactory, projectManager, projectConfigurationManager, codeProviderFactory, messageManager)
{
if (projectManager.CommandService != null)
{
var menuCommandID = new CommandID(CommandSet, CommandId);
var menuItem = new OleMenuCommand(this.ExecuteCommand, menuCommandID);
menuItem.BeforeQueryStatus += CheckCommandAccessibility;
projectManager.CommandService.AddCommand(menuItem);
}
}
/// <summary>
/// Gets the instance of the command.
/// </summary>
public static ImportOpenInVSActionCmd Instance
{
get;
private set;
}
public static void Initialize(IProjectManager projectManager, IAuthenticationManager authManager, IDialogFactory dialogFactory, IProjectConfigurationManager projectConfigurationManager, ICodeProviderFactory codeProviderFactory, MessageManager messageManager)
{
Instance = new ImportOpenInVSActionCmd(projectManager, authManager, dialogFactory, projectConfigurationManager, codeProviderFactory, messageManager);
}
public override void ExecuteCommandImpl(object sender, EventArgs args)
{
dynamic result = authManager.InnovatorInstance.applyAML(Properties.Resources.ImportOpenInVSActionAML);
IMessageBoxWindow messageBox = dialogFactory.GetMessageBoxWindow();
string title = messageManager.GetMessage("ArasVSMethodPlugin");
if (result.isError())
{
string errorMessage = messageManager.GetMessage("OpenInVSActionImportFailed", result.getErrorString());
messageBox.ShowDialog(errorMessage, title, MessageButtons.OK, MessageIcon.Error);
}
else
{
messageBox.ShowDialog(messageManager.GetMessage("OpenInVSActionImported"), title, MessageButtons.OK, MessageIcon.Information);
}
}
}
}
| 39.023256 | 263 | 0.740465 | [
"MIT"
] | FilenkoAndrii/ArasVSMethodPlugin | Aras.VS.MethodPlugin/Commands/ImportOpenInVSActionCmd.cs | 3,359 | C# |
//
// ProgressStream.cs
//
// Author: Jeffrey Stedfast <jestedfa@microsoft.com>
//
// Copyright (c) 2013-2018 Xamarin Inc. (www.xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using MimeKit.IO;
namespace MailKit {
class ProgressStream : Stream, ICancellableStream
{
readonly ICancellableStream cancellable;
public ProgressStream (Stream source, Action<int> update)
{
if (source == null)
throw new ArgumentNullException (nameof (source));
cancellable = source as ICancellableStream;
Source = source;
Update = update;
}
public Stream Source {
get; private set;
}
Action<int> Update {
get; set;
}
public override bool CanRead {
get { return Source.CanRead; }
}
public override bool CanWrite {
get { return Source.CanWrite; }
}
public override bool CanSeek {
get { return false; }
}
public override bool CanTimeout {
get { return Source.CanTimeout; }
}
public override long Length {
get { return Source.Length; }
}
public override long Position {
get { return Source.Position; }
set { Source.Position = value; }
}
public override int ReadTimeout {
get { return Source.ReadTimeout; }
set { Source.ReadTimeout = value; }
}
public override int WriteTimeout {
get { return Source.WriteTimeout; }
set { Source.WriteTimeout = value; }
}
public int Read (byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
int n;
if (cancellable != null) {
if ((n = cancellable.Read (buffer, offset, count, cancellationToken)) > 0)
Update (n);
} else {
if ((n = Source.Read (buffer, offset, count)) > 0)
Update (n);
}
return n;
}
public override int Read (byte[] buffer, int offset, int count)
{
int n;
if ((n = Source.Read (buffer, offset, count)) > 0)
Update (n);
return n;
}
public override async Task<int> ReadAsync (byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
int n;
if ((n = await Source.ReadAsync (buffer, offset, count, cancellationToken).ConfigureAwait (false)) > 0)
Update (n);
return n;
}
public void Write (byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
if (cancellable != null)
cancellable.Write (buffer, offset, count, cancellationToken);
else
Source.Write (buffer, offset, count);
if (count > 0)
Update (count);
}
public override void Write (byte[] buffer, int offset, int count)
{
Source.Write (buffer, offset, count);
if (count > 0)
Update (count);
}
public override async Task WriteAsync (byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
await Source.WriteAsync (buffer, offset, count, cancellationToken).ConfigureAwait (false);
if (count > 0)
Update (count);
}
public override long Seek (long offset, SeekOrigin origin)
{
throw new NotSupportedException ("The stream does not support seeking.");
}
public void Flush (CancellationToken cancellationToken)
{
if (cancellable != null)
cancellable.Flush (cancellationToken);
else
Source.Flush ();
}
public override void Flush ()
{
Source.Flush ();
}
public override Task FlushAsync (CancellationToken cancellationToken)
{
return Source.FlushAsync (cancellationToken);
}
public override void SetLength (long value)
{
throw new NotSupportedException ("The stream does not support resizing.");
}
}
}
| 25.202186 | 119 | 0.694493 | [
"MIT"
] | CodingSpiderFox/MailKit | MailKit/ProgressStream.cs | 4,614 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
using SausageChat.Core.Messaging;
using SausageChat.Helpers;
using SausageChat.Core;
using System.Collections.ObjectModel;
using SausageChat.Core.Networking;
using Newtonsoft.Json;
using System.Windows.Forms;
using System.Threading;
namespace SausageChat.Networking
{
static class SausageServer
{
public static bool IsOpen { get; set; } = false;
public static ViewModel Vm { get; set; }
public static MainWindow Mw { get; set; }
public static Socket MainSocket { get; set; }
public const int PORT = 60000;
public static ObservableCollection<SausageConnection> ConnectedUsers
{
get
{
return Vm.ConnectedUsers;
}
set
{
Vm.ConnectedUsers = value;
}
}
public static SausageUserList UsersDictionary { get; set; } = new SausageUserList();
public static List<IPAddress> Blacklisted { get; set; } = new List<IPAddress>();
public static IPEndPoint LocalIp { get; set; } = new IPEndPoint(IPAddress.Any, PORT);
public static SynchronizationContext UiCtx { get; set; }
public static void Open()
{
if (!IsOpen)
{
MainSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
ConnectedUsers = new ObservableCollection<SausageConnection>();
UsersDictionary = new SausageUserList();
MainSocket.Bind(LocalIp);
MainSocket.Listen(10);
UiCtx = SynchronizationContext.Current;
MainSocket.BeginAccept(OnUserConnect, null);
IsOpen = true;
UiCtx.Send(x => Vm.Messages.Add(new ServerMessage("Opened server")));
}
else
{
UiCtx.Send(x => Vm.Messages.Add(new ServerMessage("Server already open")));
}
}
public static void Close()
{
if(IsOpen)
{
MainSocket.Close();
foreach(SausageConnection u in ConnectedUsers)
{
u.Disconnect();
}
UiCtx.Send(x => Vm.Messages = new ObservableCollection<IMessage>());
UiCtx.Send(x => Vm.Messages.Add(new ServerMessage("Closed all sockets")));
IsOpen = false;
}
else
{
MessageBox.Show("Server is already closed", "Sausage Server");
}
}
// TODO: logging
public static async Task Ban(SausageConnection user)
{
try
{
if (!(user.Socket.Connected || MainSocket.Connected)) return;
// user exists
if (ConnectedUsers.Any(x => x.UserInfo.Guid == user.UserInfo.Guid))
{
Blacklisted.Add(user.Ip.Address);
PacketFormat packet = new PacketFormat(PacketOption.UserBanned)
{
Guid = user.UserInfo.Guid,
Content = "Place-holder reason"
};
Log(packet);
await Task.Delay(1000);
// delay for waiting on the client to recieve a message
user.Disconnect();
UiCtx.Send(x => ConnectedUsers.Remove(user));
}
else
{
MessageBox.Show("User not found", "Ban result");
}
}
catch (ArgumentNullException e)
{
MessageBox.Show($"User returned null {e}", "Exception Caught");
}
}
public static async Task Kick(SausageConnection user)
{
try
{
if (!(user.Socket.Connected || MainSocket.Connected)) return;
// user exists
if (ConnectedUsers.Any(x => x.UserInfo.Guid == user.UserInfo.Guid))
{
PacketFormat packet = new PacketFormat(PacketOption.UserKicked)
{
Guid = user.UserInfo.Guid,
Content = "Place-holder reason"
};
await Log(packet);
// delay for waiting on the client to recieve a message
await Task.Delay(1000);
user.Disconnect();
UiCtx.Send(x => Vm.ConnectedUsers.Remove(user));
}
else
{
MessageBox.Show("User not found", "Kick result");
}
}
catch(ArgumentNullException e)
{
MessageBox.Show($"User returned null {e}", "Exception Caught");
}
}
public static async Task Mute(SausageConnection user)
{
try
{
// user exists
if (ConnectedUsers.Any(x => x.UserInfo.Guid == user.UserInfo.Guid))
{
PacketFormat packet = new PacketFormat(PacketOption.UserMuted)
{
Guid = user.UserInfo.Guid,
Content = "Place-holder reason"
};
user.UserInfo.IsMuted = true;
await Log(packet);
}
else
{
MessageBox.Show("User not found", "Kick result");
}
}
catch(ArgumentNullException e)
{
MessageBox.Show($"User returned null {e}", "Exception Caught");
}
}
public static async Task Unmute(SausageConnection user)
{
try
{
// user exists
if (ConnectedUsers.Any(x => x.UserInfo.Guid == user.UserInfo.Guid))
{
PacketFormat packet = new PacketFormat(PacketOption.UserUnmuted)
{
Guid = user.UserInfo.Guid
};
user.UserInfo.IsMuted = false;
await Log(packet);
}
else
{
MessageBox.Show("User not found", "Kick result");
}
}
catch (ArgumentNullException e)
{
MessageBox.Show($"User returned null {e}", "Exception Caught");
}
}
// TODO: Add user list
public static void OnUserConnect(IAsyncResult ar)
{
SausageConnection user;
try
{
user = new SausageConnection(MainSocket.EndAccept(ar));
}
catch(SocketException ex)
{
Close();
return;
}
catch(ObjectDisposedException ex)
{
return;
}
if (!Blacklisted.Any(x => x == user.Ip.Address))
{
UiCtx.Send(x => ConnectedUsers.Add(user));
UiCtx.Send(x => Vm.ConnectedUsers = SortUsersList());
UiCtx.Send(x => Vm.Messages.Add(new ServerMessage($"{user} has connected")));
UiCtx.Send(x => Mw.AddTextToDebugBox($"User connected on {user.Ip}\n"));
// global packet for all the users to know the user has joined
PacketFormat GlobalPacket = new PacketFormat(PacketOption.UserConnected)
{
Guid = user.UserInfo.Guid,
NewName = user.UserInfo.Name
};
// local packet for the user (who joined) to get his GUID
PacketFormat LocalPacket = new PacketFormat(PacketOption.GetGuid)
{
Guid = user.UserInfo.Guid,
UsersList = UsersDictionary.ToArray()
};
UsersDictionary.Add(user.UserInfo);
user.SendAsync(LocalPacket);
Log(GlobalPacket, user);
}
else
{
// doesn't log if the user is blacklisted
user.Disconnect();
}
MainSocket.BeginAccept(OnUserConnect, null);
}
// TODO: make a switch for the user messge (some packets don't have content)
public async static Task Log(PacketFormat message, SausageConnection ignore = null)
{
if (message.Option == PacketOption.ClientMessage)
UiCtx.Send(x => Vm.Messages.Add(new UserMessage(message.Content, UsersDictionary[message.Guid])));
else
switch(message.Option)
{
case PacketOption.NameChange:
UiCtx.Send(x => Vm.Messages.Add(
new ServerMessage($"{UsersDictionary[message.Guid]} changed their name to {message.NewName}")));
break;
default:
UiCtx.Send(x => Vm.Messages.Add(new ServerMessage(message.Content)));
break;
}
foreach(var user in ConnectedUsers)
{
if(user != ignore)
user.SendAsync(JsonConvert.SerializeObject(message));
}
}
public static ObservableCollection<SausageConnection> SortUsersList()
{
List<SausageConnection> names = new List<SausageConnection>(Vm.ConnectedUsers);
names.Sort(new ConnectionComparer());
return new ObservableCollection<SausageConnection>(names);
}
}
}
| 36.567766 | 124 | 0.48843 | [
"MIT"
] | ArchyInUse/SausageChat | SausageChat/Networking/SausageServer.cs | 9,983 | C# |
using System;
using System.IO;
using FoxTool.Fox.Types;
using FoxTool.Fox.Types.Structs;
using FoxTool.Fox.Types.Values;
namespace FoxTool.Fox.Containers
{
internal static class FoxContainerFactory
{
public static IFoxContainer ReadFoxContainer(Stream input, FoxDataType dataType, FoxContainerType containerType,
short valueCount)
{
var container = CreateTypedContainer(dataType, containerType);
container.Read(input, valueCount);
return container;
}
public static IFoxContainer CreateTypedContainer(FoxDataType dataType, FoxContainerType containerType)
{
IFoxContainer container;
switch (dataType)
{
case FoxDataType.FoxInt8:
container = CreateContainer<FoxInt8>(containerType);
break;
case FoxDataType.FoxUInt8:
container = CreateContainer<FoxUInt8>(containerType);
break;
case FoxDataType.FoxInt16:
container = CreateContainer<FoxInt16>(containerType);
break;
case FoxDataType.FoxUInt16:
container = CreateContainer<FoxUInt16>(containerType);
break;
case FoxDataType.FoxInt32:
container = CreateContainer<FoxInt32>(containerType);
break;
case FoxDataType.FoxUInt32:
container = CreateContainer<FoxUInt32>(containerType);
break;
case FoxDataType.FoxInt64:
container = CreateContainer<FoxInt64>(containerType);
break;
case FoxDataType.FoxUInt64:
container = CreateContainer<FoxUInt64>(containerType);
break;
case FoxDataType.FoxFloat:
container = CreateContainer<FoxFloat>(containerType);
break;
case FoxDataType.FoxDouble:
container = CreateContainer<FoxDouble>(containerType);
break;
case FoxDataType.FoxBool:
container = CreateContainer<FoxBool>(containerType);
break;
case FoxDataType.FoxString:
container = CreateContainer<FoxString>(containerType);
break;
case FoxDataType.FoxPath:
container = CreateContainer<FoxPath>(containerType);
break;
case FoxDataType.FoxEntityPtr:
container = CreateContainer<FoxEntityPtr>(containerType);
break;
case FoxDataType.FoxVector3:
container = CreateContainer<FoxVector3>(containerType);
break;
case FoxDataType.FoxVector4:
container = CreateContainer<FoxVector4>(containerType);
break;
case FoxDataType.FoxQuat:
container = CreateContainer<FoxQuat>(containerType);
break;
case FoxDataType.FoxMatrix3:
container = CreateContainer<FoxMatrix3>(containerType);
break;
case FoxDataType.FoxMatrix4:
container = CreateContainer<FoxMatrix4>(containerType);
break;
case FoxDataType.FoxColor:
container = CreateContainer<FoxColor>(containerType);
break;
case FoxDataType.FoxFilePtr:
container = CreateContainer<FoxFilePtr>(containerType);
break;
case FoxDataType.FoxEntityHandle:
container = CreateContainer<FoxEntityHandle>(containerType);
break;
case FoxDataType.FoxEntityLink:
container = CreateContainer<FoxEntityLink>(containerType);
break;
case FoxDataType.FoxPropertyInfo:
container = CreateContainer<FoxPropertyInfo>(containerType);
break;
case FoxDataType.FoxWideVector3:
container = CreateContainer<FoxWideVector3>(containerType);
break;
default:
throw new ArgumentOutOfRangeException("dataType");
}
return container;
}
private static IFoxContainer CreateContainer<T>(FoxContainerType containerType) where T : IFoxValue, new()
{
switch (containerType)
{
case FoxContainerType.StaticArray:
return new FoxStaticArray<T>();
case FoxContainerType.DynamicArray:
return new FoxDynamicArray<T>();
case FoxContainerType.StringMap:
return new FoxStringMap<T>();
case FoxContainerType.List:
return new FoxList<T>();
default:
throw new ArgumentOutOfRangeException("containerType");
}
}
}
}
| 43.837398 | 121 | 0.526892 | [
"MIT"
] | Atvaark/FoxTool | FoxTool/Fox/Containers/FoxContainerFactory.cs | 5,394 | C# |
using System;
using System.Globalization;
using System.Numerics;
using BenchmarkDotNet.Extensions;
using BenchmarkDotNet.Horology;
using SimpleJson.Reflection;
namespace BenchmarkDotNet.Helpers
{
public static class SourceCodeHelper
{
public static string ToSourceCode(object value)
{
switch (value) {
case null:
return "null";
case bool b:
return b.ToLowerCase();
case string text:
return $"$@\"{text.Replace("\"", "\"\"").Replace("{", "{{").Replace("}", "}}")}\"";
case char c:
return c == '\\' ? "'\\\\'" : $"'{value}'";
case float f:
return ToSourceCode(f);
case double d:
return ToSourceCode(d);
case decimal f:
return f.ToString("G", CultureInfo.InvariantCulture) + "m";
case BigInteger bigInteger:
return $"System.Numerics.BigInteger.Parse(\"{bigInteger.ToString(CultureInfo.InvariantCulture)}\", System.Globalization.CultureInfo.InvariantCulture)";
case DateTime dateTime:
return $"System.DateTime.Parse(\"{dateTime.ToString(CultureInfo.InvariantCulture)}\", System.Globalization.CultureInfo.InvariantCulture)";
case Guid guid:
return $"System.Guid.Parse(\"{guid.ToString()}\")";
}
if (ReflectionUtils.GetTypeInfo(value.GetType()).IsEnum)
return $"({value.GetType().GetCorrectCSharpTypeName()})({ToInvariantCultureString(value)})";
if (value is Type type)
return "typeof(" + type.GetCorrectCSharpTypeName() + ")";
if (!ReflectionUtils.GetTypeInfo(value.GetType()).IsValueType)
return "System.Activator.CreateInstance<" + value.GetType().GetCorrectCSharpTypeName() + ">()";
switch (value) {
case TimeInterval interval:
return "new BenchmarkDotNet.Horology.TimeInterval(" + ToSourceCode(interval.Nanoseconds) + ")";
case IntPtr ptr:
return $"new System.IntPtr({ptr})";
case IFormattable formattable:
return formattable.ToString(null, CultureInfo.InvariantCulture);
}
return value.ToString();
}
public static bool IsCompilationTimeConstant(object value)
=> value == null || IsCompilationTimeConstant(value.GetType());
public static bool IsCompilationTimeConstant(Type type)
{
if (type == typeof(long) || type == typeof(ulong))
return true;
if (type == typeof(int) || type == typeof(uint))
return true;
if (type == typeof(short) || type == typeof(ushort))
return true;
if (type == typeof(byte) || type == typeof(sbyte))
return true;
if (type == typeof(bool))
return true;
if (type == typeof(string))
return true;
if (type == typeof(char))
return true;
if (type == typeof(float))
return true;
if (type == typeof(double))
return true;
if (type == typeof(decimal))
return true;
if (type.IsEnum)
return true;
if (type == typeof(Type))
return true;
if (type == typeof(TimeInterval))
return true;
if (type == typeof(IntPtr))
return true;
if (type == typeof(DateTime))
return true;
if (!type.IsValueType) // the difference!!
return false;
if (typeof(IFormattable).IsAssignableFrom(type))
return false;
return false;
}
private static string ToSourceCode(double value)
{
if (double.IsNaN(value))
return "System.Double.NaN";
if (double.IsPositiveInfinity(value))
return "System.Double.PositiveInfinity";
if (double.IsNegativeInfinity(value))
return "System.Double.NegativeInfinity";
if (value == double.Epsilon)
return "System.Double.Epsilon";
if (value == double.MaxValue)
return "System.Double.MaxValue";
if (value == double.MinValue)
return "System.Double.MinValue";
return value.ToString("G", CultureInfo.InvariantCulture) + "d";
}
private static string ToSourceCode(float value)
{
if (float.IsNaN(value))
return "System.Single.NaN";
if (float.IsPositiveInfinity(value))
return "System.Single.PositiveInfinity";
if (float.IsNegativeInfinity(value))
return "System.Single.NegativeInfinity";
if (value == float.Epsilon)
return "System.Single.Epsilon";
if (value == float.MaxValue)
return "System.Single.MaxValue";
if (value == float.MinValue)
return "System.Single.MinValue";
return value.ToString("G", CultureInfo.InvariantCulture) + "f";
}
private static string ToInvariantCultureString(object @enum)
{
switch (Type.GetTypeCode(Enum.GetUnderlyingType(@enum.GetType())))
{
case TypeCode.Byte:
return ((byte)@enum).ToString(CultureInfo.InvariantCulture);
case TypeCode.Int16:
return ((short)@enum).ToString(CultureInfo.InvariantCulture);
case TypeCode.Int32:
return ((int)@enum).ToString(CultureInfo.InvariantCulture);
case TypeCode.Int64:
return ((long)@enum).ToString(CultureInfo.InvariantCulture);
case TypeCode.SByte:
return ((sbyte)@enum).ToString(CultureInfo.InvariantCulture);
case TypeCode.UInt16:
return ((ushort)@enum).ToString(CultureInfo.InvariantCulture);
case TypeCode.UInt32:
return ((uint)@enum).ToString(CultureInfo.InvariantCulture);
case TypeCode.UInt64:
return ((ulong)@enum).ToString(CultureInfo.InvariantCulture);
default:
throw new ArgumentOutOfRangeException(nameof(@enum));
}
}
}
}
| 41.79375 | 171 | 0.53118 | [
"MIT"
] | FrancisChung/BenchmarkDotNet | src/BenchmarkDotNet/Helpers/SourceCodeHelper.cs | 6,689 | C# |
/*********************************************
作者:曹旭升
QQ:279060597
访问博客了解详细介绍及更多内容:
http://blog.shengxunwei.com
**********************************************/
namespace Sheng.SailingEase.Modules.DataBaseSourceModule.Localisation {
using System;
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "2.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
public class Chinese__Simplified_ : ILanguage {
private global::System.Resources.ResourceManager resourceMan;
private global::System.Globalization.CultureInfo resourceCulture;
public Chinese__Simplified_() {
}
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
public global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Sheng.SailingEase.Modules.DataBaseSourceModule.Localisation.Chinese (Simplified)", typeof(Chinese__Simplified_).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
public global::System.Globalization.CultureInfo Culture {
get {
if (object.ReferenceEquals(resourceCulture, null)) {
global::System.Globalization.CultureInfo temp = new global::System.Globalization.CultureInfo("zh-CHS");
resourceCulture = temp;
}
return resourceCulture;
}
}
public string DataSourceCreateView {
get {
return ResourceManager.GetString("DataSourceCreateView", resourceCulture);
}
}
public string DataSourceCreateView_ButtonCancel {
get {
return ResourceManager.GetString("DataSourceCreateView_ButtonCancel", resourceCulture);
}
}
public string DataSourceCreateView_ButtonOK {
get {
return ResourceManager.GetString("DataSourceCreateView_ButtonOK", resourceCulture);
}
}
public string DataSourceCreateView_ButtonRefreshDataSource {
get {
return ResourceManager.GetString("DataSourceCreateView_ButtonRefreshDataSource", resourceCulture);
}
}
public string DataSourceCreateView_GroupBoxLoginOption {
get {
return ResourceManager.GetString("DataSourceCreateView_GroupBoxLoginOption", resourceCulture);
}
}
public string DataSourceCreateView_LabelDataSourceName {
get {
return ResourceManager.GetString("DataSourceCreateView_LabelDataSourceName", resourceCulture);
}
}
public string DataSourceCreateView_LabelDataSourceType {
get {
return ResourceManager.GetString("DataSourceCreateView_LabelDataSourceType", resourceCulture);
}
}
public string DataSourceCreateView_LabelNotice {
get {
return ResourceManager.GetString("DataSourceCreateView_LabelNotice", resourceCulture);
}
}
public string DataSourceCreateView_LabelPassword {
get {
return ResourceManager.GetString("DataSourceCreateView_LabelPassword", resourceCulture);
}
}
public string DataSourceCreateView_LabelUserId {
get {
return ResourceManager.GetString("DataSourceCreateView_LabelUserId", resourceCulture);
}
}
public string DataSourceCreateView_RadioButtonIntegratedSecurity {
get {
return ResourceManager.GetString("DataSourceCreateView_RadioButtonIntegratedSecurity", resourceCulture);
}
}
public string DataSourceCreateView_RadioButtonNoIntegratedSecurity {
get {
return ResourceManager.GetString("DataSourceCreateView_RadioButtonNoIntegratedSecurity", resourceCulture);
}
}
public string DataSourceSetView {
get {
return ResourceManager.GetString("DataSourceSetView", resourceCulture);
}
}
public string DataSourceSetView_ButtonCancel {
get {
return ResourceManager.GetString("DataSourceSetView_ButtonCancel", resourceCulture);
}
}
public string DataSourceSetView_ButtonOK {
get {
return ResourceManager.GetString("DataSourceSetView_ButtonOK", resourceCulture);
}
}
public string DataSourceSetView_LabelConnectionString {
get {
return ResourceManager.GetString("DataSourceSetView_LabelConnectionString", resourceCulture);
}
}
public string DataSourceSetView_LabelTitle {
get {
return ResourceManager.GetString("DataSourceSetView_LabelTitle", resourceCulture);
}
}
public string DataSourceSetView_LinkLabelCreateDataSource {
get {
return ResourceManager.GetString("DataSourceSetView_LinkLabelCreateDataSource", resourceCulture);
}
}
public string Navigation_Menu_DataSourceSet {
get {
return ResourceManager.GetString("Navigation_Menu_DataSourceSet", resourceCulture);
}
}
public bool IsDefault {
get {
return true;
}
}
public override string ToString() {
return Culture.EnglishName;
}
}
}
| 43.93662 | 237 | 0.609072 | [
"MIT"
] | ckalvin-hub/Sheng.Winform.IDE | SourceCode/Source/Modules/Localisation/Modules.DataBaseSource.Localisation/Chinese (Simplified).Designer.cs | 6,287 | C# |
using Frw.Base;
using System;
using System.IO;
using System.Xml.XPath;
namespace Frw.Config
{
public class ConfigReader
{
public static void SetFrameworkSettings()
{
XPathItem url;
XPathItem browserType;
XPathItem isLog;
XPathItem logPath;
XPathItem appConnection;
string strFileName = Environment.CurrentDirectory.ToString() +
@"\Config\GlobalConfig.xml";
FileStream stream = new FileStream(strFileName, FileMode.Open);
XPathDocument document = new XPathDocument(stream);
XPathNavigator navigator = document.CreateNavigator();
//Get XML Details and pass it in XpathItem type variables
url = navigator.SelectSingleNode("Frw/RunSettings/URL");
browserType = navigator.SelectSingleNode("Frw/RunSettings/Browser");
isLog = navigator.SelectSingleNode("Frw/RunSettings/IsLog");
logPath = navigator.SelectSingleNode("Frw/RunSettings/LogPath");
appConnection = navigator.SelectSingleNode("Frw/RunSettings/ApplicationDb");
//Set XML Details in the property to be used across framework
Settings.Url = url.ToString();
Settings.BrowserType = (BrowserType) Enum.Parse(typeof(BrowserType), browserType.ToString());
Settings.IsLog = isLog.ToString();
Settings.LogPath = logPath.ToString();
Settings.AppConnectionString = appConnection.Value.ToString();
}
}
}
| 38.02439 | 105 | 0.641437 | [
"MIT"
] | escame/AutoFramework | Frw/Frw/Config/ConfigReader.cs | 1,561 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace RouteAPI
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
| 25.555556 | 70 | 0.643478 | [
"MIT"
] | nikoladragas/public-transport | RouteAPI/Program.cs | 690 | C# |
using umamusumeKeyCtl.AppSettings.SettingUI;
namespace umamusumeKeyCtl.AppSettings.Factory
{
public abstract class SettingUIFactoryBase
{
public SettingUIBase Create(AppSettingDescription description)
{
SettingUIBase settingUiBase = CreateSettingUiBase(description);
return settingUiBase;
}
protected abstract SettingUIBase CreateSettingUiBase(AppSettingDescription description);
}
} | 30.2 | 96 | 0.737307 | [
"MIT"
] | Sakusakumura/UmamusumeKeyCtl | umamusumeKeyCtl/src/AppSettings/Factory/SettingUIFactoryBase.cs | 453 | C# |
using UnityEngine;
using System.Collections;
/// <summary>
/// The armour generally buffs the Giant's defense
/// and other defensive stats.
/// </summary>
public class Armour : Equipment {
public Armour(string _name, string _description, Resources _resourceCost, Sprite _icon, float _craftingTime, bool _giantUse, Stats _stats, int _reinforcementCount, Stats _reinforcementStats)
: base(_name, _description, _resourceCost, _icon, _craftingTime, _giantUse, _stats, _reinforcementCount, _reinforcementStats)
{
}
/// <summary>
/// Copies the given Armour as a new Armour
/// </summary>
/// <param name="_armour"></param>
public Armour(Armour _armour) : base(_armour)
{
}
}
| 29.56 | 194 | 0.688769 | [
"MIT"
] | Tagglink/GiantFeud | Assets/Scripts/Armour.cs | 741 | 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.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Azure.WebJobs.Logging;
using Microsoft.Azure.WebJobs.Script.Diagnostics;
using Microsoft.Azure.WebJobs.Script.WebHost.Diagnostics;
using Microsoft.Azure.WebJobs.Script.WebHost.Models;
using Microsoft.Azure.WebJobs.Script.Workers;
using Microsoft.Azure.WebJobs.Script.Workers.Rpc;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.WebJobs.Script.Tests;
using Newtonsoft.Json.Linq;
using Xunit;
namespace Microsoft.Azure.WebJobs.Script.Tests.EndToEnd
{
[Trait(TestTraits.Category, TestTraits.EndToEnd)]
[Trait(TestTraits.Group, nameof(CSharpEndToEndTests))]
public class CSharpEndToEndTests : EndToEndTestsBase<CSharpEndToEndTests.TestFixture>
{
public CSharpEndToEndTests(TestFixture fixture) : base(fixture)
{
}
[Fact]
public async Task ManualTrigger_Invoke_Succeeds()
{
await ManualTrigger_Invoke_SucceedsTest();
}
[Fact]
public async Task QueueTriggerToBlob()
{
await QueueTriggerToBlobTest();
}
[Fact(Skip = "Not yet enabled.")]
public void MobileTables()
{
// await MobileTablesTest(isDotNet: true);
}
[Fact(Skip = "Not yet enabled.")]
public void NotificationHub()
{
// await NotificationHubTest("NotificationHubOut");
}
[Fact(Skip = "Not yet enabled.")]
public void NotificationHub_Out_Notification()
{
// await NotificationHubTest("NotificationHubOutNotification");
}
[Fact(Skip = "Not yet enabled.")]
public void NotificationHubNative()
{
// await NotificationHubTest("NotificationHubNative");
}
[Fact(Skip = "Not yet enabled.")]
public void MobileTablesTable()
{
//var id = Guid.NewGuid().ToString();
//Dictionary<string, object> arguments = new Dictionary<string, object>()
//{
// { "input", id }
//};
//await Fixture.Host.CallAsync("MobileTableTable", arguments);
//await WaitForMobileTableRecordAsync("Item", id);
}
[Fact]
public async Task FunctionLogging_Succeeds()
{
Fixture.Host.ClearLogMessages();
string functionName = "Scenarios";
string guid1 = Guid.NewGuid().ToString();
string guid2 = Guid.NewGuid().ToString();
var inputObject = new JObject
{
{ "Scenario", "logging" },
{ "Container", "scenarios-output" },
{ "Value", $"{guid1};{guid2}" }
};
await Fixture.Host.BeginFunctionAsync(functionName, inputObject);
IList<string> logs = null;
await TestHelpers.Await(() =>
{
logs = Fixture.Host.GetScriptHostLogMessages().Select(p => p.FormattedMessage).Where(p => p != null).ToArray();
return logs.Any(p => p.Contains(guid2));
});
logs.Single(p => p.EndsWith($"From TraceWriter: {guid1}"));
logs.Single(p => p.EndsWith($"From ILogger: {guid2}"));
// Make sure we've gotten a log from the aggregator
IEnumerable<LogMessage> getAggregatorLogs() => Fixture.Host.GetScriptHostLogMessages().Where(p => p.Category == LogCategories.Aggregator);
await TestHelpers.Await(() => getAggregatorLogs().Any());
var aggregatorLogs = getAggregatorLogs();
Assert.Equal(1, aggregatorLogs.Count());
// Make sure that no user logs made it to the EventGenerator (which the SystemLogger writes to)
IEnumerable<FunctionTraceEvent> allLogs = Fixture.EventGenerator.GetFunctionTraceEvents();
Assert.False(allLogs.Any(l => l.Summary.Contains("From ")));
Assert.False(allLogs.Any(l => l.Source.EndsWith(".User")));
Assert.False(allLogs.Any(l => l.Source == WorkerConstants.FunctionConsoleLogCategoryName));
Assert.NotEmpty(allLogs);
}
[Fact]
public async Task VerifyHostHeader()
{
const string actualHost = "actual-host";
const string actualProtocol = "https";
const string path = "api/httptrigger-scenarios";
var protocolHeaders = new[] { "https", "http" };
var request = new HttpRequestMessage
{
RequestUri = new Uri(string.Format($"http://localhost/{path}")),
Method = HttpMethod.Post
};
request.Headers.TryAddWithoutValidation("DISGUISED-HOST", actualHost);
request.Headers.Add("X-Forwarded-Proto", protocolHeaders);
var input = new JObject
{
{ "scenario", "appServiceFixupMiddleware" }
};
request.Content = new StringContent(input.ToString(), Encoding.UTF8, "application/json");
var response = await Fixture.Host.HttpClient.SendAsync(request);
response.EnsureSuccessStatusCode();
var url = await response.Content.ReadAsStringAsync();
Assert.Equal($"{actualProtocol}://{actualHost}/{path}", url);
}
[Fact]
public async Task VerifyResultRedirect()
{
const string path = "api/httptrigger-redirect";
var request = new HttpRequestMessage
{
RequestUri = new Uri(string.Format($"http://localhost/{path}")),
Method = HttpMethod.Get
};
var response = await Fixture.Host.HttpClient.SendAsync(request);
Assert.Equal(response.StatusCode, HttpStatusCode.Redirect);
}
[Fact]
public async Task VerifyAcceptResult_OtherFunctionRoute()
{
const string path = "api/httptrigger-routed";
var request = new HttpRequestMessage
{
RequestUri = new Uri(string.Format($"http://localhost/{path}?action=accept")),
Method = HttpMethod.Get
};
var response = await Fixture.Host.HttpClient.SendAsync(request);
Assert.Equal(response.StatusCode, HttpStatusCode.Accepted);
}
[Fact]
public async Task VerifyCreateResult_OtherFunctionRoute()
{
const string path = "api/httptrigger-routed";
var request = new HttpRequestMessage
{
RequestUri = new Uri(string.Format($"http://localhost/{path}?action=create")),
Method = HttpMethod.Get
};
var response = await Fixture.Host.HttpClient.SendAsync(request);
Assert.Equal(response.StatusCode, HttpStatusCode.Created);
}
[Fact]
public async Task VerifyAcceptResult_BadRoute()
{
const string path = "api/httptrigger-routed";
var request = new HttpRequestMessage
{
RequestUri = new Uri(string.Format($"http://localhost/{path}?action=acceptBadRoute")),
Method = HttpMethod.Get
};
var response = await Fixture.Host.HttpClient.SendAsync(request);
Assert.Equal(response.StatusCode, HttpStatusCode.InternalServerError);
}
[Fact]
public async Task VerifyCreateResult_BadRoute()
{
const string path = "api/httptrigger-routed";
var request = new HttpRequestMessage
{
RequestUri = new Uri(string.Format($"http://localhost/{path}?action=createBadRoute")),
Method = HttpMethod.Get
};
var response = await Fixture.Host.HttpClient.SendAsync(request);
Assert.Equal(response.StatusCode, HttpStatusCode.InternalServerError);
}
[Fact]
public async Task MultipleOutputs()
{
string id1 = Guid.NewGuid().ToString();
string id2 = Guid.NewGuid().ToString();
string id3 = Guid.NewGuid().ToString();
JObject input = new JObject
{
{ "Id1", id1 },
{ "Id2", id2 },
{ "Id3", id3 }
};
await Fixture.Host.BeginFunctionAsync("MultipleOutputs", input);
// verify all 3 output blobs were written
var blob = Fixture.TestOutputContainer.GetBlockBlobReference(id1);
await TestHelpers.WaitForBlobAsync(blob);
string blobContent = await blob.DownloadTextAsync();
Assert.Equal("Test Blob 1", Utility.RemoveUtf8ByteOrderMark(blobContent));
blob = Fixture.TestOutputContainer.GetBlockBlobReference(id2);
await TestHelpers.WaitForBlobAsync(blob);
blobContent = await blob.DownloadTextAsync();
Assert.Equal("Test Blob 2", Utility.RemoveUtf8ByteOrderMark(blobContent));
blob = Fixture.TestOutputContainer.GetBlockBlobReference(id3);
await TestHelpers.WaitForBlobAsync(blob);
blobContent = await blob.DownloadTextAsync();
Assert.Equal("Test Blob 3", Utility.RemoveUtf8ByteOrderMark(blobContent));
}
[Fact]
public async Task ScriptReference_LoadsScript()
{
HttpResponseMessage response = await Fixture.Host.HttpClient.GetAsync($"api/LoadScriptReference");
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal("TestClass", await response.Content.ReadAsStringAsync());
}
[Fact]
public async Task MissingAssemblies_ShowsHelpfulMessage()
{
HttpResponseMessage response = await Fixture.Host.HttpClient.GetAsync($"api/MissingAssemblies");
var logs = Fixture.Host.GetScriptHostLogMessages().Select(p => p.FormattedMessage).Where(p => p != null).ToArray();
var hasWarning = logs.Any(p => p.Contains("project.json' should not be used to reference NuGet packages. Try creating a 'function.proj' file instead. Learn more: https://go.microsoft.com/fwlink/?linkid=2091419"));
Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
Assert.Equal(true, hasWarning);
}
[Fact]
public async Task ExecutionContext_IsPopulated()
{
string functionName = "FunctionExecutionContext";
HttpResponseMessage response = await Fixture.Host.HttpClient.GetAsync($"api/{functionName}");
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
ExecutionContext context = await response.Content.ReadAsAsync<ExecutionContext>();
Assert.NotNull(context);
Assert.Equal(functionName, context.FunctionName);
Assert.Equal(Path.Combine(Fixture.Host.ScriptOptions.RootScriptPath, functionName), context.FunctionDirectory);
}
[Fact]
public async Task SharedAssemblyDependenciesAreLoaded()
{
HttpResponseMessage response = await Fixture.Host.HttpClient.GetAsync("api/AssembliesFromSharedLocation");
Assert.Equal("secondary type value", await response.Content.ReadAsStringAsync());
}
[Fact]
public async Task RandGuidBinding_GeneratesRandomIDs()
{
var blobs = await Scenario_RandGuidBinding_GeneratesRandomIDs();
foreach (var blob in blobs)
{
string content = await blob.DownloadTextAsync();
int blobInt = int.Parse(content.Trim(new char[] { '\uFEFF', '\u200B' }));
Assert.True(blobInt >= 0 && blobInt <= 3);
}
}
[Fact]
public async Task HttpTrigger_Post_Dynamic()
{
var input = new JObject
{
{ "name", "Mathew Charles" },
{ "location", "Seattle" }
};
HttpRequestMessage request = new HttpRequestMessage
{
RequestUri = new Uri(string.Format("http://localhost/api/httptrigger-dynamic")),
Method = HttpMethod.Post,
Content = new StringContent(input.ToString())
};
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("text/plain"));
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
HttpResponseMessage response = await Fixture.Host.HttpClient.SendAsync(request);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
string body = await response.Content.ReadAsStringAsync();
Assert.Equal("Name: Mathew Charles, Location: Seattle", body);
}
[Fact]
public async Task HttpTrigger_Model_Binding()
{
(JObject req, JObject res) = await MakeModelRequest(Fixture.Host.HttpClient);
Assert.True(JObject.DeepEquals(req, res), res.ToString());
}
[Fact]
public async Task HttpTrigger_Model_Binding_V2CompatMode()
{
// We need a custom host to set this to v2 compat mode.
using (var host = new TestFunctionHost(@"TestScripts\CSharp", Path.Combine(Path.GetTempPath(), "Functions"),
configureWebHostServices: webHostServices =>
{
var environment = new TestEnvironment();
environment.SetEnvironmentVariable(EnvironmentSettingNames.FunctionsV2CompatibilityModeKey, "true");
webHostServices.AddSingleton<IEnvironment>(_ => environment);
},
configureScriptHostWebJobsBuilder: webJobsBuilder =>
{
webJobsBuilder.Services.Configure<ScriptJobHostOptions>(o =>
{
// Only load the functions we care about
o.Functions = new[]
{
"HttpTrigger-Model-v2",
};
});
}))
{
(JObject req, JObject res) = await MakeModelRequest(host.HttpClient, "-v2");
// in v2, we expect the response to have a null customEnumerable property.
req["customEnumerable"] = null;
Assert.True(JObject.DeepEquals(req, res), res.ToString());
}
}
private static async Task<(JObject requestContent, JObject responseContent)> MakeModelRequest(HttpClient httpClient, string suffix = null)
{
var payload = new
{
custom = new { customProperty = "value" },
customEnumerable = new[] { new { customProperty = "value1" }, new { customProperty = "value2" } }
};
var jObject = JObject.FromObject(payload);
var json = jObject.ToString();
HttpRequestMessage request = new HttpRequestMessage
{
RequestUri = new Uri($"http://localhost/api/httptrigger-model{suffix}"),
Method = HttpMethod.Post,
Content = new StringContent(json, Encoding.UTF8, "application/json")
};
request.Content.Headers.ContentLength = json.Length;
HttpResponseMessage response = await httpClient.SendAsync(request);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
return (jObject, JObject.Parse(await response.Content.ReadAsStringAsync()));
}
[Fact]
public async Task HttpTriggerToBlob()
{
var request = new HttpRequestMessage
{
RequestUri = new Uri($"http://localhost/api/HttpTriggerToBlob?Suffix=TestSuffix"),
Method = HttpMethod.Post,
};
request.Headers.Add("Prefix", "TestPrefix");
request.Headers.Add("Value", "TestValue");
var id = Guid.NewGuid().ToString();
var metadata = new JObject()
{
{ "M1", "AAA" },
{ "M2", "BBB" }
};
var input = new JObject()
{
{ "Id", id },
{ "Value", "TestInput" },
{ "Metadata", metadata }
};
string content = input.ToString();
request.Content = new StringContent(content, Encoding.UTF8, "application/json");
request.Content.Headers.ContentLength = content.Length;
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("text/plain"));
HttpResponseMessage response = await Fixture.Host.HttpClient.SendAsync(request);
string body = await response.Content.ReadAsStringAsync();
string expectedValue = $"TestInput{id}TestValue";
Assert.Equal(expectedValue, body);
// verify blob was written
string blobName = $"TestPrefix-{id}-TestSuffix-BBB";
var outBlob = Fixture.TestOutputContainer.GetBlockBlobReference(blobName);
string result = await TestHelpers.WaitForBlobAndGetStringAsync(outBlob);
Assert.Equal(expectedValue, Utility.RemoveUtf8ByteOrderMark(result));
}
[Fact(Skip = "Failing due to a change in connection string validation in the WebJobs SDK. Tracking issue: https://github.com/Azure/azure-webjobs-sdk/issues/2415")]
public async Task FunctionWithIndexingError_ReturnsError()
{
FunctionStatus status = await Fixture.Host.GetFunctionStatusAsync("FunctionIndexingError");
string error = status.Errors.Single();
Assert.Equal("Microsoft.Azure.WebJobs.Host: Error indexing method 'Functions.FunctionIndexingError'. Microsoft.Azure.WebJobs.Extensions.Storage: Storage account connection string 'setting_does_not_exist' does not exist. Make sure that it is a defined App Setting.", error);
}
//[Theory(Skip = "Not yet enabled.")]
//[InlineData("application/json", "\"Name: Fabio Cavalcante, Location: Seattle\"")]
//[InlineData("application/xml", "<string xmlns=\"http://schemas.microsoft.com/2003/10/Serialization/\">Name: Fabio Cavalcante, Location: Seattle</string>")]
//[InlineData("text/plain", "Name: Fabio Cavalcante, Location: Seattle")]
//public async Task HttpTrigger_GetWithAccept_NegotiatesContent(string accept, string expectedBody)
//{
//var input = new JObject
//{
// { "name", "Fabio Cavalcante" },
// { "location", "Seattle" }
//};
//HttpRequestMessage request = new HttpRequestMessage
//{
// RequestUri = new Uri(string.Format("http://localhost/api/httptrigger-dynamic")),
// Method = HttpMethod.Post,
// Content = new StringContent(input.ToString())
//};
//request.SetConfiguration(Fixture.RequestConfiguration);
//request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept));
//request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
//Dictionary<string, object> arguments = new Dictionary<string, object>
//{
// { "input", request },
// { ScriptConstants.SystemTriggerParameterName, request }
//};
//await Fixture.Host.CallAsync("HttpTrigger-Dynamic", arguments);
//HttpResponseMessage response = (HttpResponseMessage)request.Properties[ScriptConstants.AzureFunctionsHttpResponseKey];
//Assert.Equal(HttpStatusCode.OK, response.StatusCode);
//Assert.Equal(accept, response.Content.Headers.ContentType.MediaType);
//string body = await response.Content.ReadAsStringAsync();
//Assert.Equal(expectedBody, body);
//}
public class TestFixture : EndToEndTestFixture
{
private const string ScriptRoot = @"TestScripts\CSharp";
static TestFixture()
{
CreateSharedAssemblies();
}
public TestFixture() : base(ScriptRoot, "csharp", RpcWorkerConstants.DotNetLanguageWorkerName)
{
}
private static void CreateSharedAssemblies()
{
string sharedAssembliesPath = Path.Combine(ScriptRoot, "SharedAssemblies");
if (Directory.Exists(sharedAssembliesPath))
{
Directory.Delete(sharedAssembliesPath, true);
}
Directory.CreateDirectory(sharedAssembliesPath);
string secondaryDependencyPath = Path.Combine(sharedAssembliesPath, "SecondaryDependency.dll");
string primaryReferenceSource = @"
using SecondaryDependency;
namespace PrimaryDependency
{
public class Primary
{
public string GetValue()
{
var secondary = new Secondary();
return secondary.GetSecondaryValue();
}
}
}";
string secondaryReferenceSource = @"
namespace SecondaryDependency
{
public class Secondary
{
public string GetSecondaryValue()
{
return ""secondary type value"";
}
}
}";
var secondarySyntaxTree = CSharpSyntaxTree.ParseText(secondaryReferenceSource);
Compilation secondaryCompilation = CSharpCompilation.Create("SecondaryDependency", new[] { secondarySyntaxTree })
.WithReferences(MetadataReference.CreateFromFile(typeof(object).Assembly.Location))
.WithOptions(new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));
secondaryCompilation.Emit(secondaryDependencyPath);
var primarySyntaxTree = CSharpSyntaxTree.ParseText(primaryReferenceSource);
Compilation primaryCompilation = CSharpCompilation.Create("PrimaryDependency", new[] { primarySyntaxTree })
.WithOptions(new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
.WithReferences(MetadataReference.CreateFromFile(secondaryDependencyPath), MetadataReference.CreateFromFile(typeof(object).Assembly.Location));
primaryCompilation.Emit(Path.Combine(sharedAssembliesPath, "PrimaryDependency.dll"));
}
public override void ConfigureScriptHost(IWebJobsBuilder webJobsBuilder)
{
base.ConfigureScriptHost(webJobsBuilder);
webJobsBuilder.AddAzureStorage();
webJobsBuilder.Services.Configure<ScriptJobHostOptions>(o =>
{
// Only load the functions we care about
o.Functions = new[]
{
"AssembliesFromSharedLocation",
"HttpTrigger-Dynamic",
"HttpTrigger-Scenarios",
"HttpTrigger-Model",
"HttpTrigger-Redirect",
"HttpTrigger-Routed",
"HttpTriggerToBlob",
"FunctionExecutionContext",
"LoadScriptReference",
"ManualTrigger",
"MultipleOutputs",
"QueueTriggerToBlob",
"Scenarios",
"FunctionIndexingError",
"MissingAssemblies"
};
});
webJobsBuilder.Services.Configure<FunctionResultAggregatorOptions>(o =>
{
o.BatchSize = 1;
});
}
}
public class TestInput
{
public int Id { get; set; }
public string Value { get; set; }
}
}
}
| 40.466667 | 285 | 0.595593 | [
"Apache-2.0",
"MIT"
] | ConnectionMaster/azure-functions-host | test/WebJobs.Script.Tests.Integration/WebHostEndToEnd/CSharpEndToEndTests.cs | 24,282 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Dashboard.Models
{
public partial class Description
{
public int PIN { get; set; }
public int FiscalYear { get; set; }
public DateTime FiscalEndDate { get; set; }
public int OperatingDays { get; set; }
}
}
| 26.3125 | 52 | 0.672209 | [
"MIT"
] | troyeradvisors/maryland-dashboard | src/Dashboard/Models/Description.cs | 421 | C# |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Collections.Generic;
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Platform;
using osu.Framework.Testing;
using osu.Game.Beatmaps;
using osu.Game.Rulesets;
using osu.Game.Rulesets.Objects;
using osu.Game.Rulesets.Osu.Objects;
using osu.Game.Storyboards;
using osu.Game.Tests.Beatmaps;
using osuTK;
namespace osu.Game.Tests.Visual.Gameplay
{
[HeadlessTest] // we alter unsafe properties on the game host to test inactive window state.
public class TestScenePauseWhenInactive : OsuPlayerTestScene
{
[Resolved]
private GameHost host { get; set; }
[Test]
public void TestDoesntPauseDuringIntro()
{
AddStep("set inactive", () => ((Bindable<bool>)host.IsActive).Value = false);
AddStep("resume player", () => Player.GameplayClockContainer.Start());
AddAssert("ensure not paused", () => !Player.GameplayClockContainer.IsPaused.Value);
AddStep("progress time to gameplay", () => Player.GameplayClockContainer.Seek(Player.DrawableRuleset.GameplayStartTime));
AddUntilStep("wait for pause", () => Player.GameplayClockContainer.IsPaused.Value);
}
/// <summary>
/// Tests that if a pause from focus lose is performed while in pause cooldown,
/// the player will still pause after the cooldown is finished.
/// </summary>
[Test]
public void TestPauseWhileInCooldown()
{
AddStep("move cursor outside", () => InputManager.MoveMouseTo(Player.ScreenSpaceDrawQuad.TopLeft - new Vector2(10)));
AddStep("resume player", () => Player.GameplayClockContainer.Start());
AddStep("skip to gameplay", () => Player.GameplayClockContainer.Seek(Player.DrawableRuleset.GameplayStartTime));
AddStep("set inactive", () => ((Bindable<bool>)host.IsActive).Value = false);
AddUntilStep("wait for pause", () => Player.GameplayClockContainer.IsPaused.Value);
AddStep("set active", () => ((Bindable<bool>)host.IsActive).Value = true);
AddStep("resume player", () => Player.Resume());
AddAssert("unpaused", () => !Player.GameplayClockContainer.IsPaused.Value);
bool pauseCooldownActive = false;
AddStep("set inactive again", () =>
{
pauseCooldownActive = Player.PauseCooldownActive;
((Bindable<bool>)host.IsActive).Value = false;
});
AddAssert("pause cooldown active", () => pauseCooldownActive);
AddUntilStep("wait for pause", () => Player.GameplayClockContainer.IsPaused.Value);
}
protected override TestPlayer CreatePlayer(Ruleset ruleset) => new TestPlayer(true, true, true);
protected override IBeatmap CreateBeatmap(RulesetInfo ruleset)
{
return new Beatmap
{
HitObjects = new List<HitObject>
{
new HitCircle { StartTime = 30000 },
new HitCircle { StartTime = 35000 },
},
};
}
protected override WorkingBeatmap CreateWorkingBeatmap(IBeatmap beatmap, Storyboard storyboard = null)
=> new TestWorkingBeatmap(beatmap, storyboard, Audio);
}
}
| 41.287356 | 134 | 0.623051 | [
"MIT"
] | 02Naitsirk/osu | osu.Game.Tests/Visual/Gameplay/TestScenePauseWhenInactive.cs | 3,506 | C# |
using System;
namespace GameTracker.ObservedProcesses
{
public class ObservedProcess
{
/// <summary>ProcessName recorded from Process</summary>
public string ProcessName { get; set; }
/// <summary>Full filepath for the process</summary>
public string ProcessPath { get; set; }
/// <summary>Represents if the user decided this process is not worth monitoring. Monitoring this process will not happen when this is marked false.</summary>
public bool Ignore { get; set; }
public DateTimeOffset FirstObservedTime { get; set; }
}
}
| 28.894737 | 160 | 0.739526 | [
"MIT"
] | krishemenway/game-tracker | GameTracker.Service/ObservedProcesses/ObservedProcess.cs | 551 | C# |
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.Drawing;
using System.Collections.Generic;
using PlanetSystem.Models.Utilities;
using PlanetSystem.Models.Bodies;
using System.Text;
using System;
namespace ReportsGenerators
{
public static class GeneralUIReportGenerator
{
public static void GenerateReport(
string planetarySystemName,
List<AstronomicalBody> bodiesPreMove,
List<AstronomicalBody> bodiesPostMove,
Bitmap bm)
{
FileStream fs = new FileStream("report.pdf", FileMode.Create, FileAccess.Write, FileShare.None);
Document doc = new Document(PageSize.LETTER, 10, 10, 42, 35);
PdfWriter writer = PdfWriter.GetInstance(doc, fs);
doc.Open();
Paragraph title = new Paragraph(new Phrase($"Report on {planetarySystemName}"));
title.Alignment = Element.ALIGN_CENTER;
doc.Add(title);
Paragraph date = new Paragraph(new Phrase($"Generated on {DateTime.Now}"));
date.Alignment = Element.ALIGN_CENTER;
doc.Add(date);
iTextSharp.text.Image pdfImage = iTextSharp.text.Image.GetInstance(bm, System.Drawing.Imaging.ImageFormat.Bmp);
pdfImage.Alignment = Element.ALIGN_CENTER;
doc.Add(pdfImage);
PdfPTable table = new PdfPTable(4);
table.AddCell(new Phrase("Type"));
table.AddCell(new Phrase("Name"));
table.AddCell(new Phrase("Starting Position"));
table.AddCell(new Phrase("Final Position"));
table.HeaderRows = 1;
for (int i = 0; i < bodiesPreMove.Count; i++)
{
var pre = bodiesPreMove[i];
var post = bodiesPostMove[i];
if (bodiesPostMove[i] is Star)
{
table.AddCell(new Phrase("Star"));
}
else if (bodiesPostMove[i] is Planet)
{
table.AddCell(new Phrase("Planet"));
}
else if (bodiesPostMove[i] is Moon)
{
table.AddCell(new Phrase("Moon"));
}
else if (bodiesPostMove[i] is Asteroid)
{
table.AddCell(new Phrase("Asteroid"));
}
else if (bodiesPostMove[i] is ArtificialObject)
{
table.AddCell(new Phrase("Artificial\nobject"));
}
table.AddCell(new Phrase(bodiesPreMove[i].Name));
StringBuilder sb = new StringBuilder();
sb.Append($"X: {pre.Center.X:E}\n");
sb.Append($"Y: {pre.Center.Y:E}\n");
sb.Append($"Z: {pre.Center.Z:E}");
table.AddCell(new Phrase(sb.ToString()));
sb.Clear();
sb.Append($"X: {post.Center.X:E}\n");
sb.Append($"Y: {post.Center.Y:E}\n");
sb.Append($"Z: {post.Center.Z:E}");
table.AddCell(new Phrase(sb.ToString()));
}
doc.Add(table);
doc.Close();
}
}
}
| 35.505495 | 123 | 0.529557 | [
"MIT"
] | BeerSticks/PlanetSystems | PlanetSystems/ReportsGenerators/GeneralUIReportGenerator.cs | 3,233 | C# |
// Copyright (c) Microsoft. All rights reserved.
namespace Microsoft.Azure.Devices.Routing.Core.Test.Checkpointers
{
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.Devices.Routing.Core.Checkpointers;
using Microsoft.Azure.Devices.Routing.Core.Util;
using Microsoft.Azure.Devices.Edge.Util.Test.Common;
using Microsoft.Azure.Devices.Routing.Core.MessageSources;
using Xunit;
class LoggedCheckpointer : ICheckpointer
{
readonly ICheckpointer underlying;
public IList<IMessage> Processed { get; }
public LoggedCheckpointer(ICheckpointer underlying)
{
this.underlying = underlying;
this.Processed = new List<IMessage>();
}
public string Id => this.underlying.Id;
public long Offset => this.underlying.Offset;
public Option<DateTime> LastFailedRevivalTime => this.underlying.LastFailedRevivalTime;
public Option<DateTime> UnhealthySince => this.underlying.UnhealthySince;
public long Proposed => this.underlying.Proposed;
public bool HasOutstanding => this.underlying.HasOutstanding;
public void Propose(IMessage message) => this.underlying.Propose(message);
public bool Admit(IMessage message) => this.underlying.Admit(message);
public Task CommitAsync(ICollection<IMessage> successful, ICollection<IMessage> failed, Option<DateTime> lastFailedRevivalTime, Option<DateTime> unhealthySince, CancellationToken token)
{
foreach (IMessage message in successful)
{
this.Processed.Add(message);
}
return this.underlying.CommitAsync(successful, failed, lastFailedRevivalTime, unhealthySince, token);
}
public Task CloseAsync(CancellationToken token) => this.underlying.CloseAsync(token);
public void Dispose() => this.Dispose(true);
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
this.underlying.Dispose();
}
}
}
[ExcludeFromCodeCoverage]
public class LoggedCheckpointTest : RoutingUnitTestBase
{
static readonly IMessage Message1 = new Message(TelemetryMessageSource.Instance, new byte[] {1, 2, 3, 4}, new Dictionary<string, string> { {"key1", "value1"}, {"key2", "value2"} }, 1L);
static readonly IMessage Message2 = new Message(TelemetryMessageSource.Instance, new byte[] {2, 3, 4, 1}, new Dictionary<string, string> { {"key1", "value1"}, {"key2", "value2"} }, 2L);
static readonly IMessage Message3 = new Message(TelemetryMessageSource.Instance, new byte[] {3, 4, 1, 2}, new Dictionary<string, string> { {"key1", "value1"}, {"key2", "value2"} }, 3L);
static readonly IMessage Message4 = new Message(TelemetryMessageSource.Instance, new byte[] {4, 1, 2, 3}, new Dictionary<string, string> { {"key1", "value1"}, {"key2", "value2"} }, 4L);
[Fact, Unit]
public async Task SmokeTest()
{
using (var checkpointer = new LoggedCheckpointer(new NullCheckpointer()))
{
Assert.Equal(Checkpointer.InvalidOffset, checkpointer.Offset);
Assert.True(checkpointer.Admit(Message1));
await checkpointer.CommitAsync(new[] { Message3, Message4 }, new IMessage[] {}, Option.None<DateTime>(), Option.None<DateTime>(), CancellationToken.None);
await checkpointer.CommitAsync(new[] { Message1, Message2 }, new IMessage[] { }, Option.None<DateTime>(), Option.None<DateTime>(), CancellationToken.None);
Assert.Equal(new List<IMessage> { Message3, Message4, Message1, Message2 }, checkpointer.Processed);
Assert.Equal(Checkpointer.InvalidOffset, checkpointer.Offset);
await checkpointer.CloseAsync(CancellationToken.None);
}
}
}
}
| 44.844444 | 193 | 0.662537 | [
"MIT"
] | DaveEM/iotedge | edge-hub/test/Microsoft.Azure.Devices.Routing.Core.Test/checkpointers/LoggedCheckpointer.cs | 4,036 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using SilentHunter.FileFormats.ChunkedFiles;
using SilentHunter.FileFormats.IO;
namespace SilentHunter.FileFormats.Dat.Chunks
{
/// <summary>
/// Represents a base class for extending specific chunks. Alternatively, serves as a raw chunk for unknown magics.
/// </summary>
public class DatChunk : Chunk<DatFile.Magics>, IChunk<DatFile.Magics>, ICloneable
{
/// <summary>
/// Gets the DAT-chunk header size (a header consists of a type (int), sub type (int) and chunk size (int)).
/// </summary>
public const int ChunkHeaderSize = 12;
private ulong _id, _parentId;
private long _size;
/// <summary>
/// Initializes a new instance of <see cref="DatChunk" /> using specified <paramref name="magic" />.
/// </summary>
/// <param name="magic">The magic for this chunk.</param>
public DatChunk(DatFile.Magics magic)
: base(magic)
{
}
/// <summary>
/// Initializes a new instance of <see cref="DatChunk" /> using specified <paramref name="magic" /> and chunk <paramref name="subType" />.
/// </summary>
/// <param name="magic">The magic for this chunk.</param>
/// <param name="subType">The sub type of this chunk.</param>
public DatChunk(DatFile.Magics magic, int subType)
: this(magic)
{
SubType = subType;
}
/// <summary>
/// Gets or sets the chunk subtype.
/// </summary>
public int SubType { get; set; }
/// <summary>
/// Gets whether the chunk supports an id field.
/// </summary>
public virtual bool SupportsId => false;
/// <summary>
/// Gets whether the chunk supports a parent id field.
/// </summary>
public virtual bool SupportsParentId => false;
/// <summary>
/// Gets or sets the chunk id.
/// </summary>
public virtual ulong Id
{
get => _id;
set
{
if (!SupportsId)
{
throw new NotSupportedException("Id is not supported.");
}
_id = value;
}
}
/// <summary>
/// Gets or sets the chunk its parent id.
/// </summary>
public virtual ulong ParentId
{
get => _parentId;
set
{
if (!SupportsParentId)
{
throw new NotSupportedException("ParentId is not supported.");
}
_parentId = value;
}
}
/// <summary>
/// Gets the size of the chunk.
/// </summary>
public override long Size => _size;
private List<UnknownChunkData> _unknownData;
/// <summary>
/// Gets the unknown data.
/// </summary>
public List<UnknownChunkData> UnknownData => _unknownData ?? (_unknownData = new List<UnknownChunkData>());
/// <summary>
/// Deserializes the chunk. Note that the first 12 bytes (type, subtype and chunk size) are already read by the base class. Inheritors can override the default behavior, which is nothing more then reading all data, and caching it for later (ie. for serialization).
/// </summary>
/// <param name="stream">The stream to read from.</param>
protected override async Task DeserializeAsync(Stream stream)
{
var regionStream = stream as RegionStream;
long origin = regionStream?.BaseStream.Position ?? stream.Position;
long relativeOrigin = stream.Position;
await base.DeserializeAsync(stream).ConfigureAwait(false);
if (Bytes != null && Bytes.Length > 0)
{
UnknownData.Add(new UnknownChunkData(origin, relativeOrigin, Bytes, "Unknown"));
}
}
/// <summary>
/// Deserializes the chunk, optionally including the 8 byte header, excluding the magic. To deserialize an entire chunk including magic use a ChunkReader.
/// </summary>
/// <param name="stream">The stream to read from.</param>
/// <param name="includeHeader">True to include the 8 byte header (chunk sub type and chunk size).</param>
public Task DeserializeAsync(Stream stream, bool includeHeader)
{
return includeHeader ? ((IRawSerializable)this).DeserializeAsync(stream) : DeserializeAsync(stream);
}
/// <summary>
/// Serializes the chunk, optionally including the 8 byte header, excluding the magic. The serialize an entire chunk including magic use a ChunkWriter.
/// </summary>
/// <param name="stream">The stream to write to.</param>
/// <param name="includeHeader">True to include the 8 byte header (chunk sub type and chunk size).</param>
public Task SerializeAsync(Stream stream, bool includeHeader)
{
return includeHeader ? ((IRawSerializable)this).SerializeAsync(stream) : SerializeAsync(stream);
}
/// <summary>
/// When implemented, deserializes the implemented class from specified <paramref name="stream" />.
/// </summary>
/// <param name="stream">The stream.</param>
async Task IRawSerializable.DeserializeAsync(Stream stream)
{
// Deserialize the chunk header. The magic is already read for this chunk.
using (var reader = new BinaryReader(stream, FileEncoding.Default, true))
{
// Read the subtype.
SubType = reader.ReadInt32();
// Read chunk size.
int chunkSize = reader.ReadInt32();
_size = chunkSize + ChunkHeaderSize;
if (_size < 0)
{
stream.Position -= 4;
throw new SilentHunterParserException($"Invalid chunk size ({_size} bytes). Can't be negative.");
}
long startPos = stream.Position;
if (startPos + chunkSize > stream.Length)
{
stream.Position -= 4;
throw new SilentHunterParserException($"Invalid chunk size ({_size} bytes). The stream has {stream.Length - stream.Position} bytes left.");
}
// Allow inheritors to deserialize the remainder of the chunk.
using (var regionStream = new RegionStream(stream, chunkSize))
{
await DeserializeAsync(regionStream).ConfigureAwait(false);
}
// Verify that the inheritor read the entire chunk. If not, the inheritor does not implement it correctly, so we have to halt.
if (stream.Position == startPos + chunkSize)
{
return;
}
if (stream.Position < startPos + chunkSize)
{
throw new SilentHunterParserException("Invalid deserialization of " + ToString() + ". More unparsed data in chunk.");
// stream.Position = startPos + chunkSize;
}
throw new SilentHunterParserException("Invalid deserialization of " + ToString() + ". Too much data was read while deserializing. This may indicate an invalid size specifier somewhere.");
}
}
/// <summary>
/// When implemented, serializes the implemented class to specified <paramref name="stream" />.
/// </summary>
/// <param name="stream">The stream.</param>
async Task IRawSerializable.SerializeAsync(Stream stream)
{
using (var writer = new BinaryWriter(stream, FileEncoding.Default, true))
{
writer.Write(SubType);
long origin = stream.Position;
writer.Write(0); // Empty placeholder for size.
await SerializeAsync(stream).ConfigureAwait(false);
long currentPos = stream.Position;
stream.Seek(origin, SeekOrigin.Begin);
_size = currentPos - origin - 4 + ChunkHeaderSize;
writer.Write((uint)(_size - ChunkHeaderSize));
stream.Seek(currentPos, SeekOrigin.Begin);
}
}
/// <inheritdoc />
public override string ToString()
{
return Enum.IsDefined(typeof(DatFile.Magics), Magic) ? Magic.ToString() : GetType().Name;
}
/// <inheritdoc />
public virtual object Clone()
{
using (var ms = new MemoryStream())
{
using (var writer = new ChunkWriter<DatFile.Magics, DatChunk>(ms, true))
{
writer.WriteAsync(this).GetAwaiter().GetResult();
}
ms.Position = 0;
using (ChunkReader<DatFile.Magics, DatChunk> reader = ((DatFile)ParentFile).CreateReader(ms))
{
return reader.ReadAsync().GetAwaiter().GetResult();
}
}
}
/// <summary>
/// Reads data with the <paramref name="reader"/> using specified <paramref name="func"/> and registers it as 'unknown' data.
/// </summary>
/// <typeparam name="T">The data type.</typeparam>
/// <param name="reader">The reader.</param>
/// <param name="func">The func providing the data.</param>
/// <param name="description">The description of it, if any</param>
/// <returns>Returns the value read using the <paramref name="func"/>.</returns>
protected T ReadUnknownData<T>(BinaryReader reader, Func<BinaryReader, T> func, string description)
where T : struct
{
int structSize = Marshal.SizeOf<T>();
long relativeOffset = reader.BaseStream.Position - structSize;
var regionStream = reader.BaseStream as RegionStream;
long absoluteOffset = regionStream?.BaseStream.Position - structSize ?? relativeOffset;
T value = func(reader);
PushUnknownData(absoluteOffset, relativeOffset, value, description);
return value;
}
/// <summary>
/// Registers data as 'unknown' data, at a specific <paramref name="absoluteOffset"/> and <paramref name="relativeOffset"/>.
/// </summary>
/// <typeparam name="T">The data type.</typeparam>
/// <param name="absoluteOffset">The absolute offset where the data is located in the file.</param>
/// <param name="relativeOffset">The relative offset in relation to this chunk where the data is located.</param>
/// <param name="data">The value.</param>
/// <param name="description">The description of it, if any</param>
protected void PushUnknownData<T>(long absoluteOffset, long relativeOffset, T data, string description)
{
UnknownData.Add(new UnknownChunkData(absoluteOffset, relativeOffset, data, description));
}
}
} | 34.298182 | 266 | 0.685327 | [
"Apache-2.0"
] | skwasjer/SilentHunter | src/SilentHunter.FileFormats/Dat/Chunks/DatChunk.cs | 9,434 | C# |
// Uncomment the following to provide samples for PageResult<T>. Must also add the Microsoft.AspNet.WebApi.OData
// package to your project.
////#define Handle_PageResultOfT
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net.Http.Headers;
using System.Reflection;
using System.Web;
using System.Web.Http;
#if Handle_PageResultOfT
using System.Web.Http.OData;
#endif
namespace NutritionDiary.WebAPI.Areas.HelpPage
{
/// <summary>
/// Use this class to customize the Help Page.
/// For example you can set a custom <see cref="System.Web.Http.Description.IDocumentationProvider"/> to supply the documentation
/// or you can provide the samples for the requests/responses.
/// </summary>
public static class HelpPageConfig
{
[SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters",
MessageId = "NutritionDiary.WebAPI.Areas.HelpPage.TextSample.#ctor(System.String)",
Justification = "End users may choose to merge this string with existing localized resources.")]
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly",
MessageId = "bsonspec",
Justification = "Part of a URI.")]
public static void Register(HttpConfiguration config)
{
//// Uncomment the following to use the documentation from XML documentation file.
//config.SetDocumentationProvider(new XmlDocumentationProvider(HttpContext.Current.Server.MapPath("~/App_Data/XmlDocument.xml")));
//// Uncomment the following to use "sample string" as the sample for all actions that have string as the body parameter or return type.
//// Also, the string arrays will be used for IEnumerable<string>. The sample objects will be serialized into different media type
//// formats by the available formatters.
//config.SetSampleObjects(new Dictionary<Type, object>
//{
// {typeof(string), "sample string"},
// {typeof(IEnumerable<string>), new string[]{"sample 1", "sample 2"}}
//});
// Extend the following to provide factories for types not handled automatically (those lacking parameterless
// constructors) or for which you prefer to use non-default property values. Line below provides a fallback
// since automatic handling will fail and GeneratePageResult handles only a single type.
#if Handle_PageResultOfT
config.GetHelpPageSampleGenerator().SampleObjectFactories.Add(GeneratePageResult);
#endif
// Extend the following to use a preset object directly as the sample for all actions that support a media
// type, regardless of the body parameter or return type. The lines below avoid display of binary content.
// The BsonMediaTypeFormatter (if available) is not used to serialize the TextSample object.
config.SetSampleForMediaType(
new TextSample("Binary JSON content. See http://bsonspec.org for details."),
new MediaTypeHeaderValue("application/bson"));
//// Uncomment the following to use "[0]=foo&[1]=bar" directly as the sample for all actions that support form URL encoded format
//// and have IEnumerable<string> as the body parameter or return type.
//config.SetSampleForType("[0]=foo&[1]=bar", new MediaTypeHeaderValue("application/x-www-form-urlencoded"), typeof(IEnumerable<string>));
//// Uncomment the following to use "1234" directly as the request sample for media type "text/plain" on the controller named "Values"
//// and action named "Put".
//config.SetSampleRequest("1234", new MediaTypeHeaderValue("text/plain"), "Values", "Put");
//// Uncomment the following to use the image on "../images/aspNetHome.png" directly as the response sample for media type "image/png"
//// on the controller named "Values" and action named "Get" with parameter "id".
//config.SetSampleResponse(new ImageSample("../images/aspNetHome.png"), new MediaTypeHeaderValue("image/png"), "Values", "Get", "id");
//// Uncomment the following to correct the sample request when the action expects an HttpRequestMessage with ObjectContent<string>.
//// The sample will be generated as if the controller named "Values" and action named "Get" were having string as the body parameter.
//config.SetActualRequestType(typeof(string), "Values", "Get");
//// Uncomment the following to correct the sample response when the action returns an HttpResponseMessage with ObjectContent<string>.
//// The sample will be generated as if the controller named "Values" and action named "Post" were returning a string.
//config.SetActualResponseType(typeof(string), "Values", "Post");
}
#if Handle_PageResultOfT
private static object GeneratePageResult(HelpPageSampleGenerator sampleGenerator, Type type)
{
if (type.IsGenericType)
{
Type openGenericType = type.GetGenericTypeDefinition();
if (openGenericType == typeof(PageResult<>))
{
// Get the T in PageResult<T>
Type[] typeParameters = type.GetGenericArguments();
Debug.Assert(typeParameters.Length == 1);
// Create an enumeration to pass as the first parameter to the PageResult<T> constuctor
Type itemsType = typeof(List<>).MakeGenericType(typeParameters);
object items = sampleGenerator.GetSampleObject(itemsType);
// Fill in the other information needed to invoke the PageResult<T> constuctor
Type[] parameterTypes = new Type[] { itemsType, typeof(Uri), typeof(long?), };
object[] parameters = new object[] { items, null, (long)ObjectGenerator.DefaultCollectionSize, };
// Call PageResult(IEnumerable<T> items, Uri nextPageLink, long? count) constructor
ConstructorInfo constructor = type.GetConstructor(parameterTypes);
return constructor.Invoke(parameters);
}
}
return null;
}
#endif
}
} | 57.637168 | 149 | 0.666667 | [
"MIT"
] | IliaAnastassov/NutritionDiary | NutritionDiary.WebAPI/Areas/HelpPage/App_Start/HelpPageConfig.cs | 6,513 | C# |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="EepNvmDataStructure.cs" company="Visteon">
//
// </copyright>
// <summary>
// The eep nvm data structure.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace DataParser.EEP
{
/// <summary>
/// The eep nvm data structure.
/// </summary>
internal class EepNvmDataStructure
{
/// <summary>
/// Gets or sets the Descriptor.
/// </summary>
public string Descriptor { get; set; }
/// <summary>
/// Gets or sets the Length.
/// </summary>
public int Length { get; set; }
/// <summary>
/// Gets or sets the block id.
/// </summary>
public int BlockId { get; set; }
/// <summary>
/// Gets or sets the Crc.
/// </summary>
public string Crc { get; set; }
/// <summary>
/// Gets or sets the CrcUsage.
/// </summary>
public string CrcUsage { get; set; }
/// <summary>
/// Gets or sets the Type.
/// </summary>
public string Type { get; set; }
/// <summary>
/// Gets or sets the InitCallback.
/// </summary>
public string InitCallback { get; set; }
/// <summary>
/// Gets or sets the InitCallbackValue.
/// </summary>
public string InitCallbackValue { get; set; }
/// <summary>
/// Gets or sets the rom block.
/// </summary>
public string RomBlock { get; set; }
/// <summary>
/// Gets or sets the ea ref.
/// </summary>
public string EaRef { get; set; }
}
} | 28.454545 | 120 | 0.419063 | [
"MIT"
] | atanas-georgiev/DataParser | DataParser/EEP/EepNvmDataStructure.cs | 1,880 | C# |
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using MyDailyHub.Models;
using MyDailyHub.Models.ViewModels.Home;
using MyDailyHub.Services;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
namespace MyDailyHub.Controllers
{
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
}
[HttpGet]
public IActionResult Index()
{
IpService ipService = new IpService(Request);
QuotesService quotesService = new QuotesService();
WeatherService weatherService = new WeatherService(ipService.IpModel.city);
NewsService newsService = new NewsService(ipService.IpModel.country_code);
IndexViewModel indexViewModel = new IndexViewModel(quotesService.GetRandomQuoteModel(), weatherService.GetWeatherModel(), newsService.GetNewsModel());
return View(indexViewModel);
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}
| 31 | 162 | 0.693907 | [
"CC0-1.0"
] | giddster/mydailyhub | MyDailyHub/Controllers/HomeController.cs | 1,397 | C# |
// ------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
// ------------------------------------------------------------------------------
#nullable enable
#pragma warning disable CS1591
#pragma warning disable CS0108
#pragma warning disable 618
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Linq;
using System.Runtime.Serialization;
using System.Text.Json.Serialization;
using System.Threading;
using System.Threading.Tasks;
using JetBrains.Space.Common;
using JetBrains.Space.Common.Json.Serialization;
using JetBrains.Space.Common.Json.Serialization.Polymorphism;
using JetBrains.Space.Common.Types;
namespace JetBrains.Space.Client.CodeReviewSubscriptionFilterPartialBuilder
{
public static class CodeReviewSubscriptionFilterPartialExtensions
{
public static Partial<CodeReviewSubscriptionFilter> WithProject(this Partial<CodeReviewSubscriptionFilter> it)
=> it.AddFieldName("project");
public static Partial<CodeReviewSubscriptionFilter> WithProject(this Partial<CodeReviewSubscriptionFilter> it, Func<Partial<PRProject>, Partial<PRProject>> partialBuilder)
=> it.AddFieldName("project", partialBuilder(new Partial<PRProject>(it)));
public static Partial<CodeReviewSubscriptionFilter> WithRepository(this Partial<CodeReviewSubscriptionFilter> it)
=> it.AddFieldName("repository");
public static Partial<CodeReviewSubscriptionFilter> WithAuthors(this Partial<CodeReviewSubscriptionFilter> it)
=> it.AddFieldName("authors");
public static Partial<CodeReviewSubscriptionFilter> WithAuthors(this Partial<CodeReviewSubscriptionFilter> it, Func<Partial<TDMemberProfile>, Partial<TDMemberProfile>> partialBuilder)
=> it.AddFieldName("authors", partialBuilder(new Partial<TDMemberProfile>(it)));
public static Partial<CodeReviewSubscriptionFilter> WithParticipants(this Partial<CodeReviewSubscriptionFilter> it)
=> it.AddFieldName("participants");
public static Partial<CodeReviewSubscriptionFilter> WithParticipants(this Partial<CodeReviewSubscriptionFilter> it, Func<Partial<TDMemberProfile>, Partial<TDMemberProfile>> partialBuilder)
=> it.AddFieldName("participants", partialBuilder(new Partial<TDMemberProfile>(it)));
public static Partial<CodeReviewSubscriptionFilter> WithBranchSpec(this Partial<CodeReviewSubscriptionFilter> it)
=> it.AddFieldName("branchSpec");
public static Partial<CodeReviewSubscriptionFilter> WithPathSpec(this Partial<CodeReviewSubscriptionFilter> it)
=> it.AddFieldName("pathSpec");
public static Partial<CodeReviewSubscriptionFilter> WithTitleRegex(this Partial<CodeReviewSubscriptionFilter> it)
=> it.AddFieldName("titleRegex");
}
}
| 48.074627 | 196 | 0.712201 | [
"Apache-2.0"
] | PatrickRatzow/space-dotnet-sdk | src/JetBrains.Space.Client/Generated/Partials/CodeReviewSubscriptionFilterPartialBuilder.generated.cs | 3,221 | C# |
using System;
using System.Runtime.Serialization;
namespace AutoTest.Exceptions.Exceptions
{
/// <summary>
/// Exception that is thrown if an exception cannot be tested successfully.
/// </summary>
[Serializable]
public class AutoTestException : Exception
{
/// <summary>
/// Initializes a new instance of the <see cref="AutoTestException"/> class.
/// </summary>
// ReSharper disable once UnusedMember.Global
public AutoTestException()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="AutoTestException"/> class.
/// </summary>
/// <param name="message">The message that describes the error.</param>
public AutoTestException(string message)
: base(message)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="AutoTestException"/> class.
/// </summary>
/// <param name="message">The message.</param>
/// <param name="inner">The inner.</param>
public AutoTestException(string message, Exception inner)
: base(message, inner)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="AutoTestException"/> class.
/// </summary>
/// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param>
protected AutoTestException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
}
}
| 36.52 | 178 | 0.61391 | [
"MIT"
] | jeroenpot/AutoTest.Exceptions | Source/AutoTest.Exceptions/AutoTest.Exceptions/Exceptions/AutoTestException.cs | 1,828 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
namespace DevChatter.Bot.Core.Util
{
public static class MyRandom
{
private static readonly Random Random = new Random();
private static readonly object SyncLock = new object();
public static int RandomNumber(int min, int max)
{
lock (SyncLock)
{
return Random.Next(min, max);
}
}
public static (bool Success, T ChosenItem) ChooseRandomItem<T>(IList<T> choices)
{
if (choices.Any())
{
int randomNumber = RandomNumber(0, choices.Count);
return (true, choices[randomNumber]);
}
return (false, default(T));
}
}
}
| 24.65625 | 88 | 0.548796 | [
"MIT"
] | AleksAce/devchatterbot | src/DevChatter.Bot.Core/Util/MyRandom.cs | 789 | C# |
/*
* Hydrogen Nucleus API
*
* The Hydrogen Nucleus API
*
* OpenAPI spec version: 1.9.5
* Contact: info@hydrogenplatform.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using NUnit.Framework;
using System;
using System.Linq;
using System.IO;
using System.Collections.Generic;
using Nucleus.Api;
using Nucleus.ModelEntity;
using Nucleus.Client;
using System.Reflection;
using Newtonsoft.Json;
namespace Nucleus.Test
{
/// <summary>
/// Class for testing Budget
/// </summary>
/// <remarks>
/// This file is automatically generated by Swagger Codegen.
/// Please update the test case below to test the model.
/// </remarks>
[TestFixture]
public class BudgetTests
{
// TODO uncomment below to declare an instance variable for Budget
//private Budget instance;
/// <summary>
/// Setup before each test
/// </summary>
[SetUp]
public void Init()
{
// TODO uncomment below to create an instance of Budget
//instance = new Budget();
}
/// <summary>
/// Clean up after each test
/// </summary>
[TearDown]
public void Cleanup()
{
}
/// <summary>
/// Test an instance of Budget
/// </summary>
[Test]
public void BudgetInstanceTest()
{
// TODO uncomment below to test "IsInstanceOfType" Budget
//Assert.IsInstanceOfType<Budget> (instance, "variable 'instance' is a Budget");
}
/// <summary>
/// Test the property 'AccountId'
/// </summary>
[Test]
public void AccountIdTest()
{
// TODO unit test for the property 'AccountId'
}
/// <summary>
/// Test the property 'AggregationAccounts'
/// </summary>
[Test]
public void AggregationAccountsTest()
{
// TODO unit test for the property 'AggregationAccounts'
}
/// <summary>
/// Test the property '_Budget'
/// </summary>
[Test]
public void _BudgetTest()
{
// TODO unit test for the property '_Budget'
}
/// <summary>
/// Test the property 'CardId'
/// </summary>
[Test]
public void CardIdTest()
{
// TODO unit test for the property 'CardId'
}
/// <summary>
/// Test the property 'ClientId'
/// </summary>
[Test]
public void ClientIdTest()
{
// TODO unit test for the property 'ClientId'
}
/// <summary>
/// Test the property 'CreateDate'
/// </summary>
[Test]
public void CreateDateTest()
{
// TODO unit test for the property 'CreateDate'
}
/// <summary>
/// Test the property 'CurrencyCode'
/// </summary>
[Test]
public void CurrencyCodeTest()
{
// TODO unit test for the property 'CurrencyCode'
}
/// <summary>
/// Test the property 'EndDate'
/// </summary>
[Test]
public void EndDateTest()
{
// TODO unit test for the property 'EndDate'
}
/// <summary>
/// Test the property 'Frequency'
/// </summary>
[Test]
public void FrequencyTest()
{
// TODO unit test for the property 'Frequency'
}
/// <summary>
/// Test the property 'FrequencyUnit'
/// </summary>
[Test]
public void FrequencyUnitTest()
{
// TODO unit test for the property 'FrequencyUnit'
}
/// <summary>
/// Test the property 'GoalId'
/// </summary>
[Test]
public void GoalIdTest()
{
// TODO unit test for the property 'GoalId'
}
/// <summary>
/// Test the property 'Id'
/// </summary>
[Test]
public void IdTest()
{
// TODO unit test for the property 'Id'
}
/// <summary>
/// Test the property 'IsActive'
/// </summary>
[Test]
public void IsActiveTest()
{
// TODO unit test for the property 'IsActive'
}
/// <summary>
/// Test the property 'Metadata'
/// </summary>
[Test]
public void MetadataTest()
{
// TODO unit test for the property 'Metadata'
}
/// <summary>
/// Test the property 'Name'
/// </summary>
[Test]
public void NameTest()
{
// TODO unit test for the property 'Name'
}
/// <summary>
/// Test the property 'SecondaryId'
/// </summary>
[Test]
public void SecondaryIdTest()
{
// TODO unit test for the property 'SecondaryId'
}
/// <summary>
/// Test the property 'StartDate'
/// </summary>
[Test]
public void StartDateTest()
{
// TODO unit test for the property 'StartDate'
}
/// <summary>
/// Test the property 'TotalValue'
/// </summary>
[Test]
public void TotalValueTest()
{
// TODO unit test for the property 'TotalValue'
}
/// <summary>
/// Test the property 'UpdateDate'
/// </summary>
[Test]
public void UpdateDateTest()
{
// TODO unit test for the property 'UpdateDate'
}
}
}
| 25.36 | 92 | 0.495969 | [
"Apache-2.0"
] | AbhiGupta03/SDK | atom/nucleus/csharp/src/Nucleus.Test/Model/BudgetTests.cs | 5,706 | C# |
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Composition;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Rename;
using Microsoft.CodeAnalysis.Text;
namespace NewAnalyzerTemplate
{
[ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(NewAnalyzerTemplateCodeFixProvider)), Shared]
public class NewAnalyzerTemplateCodeFixProvider : CodeFixProvider
{
public override ImmutableArray<string> FixableDiagnosticIds
{
get
{
throw new NotImplementedException();
}
}
public override Task RegisterCodeFixesAsync(CodeFixContext context)
{
throw new NotImplementedException();
}
}
} | 29.558824 | 108 | 0.737313 | [
"Apache-2.0"
] | tmeschter/roslyn-analyzers | NewAnalyzerTemplate/NewAnalyzerTemplate/NewAnalyzerTemplate/CodeFixProvider.cs | 1,007 | C# |
using System.Collections.Generic;
using Newtonsoft.Json;
namespace SmsPortal.Models
{
public class MessageResponse
{
[JsonProperty("Cost")]
public decimal Cost { get; set; }
[JsonProperty("RemainingBalance")]
public decimal RemainingBalance { get; set; }
[JsonProperty("EventId")]
public long EventId { get; set; }
[JsonProperty("Sample")]
public string Sample { get; set; }
[JsonProperty("Messages")]
public int Messages { get; set; }
[JsonProperty("Parts")]
public int Parts { get; set; }
[JsonProperty("CostBreakDown")]
public IList<CostBreakDown> CostBreakDown { get; set; }
[JsonProperty("ErrorReport")]
public ErrorReport ErrorReport { get; set; }
}
public class Message
{
[JsonProperty("Content")]
public string Content { get; set; }
[JsonProperty("Destination")]
public string Destination { get; set; }
}
public class MessageRequest
{
[JsonProperty("Messages")]
public IList<Message> Messages { get; set; }
}
} | 24.297872 | 63 | 0.595447 | [
"MIT"
] | NanotechComputers/ISmsPortalService | SmsPortal/Models/MessageResponse.cs | 1,144 | C# |
using System;
using System.Windows.Media.Imaging;
using ThetaNetCore.Common;
using ThetaNetCore.Wifi;
using ThetaNetCoreApp.Utils;
namespace ThetaNetCoreApp.Info
{
public class FileEntryWrapper : BindableBase
{
private bool _isChecked = false;
public bool IsChecked
{
get => _isChecked;
set { SetProperty<bool>(ref _isChecked, value); }
}
public FileEntry Data { get; set; }
private BitmapSource _thumbImage = null;
public BitmapSource ThumbImage
{
get { return _thumbImage; }
set { SetProperty<BitmapSource>(ref _thumbImage, value); }
}
private string _localThumbFile = "";
public String LocalThumbFile
{
get { return _localThumbFile; }
set
{
if (value == _localThumbFile)
return;
_localThumbFile = value;
if (value != null)
{
this.ThumbImage = ImageTools.LoadThumbnail(_localThumbFile);
}
}
}
public String SimpleDate
{
get { return Data.DateTime.Substring(0, 10).Replace(":", "-"); }
}
public String TimeString
{
get { return Data.DateTime.Substring(12); }
}
private int _downloadProgress = -1;
/// <summary>
/// 0: not downloaded, 100 : downloaded, in-between : download in progress
/// </summary>
public int DownloadProgress
{
get { return _downloadProgress; }
set {
SetProperty<int>(ref _downloadProgress, value);
}
}
/// <summary>
/// Get the status of download
/// </summary>
public DOWNLOAD_STATUS DownloadStatus
{
get
{
switch(_downloadProgress)
{
case 100:
return DOWNLOAD_STATUS.DOWNLOADED;
case -1:
return DOWNLOAD_STATUS.NOT_DOWNLOADED;
case 0:
return DOWNLOAD_STATUS.WAINTING;
default:
return DOWNLOAD_STATUS.DOWNLOADING;
}
}
set
{
switch (value)
{
case DOWNLOAD_STATUS.NOT_DOWNLOADED:
this.DownloadProgress = -1;
break;
case DOWNLOAD_STATUS.WAINTING:
this.DownloadProgress = 0;
break;
case DOWNLOAD_STATUS.DOWNLOADED:
this.DownloadProgress = 100;
break;
default:
// Unsupported
break;
}
}
}
public int EntryNo { get; set; }
}
public enum DOWNLOAD_STATUS { NOT_DOWNLOADED, WAINTING, DOWNLOADING, DOWNLOADED };
}
| 20.035714 | 83 | 0.652406 | [
"MIT"
] | ryo4600/ThetaNetCore | ThetaNetCoreApp/Info/FileEntryWrapper.cs | 2,246 | C# |
using System;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using System.Runtime.CompilerServices;
using JetBrains.Annotations;
using static System.Linq.Expressions.Expression;
namespace ZeroLog.Utils
{
internal static class TypeUtil
{
private static readonly Func<IntPtr, Type> _getTypeFromHandleFunc = BuildGetTypeFromHandleFunc();
public static IntPtr GetTypeHandleSlow(Type type)
=> type?.TypeHandle.Value ?? IntPtr.Zero;
public static Type GetTypeFromHandle(IntPtr typeHandle)
=> _getTypeFromHandleFunc?.Invoke(typeHandle);
private static Func<IntPtr, Type> BuildGetTypeFromHandleFunc()
{
var method = typeof(Type).GetMethod("GetTypeFromHandleUnsafe", BindingFlags.Static | BindingFlags.NonPublic, null, new[] { typeof(IntPtr) }, null);
if (method == null)
return null;
var param = Parameter(typeof(IntPtr));
return Lambda<Func<IntPtr, Type>>(
Call(method, param),
param
).Compile();
}
public static bool GetIsUnmanagedSlow<T>()
{
#if NETCOREAPP
return !RuntimeHelpers.IsReferenceOrContainsReferences<T>();
#else
return GetIsUnmanagedSlow(typeof(T));
#endif
}
public static bool GetIsUnmanagedSlow(Type type)
{
#if NETCOREAPP
return !(bool)typeof(RuntimeHelpers).GetMethod(nameof(RuntimeHelpers.IsReferenceOrContainsReferences), BindingFlags.Static | BindingFlags.Public)
.MakeGenericMethod(type)
.Invoke(null, null);
#else
if (type.IsPrimitive || type.IsPointer || type.IsEnum)
return true;
if (!type.IsValueType)
return false;
foreach (var field in type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))
{
if (!GetIsUnmanagedSlow(field.FieldType))
return false;
}
return true;
#endif
}
}
internal static class TypeUtil<T>
{
public static readonly IntPtr TypeHandle = TypeUtil.GetTypeHandleSlow(typeof(T));
public static readonly bool IsEnum = typeof(T).IsEnum;
}
[SuppressMessage("ReSharper", "StaticMemberInGenericType")]
internal static class TypeUtilSlow<T>
{
// Initializing this type will allocate
[CanBeNull]
private static readonly Type _underlyingType = Nullable.GetUnderlyingType(typeof(T));
public static readonly bool IsNullableEnum = _underlyingType?.IsEnum == true;
public static readonly IntPtr UnderlyingTypeHandle = TypeUtil.GetTypeHandleSlow(_underlyingType);
public static readonly TypeCode UnderlyingTypeCode = Type.GetTypeCode(_underlyingType);
public static readonly bool IsUnmanaged = TypeUtil.GetIsUnmanagedSlow<T>();
}
}
| 34.83908 | 159 | 0.637413 | [
"MIT"
] | Sergei-Y/ZeroLog | src/ZeroLog/Utils/TypeUtil.cs | 3,033 | C# |
namespace Dev.Core.Model
{
internal class Operators
{
public const string Equal = "eq";
public const string NotEqual = "neq";
public const string IsNull = "isnull";
public const string IsNotNull = "isnotnull";
public const string StartsWith = "startswith";
public const string Contains = "contains";
public const string EndsWith = "endswith";
public const string DoesNotContain = "doesnotcontain";
public const string GreaterThan = "gt";
public const string GreaterThanOrEqual = "gte";
public const string LessThan = "lt";
public const string LessThanOrEqual = "lte";
}
}
| 35.842105 | 62 | 0.641703 | [
"MIT"
] | mehmetunal/devfreco | src/Libraries/Dev.Core/Model/Operators.cs | 683 | C# |
using System;
using System.Runtime.Serialization;
namespace NLua.Exceptions
{
/// <summary>
/// Exceptions thrown by the Lua runtime
/// </summary>
[Serializable]
public class LuaException : Exception
{
public LuaException()
{}
public LuaException(string message) : base(message)
{}
public LuaException(string message, Exception innerException) : base(message, innerException)
{}
protected LuaException(SerializationInfo info, StreamingContext context) : base(info, context)
{}
}
} | 24.041667 | 102 | 0.646447 | [
"MIT"
] | CognitiaAI/StreetFighterRL | emulator/Bizhawk/BizHawk-master/LuaInterface/LuaInterface/LuaException.cs | 577 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.IO;
using MyGeneration;
namespace MyGeneration.UI.Plugins.SqlTool
{
public class SqlToolEditorManager : IEditorManager
{
public const string SQL_FILE = "SQL File";
private SortedList<string, string> fileExtensions;
private List<string> fileTypes;
public string Name
{
get
{
return "SQL Execution Tool";
}
}
public string Description
{
get { return "This is a SQL Execution Tool document plugin. - komma8.komma1"; }
}
public Uri AuthorUri
{
get
{
return new Uri("http://sourceforge.net/projects/mygeneration/");
}
}
public Image GetMenuImage(string fileType)
{
return Properties.Resources.riskdb;
}
public SortedList<string, string> FileExtensions
{
get
{
if (fileExtensions == null)
{
fileExtensions = new SortedList<string, string>();
fileExtensions.Add("sql", "SQL Files");
}
return fileExtensions;
}
}
public List<string> FileTypes
{
get
{
if (fileTypes == null)
{
fileTypes = new List<string>();
fileTypes.Add(SqlToolEditorManager.SQL_FILE);
}
return fileTypes;
}
}
public IMyGenDocument Open(IMyGenerationMDI mdi, FileInfo file, params string[] args)
{
SqlToolForm edit = null;
if (file.Exists)
{
bool isopen = mdi.IsDocumentOpen(file.FullName);
if (!isopen)
{
edit = new SqlToolForm(mdi);
edit.Open(file.FullName);
}
else
{
edit = mdi.FindDocument(file.FullName) as SqlToolForm;
if (edit != null)
{
edit.Activate();
}
}
}
return edit;
}
public IMyGenDocument Create(IMyGenerationMDI mdi, params string[] args)
{
SqlToolForm edit = new SqlToolForm(mdi);
switch (args[0])
{
case SqlToolEditorManager.SQL_FILE:
default:
//edit.CreateNewImage();
break;
}
return edit;
}
public virtual bool CanOpenFile(FileInfo file)
{
return FileExtensions.ContainsKey(file.Extension.Trim('.'));
}
}
}
| 25.293103 | 93 | 0.461145 | [
"BSD-3-Clause"
] | cafephin/mygeneration | src/plugins/MyGeneration.UI.Plugins.SqlTool/SqlToolEditorManager.cs | 2,934 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNative.Network.V20150501Preview.Outputs
{
/// <summary>
/// Rules of the load balancer
/// </summary>
[OutputType]
public sealed class LoadBalancingRuleResponse
{
/// <summary>
/// Gets or sets a reference to a pool of DIPs. Inbound traffic is randomly load balanced across IPs in the backend IPs
/// </summary>
public readonly Outputs.SubResourceResponse BackendAddressPool;
/// <summary>
/// Gets or sets a port used for internal connections on the endpoint. The localPort attribute maps the eternal port of the endpoint to an internal port on a role. This is useful in scenarios where a role must communicate to an internal component on a port that is different from the one that is exposed externally. If not specified, the value of localPort is the same as the port attribute. Set the value of localPort to '*' to automatically assign an unallocated port that is discoverable using the runtime API
/// </summary>
public readonly int? BackendPort;
/// <summary>
/// Configures a virtual machine's endpoint for the floating IP capability required to configure a SQL AlwaysOn availability Group. This setting is required when using the SQL Always ON availability Groups in SQL server. This setting can't be changed after you create the endpoint
/// </summary>
public readonly bool EnableFloatingIP;
/// <summary>
/// A unique read-only string that changes whenever the resource is updated
/// </summary>
public readonly string? Etag;
/// <summary>
/// Gets or sets a reference to frontend IP Addresses
/// </summary>
public readonly Outputs.SubResourceResponse? FrontendIPConfiguration;
/// <summary>
/// Gets or sets the port for the external endpoint. You can specify any port number you choose, but the port numbers specified for each role in the service must be unique. Possible values range between 1 and 65535, inclusive
/// </summary>
public readonly int FrontendPort;
/// <summary>
/// Resource Id
/// </summary>
public readonly string? Id;
/// <summary>
/// Gets or sets the timeout for the Tcp idle connection. The value can be set between 4 and 30 minutes. The default value is 4 minutes. This element is only used when the protocol is set to Tcp
/// </summary>
public readonly int? IdleTimeoutInMinutes;
/// <summary>
/// Gets or sets the load distribution policy for this rule
/// </summary>
public readonly string? LoadDistribution;
/// <summary>
/// Gets name of the resource that is unique within a resource group. This name can be used to access the resource
/// </summary>
public readonly string? Name;
/// <summary>
/// Gets or sets the reference of the load balancer probe used by the Load Balancing rule.
/// </summary>
public readonly Outputs.SubResourceResponse? Probe;
/// <summary>
/// Gets or sets the transport protocol for the external endpoint. Possible values are Udp or Tcp
/// </summary>
public readonly string Protocol;
/// <summary>
/// Gets or sets Provisioning state of the PublicIP resource Updating/Deleting/Failed
/// </summary>
public readonly string? ProvisioningState;
[OutputConstructor]
private LoadBalancingRuleResponse(
Outputs.SubResourceResponse backendAddressPool,
int? backendPort,
bool enableFloatingIP,
string? etag,
Outputs.SubResourceResponse? frontendIPConfiguration,
int frontendPort,
string? id,
int? idleTimeoutInMinutes,
string? loadDistribution,
string? name,
Outputs.SubResourceResponse? probe,
string protocol,
string? provisioningState)
{
BackendAddressPool = backendAddressPool;
BackendPort = backendPort;
EnableFloatingIP = enableFloatingIP;
Etag = etag;
FrontendIPConfiguration = frontendIPConfiguration;
FrontendPort = frontendPort;
Id = id;
IdleTimeoutInMinutes = idleTimeoutInMinutes;
LoadDistribution = loadDistribution;
Name = name;
Probe = probe;
Protocol = protocol;
ProvisioningState = provisioningState;
}
}
}
| 42.336207 | 520 | 0.648748 | [
"Apache-2.0"
] | polivbr/pulumi-azure-native | sdk/dotnet/Network/V20150501Preview/Outputs/LoadBalancingRuleResponse.cs | 4,911 | C# |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
using System.Collections.Generic;
using Aliyun.Acs.Core;
using Aliyun.Acs.Core.Http;
using Aliyun.Acs.Core.Transform;
using Aliyun.Acs.Core.Utils;
using Aliyun.Acs.Cms.Transform;
using Aliyun.Acs.Cms.Transform.V20180308;
namespace Aliyun.Acs.Cms.Model.V20180308
{
public class DeleteMyGroupsRequest : RpcAcsRequest<DeleteMyGroupsResponse>
{
public DeleteMyGroupsRequest()
: base("Cms", "2018-03-08", "DeleteMyGroups", "cms", "openAPI")
{
}
private long? groupId;
public long? GroupId
{
get
{
return groupId;
}
set
{
groupId = value;
DictionaryUtil.Add(QueryParameters, "GroupId", value.ToString());
}
}
public override DeleteMyGroupsResponse GetResponse(UnmarshallerContext unmarshallerContext)
{
return DeleteMyGroupsResponseUnmarshaller.Unmarshall(unmarshallerContext);
}
}
}
| 29.844828 | 99 | 0.708839 | [
"Apache-2.0"
] | AxiosCros/aliyun-openapi-net-sdk | aliyun-net-sdk-cms/Cms/Model/V20180308/DeleteMyGroupsRequest.cs | 1,731 | C# |
using FreeSql.Internal;
using FreeSql.Internal.Model;
using FirebirdSql.Data.FirebirdClient;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using FreeSql.DataAnnotations;
namespace FreeSql.Firebird
{
class FirebirdCodeFirst : Internal.CommonProvider.CodeFirstProvider
{
public FirebirdCodeFirst(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression) : base(orm, commonUtils, commonExpression) { }
static object _dicCsToDbLock = new object();
static Dictionary<string, CsToDb<FbDbType>> _dicCsToDb = new Dictionary<string, CsToDb<FbDbType>>() {
{ typeof(sbyte).FullName, CsToDb.New(FbDbType.SmallInt, "smallint","smallint NOT NULL", false, false, 0) },{ typeof(sbyte?).FullName, CsToDb.New(FbDbType.SmallInt, "smallint", "smallint", false, true, null) },
{ typeof(short).FullName, CsToDb.New(FbDbType.SmallInt, "smallint","smallint NOT NULL", false, false, 0) },{ typeof(short?).FullName, CsToDb.New(FbDbType.SmallInt, "smallint", "smallint", false, true, null) },
{ typeof(int).FullName, CsToDb.New(FbDbType.Integer, "integer","integer NOT NULL", false, false, 0) },{ typeof(int?).FullName, CsToDb.New(FbDbType.Integer, "integer", "integer", false, true, null) },
{ typeof(long).FullName, CsToDb.New(FbDbType.BigInt, "bigint","bigint NOT NULL", false, false, 0) },{ typeof(long?).FullName, CsToDb.New(FbDbType.BigInt, "bigint", "bigint", false, true, null) },
{ typeof(byte).FullName, CsToDb.New(FbDbType.SmallInt, "smallint","smallint NOT NULL", false, false, 0) },{ typeof(byte?).FullName, CsToDb.New(FbDbType.SmallInt, "smallint", "smallint", false, true, null) },
{ typeof(ushort).FullName, CsToDb.New(FbDbType.Integer, "integer","integer NOT NULL", false, false, 0) },{ typeof(ushort?).FullName, CsToDb.New(FbDbType.Integer, "integer", "integer", false, true, null) },
{ typeof(uint).FullName, CsToDb.New(FbDbType.BigInt, "bigint","bigint NOT NULL", false, false, 0) },{ typeof(uint?).FullName, CsToDb.New(FbDbType.BigInt, "bigint", "bigint", false, true, null) },
{ typeof(ulong).FullName, CsToDb.New(FbDbType.Decimal, "decimal","decimal(18,0) NOT NULL", false, false, 0) },{ typeof(ulong?).FullName, CsToDb.New(FbDbType.Decimal, "decimal", "decimal(18,0)", false, true, null) },
{ typeof(float).FullName, CsToDb.New(FbDbType.Float, "float","float NOT NULL", false, false, 0) },{ typeof(float?).FullName, CsToDb.New(FbDbType.Float, "float", "float", false, true, null) },
{ typeof(double).FullName, CsToDb.New(FbDbType.Double, "double precision","double precision NOT NULL", false, false, 0) },{ typeof(double?).FullName, CsToDb.New(FbDbType.Double, "double precision", "double precision", false, true, null) },
{ typeof(decimal).FullName, CsToDb.New(FbDbType.Decimal, "decimal", "decimal(10,2) NOT NULL", false, false, 0) },{ typeof(decimal?).FullName, CsToDb.New(FbDbType.Numeric, "decimal", "decimal(10,2)", false, true, null) },
{ typeof(string).FullName, CsToDb.New(FbDbType.VarChar, "varchar", "varchar(255)", false, null, "") },
{ typeof(TimeSpan).FullName, CsToDb.New(FbDbType.Time, "time","time NOT NULL", false, false, 0) },{ typeof(TimeSpan?).FullName, CsToDb.New(FbDbType.Time, "time", "time",false, true, null) },
{ typeof(DateTime).FullName, CsToDb.New(FbDbType.TimeStamp, "timestamp", "timestamp NOT NULL", false, false, new DateTime(1970,1,1)) },{ typeof(DateTime?).FullName, CsToDb.New(FbDbType.TimeStamp, "timestamp", "timestamp", false, true, null) },
{ typeof(bool).FullName, CsToDb.New(FbDbType.Boolean, "boolean","boolean NOT NULL", null, false, false) },{ typeof(bool?).FullName, CsToDb.New(FbDbType.Boolean, "boolean","boolean", null, true, null) },
{ typeof(byte[]).FullName, CsToDb.New(FbDbType.Binary, "blob", "blob", false, null, new byte[0]) },
{ typeof(Guid).FullName, CsToDb.New(FbDbType.Guid, "char(36)", "char(36) NOT NULL", false, false, Guid.Empty) },{ typeof(Guid?).FullName, CsToDb.New(FbDbType.Guid, "char(36)", "char(36)", false, true, null) },
};
public override DbInfoResult GetDbInfo(Type type)
{
var info = GetDbInfoNoneArray(type);
if (info == null) return null;
return new DbInfoResult((int)info.type, info.dbtype, info.dbtypeFull, info.isnullable, info.defaultValue);
//var isarray = type.FullName != "System.Byte[]" && type.IsArray;
//var elementType = isarray ? type.GetElementType() : type;
//var info = GetDbInfoNoneArray(elementType);
//if (info == null) return null;
//if (isarray == false) return new DbInfoResult((int)info.type, info.dbtype, info.dbtypeFull, info.isnullable, info.defaultValue);
//var dbtypefull = Regex.Replace(info.dbtypeFull, $@"{info.dbtype}(\s*\([^\)]+\))?", "$0[]").Replace(" NOT NULL", "");
//return new DbInfoResult((int)(info.type | FbDbType.Array), $"{info.dbtype}[]", dbtypefull, null, Array.CreateInstance(elementType, 0));
}
CsToDb<FbDbType> GetDbInfoNoneArray(Type type)
{
if (_dicCsToDb.TryGetValue(type.FullName, out var trydc)) return trydc;
if (type.IsArray) return null;
var enumType = type.IsEnum ? type : null;
if (enumType == null && type.IsNullableType() && type.GenericTypeArguments.Length == 1 && type.GenericTypeArguments.First().IsEnum) enumType = type.GenericTypeArguments.First();
if (enumType != null)
{
var newItem = enumType.GetCustomAttributes(typeof(FlagsAttribute), false).Any() ?
CsToDb.New(FbDbType.BigInt, "bigint", $"bigint{(type.IsEnum ? " NOT NULL" : "")}", false, type.IsEnum ? false : true, enumType.CreateInstanceGetDefaultValue()) :
CsToDb.New(FbDbType.Integer, "integer", $"integer{(type.IsEnum ? " NOT NULL" : "")}", false, type.IsEnum ? false : true, enumType.CreateInstanceGetDefaultValue());
if (_dicCsToDb.ContainsKey(type.FullName) == false)
{
lock (_dicCsToDbLock)
{
if (_dicCsToDb.ContainsKey(type.FullName) == false)
_dicCsToDb.Add(type.FullName, newItem);
}
}
return newItem;
}
return null;
}
protected override string GetComparisonDDLStatements(params TypeAndName[] objects)
{
var sb = new StringBuilder();
foreach (var obj in objects)
{
if (sb.Length > 0) sb.Append("\r\n");
var tb = _commonUtils.GetTableByEntity(obj.entityType);
if (tb == null) throw new Exception($"类型 {obj.entityType.FullName} 不可迁移");
if (tb.Columns.Any() == false) throw new Exception($"类型 {obj.entityType.FullName} 不可迁移,可迁移属性0个");
var tbname = tb.DbName;
var tboldname = tb.DbOldName; //旧表名
if (string.IsNullOrEmpty(obj.tableName) == false)
{
var tbtmpname = obj.tableName;
if (tbname != tbtmpname)
{
tbname = tbtmpname;
tboldname = null;
}
}
if (_orm.Ado.ExecuteScalar(CommandType.Text, string.Format(" select 1 from rdb$relations where rdb$system_flag = 0 and trim(rdb$relation_name) = '{0}'", tbname)) == null)
{ //表不存在
if (tboldname != null)
{
if (_orm.Ado.ExecuteScalar(CommandType.Text, string.Format(" select 1 from rdb$relations where rdb$system_flag = 0 and trim(rdb$relation_name) = '{0}'", tboldname)) == null)
//旧表不存在
tboldname = null;
}
if (tboldname == null)
{
//创建表
var createTableName = _commonUtils.QuoteSqlName(tbname);
sb.Append("CREATE TABLE ").Append(createTableName).Append(" ( ");
foreach (var tbcol in tb.ColumnsByPosition)
{
sb.Append(" \r\n ").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(" ").Append(tbcol.Attribute.DbType);
if (tbcol.Attribute.IsIdentity == true) sb.Append(" GENERATED BY DEFAULT AS IDENTITY");
sb.Append(",");
}
if (tb.Primarys.Any())
{
var pkname = $"{tbname}_PKEY";
sb.Append(" \r\n CONSTRAINT ").Append(_commonUtils.QuoteSqlName(pkname)).Append(" PRIMARY KEY (");
foreach (var tbcol in tb.Primarys) sb.Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(", ");
sb.Remove(sb.Length - 2, 2).Append("),");
}
sb.Remove(sb.Length - 1, 1);
sb.Append("\r\n);\r\n");
//创建表的索引
foreach (var uk in tb.Indexes)
{
sb.Append("CREATE ");
if (uk.IsUnique) sb.Append("UNIQUE ");
sb.Append("INDEX ").Append(_commonUtils.QuoteSqlName(uk.Name)).Append(" ON ").Append(createTableName).Append("(");
foreach (var tbcol in uk.Columns)
{
sb.Append(_commonUtils.QuoteSqlName(tbcol.Column.Attribute.Name));
sb.Append(", ");
}
sb.Remove(sb.Length - 2, 2).Append(");\r\n");
}
//备注
foreach (var tbcol in tb.ColumnsByPosition)
{
if (string.IsNullOrEmpty(tbcol.Comment) == false)
sb.Append("COMMENT ON COLUMN ").Append(_commonUtils.QuoteSqlName($"{tbname}.{tbcol.Attribute.Name}")).Append(" IS ").Append(_commonUtils.FormatSql("{0}", tbcol.Comment)).Append(";\r\n");
}
if (string.IsNullOrEmpty(tb.Comment) == false)
sb.Append("COMMENT ON TABLE ").Append(_commonUtils.QuoteSqlName(tbname)).Append(" IS ").Append(_commonUtils.FormatSql("{0}", tb.Comment)).Append(";\r\n");
continue;
}
sb.Append("ALTER TABLE ").Append(_commonUtils.QuoteSqlName(tboldname)).Append(" RENAME TO ").Append(_commonUtils.QuoteSqlName(tbname)).Append(";\r\n");
}
else
tboldname = null; //如果新表已经存在,不走改表名逻辑
//对比字段,只可以修改类型、增加字段、有限的修改字段名;保证安全不删除字段
var sql = _commonUtils.FormatSql(@"
select
trim(a.rdb$field_name),
case
when b.rdb$field_sub_type = 2 then (select 'DECIMAL(' || rdb$field_precision || ',' || abs(rdb$field_scale) || ')' from rdb$types where b.rdb$field_sub_type = 2 and rdb$type = b.rdb$field_sub_type and rdb$field_name = 'RDB$FIELD_SUB_TYPE' rows 1)
when b.rdb$field_type = 14 then 'CHAR(' || b.rdb$character_length || ')'
when b.rdb$field_type = 37 then 'VARCHAR(' || b.rdb$character_length || ')'
when b.rdb$field_type = 8 then 'INTEGER'
when b.rdb$field_type = 16 then 'BIGINT'
when b.rdb$field_type = 27 then 'DOUBLE PRECISION'
when b.rdb$field_type = 7 then 'SMALLINT'
else
(select trim(rdb$type_name) from rdb$types where rdb$type = b.rdb$field_type and rdb$field_name = 'RDB$FIELD_TYPE' rows 1) ||
coalesce((select ' SUB_TYPE ' || rdb$type from rdb$types where b.rdb$field_type = 261 and rdb$type = b.rdb$field_sub_type and rdb$field_name = 'RDB$FIELD_SUB_TYPE' rows 1),'')
end || trim(case when b.rdb$dimensions = 1 then '[]' else '' end),
case when a.rdb$null_flag = 1 then 0 else 1 end,
case when a.rdb$identity_type = 1 then 1 else 0 end,
a.rdb$description
from rdb$relation_fields a
inner join rdb$fields b on b.rdb$field_name = a.rdb$field_source
inner join rdb$relations d on d.rdb$relation_name = a.rdb$relation_name
where a.rdb$system_flag = 0 and trim(d.rdb$relation_name) = {0}
order by a.rdb$relation_name, a.rdb$field_position", tboldname ?? tbname);
var ds = _orm.Ado.ExecuteArray(CommandType.Text, sql);
var tbstruct = ds.ToDictionary(a => string.Concat(a[0]), a =>
{
var a1 = string.Concat(a[1]);
if (a1 == "BLOB SUB_TYPE 0") a1 = "BLOB";
return new
{
column = string.Concat(a[0]),
sqlType = a1,
is_nullable = string.Concat(a[2]) == "1",
is_identity = string.Concat(a[3]) == "1",
comment = string.Concat(a[4])
};
}, StringComparer.CurrentCultureIgnoreCase);
var existsPrimary = _orm.Ado.ExecuteScalar(_commonUtils.FormatSql(@" select 1 from rdb$relation_constraints d where d.rdb$constraint_type = 'PRIMARY KEY' and trim(d.rdb$relation_name) = {0}", tbname));
foreach (var tbcol in tb.ColumnsByPosition)
{
if (tbstruct.TryGetValue(tbcol.Attribute.Name, out var tbstructcol) ||
string.IsNullOrEmpty(tbcol.Attribute.OldName) == false && tbstruct.TryGetValue(tbcol.Attribute.OldName, out tbstructcol))
{
var isCommentChanged = tbstructcol.comment != (tbcol.Comment ?? "");
var isDbTypeChanged = tbcol.Attribute.DbType.StartsWith(tbstructcol.sqlType, StringComparison.CurrentCultureIgnoreCase) == false;
if (isDbTypeChanged ||
tbcol.Attribute.IsIdentity != tbstructcol.is_identity)
{
if (tbcol.Attribute.IsNullable != tbstructcol.is_nullable && tbcol.Attribute.IsNullable == false && tbcol.DbDefaultValue != "NULL" && tbcol.Attribute.IsIdentity == false)
sb.Append("UPDATE ").Append(_commonUtils.QuoteSqlName(tbname)).Append(" SET ").Append(_commonUtils.QuoteSqlName(tbstructcol.column)).Append(" = ").Append(tbcol.DbDefaultValue).Append(" WHERE ").Append(_commonUtils.QuoteSqlName(tbstructcol.column)).Append(" IS NULL;\r\n");
sb.Append("ALTER TABLE ").Append(_commonUtils.QuoteSqlName(tbname)).Append(" ALTER COLUMN ").Append(_commonUtils.QuoteSqlName(tbstructcol.column)).Append(" TYPE ").Append(tbcol.Attribute.DbType.Replace("NOT NULL", ""));
if (tbcol.Attribute.IsIdentity == true && tbstructcol.is_identity == false) sb.Append(" GENERATED BY DEFAULT AS IDENTITY");
sb.Append(";\r\n");
}
//if (tbcol.Attribute.IsNullable != tbstructcol.is_nullable)
// sb.Append("ALTER TABLE ").Append(_commonUtils.QuoteSqlName(tbname)).Append(" ALTER COLUMN ").Append(_commonUtils.QuoteSqlName(tbstructcol.column)).Append(tbcol.Attribute.IsNullable ? " SET DEFAULT NULL" : $" SET DEFAULT {tbcol.DbDefaultValue}").Append(";\r\n");
if (string.Compare(tbstructcol.column, tbcol.Attribute.OldName, true) == 0) //修改列名
sb.Append("ALTER TABLE ").Append(_commonUtils.QuoteSqlName(tbname)).Append(" ALTER COLUMN ").Append(_commonUtils.QuoteSqlName(tbstructcol.column)).Append(" TO ").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(";\r\n");
if (isCommentChanged)
sb.Append("COMMENT ON COLUMN ").Append(_commonUtils.QuoteSqlName($"{tbname}.{tbcol.Attribute.Name}")).Append(" IS ").Append(_commonUtils.FormatSql("{0}", tbcol.Comment ?? "")).Append(";\r\n");
continue;
}
//添加列
sb.Append("ALTER TABLE ").Append(_commonUtils.QuoteSqlName(tbname)).Append(" ADD ").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(" ").Append(tbcol.Attribute.DbType.Replace("NOT NULL", ""));
if (tbcol.Attribute.IsNullable == false && tbcol.DbDefaultValue != "NULL" && tbcol.Attribute.IsIdentity == false) sb.Append(" DEFAULT ").Append(tbcol.DbDefaultValue);
if (tbcol.Attribute.IsIdentity == true) sb.Append(" GENERATED BY DEFAULT AS IDENTITY");
if (tbcol.Attribute.DbType.Contains("NOT NULL")) sb.Append(" NOT NULL");
sb.Append(";\r\n");
if (string.IsNullOrEmpty(tbcol.Comment) == false)
sb.Append("COMMENT ON COLUMN ").Append(_commonUtils.QuoteSqlName($"{tbname}.{tbcol.Attribute.Name}")).Append(" IS ").Append(_commonUtils.FormatSql("{0}", tbcol.Comment ?? "")).Append(";\r\n");
}
var dsuksql = _commonUtils.FormatSql(@"
select
trim(c.rdb$field_name),
trim(d.rdb$index_name),
0,
case when d.rdb$unique_flag = 1 then 1 else 0 end
from rdb$indices d
inner join rdb$index_segments c on c.rdb$index_name = d.rdb$index_name
where d.rdb$index_type = 0 and trim(d.rdb$relation_name) = {0}", tboldname ?? tbname);
var dsuk = _orm.Ado.ExecuteArray(CommandType.Text, dsuksql).Select(a => new[] { string.Concat(a[0]), string.Concat(a[1]), string.Concat(a[2]), string.Concat(a[3]) });
foreach (var uk in tb.Indexes)
{
if (string.IsNullOrEmpty(uk.Name) || uk.Columns.Any() == false) continue;
var ukname = ReplaceIndexName(uk.Name, tbname);
var dsukfind1 = dsuk.Where(a => string.Compare(a[1], ukname, true) == 0).ToArray();
if (dsukfind1.Any() == false || dsukfind1.Length != uk.Columns.Length || dsukfind1.Where(a => (a[3] == "1") == uk.IsUnique && uk.Columns.Where(b => string.Compare(b.Column.Attribute.Name, a[0], true) == 0 && (a[2] == "1") == b.IsDesc).Any()).Count() != uk.Columns.Length)
{
if (dsukfind1.Any()) sb.Append("DROP INDEX ").Append(_commonUtils.QuoteSqlName(ukname)).Append(" ON ").Append(_commonUtils.QuoteSqlName(tbname)).Append(";\r\n");
sb.Append("CREATE ");
if (uk.IsUnique) sb.Append("UNIQUE ");
sb.Append("INDEX ").Append(_commonUtils.QuoteSqlName(ukname)).Append(" ON ").Append(_commonUtils.QuoteSqlName(tbname)).Append("(");
foreach (var tbcol in uk.Columns)
{
sb.Append(_commonUtils.QuoteSqlName(tbcol.Column.Attribute.Name));
if (tbcol.IsDesc) sb.Append(" DESC");
sb.Append(", ");
}
sb.Remove(sb.Length - 2, 2).Append(");\r\n");
}
}
var dbcomment = string.Concat(_orm.Ado.ExecuteScalar(CommandType.Text, _commonUtils.FormatSql(@" select trim(rdb$external_description) from rdb$relations where rdb$system_flag=0 and trim(rdb$relation_name) = {0}", tbname)));
if (dbcomment != (tb.Comment ?? ""))
sb.Append("ALTER TABLE ").Append(_commonUtils.QuoteSqlName(tbname)).Append(" COMMENT ").Append(" ").Append(_commonUtils.FormatSql("{0}", tb.Comment ?? "")).Append(";\r\n");
}
return sb.Length == 0 ? null : sb.ToString();
}
}
} | 73.637363 | 304 | 0.573298 | [
"MIT"
] | p0nley/FreeSql | Providers/FreeSql.Provider.Firebird/FirebirdCodeFirst.cs | 20,307 | C# |
// Copyright (c) .NET Foundation and Contributors (https://dotnetfoundation.org)
// Copyright (c) 2018-2021 Stride and its contributors (https://stride3d.net)
// Copyright (c) 2011-2018 Silicon Studio Corp. (https://www.siliconstudio.co.jp)
// Copyright (c) 2011 Irony - Roman Ivantsov
// See the LICENSE.md file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using Irony.Parsing;
namespace Irony.GrammarExplorer {
public delegate void ColorizeMethod();
public interface IUIThreadInvoker {
void InvokeOnUIThread(ColorizeMethod colorize);
}
public class ColorizeEventArgs : EventArgs {
public readonly TokenList Tokens;
public ColorizeEventArgs(TokenList tokens) {
Tokens = tokens;
}
}
//Container for two numbers representing visible range of the source text (min...max)
// we use it to allow replacing two numbers in atomic operation
public class ViewRange {
public readonly int Min, Max;
public ViewRange(int min, int max) {
Min = min;
Max = max;
}
public bool Equals(ViewRange other) {
return other.Min == Min && other.Max == Max;
}
}
public class ViewData {
// ColoredTokens + NotColoredTokens == Source.Tokens
public readonly TokenList ColoredTokens = new TokenList();
public readonly TokenList NotColoredTokens = new TokenList(); //tokens not colored yet
public ParseTree Tree;
public ViewData(ParseTree tree) {
this.Tree = tree;
if (tree == null) return;
NotColoredTokens.AddRange(tree.Tokens);
}
}
//Two scenarios:
// 1. Colorizing in current view range. We colorize only those tokens in current view range that were not colorized yet.
// For this we keep two lists (colorized and not colorized) tokens, and move tokens from one list to another when
// we actually colorize them.
// 2. Typing/Editing - new editor content is being pushed from EditorAdapter. We try to avoid recoloring all visible tokens, when
// user just typed a single char. What we do is try to identify "already-colored" tokens in new token list by matching
// old viewData.ColoredTokens to newly scanned token list - initially in new-viewData.NonColoredTokens. If we find a "match",
// we move the token from NonColored to Colored in new viewData. This all happens on background thread.
public class EditorViewAdapterList : List<EditorViewAdapter> { }
public class EditorViewAdapter {
public readonly EditorAdapter Adapter;
private IUIThreadInvoker _invoker;
//public readonly Control Control;
ViewData _data;
ViewRange _range;
bool _wantsColorize;
int _colorizing;
public event EventHandler<ColorizeEventArgs> ColorizeTokens;
public EditorViewAdapter(EditorAdapter adapter, IUIThreadInvoker invoker) {
Adapter = adapter;
_invoker = invoker;
Adapter.AddView(this);
_range = new ViewRange(-1, -1);
}
//SetViewRange and SetNewText are called by text box's event handlers to notify adapter that user did something edit box
public void SetViewRange(int min, int max) {
_range = new ViewRange(min, max);
_wantsColorize = true;
}
//The new text is passed directly to EditorAdapter instance (possibly shared by several view adapters).
// EditorAdapter parses the text on a separate background thread, and notifies back this and other
// view adapters and provides them with newly parsed source through UpdateParsedSource method (see below)
public void SetNewText(string newText) {
//TODO: fix this
//hack, temp solution for more general problem
//When we load/replace/clear entire text, clear out colored tokens to force recoloring from scratch
if (string.IsNullOrEmpty(newText))
_data = null;
Adapter.SetNewText(newText);
}
//Called by EditorAdapter to provide the latest parsed source
public void UpdateParsedSource(ParseTree newTree) {
lock (this) {
var oldData = _data;
_data = new ViewData(newTree);
//Now try to figure out tokens that match old Colored tokens
if (oldData != null && oldData.Tree != null) {
DetectAlreadyColoredTokens(oldData.ColoredTokens, _data.Tree.SourceText.Length - oldData.Tree.SourceText.Length);
}
_wantsColorize = true;
}//lock
}
#region Colorizing
public bool WantsColorize {
get { return _wantsColorize; }
}
public void TryInvokeColorize() {
if (!_wantsColorize) return;
int colorizing = Interlocked.Exchange(ref _colorizing, 1);
if (colorizing != 0) return;
_invoker.InvokeOnUIThread(Colorize);
}
private void Colorize() {
var range = _range;
var data = _data;
if (data != null) {
TokenList tokensToColor;
lock (this) {
tokensToColor = ExtractTokensInRange(data.NotColoredTokens, range.Min, range.Max);
}
if (ColorizeTokens != null && tokensToColor != null && tokensToColor.Count > 0) {
data.ColoredTokens.AddRange(tokensToColor);
ColorizeEventArgs args = new ColorizeEventArgs(tokensToColor);
ColorizeTokens(this, args);
}
}//if data != null ...
_wantsColorize = false;
_colorizing = 0;
}
private void DetectAlreadyColoredTokens(TokenList oldColoredTokens, int shift) {
foreach (Token oldColored in oldColoredTokens) {
int index;
Token newColored;
if (FindMatchingToken(_data.NotColoredTokens, oldColored, 0, out index, out newColored) ||
FindMatchingToken(_data.NotColoredTokens, oldColored, shift, out index, out newColored)) {
_data.NotColoredTokens.RemoveAt(index);
_data.ColoredTokens.Add(newColored);
}
}//foreach
}
#endregion
#region token utilities
private bool FindMatchingToken(TokenList inTokens, Token token, int shift, out int index, out Token result) {
index = LocateToken(inTokens, token.Location.Position + shift);
if (index >= 0) {
result = inTokens[index];
if (TokensMatch(token, result, shift)) return true;
}
index = -1;
result = null;
return false;
}
public bool TokensMatch(Token x, Token y, int shift) {
if (x.Location.Position + shift != y.Location.Position) return false;
if (x.Terminal != y.Terminal) return false;
if (x.Text != y.Text) return false;
//Note: be careful comparing x.Value and y.Value - if value is "ValueType", it is boxed and erroneously reports non-equal
//if (x.ValueString != y.ValueString) return false;
return true;
}
public TokenList ExtractTokensInRange(TokenList tokens, int from, int until) {
TokenList result = new TokenList();
for (int i = tokens.Count - 1; i >= 0; i--) {
var tkn = tokens[i];
if (tkn.Location.Position > until || (tkn.Location.Position + tkn.Length < from)) continue;
result.Add(tkn);
tokens.RemoveAt(i);
}
return result;
}
public TokenList GetTokensInRange(int from, int until) {
ViewData data = _data;
if (data == null) return null;
return GetTokensInRange(data.Tree.Tokens, from, until);
}
public TokenList GetTokensInRange(TokenList tokens, int from, int until) {
TokenList result = new TokenList();
int fromIndex = LocateToken(tokens, from);
int untilIndex = LocateToken(tokens, until);
if (fromIndex < 0) fromIndex = 0;
if (untilIndex >= tokens.Count) untilIndex = tokens.Count - 1;
for (int i = fromIndex; i <= untilIndex; i++) {
result.Add(tokens[i]);
}
return result;
}
//TODO: find better place for these methods
public int LocateToken(TokenList tokens, int position) {
if (tokens == null || tokens.Count == 0) return -1;
var lastToken = tokens[tokens.Count - 1];
var lastTokenEnd = lastToken.Location.Position + lastToken.Length;
if (position < tokens[0].Location.Position || position > lastTokenEnd) return -1;
return LocateTokenExt(tokens, position, 0, tokens.Count - 1);
}
private int LocateTokenExt(TokenList tokens, int position, int fromIndex, int untilIndex) {
if (fromIndex + 1 >= untilIndex) return fromIndex;
int midIndex = (fromIndex + untilIndex) / 2;
Token middleToken = tokens[midIndex];
if (middleToken.Location.Position <= position)
return LocateTokenExt(tokens, position, midIndex, untilIndex);
else
return LocateTokenExt(tokens, position, fromIndex, midIndex);
}
#endregion
}//EditorViewAdapter class
}//namespace
| 39.137778 | 132 | 0.674654 | [
"MIT"
] | Ethereal77/stride | sources/shaders/Irony.GrammarExplorer/Highlighter/EditorViewAdapter.cs | 8,808 | C# |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// <auto-generated/>
// Template Source: Templates\CSharp\Requests\IEntityRequest.cs.tt
namespace Microsoft.Graph
{
using System;
using System.IO;
using System.Net.Http;
using System.Threading;
using System.Linq.Expressions;
/// <summary>
/// The interface ISkypeForBusinessDeviceUsageDistributionUserCountsRequest.
/// </summary>
public partial interface ISkypeForBusinessDeviceUsageDistributionUserCountsRequest : IBaseRequest
{
/// <summary>
/// Creates the specified SkypeForBusinessDeviceUsageDistributionUserCounts using POST.
/// </summary>
/// <param name="skypeForBusinessDeviceUsageDistributionUserCountsToCreate">The SkypeForBusinessDeviceUsageDistributionUserCounts to create.</param>
/// <returns>The created SkypeForBusinessDeviceUsageDistributionUserCounts.</returns>
System.Threading.Tasks.Task<SkypeForBusinessDeviceUsageDistributionUserCounts> CreateAsync(SkypeForBusinessDeviceUsageDistributionUserCounts skypeForBusinessDeviceUsageDistributionUserCountsToCreate); /// <summary>
/// Creates the specified SkypeForBusinessDeviceUsageDistributionUserCounts using POST.
/// </summary>
/// <param name="skypeForBusinessDeviceUsageDistributionUserCountsToCreate">The SkypeForBusinessDeviceUsageDistributionUserCounts to create.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The created SkypeForBusinessDeviceUsageDistributionUserCounts.</returns>
System.Threading.Tasks.Task<SkypeForBusinessDeviceUsageDistributionUserCounts> CreateAsync(SkypeForBusinessDeviceUsageDistributionUserCounts skypeForBusinessDeviceUsageDistributionUserCountsToCreate, CancellationToken cancellationToken);
/// <summary>
/// Deletes the specified SkypeForBusinessDeviceUsageDistributionUserCounts.
/// </summary>
/// <returns>The task to await.</returns>
System.Threading.Tasks.Task DeleteAsync();
/// <summary>
/// Deletes the specified SkypeForBusinessDeviceUsageDistributionUserCounts.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The task to await.</returns>
System.Threading.Tasks.Task DeleteAsync(CancellationToken cancellationToken);
/// <summary>
/// Gets the specified SkypeForBusinessDeviceUsageDistributionUserCounts.
/// </summary>
/// <returns>The SkypeForBusinessDeviceUsageDistributionUserCounts.</returns>
System.Threading.Tasks.Task<SkypeForBusinessDeviceUsageDistributionUserCounts> GetAsync();
/// <summary>
/// Gets the specified SkypeForBusinessDeviceUsageDistributionUserCounts.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The SkypeForBusinessDeviceUsageDistributionUserCounts.</returns>
System.Threading.Tasks.Task<SkypeForBusinessDeviceUsageDistributionUserCounts> GetAsync(CancellationToken cancellationToken);
/// <summary>
/// Updates the specified SkypeForBusinessDeviceUsageDistributionUserCounts using PATCH.
/// </summary>
/// <param name="skypeForBusinessDeviceUsageDistributionUserCountsToUpdate">The SkypeForBusinessDeviceUsageDistributionUserCounts to update.</param>
/// <returns>The updated SkypeForBusinessDeviceUsageDistributionUserCounts.</returns>
System.Threading.Tasks.Task<SkypeForBusinessDeviceUsageDistributionUserCounts> UpdateAsync(SkypeForBusinessDeviceUsageDistributionUserCounts skypeForBusinessDeviceUsageDistributionUserCountsToUpdate);
/// <summary>
/// Updates the specified SkypeForBusinessDeviceUsageDistributionUserCounts using PATCH.
/// </summary>
/// <param name="skypeForBusinessDeviceUsageDistributionUserCountsToUpdate">The SkypeForBusinessDeviceUsageDistributionUserCounts to update.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <exception cref="ClientException">Thrown when an object returned in a response is used for updating an object in Microsoft Graph.</exception>
/// <returns>The updated SkypeForBusinessDeviceUsageDistributionUserCounts.</returns>
System.Threading.Tasks.Task<SkypeForBusinessDeviceUsageDistributionUserCounts> UpdateAsync(SkypeForBusinessDeviceUsageDistributionUserCounts skypeForBusinessDeviceUsageDistributionUserCountsToUpdate, CancellationToken cancellationToken);
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="value">The expand value.</param>
/// <returns>The request object to send.</returns>
ISkypeForBusinessDeviceUsageDistributionUserCountsRequest Expand(string value);
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="expandExpression">The expression from which to calculate the expand value.</param>
/// <returns>The request object to send.</returns>
ISkypeForBusinessDeviceUsageDistributionUserCountsRequest Expand(Expression<Func<SkypeForBusinessDeviceUsageDistributionUserCounts, object>> expandExpression);
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="value">The select value.</param>
/// <returns>The request object to send.</returns>
ISkypeForBusinessDeviceUsageDistributionUserCountsRequest Select(string value);
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="selectExpression">The expression from which to calculate the select value.</param>
/// <returns>The request object to send.</returns>
ISkypeForBusinessDeviceUsageDistributionUserCountsRequest Select(Expression<Func<SkypeForBusinessDeviceUsageDistributionUserCounts, object>> selectExpression);
}
}
| 61.148148 | 245 | 0.722744 | [
"MIT"
] | OfficeGlobal/msgraph-beta-sdk-dotnet | src/Microsoft.Graph/Requests/Generated/ISkypeForBusinessDeviceUsageDistributionUserCountsRequest.cs | 6,604 | 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>
//------------------------------------------------------------------------------
using System;
using System.Reflection;
[assembly: System.Reflection.AssemblyCompanyAttribute("TelnyxTests")]
[assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")]
[assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")]
[assembly: System.Reflection.AssemblyProductAttribute("TelnyxTests")]
[assembly: System.Reflection.AssemblyTitleAttribute("TelnyxTests")]
[assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")]
// Generated by the MSBuild WriteCodeFragment class.
| 40.958333 | 80 | 0.648016 | [
"MIT"
] | thedonmon/telnyx-dotnet | src/TelnyxTests/obj/Debug/netcoreapp2.0/TelnyxTests.AssemblyInfo.cs | 983 | C# |
namespace Photon
{
public interface IPunObservable
{
void OnPhotonSerializeView(PhotonStream stream, PhotonMessageInfo info);
}
}
| 16.777778 | 80 | 0.715232 | [
"Apache-2.0"
] | ITALIA195/Shelter | Shelter/Photon/IPunObservable.cs | 151 | C# |
using System;
class Program
{
static void Main()
{
var lenght = double.Parse(Console.ReadLine());
var width = double.Parse(Console.ReadLine());
var height = double.Parse(Console.ReadLine());
Box box = new Box(lenght, width, height);
Console.WriteLine(box.SurfaceArea());
Console.WriteLine(box.LateralSurfaceArea());
Console.WriteLine(box.Volume());
}
}
| 22.421053 | 54 | 0.615023 | [
"MIT"
] | SonicTheCat/CSharp-OOP-Basics | 06.Encapsulation - Exercise/01.ClassBox/Program.cs | 428 | C# |
using System.IO;
using System.Runtime.Serialization;
using WolvenKit.CR2W.Reflection;
using FastMember;
using static WolvenKit.CR2W.Types.Enums;
namespace WolvenKit.CR2W.Types
{
[DataContract(Namespace = "")]
[REDMeta]
public class CBTTaskIsInChatSceneDef : IBehTreeReactionTaskDefinition
{
public CBTTaskIsInChatSceneDef(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name){ }
public static new CVariable Create(CR2WFile cr2w, CVariable parent, string name) => new CBTTaskIsInChatSceneDef(cr2w, parent, name);
public override void Read(BinaryReader file, uint size) => base.Read(file, size);
public override void Write(BinaryWriter file) => base.Write(file);
}
} | 31.478261 | 135 | 0.752762 | [
"MIT"
] | DerinHalil/CP77Tools | CP77.CR2W/Types/W3/RTTIConvert/CBTTaskIsInChatSceneDef.cs | 702 | C# |
/********************************************************************************
Copyright (C) Binod Nepal, Mix Open Foundation (http://mixof.org).
This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
If a copy of the MPL was not distributed with this file, You can obtain one at
http://mozilla.org/MPL/2.0/.
***********************************************************************************/
using System;
using System.Data.Common;
using System.Diagnostics.CodeAnalysis;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using MixERP.Net.Common;
using MixERP.Net.Common.Models.Office;
namespace MixERP.Net.BusinessLayer.Security
{
public static class User
{
public static bool SetSession(Page page, string user)
{
if (page != null)
{
try
{
SignInView signInView = GetLastSignInView(user);
long logOnId = signInView.LogOnId;
if (logOnId.Equals(0))
{
MixERPWebpage.RequestLogOnPage();
return false;
}
page.Session["LogOnId"] = signInView.LogOnId;
page.Session["UserId"] = signInView.UserId;
page.Session["Culture"] = signInView.Culture;
page.Session["UserName"] = user;
page.Session["FullUserName"] = signInView.FullName;
page.Session["Role"] = signInView.Role;
page.Session["IsSystem"] = signInView.IsSystem;
page.Session["IsAdmin"] = signInView.IsAdmin;
page.Session["OfficeCode"] = signInView.OfficeCode;
page.Session["OfficeId"] = signInView.OfficeId;
page.Session["NickName"] = signInView.Nickname;
page.Session["OfficeName"] = signInView.OfficeName;
page.Session["RegistrationDate"] = signInView.RegistrationDate;
page.Session["RegistrationNumber"] = signInView.RegistrationNumber;
page.Session["PanNumber"] = signInView.PanNumber;
page.Session["AddressLine1"] = signInView.AddressLine1;
page.Session["AddressLine2"] = signInView.AddressLine2;
page.Session["Street"] = signInView.Street;
page.Session["City"] = signInView.City;
page.Session["State"] = signInView.State;
page.Session["Country"] = signInView.Country;
page.Session["ZipCode"] = signInView.ZipCode;
page.Session["Phone"] = signInView.Phone;
page.Session["Fax"] = signInView.Fax;
page.Session["Email"] = signInView.Email;
page.Session["Url"] = signInView.Url;
return true;
}
catch (DbException)
{
//Swallow the exception
}
}
return false;
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
public static bool SignIn(int officeId, string userName, string password, string culture, bool remember, Page page)
{
if (page != null)
{
try
{
string remoteAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
string remoteUser = HttpContext.Current.Request.ServerVariables["REMOTE_USER"];
long logOnId = DatabaseLayer.Security.User.SignIn(officeId, userName, Conversion.HashSha512(password, userName), page.Request.UserAgent, remoteAddress, remoteUser, culture);
if (logOnId > 0)
{
page.Session["Culture"] = culture;
SetSession(page, userName);
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, userName, DateTime.Now, DateTime.Now.AddMinutes(30), remember, String.Empty, FormsAuthentication.FormsCookiePath);
string encryptedCookie = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedCookie);
cookie.Domain = FormsAuthentication.CookieDomain;
cookie.Path = ticket.CookiePath;
page.Response.Cookies.Add(cookie);
page.Response.Redirect(FormsAuthentication.GetRedirectUrl(userName, remember));
return true;
}
}
// ReSharper disable once EmptyGeneralCatchClause
catch
{
//Swallow the exception here
}
}
return false;
}
public static SignInView GetLastSignInView(string userName)
{
return DatabaseLayer.Security.User.GetLastSignInView(userName);
}
}
}
| 42.680328 | 206 | 0.531784 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | andreboni66/mixerp | MixERP.Net.BusinessLayer/Security/User.cs | 5,209 | C# |
using lightweight.data.Model;
using System.Collections.Generic;
namespace lightweight.business.Abstract
{
public interface IUserService
{
ServiceResponse<Users> Authenticate(string user,string pass);
ServiceResponse<Users> GetList();
public ServiceResponse<bool> Register(Users user);
}
} | 27.166667 | 69 | 0.730061 | [
"MIT"
] | ReyhanSimsek/lightweight | lightweight.business/Abstract/IUserService.cs | 328 | C# |
// *****************************************************************************
//
// © Component Factory Pty Ltd 2012. All rights reserved.
// The software and associated documentation supplied hereunder are the
// proprietary information of Component Factory Pty Ltd, 17/267 Nepean Hwy,
// Seaford, Vic 3198, Australia and are supplied subject to licence terms.
//
// Version 4.4.1.0 www.ComponentFactory.com
// *****************************************************************************
using System;
using System.Drawing;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Windows.Forms;
using System.Windows.Forms.Design;
namespace ComponentFactory.Krypton.Toolkit
{
internal class KryptonDropButtonActionList : DesignerActionList
{
#region Instance Fields
private KryptonDropButton _dropButton;
private IComponentChangeService _service;
#endregion
#region Identity
/// <summary>
/// Initialize a new instance of the KryptonDropButtonActionList class.
/// </summary>
/// <param name="owner">Designer that owns this action list instance.</param>
public KryptonDropButtonActionList(KryptonDropButtonDesigner owner)
: base(owner.Component)
{
// Remember the button instance
_dropButton = owner.Component as KryptonDropButton;
// Cache service used to notify when a property has changed
_service = (IComponentChangeService)GetService(typeof(IComponentChangeService));
}
#endregion
#region Public
/// <summary>
/// Gets and sets the button style.
/// </summary>
public ButtonStyle ButtonStyle
{
get { return _dropButton.ButtonStyle; }
set
{
if (_dropButton.ButtonStyle != value)
{
_service.OnComponentChanged(_dropButton, null, _dropButton.ButtonStyle, value);
_dropButton.ButtonStyle = value;
}
}
}
/// <summary>
/// Gets and sets the visual button orientation.
/// </summary>
public VisualOrientation ButtonOrientation
{
get { return _dropButton.ButtonOrientation; }
set
{
if (_dropButton.ButtonOrientation != value)
{
_service.OnComponentChanged(_dropButton, null, _dropButton.ButtonOrientation, value);
_dropButton.ButtonOrientation = value;
}
}
}
/// <summary>
/// Gets and sets the visual drop down position.
/// </summary>
public VisualOrientation DropDownPosition
{
get { return _dropButton.DropDownPosition; }
set
{
if (_dropButton.DropDownPosition != value)
{
_service.OnComponentChanged(_dropButton, null, _dropButton.DropDownPosition, value);
_dropButton.DropDownPosition = value;
}
}
}
/// <summary>
/// Gets and sets the visual drop down orientation.
/// </summary>
public VisualOrientation DropDownOrientation
{
get { return _dropButton.DropDownOrientation; }
set
{
if (_dropButton.DropDownOrientation != value)
{
_service.OnComponentChanged(_dropButton, null, _dropButton.DropDownOrientation, value);
_dropButton.DropDownOrientation = value;
}
}
}
/// <summary>
/// Gets and sets the splitter or drop down functionality.
/// </summary>
public bool Splitter
{
get { return _dropButton.Splitter; }
set
{
if (_dropButton.Splitter != value)
{
_service.OnComponentChanged(_dropButton, null, _dropButton.Splitter, value);
_dropButton.Splitter = value;
}
}
}
/// <summary>
/// Gets and sets the button text.
/// </summary>
public string Text
{
get { return _dropButton.Values.Text; }
set
{
if (_dropButton.Values.Text != value)
{
_service.OnComponentChanged(_dropButton, null, _dropButton.Values.Text, value);
_dropButton.Values.Text = value;
}
}
}
/// <summary>
/// Gets and sets the extra button text.
/// </summary>
public string ExtraText
{
get { return _dropButton.Values.ExtraText; }
set
{
if (_dropButton.Values.ExtraText != value)
{
_service.OnComponentChanged(_dropButton, null, _dropButton.Values.ExtraText, value);
_dropButton.Values.ExtraText = value;
}
}
}
/// <summary>
/// Gets and sets the button image.
/// </summary>
public Image Image
{
get { return _dropButton.Values.Image; }
set
{
if (_dropButton.Values.Image != value)
{
_service.OnComponentChanged(_dropButton, null, _dropButton.Values.Image, value);
_dropButton.Values.Image = value;
}
}
}
/// <summary>
/// Gets and sets the palette mode.
/// </summary>
public PaletteMode PaletteMode
{
get { return _dropButton.PaletteMode; }
set
{
if (_dropButton.PaletteMode != value)
{
_service.OnComponentChanged(_dropButton, null, _dropButton.PaletteMode, value);
_dropButton.PaletteMode = value;
}
}
}
#endregion
#region Public Override
/// <summary>
/// Returns the collection of DesignerActionItem objects contained in the list.
/// </summary>
/// <returns>A DesignerActionItem array that contains the items in this list.</returns>
public override DesignerActionItemCollection GetSortedActionItems()
{
// Create a new collection for holding the single item we want to create
DesignerActionItemCollection actions = new DesignerActionItemCollection();
// This can be null when deleting a control instance at design time
if (_dropButton != null)
{
// Add the list of button specific actions
actions.Add(new DesignerActionHeaderItem("Appearance"));
actions.Add(new DesignerActionPropertyItem("Splitter", "Splitter", "Appearance", "Splitter of DropDown"));
actions.Add(new DesignerActionPropertyItem("ButtonStyle", "ButtonStyle", "Appearance", "Button style"));
actions.Add(new DesignerActionPropertyItem("ButtonOrientation", "ButtonOrientation", "Appearance", "Button orientation"));
actions.Add(new DesignerActionPropertyItem("DropDownPosition", "DropDownPosition", "Appearance", "DropDown position"));
actions.Add(new DesignerActionPropertyItem("DropDownOrientation", "DropDownOrientation", "Appearance", "DropDown orientation"));
actions.Add(new DesignerActionHeaderItem("Values"));
actions.Add(new DesignerActionPropertyItem("Text", "Text", "Values", "Button text"));
actions.Add(new DesignerActionPropertyItem("ExtraText", "ExtraText", "Values", "Button extra text"));
actions.Add(new DesignerActionPropertyItem("Image", "Image", "Values", "Button image"));
actions.Add(new DesignerActionHeaderItem("Visuals"));
actions.Add(new DesignerActionPropertyItem("PaletteMode", "Palette", "Visuals", "Palette applied to drawing"));
}
return actions;
}
#endregion
}
}
| 36.354978 | 144 | 0.543106 | [
"BSD-3-Clause"
] | Cocotteseb/Krypton | Source/Krypton Components/ComponentFactory.Krypton.Design/Toolkit/KryptonDropButtonActionList.cs | 8,401 | C# |
using System.Linq;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using JuryApp.Core.Models;
using JuryApp.Core.Models.Collections;
using JuryApp.Core.Services.Interfaces;
using JuryApp.Services;
namespace JuryApp.ViewModels
{
public class MainViewModel : ViewModelBase
{
private readonly INavigationServiceEx _navigationService;
private readonly IRoundService _roundService;
private readonly ITeamService _teamService;
public Rounds Rounds { get; set; } = new Rounds();
public string SelectionMode { get; set; } = "Single";
public Teams TeamsBySelectedRound { get; set; } = new Teams();
public MainViewModel(ITeamService teamService, IRoundService roundService, INavigationServiceEx navigationService)
{
_teamService = teamService;
_roundService = roundService;
_navigationService = navigationService;
GetRoundsFromEnabledQuiz();
_navigationService.Navigated += NavigationService_Navigated;
}
public RelayCommand<Round> EnableRoundCommand => new RelayCommand<Round>(EnableRound);
public RelayCommand DisableAllRoundsCommand => new RelayCommand(DisableAllRounds);
public RelayCommand<Round> GetTeamsOfSelectedRoundCommand => new RelayCommand<Round>(FetchListOfTeamsByRound);
public RelayCommand<Round> RefreshTeamsCommand => new RelayCommand<Round>(RefreshTeams);
private void RefreshTeams(Round selectedRound)
{
GetRoundsFromEnabledQuiz();
}
private void DisableAllRounds()
{
if (!Rounds.Any(r => r.RoundEnabled)) return;
Rounds.ToList().ForEach(async r =>
{
r.RoundEnabled = false;
await _roundService.EditRound(r.RoundId, r);
});
}
private void EnableRound(Round selectedRound)
{
if (selectedRound == null) return;
Rounds.ToList().ForEach(async r =>
{
r.RoundEnabled = r.RoundId == selectedRound.RoundId;
await _roundService.EditRound(r.RoundId, r);
});
}
private void NavigationService_Navigated(object sender, Windows.UI.Xaml.Navigation.NavigationEventArgs e)
{
GetRoundsFromEnabledQuiz();
}
private async void GetRoundsFromEnabledQuiz()
{
Rounds = await _roundService.GetAllRoundsByEnabledQuiz();
RaisePropertyChanged(() => Rounds);
}
private async void FetchListOfTeamsByRound(Round selectedRound)
{
if (selectedRound == null) return;
var teams = await _teamService.GetAllTeams();
TeamsBySelectedRound.Clear();
teams.ToList().Where(t => selectedRound.RoundTeamsIndication.Contains(t.TeamId)).ToList().ForEach(t => TeamsBySelectedRound.Add(t));
}
}
}
| 33.325843 | 144 | 0.644639 | [
"MIT"
] | JegorRysskin/boektquizt-jordydriesjegor_enterprisemobile | Frontend/JuryApp/JuryApp/ViewModels/MainViewModel.cs | 2,968 | C# |
#region Copyright
// Copyright (c) Tobias Wilker and contributors
// This file is licensed under MIT
#endregion
using System;
using System.Collections.Generic;
using System.IO;
using Agents.Net;
namespace Agents.Net.Benchmarks.FileManipulation
{
[Consumes(typeof(RootDirectoryDefinedMessage))]
[Consumes(typeof(FileCompletedMessage))]
[Produces(typeof(FileFoundMessage))]
public class FileFinder : Agent
{
private readonly MessageGate<FileFoundMessage, FileCompletedMessage> gate = new();
private readonly Action terminateAction;
public FileFinder(IMessageBoard messageBoard, Action terminateAction) : base(messageBoard)
{
this.terminateAction = terminateAction;
}
protected override void ExecuteCore(Message messageData)
{
if (gate.Check(messageData))
{
return;
}
RootDirectoryDefinedMessage definedMessage = messageData.Get<RootDirectoryDefinedMessage>();
List<FileFoundMessage> messages = new();
foreach (FileInfo file in definedMessage.RootDirectory.EnumerateFiles())
{
messages.Add(new FileFoundMessage(file, messageData));
}
gate.SendAndContinue(messages,OnMessage, result =>
{
terminateAction();
});
}
}
}
| 32.266667 | 105 | 0.620523 | [
"MIT"
] | agents-net/agents.net | src/Agents.Net.Benchmarks/FileManipulation/FileFinder.cs | 1,454 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public enum AxisType
{
X,
Y,
Z,
}
public class rotateWithMove : MonoBehaviour
{
public float _max = 360f;
public float _min = 0f;
public float _speed;
[SerializeField]private float _normalizedValue;
private float _lerpValue;
public bool _moveWithSight;
public AxisType _axis;
private RectTransform _thisTransform;
void Start()
{
_thisTransform = GetComponent<RectTransform>();
_normalizedValue = Mathf.Abs(Mathf.DeltaAngle(_min, _max));
_lerpValue = _thisTransform.eulerAngles.z;
}
void Update()
{
if (_moveWithSight)
{
float _ratio = 360 / _normalizedValue;
// float _value = Mathf.Clamp(Mathf.DeltaAngle(0, Mathf.Abs(Camera.main.transform.eulerAngles.y)) / _ratio, _min, _max);
float _value = Mathf.Clamp(Camera.main.transform.eulerAngles.y, _min, _max);
_lerpValue = Mathf.MoveTowards(_lerpValue, _value, _speed * Time.deltaTime);
_thisTransform.localRotation = Quaternion.Euler(0,0,_lerpValue/_ratio);
}
}
public void RotateSprite(float f)
{
_thisTransform.localRotation = Quaternion.Euler(0,0,f);
}
}
| 27.4375 | 132 | 0.659833 | [
"Apache-2.0"
] | rafa-s-7/turn-off-the-lights | Assets/[ImportedAssets]/UserInterface/VirtualRealitySterileFuture/Scripts/rotateWithMove.cs | 1,319 | C# |
/*
* Copyright 2008 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using BinaryBitmap = com.google.zxing.BinaryBitmap;
using DecodeHintType = com.google.zxing.DecodeHintType;
using Reader = com.google.zxing.Reader;
using ReaderException = com.google.zxing.ReaderException;
using Result = com.google.zxing.Result;
using ResultMetadataType = com.google.zxing.ResultMetadataType;
using ResultPoint = com.google.zxing.ResultPoint;
using BitArray = com.google.zxing.common.BitArray;
namespace com.google.zxing.oned
{
/// <summary> Encapsulates functionality and implementation that is common to all families
/// of one-dimensional barcodes.
///
/// </summary>
/// <author> dswitkin@google.com (Daniel Switkin)
/// </author>
/// <author> Sean Owen
/// </author>
/// <author>www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source
/// </author>
public abstract class OneDReader : Reader
{
private const int INTEGER_MATH_SHIFT = 8;
//UPGRADE_NOTE: Final was removed from the declaration of 'PATTERN_MATCH_RESULT_SCALE_FACTOR '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
internal static readonly int PATTERN_MATCH_RESULT_SCALE_FACTOR = 1 << INTEGER_MATH_SHIFT;
public virtual Result decode(BinaryBitmap image)
{
return decode(image, null);
}
// Note that we don't try rotation without the try harder flag, even if rotation was supported.
// public virtual Result decode(BinaryBitmap image, System.Collections.Hashtable hints) // commented by .net follower (http://dotnetfollower.com)
public virtual Result decode(BinaryBitmap image, System.Collections.Generic.Dictionary<Object, Object> hints) // added by .net follower (http://dotnetfollower.com)
{
try
{
return doDecode(image, hints);
}
catch (ReaderException re)
{
bool tryHarder = hints != null && hints.ContainsKey(DecodeHintType.TRY_HARDER);
if (tryHarder && image.RotateSupported)
{
BinaryBitmap rotatedImage = image.rotateCounterClockwise();
Result result = doDecode(rotatedImage, hints);
// Record that we found it rotated 90 degrees CCW / 270 degrees CW
// System.Collections.Hashtable metadata = result.ResultMetadata; // commented by .net follower (http://dotnetfollower.com)
System.Collections.Generic.Dictionary<Object, Object> metadata = result.ResultMetadata; // added by .net follower (http://dotnetfollower.com)
int orientation = 270;
if (metadata != null && metadata.ContainsKey(ResultMetadataType.ORIENTATION))
{
// But if we found it reversed in doDecode(), add in that result here:
orientation = (orientation + ((System.Int32) metadata[ResultMetadataType.ORIENTATION])) % 360;
}
result.putMetadata(ResultMetadataType.ORIENTATION, (System.Object) orientation);
// Update result points
ResultPoint[] points = result.ResultPoints;
int height = rotatedImage.Height;
for (int i = 0; i < points.Length; i++)
{
points[i] = new ResultPoint(height - points[i].Y - 1, points[i].X);
}
return result;
}
else
{
throw re;
}
}
}
/// <summary> We're going to examine rows from the middle outward, searching alternately above and below the
/// middle, and farther out each time. rowStep is the number of rows between each successive
/// attempt above and below the middle. So we'd scan row middle, then middle - rowStep, then
/// middle + rowStep, then middle - (2 * rowStep), etc.
/// rowStep is bigger as the image is taller, but is always at least 1. We've somewhat arbitrarily
/// decided that moving up and down by about 1/16 of the image is pretty good; we try more of the
/// image if "trying harder".
///
/// </summary>
/// <param name="image">The image to decode
/// </param>
/// <param name="hints">Any hints that were requested
/// </param>
/// <returns> The contents of the decoded barcode
/// </returns>
/// <throws> ReaderException Any spontaneous errors which occur </throws>
// private Result doDecode(BinaryBitmap image, System.Collections.Hashtable hints) // commented by .net follower (http://dotnetfollower.com)
private Result doDecode(BinaryBitmap image, System.Collections.Generic.Dictionary<Object, Object> hints) // added by .net follower (http://dotnetfollower.com)
{
int width = image.Width;
int height = image.Height;
BitArray row = new BitArray(width);
int middle = height >> 1;
bool tryHarder = hints != null && hints.ContainsKey(DecodeHintType.TRY_HARDER);
int rowStep = System.Math.Max(1, height >> (tryHarder?7:4));
int maxLines;
if (tryHarder)
{
maxLines = height; // Look at the whole image, not just the center
}
else
{
maxLines = 9; // Nine rows spaced 1/16 apart is roughly the middle half of the image
}
for (int x = 0; x < maxLines; x++)
{
// Scanning from the middle out. Determine which row we're looking at next:
int rowStepsAboveOrBelow = (x + 1) >> 1;
bool isAbove = (x & 0x01) == 0; // i.e. is x even?
int rowNumber = middle + rowStep * (isAbove?rowStepsAboveOrBelow:- rowStepsAboveOrBelow);
if (rowNumber < 0 || rowNumber >= height)
{
// Oops, if we run off the top or bottom, stop
break;
}
// Estimate black point for this row and load it:
try
{
row = image.getBlackRow(rowNumber, row);
}
catch (ReaderException re)
{
continue;
}
// While we have the image data in a BitArray, it's fairly cheap to reverse it in place to
// handle decoding upside down barcodes.
for (int attempt = 0; attempt < 2; attempt++)
{
if (attempt == 1)
{
// trying again?
row.reverse(); // reverse the row and continue
// This means we will only ever draw result points *once* in the life of this method
// since we want to avoid drawing the wrong points after flipping the row, and,
// don't want to clutter with noise from every single row scan -- just the scans
// that start on the center line.
if (hints != null && hints.ContainsKey(DecodeHintType.NEED_RESULT_POINT_CALLBACK))
{
// System.Collections.Hashtable newHints = System.Collections.Hashtable.Synchronized(new System.Collections.Hashtable()); // Can't use clone() in J2ME // commented by .net follower (http://dotnetfollower.com)
System.Collections.Generic.Dictionary<Object, Object> newHints = new System.Collections.Generic.Dictionary<Object, Object>(); // Can't use clone() in J2ME // added by .net follower (http://dotnetfollower.com)
System.Collections.IEnumerator hintEnum = hints.Keys.GetEnumerator();
//UPGRADE_TODO: Method 'java.util.Enumeration.hasMoreElements' was converted to 'System.Collections.IEnumerator.MoveNext' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilEnumerationhasMoreElements'"
while (hintEnum.MoveNext())
{
//UPGRADE_TODO: Method 'java.util.Enumeration.nextElement' was converted to 'System.Collections.IEnumerator.Current' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilEnumerationnextElement'"
System.Object key = hintEnum.Current;
if (!key.Equals(DecodeHintType.NEED_RESULT_POINT_CALLBACK))
{
newHints[key] = hints[key];
}
}
hints = newHints;
}
}
try
{
// Look for a barcode
Result result = decodeRow(rowNumber, row, hints);
// We found our barcode
if (attempt == 1)
{
// But it was upside down, so note that
result.putMetadata(ResultMetadataType.ORIENTATION, (System.Object) 180);
// And remember to flip the result points horizontally.
ResultPoint[] points = result.ResultPoints;
points[0] = new ResultPoint(width - points[0].X - 1, points[0].Y);
points[1] = new ResultPoint(width - points[1].X - 1, points[1].Y);
}
return result;
}
catch (ReaderException re)
{
// continue -- just couldn't decode this row
}
}
}
throw ReaderException.Instance;
}
/// <summary> Records the size of successive runs of white and black pixels in a row, starting at a given point.
/// The values are recorded in the given array, and the number of runs recorded is equal to the size
/// of the array. If the row starts on a white pixel at the given start point, then the first count
/// recorded is the run of white pixels starting from that point; likewise it is the count of a run
/// of black pixels if the row begin on a black pixels at that point.
///
/// </summary>
/// <param name="row">row to count from
/// </param>
/// <param name="start">offset into row to start at
/// </param>
/// <param name="counters">array into which to record counts
/// </param>
/// <throws> ReaderException if counters cannot be filled entirely from row before running out </throws>
/// <summary> of pixels
/// </summary>
internal static void recordPattern(BitArray row, int start, int[] counters)
{
int numCounters = counters.Length;
for (int i = 0; i < numCounters; i++)
{
counters[i] = 0;
}
int end = row.Size;
if (start >= end)
{
throw ReaderException.Instance;
}
bool isWhite = !row.get_Renamed(start);
int counterPosition = 0;
int i2 = start;
while (i2 < end)
{
bool pixel = row.get_Renamed(i2);
if (pixel ^ isWhite)
{
// that is, exactly one is true
counters[counterPosition]++;
}
else
{
counterPosition++;
if (counterPosition == numCounters)
{
break;
}
else
{
counters[counterPosition] = 1;
isWhite ^= true; // isWhite = !isWhite;
}
}
i2++;
}
// If we read fully the last section of pixels and filled up our counters -- or filled
// the last counter but ran off the side of the image, OK. Otherwise, a problem.
if (!(counterPosition == numCounters || (counterPosition == numCounters - 1 && i2 == end)))
{
throw ReaderException.Instance;
}
}
/// <summary> Determines how closely a set of observed counts of runs of black/white values matches a given
/// target pattern. This is reported as the ratio of the total variance from the expected pattern
/// proportions across all pattern elements, to the length of the pattern.
///
/// </summary>
/// <param name="counters">observed counters
/// </param>
/// <param name="pattern">expected pattern
/// </param>
/// <param name="maxIndividualVariance">The most any counter can differ before we give up
/// </param>
/// <returns> ratio of total variance between counters and pattern compared to total pattern size,
/// where the ratio has been multiplied by 256. So, 0 means no variance (perfect match); 256 means
/// the total variance between counters and patterns equals the pattern length, higher values mean
/// even more variance
/// </returns>
internal static int patternMatchVariance(int[] counters, int[] pattern, int maxIndividualVariance)
{
int numCounters = counters.Length;
int total = 0;
int patternLength = 0;
for (int i = 0; i < numCounters; i++)
{
total += counters[i];
patternLength += pattern[i];
}
if (total < patternLength)
{
// If we don't even have one pixel per unit of bar width, assume this is too small
// to reliably match, so fail:
return System.Int32.MaxValue;
}
// We're going to fake floating-point math in integers. We just need to use more bits.
// Scale up patternLength so that intermediate values below like scaledCounter will have
// more "significant digits"
int unitBarWidth = (total << INTEGER_MATH_SHIFT) / patternLength;
maxIndividualVariance = (maxIndividualVariance * unitBarWidth) >> INTEGER_MATH_SHIFT;
int totalVariance = 0;
for (int x = 0; x < numCounters; x++)
{
int counter = counters[x] << INTEGER_MATH_SHIFT;
int scaledPattern = pattern[x] * unitBarWidth;
int variance = counter > scaledPattern?counter - scaledPattern:scaledPattern - counter;
if (variance > maxIndividualVariance)
{
return System.Int32.MaxValue;
}
totalVariance += variance;
}
return totalVariance / total;
}
/// <summary> <p>Attempts to decode a one-dimensional barcode format given a single row of
/// an image.</p>
///
/// </summary>
/// <param name="rowNumber">row number from top of the row
/// </param>
/// <param name="row">the black/white pixel data of the row
/// </param>
/// <param name="hints">decode hints
/// </param>
/// <returns> {@link Result} containing encoded string and start/end of barcode
/// </returns>
/// <throws> ReaderException if an error occurs or barcode cannot be found </throws>
// public abstract Result decodeRow(int rowNumber, BitArray row, System.Collections.Hashtable hints); // commented by .net follower (http://dotnetfollower.com)
public abstract Result decodeRow(int rowNumber, BitArray row, System.Collections.Generic.Dictionary<Object, Object> hints); // added by .net follower (http://dotnetfollower.com)
}
} | 42.581602 | 305 | 0.660767 | [
"Unlicense"
] | StackTipsLab/phonegap-plugins | WindowsPhone/BarcodeScanner/sources/ZXing7_1Port/oned/OneDReader.cs | 14,350 | C# |
using System.Text.Json.Serialization;
namespace Horizon.Payment.Alipay.Response
{
/// <summary>
/// KoubeiMerchantInfoSimpleQueryResponse.
/// </summary>
public class KoubeiMerchantInfoSimpleQueryResponse : AlipayResponse
{
/// <summary>
/// 操作员登录账号前缀,例如cc123@alitest.com#001
/// </summary>
[JsonPropertyName("operator_prefix")]
public string OperatorPrefix { get; set; }
/// <summary>
/// 商户id,2088121509924973
/// </summary>
[JsonPropertyName("partner_id")]
public string PartnerId { get; set; }
/// <summary>
/// 用户名
/// </summary>
[JsonPropertyName("user_name")]
public string UserName { get; set; }
}
}
| 26.068966 | 71 | 0.585979 | [
"Apache-2.0"
] | bluexray/Horizon.Sample | Horizon.Payment.Alipay/Response/KoubeiMerchantInfoSimpleQueryResponse.cs | 794 | C# |
using System;
namespace Prise.IntegrationTestsContract
{
// Plugin Parameter types are not required to be serializable, Newtonsoft JSON takes care of this
public class ComplexCalculationContext
{
public CalculationContext[] Calculations { get; set; }
}
} | 27.9 | 101 | 0.738351 | [
"MIT"
] | Duan112358/Prise | src/Tests/Prise.IntegrationTestsContract/ComplexCalculationContext.cs | 279 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using AccessibilityInsights.CommonUxComponents.Controls;
using Axe.Windows.Core.Bases;
using Axe.Windows.Core.Misc;
using Axe.Windows.Core.Results;
using Axe.Windows.Core.Types;
using AccessibilityInsights.SharedUx.Properties;
using AccessibilityInsights.SharedUx.Utilities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
namespace AccessibilityInsights.SharedUx.ViewModels
{
/// <summary>
/// HierarchyTreeItem class
/// ViewModel for A11yElement in Hierarchy tree
/// </summary>
public class HierarchyNodeViewModel: ViewModelBase
{
const int NormalIconSizeBack = 14; // size for non composite icon
const int TreeIconSizeBack = 16; // size for tree in composite icon
const int NormalIconSizeFront = 9; // size for error state in composite icon
/// <summary>
/// Show uncertain results Icon
/// </summary>
private readonly bool ShowUncertain;
/// <summary>
/// Element which is represented via this ViewModel
/// </summary>
public A11yElement Element { get; private set; }
/// <summary>
/// Child ViewModels
/// </summary>
public List<HierarchyNodeViewModel> Children { get; private set; }
#pragma warning disable CA1819 // Properties should not return arrays
/// <summary>
/// Counts of aggregate scan statuses
/// result[ScanStatusEnum] -> number of descendents with that scan status (including this element)
/// </summary>
public int[] AggregateStatusCounts { get; private set; }
#pragma warning restore CA1819 // Properties should not return arrays
/// <summary>
/// indicate whether new Snapshot is needed if asked for expand.
/// </summary>
public bool NeedSnapshot { get; }
/// <summary>
/// Error icon to show
/// </summary>
public FabricIcon? IconBack { get; private set; }
/// <summary>
/// Icon to overlay.
/// </summary>
public FabricIcon? IconFront { get; private set; }
/// <summary>
/// Background Icon Size
/// </summary>
public int IconSizeBack { get; private set; } = NormalIconSizeBack;
/// <summary>
/// front Icon size
/// </summary>
public int IconSizeFront { get; private set; } = NormalIconSizeFront;
/// <summary>
/// Whether or not the File Bug button should be made visible
/// </summary>
public static Visibility FileBugVisibility => HelperMethods.FileBugVisibility;
private Visibility _iconVisibility = Visibility.Collapsed;
/// <summary>
/// Visibility of error icon
/// </summary>
public Visibility IconVisibility
{
get
{
return this._iconVisibility;
}
private set
{
this._iconVisibility = value;
OnPropertyChanged(nameof(IconVisibility));
}
}
/// <summary>
/// Display text for the issue
/// </summary>
public string IssueDisplayText
{
get
{
return Element.IssueDisplayText;
}
set
{
Element.IssueDisplayText = value;
OnPropertyChanged(nameof(IssueDisplayText));
OnPropertyChanged(nameof(BugVisibility));
}
}
/// <summary>
/// Used to store the issue link.
/// </summary>
public Uri IssueLink { get; set; }
/// <summary>
/// Visibility of bug icon when node selected
/// </summary>
public Visibility BugVisibility
{
get
{
return string.IsNullOrEmpty(IssueDisplayText) ? Visibility.Visible : Visibility.Collapsed;
}
}
/// <summary>
/// AutomationProperties.Name
/// </summary>
public string AutomationName { get; private set; }
private Visibility _visibility = Visibility.Visible;
public Visibility Visibility
{
get
{
return this._visibility;
}
private set
{
this._visibility = value;
OnPropertyChanged(nameof(Visibility));
}
}
/// <summary>
/// to indicate whether the node should be hilighted or not
/// </summary>
private bool _ishilighted;
public bool IsHilighted
{
get
{
return this._ishilighted;
}
private set
{
this._ishilighted = value;
OnPropertyChanged(nameof(IsHilighted));
}
}
/// <summary>
/// Is node selected
/// </summary>
private bool _isselected;
public bool IsSelected
{
get
{
return this._isselected;
}
set
{
this._isselected = value;
OnPropertyChanged(nameof(IsSelected));
}
}
/// <summary>
/// Is node selected
/// </summary>
private bool _isexpanded;
public bool IsExpanded
{
get
{
return this._isexpanded;
}
set
{
this._isexpanded = value;
this.IconVisibility = (value && this.IconBack != FabricIcon.DOM && this.IconBack != default(FabricIcon)) || (!value && this.IconBack != default(FabricIcon)) ? Visibility.Visible : Visibility.Collapsed;
OnPropertyChanged(nameof(IsExpanded));
}
}
/// <summary>
/// Header for tree node item
/// </summary>
public string Header { get; private set; }
private readonly string SearchContext;
/// <summary>
/// These are searchable string properties
/// Not all string properties are included to improve performance
/// </summary>
private static int[] CommonStringProperties =
{
PropertyType.UIA_LocalizedControlTypePropertyId,
PropertyType.UIA_NamePropertyId,
PropertyType.UIA_AutomationIdPropertyId,
PropertyType.UIA_ClassNamePropertyId,
PropertyType.UIA_HelpTextPropertyId,
PropertyType.UIA_FrameworkIdPropertyId,
PropertyType.UIA_ItemStatusPropertyId,
PropertyType.UIA_ItemTypePropertyId,
PropertyType.UIA_ValuePattern_ValuePropertyId,
PropertyType.UIA_AriaRolePropertyId,
PropertyType.UIA_AriaPropertiesPropertyId,
PropertyType.UIA_LocalizedLandmarkTypePropertyId,
PropertyType.UIA_FullDescriptionPropertyId,
};
/// <summary>
/// Is node for live mode
/// </summary>
public bool IsLiveMode { get; private set; }
/// <summary>
/// constructor
/// </summary>
/// <param name="ce">Current Element</param>
/// <param name="se">Selected Element</param>
/// <param name="showUncertain">Show uncertain result icon or not. </param>
/// <param name="needSnapshotMenu">default is true</param>
/// <param name="isLiveMode">Is node for live mode</param>
public HierarchyNodeViewModel(A11yElement ce, bool showUncertain, bool isLiveMode)
{
this.ShowUncertain = showUncertain;
this.Element = ce ?? throw new ArgumentNullException(nameof(ce));
if (this.Element.UniqueId == 0)
{
this.IsExpanded = true;
this.IsSelected = true;
this.NeedSnapshot = false;
}
else if (this.Element.UniqueId > 0)
{
this.IsExpanded = false;
this.IsSelected = false;
this.NeedSnapshot = false;
}
else
{
this.IsExpanded = true;
this.IsSelected = false;
this.NeedSnapshot = true;
}
if (ce.Children != null)
{
this.Children = (from c in ce.Children
select new HierarchyNodeViewModel(c, showUncertain, isLiveMode)).ToList();
}
if (isLiveMode == false)
{
var childrenAggregateCounts = (from c in this.Children
select c.AggregateStatusCounts);
// Sum together counts from immediate children & increment current element's status
this.AggregateStatusCounts = childrenAggregateCounts.Aggregate(new int[Enum.GetNames(typeof(ScanStatus)).Length],
(countsA, countsB) => countsA.Zip(countsB, (x, y) => x + y).ToArray());
this.AggregateStatusCounts[(int)this.Element.TestStatus]++;
}
this.Header = ce.Glimpse;
this.SearchContext = CreateSearchContext(ce);
this.IsLiveMode = isLiveMode;
UpdateIconInfoAndAutomationName(isLiveMode);
}
/// <summary>
/// Update Icon information and AutomationProperties.Name
/// since they share similar logic, combine calculation to improve perf.
/// </summary>
/// <param name="isLiveMode">Is node in live mode</param>
private void UpdateIconInfoAndAutomationName(bool isLiveMode)
{
StringBuilder sb = new StringBuilder();
sb.Append(this.Element.Glimpse);
this.IconVisibility = Visibility.Collapsed;
if (!isLiveMode)
{
if (this.Element.TestStatus == ScanStatus.Fail)
{
this.IconBack = FabricIcon.AlertSolid;
this.IconSizeBack = NormalIconSizeBack;
this.IconVisibility = Visibility.Visible;
sb.Append(" has failed test results.");
}
else if(this.Element.TestStatus == ScanStatus.ScanNotSupported)
{
this.IconBack = FabricIcon.MapDirections;
this.IconSizeBack = NormalIconSizeBack;
this.IconVisibility = Visibility.Visible;
sb.Append(" is not scanned since it is Web element.");
}
else if (this.Element.TestStatus == ScanStatus.Uncertain && this.ShowUncertain)
{
this.IconBack = FabricIcon.IncidentTriangle;
this.IconSizeBack = NormalIconSizeBack;
this.IconVisibility = Visibility.Visible;
sb.Append(" has uncertain test results.");
}
else
{
// no result or all pass, we need to use aggregated data.
this.IconBack = FabricIcon.DOM;
this.IconSizeBack = TreeIconSizeBack;
if (this.AggregateStatusCounts[(int)ScanStatus.Fail] > 0)
{
this.IconFront = FabricIcon.AlertSolid;
sb.Append(Resources.HierarchyNodeViewModel_UpdateIconInfoAndAutomationName_has_failed_test_results_in_descendants);
}
else if (this.AggregateStatusCounts[(int)ScanStatus.Uncertain] > 0 && this.ShowUncertain)
{
this.IconFront = FabricIcon.IncidentTriangle;
sb.Append(Resources.HierarchyNodeViewModel_UpdateIconInfoAndAutomationName_has_uncertain_test_results_in_descendants);
}
else
{
this.IconBack = default(FabricIcon);
sb.Append(Resources.HierarchyNodeViewModel_UpdateIconInfoAndAutomationName_has_no_failed_or_uncertain_test_result);
}
this.IconVisibility = this.IsExpanded == false && this.IconBack != default(FabricIcon) ? Visibility.Visible : Visibility.Collapsed;
}
}
this.AutomationName = sb.ToString();
}
public bool ApplyFilter(string filter)
{
bool isfiltered = true;
if (this.Children != null && this.Children.Count != 0)
{
var cnt = (from c in this.Children
let f = c.ApplyFilter(filter)
where f == false
select c).Count();
if (cnt != 0)
{
isfiltered = false;
}
}
if (string.IsNullOrEmpty(filter)
|| (this.SearchContext != null
&& this.SearchContext.IndexOf(filter, StringComparison.OrdinalIgnoreCase) != -1))
{
isfiltered = false;
this.IsHilighted = true;
}
if(isfiltered)
{
this.Visibility = Visibility.Collapsed;
}
else
{
this.Visibility = Visibility.Visible;
}
return isfiltered;
}
public void SelectFirstVisibleLeafNode()
{
SelectFirstVisibleLeafNodeWorker();
}
private bool SelectFirstVisibleLeafNodeWorker()
{
if (this.Children != null)
{
foreach (var child in this.Children)
{
if (child.SelectFirstVisibleLeafNodeWorker())
return true;
} // for each child
}
if (this.IsVisible)
{
this.IsSelected = true;
return true;
}
return false;
}
private bool IsVisible
{
get
{
return this.Visibility == Visibility.Visible;
}
}
/// <summary>
/// Expand tree
/// if expandchildren is true, make children expanded too
/// it will expand all descendants
/// </summary>
/// <param name="expandchildren"></param>
internal void Expand(bool expandchildren = false)
{
this.IsExpanded = true;
if(expandchildren && this.Children.Count != 0)
{
foreach(var c in this.Children)
{
c.Expand(true);
}
}
}
internal void Clear()
{
if (this.Children != null)
{
foreach (var c in this.Children)
{
c.Clear();
}
this.Children.Clear();
}
this.Element = null;
}
private static string CreateSearchContext(A11yElement e)
{
if (e == null)
return null;
var properties = CreateSearchPropertiesString(e);
var patterns = CreateSearchPatternsString(e);
var controlTypeName = ControlType.GetInstance().GetNameById(e.ControlTypeId);
return string.Join(" ", properties, patterns, controlTypeName);
}
private static string CreateSearchPropertiesString(A11yElement e)
{
if (e == null)
return null;
var properties = from p in CommonStringProperties
let value = e.GetPropertyOrDefault<string>(p)
select value;
if (properties == null)
return null;
return string.Join(" ", properties);
}
private static string CreateSearchPatternsString(A11yElement e)
{
if (e == null)
return null;
var patterns = e.Patterns?.Select(p => PatternType.GetInstance().GetNameById(p.Id));
if (patterns == null)
return null;
return string.Join(" ", patterns);
}
}
}
| 33.962302 | 218 | 0.510136 | [
"MIT"
] | karanbirsingh/accessibility-insights-windows | src/AccessibilityInsights.SharedUx/ViewModels/HierarchyNodeViewModel.cs | 16,614 | C# |
using Oditel.Cirqus.Models.BaseContext.Commands;
using Oditel.Models.CustomerContext;
namespace Oditel.Cirqus.Models.CustomerContext.Commands
{
public class AddCustomerCommand : CreateCommand<Customer>
{
private readonly Address _address;
private readonly string _email;
private readonly string _name;
public AddCustomerCommand(string name, string email, Address address)
{
_name = name;
_email = email;
_address = address;
}
public AddCustomerCommand(ICustomer customer) : this(customer.Name, customer.Email, customer.Address)
{
}
protected override void Update(Customer instance)
{
instance.UpdateInfo(_name, _email, _address);
}
}
} | 28.428571 | 109 | 0.648241 | [
"MIT"
] | SamuelDebruyn/AD5-Cirqus-demo | Oditel.Cirqus.Models/CustomerContext/Commands/AddCustomerCommand.cs | 798 | C# |
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.Aiven.Outputs
{
[OutputType]
public sealed class GetElasticSearchElasticsearchUserConfigKibanaResult
{
/// <summary>
/// Timeout in milliseconds for requests
/// made by Kibana towards Elasticsearch.
/// </summary>
public readonly string? ElasticsearchRequestTimeout;
/// <summary>
/// Enable or disable Kibana.
/// </summary>
public readonly string? Enabled;
/// <summary>
/// Limits the maximum amount of memory (in MiB) the
/// Kibana process can use. This sets the max_old_space_size option of the nodejs running
/// the Kibana. Note: the memory reserved by Kibana is not available for Elasticsearch.
/// </summary>
public readonly string? MaxOldSpaceSize;
[OutputConstructor]
private GetElasticSearchElasticsearchUserConfigKibanaResult(
string? elasticsearchRequestTimeout,
string? enabled,
string? maxOldSpaceSize)
{
ElasticsearchRequestTimeout = elasticsearchRequestTimeout;
Enabled = enabled;
MaxOldSpaceSize = maxOldSpaceSize;
}
}
}
| 33.043478 | 97 | 0.655263 | [
"ECL-2.0",
"Apache-2.0"
] | pulumi/pulumi-aiven | sdk/dotnet/Outputs/GetElasticSearchElasticsearchUserConfigKibanaResult.cs | 1,520 | C# |
using System;
using NUnit.Framework;
using FluentAssertions;
using TechTalk.SpecFlow.Assist.ValueRetrievers;
namespace TechTalk.SpecFlow.RuntimeTests.AssistTests.ValueRetrieverTests
{
[TestFixture]
public class NullableUShortValueRetrieverTests
{
[Test]
public void Returns_null_when_the_value_is_null()
{
var retriever = new NullableUShortValueRetriever(v => 0);
retriever.GetValue(null).Should().Be(null);
}
[Test]
public void Returns_value_from_UShortValueRetriever_when_passed_not_empty_string()
{
Func<string, ushort> func = v =>
{
if (v == "test value") return 123;
if (v == "another test value") return 456;
return 0;
};
var retriever = new NullableUShortValueRetriever(func);
retriever.GetValue("test value").Should().Be((ushort?)123);
retriever.GetValue("another test value").Should().Be((ushort?)456);
}
[Test]
public void Returns_null_when_passed_empty_string()
{
var retriever = new NullableUShortValueRetriever(v => 3);
retriever.GetValue(string.Empty).Should().Be(null);
}
}
} | 31.875 | 90 | 0.609412 | [
"Apache-2.0",
"MIT"
] | ImanMesgaran/SpecFlow | Tests/TechTalk.SpecFlow.RuntimeTests/AssistTests/ValueRetrieverTests/NullableUShortValueRetrieverTests.cs | 1,277 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NetworkManager : MonoBehaviour
{
public static NetworkManager instance;
public GameObject playerPrefab;
private void Awake()
{
if (instance == null)
{
instance = this;
}
else if (instance != this)
{
Debug.Log("Instance already exists, destroying object!");
Destroy(this);
}
}
private void Start()
{
QualitySettings.vSyncCount = 0;
Application.targetFrameRate = 30;
#if UNITY_EDITOR
Debug.Log("Build the project to start the server!");
#else
Server.Start(50, 26950);
#endif
}
public Player InstantiatePlayer()
{
return Instantiate(playerPrefab, Vector3.zero, Quaternion.identity).GetComponent<Player>();
}
}
| 21.902439 | 99 | 0.599109 | [
"MIT"
] | ajinori3/tcp-udp-networking | UnityGameServer/Assets/Scripts/NetworkManager.cs | 900 | C# |
//-----------------------------------------------------------------------
// <copyright company="Nuclei">
// Copyright 2013 Nuclei. Licensed under the Apache License, Version 2.0.
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
namespace Sherlock.Executor.Nuclei.ExceptionHandling
{
/// <summary>
/// Defines a top level exception handler which stops all exceptions from propagating out of the application, thus
/// providing a chance for logging and semi-graceful termination of the application.
/// </summary>
internal static class TopLevelExceptionGuard
{
/// <summary>
/// Runs an action inside a high level try .. catch construct that will not let any errors escape
/// but will log errors to a file and the event log.
/// </summary>
/// <param name="actionToExecute">The action that should be executed.</param>
/// <param name="exceptionProcessors">The collection of exception processors that will be used to log any unhandled exception.</param>
/// <returns>
/// A value indicating whether the action executed successfully or not.
/// </returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Catching an Exception object here because this is the top-level exception handler.")]
public static GuardResult RunGuarded(Action actionToExecute, params ExceptionProcessor[] exceptionProcessors)
{
{
Debug.Assert(actionToExecute != null, "The application method should not be null.");
}
var processor = new ExceptionHandler(exceptionProcessors);
var result = GuardResult.None;
ExceptionFilter.ExecuteWithFilter(
() =>
{
actionToExecute();
result = GuardResult.Success;
},
e =>
{
processor.OnException(e, false);
result = GuardResult.Failure;
});
return result;
}
}
}
| 41.963636 | 143 | 0.562825 | [
"Apache-2.0"
] | pvandervelde/Sherlock | src/executor/Nuclei/ExceptionHandling/TopLevelExceptionGuard.cs | 2,308 | C# |
using System;
using Shouldly;
using Xunit;
namespace Baseline.Testing.Dates
{
public class DateTester
{
[Fact]
public void convert_by_constructor()
{
var date = new Date("22022012");
date.Day.ShouldBe(new DateTime(2012, 2, 22));
}
[Fact]
public void equals_method()
{
var date1 = new Date("22022012");
var date2 = new Date("22022012");
var date3 = new Date("22022013");
date1.ShouldBe(date2);
date2.ShouldBe(date1);
date3.ShouldNotBe(date1);
}
[Fact]
public void to_string_uses_the_ugly_ddMMyyyy_format()
{
var date = new Date(2, 22, 2012);
date.ToString().ShouldBe("22022012");
}
[Fact]
public void ctor_by_date_loses_the_time()
{
var date = new Date(DateTime.Now);
date.Day.ShouldBe(DateTime.Today);
}
}
} | 23.186047 | 61 | 0.525577 | [
"Apache-2.0"
] | Hawxy/baseline | src/Baseline.Testing/Dates/DateTester.cs | 997 | C# |
using System.Threading.Tasks;
using Cursed.Models.Services;
using Cursed.Models.Entities.Data;
using Cursed.Models.DataModel.ErrorHandling;
namespace Cursed.Tests.Stubs
{
/// <summary>
/// Stub for using instead of IOperationDataValidation. Returns valid status message
/// </summary>
public class OperationValidationStub : IOperationDataValidation
{
/// <returns>valid status message</returns>
public async Task<IErrorHandler> IsValidAsync(Operation operation)
{
return new StatusMessage
{
ProblemStatus = new Problem
{
Entity = "Operation.",
EntityKey = operation.Id.ToString()
}
};
}
}
}
| 28.703704 | 88 | 0.597419 | [
"MIT"
] | 42ama/Cursed | Cursed.Tests/Stubs/OperationValidationStub.cs | 777 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.