content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2
values |
|---|---|---|---|---|---|---|---|---|
using System;
using System.IO;
namespace NanoSerializer.Mappers
{
internal class EnumMapper : TypeMapper
{
public override bool Can(Type type)
{
return type.BaseType == typeof(Enum);
}
public override void Set(ref NanoReader reader)
{
var value = reader.Read(sizeof(byte))[0];
Setter(reader.Instance, value);
}
public override void Get(object obj, Stream stream)
{
var prop = (byte)Getter(obj);
stream.WriteByte(prop);
}
}
}
| 21.259259 | 59 | 0.555749 | [
"MIT"
] | SeletskySergey/NanoSerializer | NanoSerializer/Mappers/EnumMapper.cs | 576 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
using System;
using System.Collections.Generic;
#if !NETSTANDARD
using System.Runtime.Serialization;
#endif
namespace Amazon.Runtime.Internal
{
/// <summary>
/// Collection used to indicate if the property was initialized was created by the SDK.
/// </summary>
/// <typeparam name="T"></typeparam>
public class AutoConstructedList<T> : List<T>
{
}
/// <summary>
/// Collection used to indicate if the property was initialized was created by the SDK.
/// </summary>
/// <typeparam name="K"></typeparam>
/// <typeparam name="V"></typeparam>
#if !NETSTANDARD
[Serializable]
#endif
public class AutoConstructedDictionary<K, V> : Dictionary<K, V>
{
#if !NETSTANDARD
protected AutoConstructedDictionary(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
#endif
}
}
| 28.921569 | 93 | 0.679322 | [
"Apache-2.0"
] | KenHundley/aws-sdk-net | sdk/src/Core/Amazon.Runtime/Internal/AutoConstructedTypes.cs | 1,477 | C# |
using System;
using AutoTest.Core.DebugLog;
namespace AutoTest.Core.Configuration
{
public interface ILocateWriteLocation
{
string GetLogfile();
string GetConfigurationFile();
}
}
| 16.166667 | 38 | 0.757732 | [
"MIT"
] | acken/AutoTest.Net | src/AutoTest.Core/Configuration/ILocateWriteLocation.cs | 194 | C# |
using System;
using System.Text;
using System.Collections;
using System.IO;
using t = CodeGenerator.ParseTree;
using a = CodeGenerator.Application;
namespace CodeGenerator
{
public class Main
{
public Main(string connection, string parentNamespace, string outputDir, bool isCs) :
this(connection, null, parentNamespace, outputDir, isCs)
{ }
public Main(
string connection, string schemaPath, string parentNamespace, string outputDir, bool isCs)
{
this.schemaPath = schemaPath;
dbTool = new DatabaseTool(connection);
this.parentNamespace = parentNamespace;
this.outputDir = outputDir;
this.isCs = isCs;
}
public void Run()
{
try
{
if (schemaPath == null)
schemaPath = getSchemaFile();
Parser schParser = new Parser(schemaPath);
t.ApplicationNode appRootNode = schParser.ParseSchema();
SchemaValidator schValidator = new SchemaValidator(appRootNode);
schValidator.Validate();
SchemaDatabaseLoader schLoader = new SchemaDatabaseLoader(appRootNode);
Sql.Database schemaDatabase = schLoader.Database;
SqlDatabaseLoader sqlLoader = new SqlDatabaseLoader(dbTool.Connection, false);
Sql.Database sqlDatabase = sqlLoader.Database;
DatabaseComparer comparer = new DatabaseComparer(sqlDatabase, schemaDatabase);
DatabaseUpdatesHelper helper = new DatabaseUpdatesHelper(comparer);
ApplicationLoader appLoader = new ApplicationLoader(appRootNode);
Console.WriteLine();
Console.WriteLine("The following changes will be made to the database:");
Console.WriteLine(helper.GetTableUpdatesSummary());
Console.WriteLine(helper.GetConstraintUpdatesSummary());
Console.WriteLine(helper.GetFieldUpdatesSummary());
getUserConfirmation();
Console.WriteLine("UPDATING DATABASE...");
UpdateTablesConstraints(helper);
generateSprocs(appLoader.Application);
Console.WriteLine("DATABASE UPDATES COMPLETE\nGENERATING CODE...");
generateCode(appLoader.Application);
Console.WriteLine("CODE GENERATION COMPLETE!");
}
catch (Exception e)
{
Console.Error.WriteLine("Process aborted due to the following problem:");
Console.Error.WriteLine(e.Message + "\n" + e.ToString());
}
}
public void UpdateTablesConstraints(DatabaseUpdatesHelper helper)
{
StringBuilder sb = new StringBuilder();
sb.Append(helper.GetDropConstraintsScript()); //drop ALL constraints
sb.Append(helper.GetDropTablesScript()); //drop tables (DeleteTables collection)
sb.Append(helper.GetCreateTablesScript()); //create tables (AddTables collection)
sb.Append(helper.GetAlterTablesScript(true)); //alter table fields WITHOUT null edits
sb.Append(helper.GetCreateConstraintsScript()); //create ALL constraints
sb.Append(helper.GetAlterTablesScript(false)); //alter table fields with null edits
dbTool.executeSql(sb.ToString());
}
private void generateSprocs(a.ApplicationObject application)
{
foreach (a.NamespaceObject n in application.NamespacesList)
{
foreach (a.ClassObject c in n.NonLinkClassesList)
new RecordSprocGenerator(c, dbTool).CreateProcedures();
foreach (a.ClassObject c in n.LinkClassesList)
new LinkSprocGenerator(c, dbTool).CreateProcedures();
}
}
private void generateCode(a.ApplicationObject application)
{
Code.ClassGenerator g, g1, g2, g3, g4, g5;
foreach (a.NamespaceObject n in application.NamespacesList)
foreach (a.ClassObject c in n.ClassesList)
if (c.Type == a.ClassType.Link)
{
g = new Code.Cs.LinkClassGenerator(c, parentNamespace);
writeFile(c.Namespace.Name, g.GetFileName(), g.GetCode());
}
else
{
g1 = new Code.Cs.InstanceClassGenerator(c, parentNamespace);
g2 = new Code.Cs.TableClassGenerator(c, parentNamespace);
g3 = new Code.Cs.ListClassGenerator(c, parentNamespace);
g4 = new Code.Cs.DataClassGenerator(c, parentNamespace);
writeFile(c.Namespace.Name, g1.GetFileName(), g1.GetCode());
writeFile(c.Namespace.Name, g2.GetFileName(), g2.GetCode());
writeFile(c.Namespace.Name, g3.GetFileName(), g3.GetCode());
writeFile(c.Namespace.Name, g4.GetFileName(), g4.GetCode());
foreach (a.SprocObject sproc in c.CustomReturnTypeSprocsList)
{
g5 = new Code.Cs.CustomTableClassGenerator(c, parentNamespace, sproc);
writeFile(c.Namespace.Name, g5.GetFileName(), g5.GetCode());
}
}
}
private void writeFile(string subdir, string fileName, string code)
{
if (!Directory.Exists(outputDir))
Directory.CreateDirectory(outputDir);
if (!Directory.Exists(outputDir + "\\" + subdir))
Directory.CreateDirectory(outputDir + "\\" + subdir);
StreamWriter writer = File.CreateText(outputDir + "\\" + subdir + "\\" + fileName);
writer.Write(code);
writer.Flush();
writer.Close();
}
private string getSchemaFile()
{
string path;
while (true)
{
Console.WriteLine("Please provide the schema file path or type 'N' to abort");
path = Console.ReadLine();
if (path != "")
if (path == "N" || path == "n")
System.Environment.Exit(0);
if (File.Exists(path))
return path;
else
Console.WriteLine("File not found");
}
}
private void getUserConfirmation()
{
string input;
while (true)
{
Console.WriteLine();
Console.WriteLine("To proceed with these updates type 'yes', to abort type 'N'");
input = Console.ReadLine();
if (input != "")
if (string.Compare(input, "N", true) == 0)
{
Console.WriteLine("UPDATE ABORTED");
System.Environment.Exit(0);
}
else if (string.Compare(input, "yes", true) == 0)
return;
}
}
private DatabaseTool dbTool;
private string schemaPath;
private string parentNamespace;
private string outputDir;
private bool isCs;
}
}
| 41.561111 | 103 | 0.548723 | [
"MIT"
] | ic4f/codegenerator | CodeGenerator/Main.cs | 7,481 | C# |
using Microsoft.AspNetCore.Http;
using System.Threading.Tasks;
namespace Toggly.FeatureManagement.Web
{
public class HttpFeatureContextProvider : IFeatureContextProvider
{
private readonly IHttpContextAccessor _httpContextAccessor;
public HttpFeatureContextProvider(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
public Task<bool> AccessedInRequestAsync(string featureName)
{
if (_httpContextAccessor.HttpContext == null)
return Task.FromResult(true);
if (_httpContextAccessor.HttpContext.Items.ContainsKey($"feature-{featureName}"))
return Task.FromResult(true);
else
_httpContextAccessor.HttpContext.Items.Add($"feature-{featureName}", true);
return Task.FromResult(false);
}
public Task<bool> AccessedInRequestAsync<TContext>(string featureName, TContext context)
{
if (_httpContextAccessor.HttpContext == null)
return Task.FromResult(true);
if (_httpContextAccessor.HttpContext.Items.ContainsKey($"feature-{featureName}"))
return Task.FromResult(true);
else
_httpContextAccessor.HttpContext.Items.Add($"feature-{featureName}", true);
return Task.FromResult(false);
}
public Task<string> GetContextIdentifierAsync()
{
if (_httpContextAccessor.HttpContext == null)
return Task.FromResult("");
if (_httpContextAccessor.HttpContext.User != null && _httpContextAccessor.HttpContext.User.Identity?.Name != null)
return Task.FromResult(_httpContextAccessor.HttpContext.User.Identity.Name!);
return Task.FromResult(_httpContextAccessor.HttpContext.Connection.RemoteIpAddress.ToString());
}
public Task<string> GetContextIdentifierAsync<TContext>(TContext context)
{
if (_httpContextAccessor.HttpContext == null)
return Task.FromResult("");
if (_httpContextAccessor.HttpContext.User != null && _httpContextAccessor.HttpContext.User.Identity?.Name != null)
return Task.FromResult(_httpContextAccessor.HttpContext.User.Identity.Name!);
return Task.FromResult(_httpContextAccessor.HttpContext.Connection.RemoteIpAddress.ToString());
}
}
} | 40.639344 | 126 | 0.657927 | [
"MIT"
] | ops-ai/Toggly.FeatureManagement | Toggly.FeatureManagement.Web/HttpFeatureContextProvider.cs | 2,481 | C# |
/*
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/.
Copyright (C) 2012-2015 Michael Möller <mmoeller@openhardwaremonitor.org>
*/
using System.Collections.Generic;
using OpenHardwareMonitor.Collections;
namespace OpenHardwareMonitor.Hardware.HDD {
[NamePrefix(""), RequireSmart(0xAA), RequireSmart(0xAB), RequireSmart(0xAC),
RequireSmart(0xAD), RequireSmart(0xAE), RequireSmart(0xCA)]
internal class SSDMicron : AbstractHarddrive {
private static readonly IEnumerable<SmartAttribute> smartAttributes =
new List<SmartAttribute> {
new SmartAttribute(0x01, SmartNames.ReadErrorRate, RawToInt),
new SmartAttribute(0x05, SmartNames.ReallocatedSectorsCount, RawToInt),
new SmartAttribute(0x09, SmartNames.PowerOnHours, RawToInt),
new SmartAttribute(0x0C, SmartNames.PowerCycleCount, RawToInt),
new SmartAttribute(0xAA, SmartNames.NewFailingBlockCount, RawToInt),
new SmartAttribute(0xAB, SmartNames.ProgramFailCount, RawToInt),
new SmartAttribute(0xAC, SmartNames.EraseFailCount, RawToInt),
new SmartAttribute(0xAD, SmartNames.WearLevelingCount, RawToInt),
new SmartAttribute(0xAE, SmartNames.UnexpectedPowerLossCount, RawToInt),
new SmartAttribute(0xB5, SmartNames.Non4kAlignedAccess,
(byte[] raw, byte value, IReadOnlyArray<IParameter> p)
=> { return 6e4f * ((raw[5] << 8) | raw[4]); }),
new SmartAttribute(0xB7, SmartNames.SataDownshiftErrorCount, RawToInt),
new SmartAttribute(0xBB, SmartNames.ReportedUncorrectableErrors, RawToInt),
new SmartAttribute(0xBC, SmartNames.CommandTimeout, RawToInt),
new SmartAttribute(0xBD, SmartNames.FactoryBadBlockCount, RawToInt),
new SmartAttribute(0xC4, SmartNames.ReallocationEventCount, RawToInt),
new SmartAttribute(0xC5, SmartNames.CurrentPendingSectorCount),
new SmartAttribute(0xC6, SmartNames.OffLineUncorrectableErrorCount, RawToInt),
new SmartAttribute(0xC7, SmartNames.UltraDmaCrcErrorCount, RawToInt),
new SmartAttribute(0xCA, SmartNames.RemainingLife,
(byte[] raw, byte value, IReadOnlyArray<IParameter> p)
=> { return 100 - RawToInt(raw, value, p); },
SensorType.Level, 0, SmartNames.RemainingLife),
new SmartAttribute(0xCE, SmartNames.WriteErrorRate,
(byte[] raw, byte value, IReadOnlyArray<IParameter> p)
=> { return 6e4f * ((raw[1] << 8) | raw[0]); }),
};
public SSDMicron(ISmart smart, string name, string firmwareRevision,
int index, ISettings settings)
: base(smart, name, firmwareRevision, index, smartAttributes, settings) {}
}
}
| 49.894737 | 85 | 0.714135 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | Epsil0neR/openhardwaremonitor-core | Hardware/HDD/SSDMicron.cs | 2,847 | C# |
namespace ProcessesTheater.Core
{
using System.Threading;
/// <summary>
/// Cause interface.
/// </summary>
public interface ICause
{
/// <summary>
/// Check cause for effect.
/// </summary>
/// <param name="cancellationToken"> Cancellation token. </param>
/// <returns> The <see cref="IEffect"/>. </returns>
IEffect Check(CancellationToken cancellationToken);
}
} | 26 | 73 | 0.579186 | [
"MIT"
] | vasmanas/ProcessesTheater | src/ProcessesTheater.Core/ICause.cs | 444 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using hf.Models;
using hf.Repository;
namespace hf.Controllers
{
public class OrderController : Controller
{
private IEnumerable<Ticket> tickets = new List<Ticket>();
private IOrderRepository repoOrder = new OrderRepository();
// GET: Order
[HttpGet]
public ActionResult Index()
{
//check cart session en slaat het op in globaal variabel tickets
if(Session["Cart"] != null)
{
tickets = Session["Cart"] as List<Ticket>;
}
return View();
}
// Create new order
[HttpPost]
public ActionResult Index(string userMail)
{
//check cart session en slaat het op in globaal variabel tickets
if (Session["Cart"] != null)
{
tickets = Session["Cart"] as List<Ticket>;
}
//check if key already exists
string key = GenerateKey();
bool isUniekkey = repoOrder.CheckifKeyExist(key);
do {
key = GenerateKey();
isUniekkey = repoOrder.CheckifKeyExist(key);
} while (isUniekkey == true);
//create order object
Order order = new Order()
{
PaymentReceived = true,
OrderKey = key,
Tickets = tickets,
Email = userMail,
};
//modify tickets and add order
foreach (Ticket ticket in tickets)
{
ticket.OrderId = order.Id;
ticket.Order = order;
ticket.Event = repoOrder.GetEventByEvent(ticket.Event);
}
//modify order
order.Tickets = tickets;
string orderStatus = "There was something wrong.";
if (tickets != null)
{
repoOrder.CreateOrder(order);
orderStatus = "Successfully ordered!";
}
return RedirectToAction("orderStatus", "Order", new { status = orderStatus, orderkey = key});
}
private string GenerateKey()
{
string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
char[] stringchars = new char[8];
Random random = new Random();
for (int i = 0; i < stringchars.Length; i++)
{
stringchars[i] = chars[random.Next(chars.Length)];
}
String finalstring = new String(stringchars);
return finalstring;
}
public ActionResult orderStatus(string status, string orderkey)
{
ViewBag.orderStatus = status;
ViewBag.key = orderkey;
//clear session
Session.Clear();
return View();
}
// GET: Order/Create
public ActionResult Create()
{
return View();
}
}
}
| 27.109244 | 105 | 0.518289 | [
"Apache-2.0"
] | Lyntier/haarlemfestival | hf/Controllers/OrderController.cs | 3,228 | C# |
// Url:https://leetcode.com/problems/largest-time-for-given-digits
/*
949. Largest Time for Given Digits
Easy
Given an array of 4 digits, return the largest 24 hour time that can be made.
The smallest 24 hour time is 00:00, and the largest is 23:59.  Starting from 00:00, a time is larger if more time has elapsed since midnight.
Return the answer as a string of length 5.  If no valid time can be made, return an empty string.
 
Example 1:
Input: [1,2,3,4]
Output: "23:41"
Example 2:
Input: [5,5,5,5]
Output: ""
 
Note:
A.length == 4
0 <= A[i] <= 9
*/
using System;
namespace InterviewPreperationGuide.Core.LeetCode.Solution949
{
public class Solution
{
public void Init() { }
public string LargestTimeFromDigits(int[] A) { }
}
}
| 16.877551 | 146 | 0.679565 | [
"MIT"
] | tarunbatta/leetcodeScraper | problems/cs/949.cs | 827 | C# |
using UnityEngine;
using UnityEngine.UI;
/** */
public class UI_updater : MonoBehaviour
{
public Text gem_text; /*!< Reference to a text object in the UI */
private int gems_aquired = 0; /*!< Internal count of the gems collected */
private int total_gems = 0; /*!< Internal count of the gems collected */
private string base_text = "Gems: "; /*! Base UI text */
/** Start is called before the first frame update. Initialise the text showing in the UI */
void Start()
{
gem_text.text+=gems_aquired;
total_gems=crystal_manager.crystal_count();
}
/** Get the current collected gems from the crystal manager and add it to the UI text object */
private void update_text()
{
gems_aquired=crystal_manager.collected_amount();
gem_text.text=base_text+$"{gems_aquired}/{total_gems}";
}
/** Update is called once per frame. Update the UI text to the current amount collected */
void Update()
{
update_text();
}
}
| 29.457143 | 99 | 0.645975 | [
"MIT"
] | Kiandisor/Walking-Simulator-Assessment | Assets/Scripts/UI/UI_updater.cs | 1,033 | C# |
using System;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using NLog;
using NLog.Web;
using LogLevel = Microsoft.Extensions.Logging.LogLevel;
namespace ExamQuestion
{
public class Program
{
public static void Main(string[] args)
{
var logger = NLogBuilder.ConfigureNLog("nLog.config").GetCurrentClassLogger();
try
{
logger.Debug("init main");
CreateHostBuilder(args).Build().Run();
}
catch (Exception ex)
{
//NLog: catch setup errors
logger.Error(ex, "Stopped program because of exception");
throw;
}
finally
{
// Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux)
LogManager.Shutdown();
}
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args).ConfigureWebHostDefaults(webBuilder => webBuilder.UseStartup<Startup>())
.ConfigureLogging(logging =>
{
logging.ClearProviders();
logging.SetMinimumLevel(LogLevel.Trace);
}).UseNLog();
}
} | 29.978261 | 127 | 0.568528 | [
"MIT"
] | rtbsoft/examQuestionCore | ExamQuestion/Program.cs | 1,379 | C# |
using System;
namespace MoneyManager.SaraivaDev.API.Models.Dto
{
public class EntryCollectionListDto
{
public string Id { get; set; }
public string AccountId { get; set; }
public short EntryType { get; set; }
public DateTime EntryConfirmedDate { get; set; }
public DateTime EntryDate { get; set; }
public decimal EntryValue { get; set; }
public string CategoryId { get; set; }
public string CostCenterId { get; set; }
public string PaymentTypeId { get; set; }
}
}
| 30.555556 | 56 | 0.627273 | [
"MIT"
] | carlosaraiva/MoneyManager | MoneyManager.SaraivaDev.API/Models/Dto/EntryCollectionListDto.cs | 552 | C# |
using MediaBrowser.Common;
using MediaBrowser.Common.Updates;
using MediaBrowser.Model.Updates;
using MediaBrowser.Theater.Interfaces.Navigation;
using MediaBrowser.Theater.Interfaces.Presentation;
using MediaBrowser.Theater.Interfaces.ViewModels;
using System;
using System.Linq;
using System.Threading;
using System.Windows.Data;
namespace MediaBrowser.Theater.Core.Plugins
{
public class PluginCategoryListViewModel : BaseViewModel
{
private readonly IPresentationManager _presentationManager;
private readonly IInstallationManager _installationManager;
private readonly INavigationService _nav;
private readonly IApplicationHost _appHost;
private readonly RangeObservableCollection<PluginCategoryViewModel> _listItems = new RangeObservableCollection<PluginCategoryViewModel>();
private ListCollectionView _listCollectionView;
public PluginCategoryListViewModel(IPresentationManager presentationManager, IInstallationManager installationManager, INavigationService nav, IApplicationHost appHost)
{
_presentationManager = presentationManager;
_installationManager = installationManager;
_nav = nav;
_appHost = appHost;
}
public ListCollectionView ListCollectionView
{
get
{
if (_listCollectionView == null)
{
_listCollectionView = new ListCollectionView(_listItems);
ReloadList();
}
return _listCollectionView;
}
private set
{
var changed = _listCollectionView != value;
_listCollectionView = value;
if (changed)
{
OnPropertyChanged("ListCollectionView");
}
}
}
public int PluginCount
{
get { return _listItems.Count; }
}
private async void ReloadList()
{
try
{
var packages = await _installationManager.GetAvailablePackagesWithoutRegistrationInfo(CancellationToken.None);
packages = packages.Where(i => i.versions != null && i.versions.Count > 0);
_listItems.Clear();
var categories = packages
.Where(i => i.type == PackageType.UserInstalled && i.targetSystem == PackageTargetSystem.MBTheater)
.OrderBy(i => string.IsNullOrEmpty(i.category) ? "General" : i.category)
.GroupBy(i => string.IsNullOrEmpty(i.category) ? "General" : i.category)
.ToList();
_listItems.AddRange(categories.Select(i => new PluginCategoryViewModel(_presentationManager, _installationManager, _nav, _appHost)
{
Name = i.Key,
Packages = i.Select(p => new PackageInfoViewModel(_installationManager, _nav)
{
PackageInfo = p
}).ToList()
}));
}
catch (Exception)
{
_presentationManager.ShowDefaultErrorMessage();
}
}
}
}
| 34.208333 | 176 | 0.595006 | [
"MIT"
] | thogil/MediaBrowser.Theater | MediaBrowser.Theater.Core/Plugins/PluginCategoryListViewModel.cs | 3,286 | C# |
using System;
namespace MaryHelp.Util
{
public static class Utilities
{
public static double ConvertTimeBase60To100(double hour)
{
double hrReturn;
int result;
if (!int.TryParse(hour.ToString(), out result))
{
string minutesBase100 = hour.ToString().Substring(hour.ToString().IndexOf('.'));
minutesBase100 = ((Convert.ToDouble(minutesBase100) / 60) * 100).ToString();
hrReturn = Convert.ToDouble(hour.ToString().Substring(0, hour.ToString().IndexOf('.')) + minutesBase100.Substring(minutesBase100.IndexOf('.')));
}
else
hrReturn = hour;
return hrReturn;
}
public static double ConvertTimeBase100To60(double hour)
{
double hrReturn;
int result;
if (!int.TryParse(hour.ToString(), out result))
{
string minutesBase60 = hour.ToString().Substring(hour.ToString().IndexOf('.'));
minutesBase60 = ((Convert.ToDouble(minutesBase60) * 60) / 100).ToString();
hrReturn = Convert.ToDouble(hour.ToString().Substring(0, hour.ToString().IndexOf('.')) + minutesBase60.Substring(minutesBase60.IndexOf('.')));
}
else
hrReturn = hour;
return hrReturn;
}
}
}
| 31.909091 | 160 | 0.551994 | [
"MIT"
] | apezzatto/pulito.NET | MaryHelp/Util/Util.cs | 1,406 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
namespace Aeon.Emulator.Memory
{
/// <summary>
/// Simple memory allocator for reserving regions of conventional memory.
/// </summary>
internal sealed class MetaAllocator
{
private readonly LinkedList<Allocation> allocations = new LinkedList<Allocation>();
public MetaAllocator() => this.Clear();
/// <summary>
/// Clears all allocations and resets the allocator to its initial state.
/// </summary>
public void Clear()
{
lock (this.allocations)
{
this.allocations.Clear();
this.allocations.AddLast(new Allocation(0, PhysicalMemory.ConvMemorySize >> 4, false));
}
}
/// <summary>
/// Reserves a new block of memory.
/// </summary>
/// <param name="minimumSegment">Minimum requested segment to return.</param>
/// <param name="bytes">Number of bytes requested.</param>
/// <returns>Starting segment of the requested block of memory.</returns>
public ushort Allocate(ushort minimumSegment, int bytes)
{
if (bytes <= 0)
throw new ArgumentOutOfRangeException("bytes");
uint paragraphs = (uint)(bytes >> 4);
if ((bytes % 16) != 0)
paragraphs++;
lock (this.allocations)
{
Allocation freeBlock;
try
{
freeBlock = this.allocations.Where(a => !a.IsUsed && InRange(a, minimumSegment, paragraphs)).First();
}
catch (InvalidOperationException ex)
{
throw new InvalidOperationException("Not enough conventional memory.", ex);
}
if (freeBlock.Length == paragraphs)
{
freeBlock.IsUsed = true;
return freeBlock.Segment;
}
var providedSegment = Math.Max(minimumSegment, freeBlock.Segment);
var newFreeBlockA = new Allocation(freeBlock.Segment, (uint)providedSegment - (uint)freeBlock.Segment, false);
var newUsedBlock = new Allocation(providedSegment, paragraphs, true);
var newFreeBlockB = new Allocation((ushort)(providedSegment + paragraphs), freeBlock.Length - newFreeBlockA.Length - paragraphs, false);
var newBlocks = new List<Allocation>(3);
if (newFreeBlockA.Length > 0)
newBlocks.Add(newFreeBlockA);
newBlocks.Add(newUsedBlock);
if (newFreeBlockB.Length > 0)
newBlocks.Add(newFreeBlockB);
this.allocations.Replace(freeBlock, newBlocks.ToArray());
return newUsedBlock.Segment;
}
}
/// <summary>
/// Returns the size of the largest free block of memory.
/// </summary>
/// <returns>Size in bytes of the largest free block of memory.</returns>
public uint GetLargestFreeBlockSize()
{
lock (this.allocations)
{
return this.allocations.Where(a => !a.IsUsed).Max(a => a.Length) << 4;
}
}
/// <summary>
/// Returns a value indicating whether an allocation contains an address range.
/// </summary>
/// <param name="a">Allocation to test.</param>
/// <param name="segment">Minimum requested segment address.</param>
/// <param name="length">Requested allocation length.</param>
/// <returns>True if allocation is acceptable; otherwise false.</returns>
private static bool InRange(Allocation a, ushort segment, uint length)
{
if (a.Segment + a.Length >= segment + length)
return true;
if (a.Segment >= segment && a.Length >= length)
return true;
return false;
}
/// <summary>
/// Describes a conventional memory allocation.
/// </summary>
private sealed class Allocation : IEquatable<Allocation>
{
/// <summary>
/// The starting segment of the allocation.
/// </summary>
public ushort Segment;
/// <summary>
/// Indicates whether the allocation is in use or a free block.
/// </summary>
public bool IsUsed;
/// <summary>
/// The length of the allocation in 16-byte paragraphs.
/// </summary>
public uint Length;
/// <summary>
/// Initializes a new instance of the Allocation class.
/// </summary>
/// <param name="segment">The starging segment of the allocation.</param>
/// <param name="length">The length of the allocation in 16-byte paragraphs.</param>
/// <param name="isUsed">Indicates whether the allocation is in use or a free block.</param>
public Allocation(ushort segment, uint length, bool isUsed)
{
this.Segment = segment;
this.Length = length;
this.IsUsed = isUsed;
}
public bool Equals(Allocation other)
{
if (other == null)
return false;
return this.Segment == other.Segment && this.IsUsed == other.IsUsed && this.Length == other.Length;
}
public override bool Equals(object obj) => Equals(obj as Allocation);
public override int GetHashCode() => this.Segment;
public override string ToString() => $"{this.Segment:X4}: {this.Length}";
}
}
}
| 38.328947 | 152 | 0.543426 | [
"Apache-2.0"
] | gregdivis/Aeon | src/Aeon.Emulator/Memory/MetaAllocator.cs | 5,828 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
namespace CoralEngine
{
public class Marker : Entity
{
}
}
| 20.25 | 39 | 0.780864 | [
"MIT"
] | AngeloG/Coral | Entities/Marker.cs | 326 | C# |
using CommandLine;
namespace Teronis.DotNet.Build.CommandOptions
{
[Verb(PackCommand)]
public class PackCommandOptions : CommandOptionsBase
{
public const string PackCommand = "pack";
public override string Command => PackCommand;
}
}
| 20.769231 | 56 | 0.7 | [
"MIT"
] | BrunoZell/Teronis.DotNet | src/DotNet/Build/Build/src/CommandOptions/PackCommandOptions.cs | 272 | C# |
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Pathoschild.Stardew.Common;
using StardewModdingAPI;
namespace Pathoschild.Stardew.ChestsAnywhere.Framework
{
/// <summary>The mod configuration.</summary>
internal class ModConfig
{
/*********
** Accessors
*********/
/// <summary>Whether to show the chest name in a tooltip when you point at a chest.</summary>
public bool ShowHoverTooltips { get; set; } = true;
/// <summary>Whether to enable access to the shipping bin.</summary>
public bool EnableShippingBin { get; set; } = true;
/// <summary>The range at which chests are accessible.</summary>
[JsonConverter(typeof(StringEnumConverter))]
public ChestRange Range { get; set; } = ChestRange.Unlimited;
/// <summary>The control bindings.</summary>
public ModConfigControls Controls { get; set; } = new ModConfigControls();
/// <summary>The locations in which to disable remote chest lookups.</summary>
public string[] DisabledInLocations { get; set; } = new string[0];
/*********
** Nested models
*********/
/// <summary>A set of control bindings.</summary>
internal class ModConfigControls
{
/// <summary>The control which toggles the chest UI.</summary>
[JsonConverter(typeof(StringEnumArrayConverter))]
public SButton[] Toggle { get; set; } = { SButton.B };
/// <summary>The control which navigates to the previous chest.</summary>
[JsonConverter(typeof(StringEnumArrayConverter))]
public SButton[] PrevChest { get; set; } = { SButton.Left, SButton.LeftShoulder };
/// <summary>The control which navigates to the next chest.</summary>
[JsonConverter(typeof(StringEnumArrayConverter))]
public SButton[] NextChest { get; set; } = { SButton.Right, SButton.RightShoulder };
/// <summary>The control which navigates to the previous category.</summary>
[JsonConverter(typeof(StringEnumArrayConverter))]
public SButton[] PrevCategory { get; set; } = { SButton.Up, SButton.LeftTrigger };
/// <summary>The control which navigates to the next category.</summary>
[JsonConverter(typeof(StringEnumArrayConverter))]
public SButton[] NextCategory { get; set; } = { SButton.Down, SButton.RightTrigger };
/// <summary>The control which edits the current chest.</summary>
[JsonConverter(typeof(StringEnumArrayConverter))]
public SButton[] EditChest { get; set; } = new SButton[0];
/// <summary>The control which sorts items in the chest.</summary>
[JsonConverter(typeof(StringEnumArrayConverter))]
public SButton[] SortItems { get; set; } = new SButton[0];
}
}
}
| 43.507463 | 101 | 0.626758 | [
"MIT"
] | CrimsonTautology/StardewMods | ChestsAnywhere/Framework/ModConfig.cs | 2,915 | C# |
using component.logger.data.log.Model;
using component.logger.data.log.Repositories;
using component.logger.platform.common.Enums;
using System;
using System.Collections.Generic;
using System.Linq;
namespace component.logger.platform.common
{
public class LogConfigurations
{
#region Private Variable
private static LogConfigurations instance;
private static List<ComponentConfiguration> componentConfigurationList;
private static List<LogConfiguration> listLogConfiguration;
private static List<Component> listLogComponent;
static readonly Object _lock = new Object();
static readonly Object _lockConfig = new Object();
static readonly Object _lockConfigObject = new Object();
static readonly Object _lockLogConfig = new Object();
static readonly Object _lockLogComponent = new Object();
#endregion
#region Singleton Implementation
private LogConfigurations()
{
componentConfigurationList = new List<ComponentConfiguration>();
listLogConfiguration = new List<LogConfiguration>();
listLogComponent = new List<Component>();
}
public static LogConfigurations Instance
{
get
{
if (instance == null)
{
lock (_lock)
{
if (instance == null)
{
instance = new LogConfigurations();
}
}
}
return instance;
}
}
public ComponentConfiguration AddComponentConfiguration(string applicationCode, string logger)
{
lock (_lockConfig)
{
LogManagementRepository logManagementRepository = new LogManagementRepository();
bool isSucess = logManagementRepository.AddComponentConfiguration(applicationCode, logger);
return GetConfiguration(applicationCode, logger);
}
}
public ComponentConfiguration GetConfiguration(string applicationCode, string logger)
{
lock (_lockConfig)
{
if (applicationCode == null)
applicationCode = string.Empty;
if (componentConfigurationList.FirstOrDefault(x => string.Equals(x.ApplicationCode, applicationCode, StringComparison.CurrentCulture)) == null)
{
LogManagementRepository logManagementRepository = new LogManagementRepository();
DataResponse<List<ComponentConfiguration>> dataResponse = logManagementRepository.LogComponentList(applicationCode);
lock (_lockConfigObject)
{
if (dataResponse != null && dataResponse.Data != null && dataResponse.Data.Count > 0)
{
componentConfigurationList.AddRange(dataResponse.Data);
return componentConfigurationList.FirstOrDefault(x => x.Component.Name.Equals(logger, StringComparison.CurrentCultureIgnoreCase) && string.Equals(x.ApplicationCode, applicationCode, StringComparison.CurrentCulture));
}
else if ((componentConfigurationList == null && componentConfigurationList.Count == 0) || !componentConfigurationList.Exists(x => x.ApplicationCode == string.Empty))
{
DataResponse<List<ComponentConfiguration>> dataResponseEmptyApp = logManagementRepository.LogComponentList(string.Empty);
if (dataResponseEmptyApp != null && dataResponseEmptyApp.Data != null)
componentConfigurationList.AddRange(dataResponseEmptyApp.Data);
}
}
}
}
return componentConfigurationList.FirstOrDefault(x => x.Component.Name.Equals(logger, StringComparison.CurrentCultureIgnoreCase) && x.ApplicationCode == applicationCode);
}
public LogConfiguration GetLogSeverity(LogSeverity logSeverity)
{
lock (_lockLogConfig)
{
if (listLogConfiguration == null || listLogConfiguration.Count == 0)
{
LogManagementRepository logManagementRepository = new LogManagementRepository();
DataResponse<List<LogConfiguration>> dataResponse = logManagementRepository.GetSeverityList();
listLogConfiguration = dataResponse.Data;
}
}
return listLogConfiguration.FirstOrDefault(x => x.Type.Equals(Convert.ToString(logSeverity), StringComparison.CurrentCultureIgnoreCase));
}
public Component GetLogComponents(string logComponent)
{
lock (_lockLogComponent)
{
if (listLogComponent == null || listLogComponent.Count == 0)
{
LogManagementRepository logManagementRepository = new LogManagementRepository();
DataResponse<List<Component>> dataResponse = logManagementRepository.ComponentList();
listLogComponent = dataResponse.Data;
}
}
return listLogComponent.FirstOrDefault(x => x.Name.Equals(Convert.ToString(logComponent), StringComparison.CurrentCultureIgnoreCase));
}
#endregion
}
}
| 44.927419 | 244 | 0.603482 | [
"MIT"
] | iotconnect-apps/AppConnect-AirQualityMonitoring | iot.solution.log.common/LogConfigurations.cs | 5,573 | 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("Open-Lab-05.03")]
[assembly: System.Reflection.AssemblyConfigurationAttribute("Release")]
[assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")]
[assembly: System.Reflection.AssemblyProductAttribute("Open-Lab-05.03")]
[assembly: System.Reflection.AssemblyTitleAttribute("Open-Lab-05.03")]
[assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")]
// Generated by the MSBuild WriteCodeFragment class.
| 42.375 | 81 | 0.628319 | [
"MIT"
] | Ondrejmuran4691/Open-Lab-05.03 | Open-Lab-05.03/Open-Lab-05.03/obj/Release/netcoreapp3.0/Open-Lab-05.03.AssemblyInfo.cs | 1,017 | C# |
namespace MandateThat
{
public class MandateContext<T>
{
protected internal MandateContext(MandateContext<T> parentContext) : this(parentContext.ParamName,
parentContext.Value)
{
ParentContext = parentContext;
ParentContext.HasChild = true;
}
protected internal MandateContext(string paramName, T value)
{
ParamName = paramName;
Value = value;
}
public bool HasChild { get; protected set; }
public MandateContext<T> ParentContext { get; }
public string ParamName { get; }
public T Value { get; }
}
} | 27.291667 | 106 | 0.593893 | [
"MIT"
] | lyonl/MandateThat | MandateThat/MandateContext.cs | 657 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System.Collections.Generic;
using System.Text.Json;
using Azure.Core;
namespace Azure.Management.Network.Models
{
public partial class EffectiveNetworkSecurityGroup
{
internal static EffectiveNetworkSecurityGroup DeserializeEffectiveNetworkSecurityGroup(JsonElement element)
{
SubResource networkSecurityGroup = default;
EffectiveNetworkSecurityGroupAssociation association = default;
IReadOnlyList<EffectiveNetworkSecurityRule> effectiveSecurityRules = default;
string tagMap = default;
foreach (var property in element.EnumerateObject())
{
if (property.NameEquals("networkSecurityGroup"))
{
if (property.Value.ValueKind == JsonValueKind.Null)
{
continue;
}
networkSecurityGroup = SubResource.DeserializeSubResource(property.Value);
continue;
}
if (property.NameEquals("association"))
{
if (property.Value.ValueKind == JsonValueKind.Null)
{
continue;
}
association = EffectiveNetworkSecurityGroupAssociation.DeserializeEffectiveNetworkSecurityGroupAssociation(property.Value);
continue;
}
if (property.NameEquals("effectiveSecurityRules"))
{
if (property.Value.ValueKind == JsonValueKind.Null)
{
continue;
}
List<EffectiveNetworkSecurityRule> array = new List<EffectiveNetworkSecurityRule>();
foreach (var item in property.Value.EnumerateArray())
{
if (item.ValueKind == JsonValueKind.Null)
{
array.Add(null);
}
else
{
array.Add(EffectiveNetworkSecurityRule.DeserializeEffectiveNetworkSecurityRule(item));
}
}
effectiveSecurityRules = array;
continue;
}
if (property.NameEquals("tagMap"))
{
if (property.Value.ValueKind == JsonValueKind.Null)
{
continue;
}
tagMap = property.Value.GetString();
continue;
}
}
return new EffectiveNetworkSecurityGroup(networkSecurityGroup, association, effectiveSecurityRules, tagMap);
}
}
}
| 38.558442 | 143 | 0.510946 | [
"MIT"
] | AzureDataBox/azure-sdk-for-net | sdk/testcommon/Azure.Management.Network.2020_04/src/Generated/Models/EffectiveNetworkSecurityGroup.Serialization.cs | 2,969 | C# |
using Microsoft.EntityFrameworkCore.Migrations;
using System;
using System.Collections.Generic;
namespace EventManagement.Registration.Data.Migrations
{
public partial class Initial : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
}
protected override void Down(MigrationBuilder migrationBuilder)
{
}
}
}
| 19.95 | 71 | 0.699248 | [
"MIT"
] | atanas-georgiev/EventManagement | EventManagement.Registration/EventManagement.Registration.Data/Migrations/20180321114956_Initial.cs | 401 | C# |
using DevPodcasts.DataLayer.Models;
using MediatR;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
namespace DevPodcasts.Web.Features.Library
{
public class ListEpisodes
{
public class Query : IRequest<ViewModel>
{
public string UserId { get; set; }
}
public class QueryHandler : IAsyncRequestHandler<Query, ViewModel>
{
private readonly ApplicationDbContext _context;
public QueryHandler(ApplicationDbContext context)
{
_context = context;
}
public async Task<ViewModel> Handle(Query message)
{
var viewModel = new ViewModel();
var bookmarkedEpisodes = await _context.LibraryEpisodes
.Where(user => user.UserId == message.UserId)
.OrderByDescending(episode => episode.DateAdded)
.Select(episode => new BookmarkedEpisode
{
EpisodeId = episode.EpisodeId,
EpisodeTitle = episode.Episode.Title,
PodcastTitle = episode.Episode.Podcast.Title
}).ToListAsync();
viewModel.BookmarkedEpisodes = bookmarkedEpisodes;
viewModel.UserId = message.UserId;
return viewModel;
}
}
public class ViewModel
{
public IEnumerable<BookmarkedEpisode> BookmarkedEpisodes { get; set; }
public string UserId { get; set; }
}
public class BookmarkedEpisode
{
public int EpisodeId { get; set; }
public string EpisodeTitle { get; set; }
public string PodcastTitle { get; set; }
}
}
} | 31.40678 | 82 | 0.560173 | [
"MIT"
] | NRKirby/DevPodcasts | src/DevPodcasts.Web/Features/Library/ListEpisodes.cs | 1,855 | C# |
using System;
using System.Collections.Generic;
using SMBSharesUtils;
using CommandLine;
using System.IO;
using System.Linq;
namespace ShareMapperCLI
{
class Program
{
class CommonOptions
{
[Option('d', "debug", Required = false, Default = false)]
public bool Debug { get; set; }
}
class DirScanMTOptions : CommonOptions
{
[Option('C', "dirMaxThreads", Default = 1, HelpText = "How many concurrent threads will be launched during subdirectories scan.")]
public int DirScanMaxThreads { get; set; }
[Option('M', "dirMaxAttemps", Default = 0, HelpText = "How many tries to join a thread before killing a directory scan thread.")]
public int DirScanThreadJoinMaxAttempts { get; set; }
[Option('J', "dirJoinTimeout", Default = 100, HelpText = "How much time in ms the join call will wait a directory scan thread.")]
public int DirScanThreadJoinTimeout { get; set; }
}
class MTOptions : DirScanMTOptions
{
[Option('c', "maxThreads", Default = 1, HelpText = "How many concurrent threads will be launched to scan the hosts.")]
public int MaxThreads { get; set; }
[Option('m', "maxAttemps", Default = 0, HelpText = "How many tries to join a scanning host thread before killing it.")]
public int ThreadJoinMaxAttempts { get; set; }
[Option('j', "joinTimeout", Default = 100, HelpText = "How much time in ms the join call will wait a scanning host thread.")]
public int ThreadJoinTimeout { get; set; }
}
class ScanCommonOptions : MTOptions
{
[Option('r', "recursiveLevel", Default = 0, HelpText = "How deep the scan should go into shares.")]
public int RecursiveLevel { get; set; }
[Option("dns", Default = true, HelpText = "Perform a DNS resolution on host names before scan. If the resolution fails the target will not be scanned. (If the target is an IP address the resolution will not be performed)")]
public bool ResolveHostname { get; set; }
[Option('o', "outReport", Default = "", HelpText = "The filename of the xlsx report.")]
public string OutReport { get; set; }
[Option('s', "sid", HelpText = "File that contains a list of comma separated SID,name that will be used during report generation to resolve SIDs.")]
public string SIDFileIn { get; set; }
[Option('x', "outData", Required = true, HelpText = "File path to save the serialized result to be used for future scan.")]
public string OutData { get; set; }
[Option('b', "blacklist", Default = "", Required = false, HelpText = "List of comma separated shares names to not scan recursively (or file of shares list)")]
public string BlackList { get; set; }
[Option('w', "whitelist", Default = "", Required = false, HelpText = "List of comma separated shares names to scan recursively (or file of shares list)")]
public string WhiteList { get; set; }
}
[Verb("scanSMB", HelpText = "Perform a SMB scan.")]
class SMBOptions : ScanCommonOptions
{
[Option('t', "target", Required = true, HelpText = "Targets to scan.")]
public string Target { get; set; }
[Option("targetType", Default = "hosts", HelpText = "Target type : hosts or file.")]
public string TargetType { get; set; }
}
[Verb("rescanSMB", HelpText = "Perform a new scan on previous result.")]
class RescanSMBOptions : ScanCommonOptions
{
[Option('i', "inputfile", Required = true, HelpText = "Serialized result of a SMB scan.")]
public string InputFile { get; set; }
[Option('n', "newshares", Default = true, HelpText = "Perform a new discovery of hosts' shares and shares' subdirectories.")]
public bool ScanForNewShares { get; set; }
[Option('a', "appendhosts", Default = null, HelpText = "Append the comma separated hosts to the previous result.")]
public string AppendHosts { get; set; }
[Option('f', "appendhostsfile", Default = null, HelpText = "Append file's hosts to the previous result.")]
public string AppendHostsFile { get; set; }
}
[Verb("getSMBShares", HelpText = "Preview SMB shares of host.")]
class GetSMBSharesOptions : CommonOptions
{
[Option('h', "hostname", Required = true, HelpText = "Host to scan.")]
public string HostName { get; set; }
[Option('a', "ACL", HelpText = "Show ACL of every share.", Default = false)]
public bool PrintACL { get; set; }
}
[Verb("scanSMBShareDir", HelpText = "Scan SMB share directories.")]
class ScanSMBShareDirOptions : DirScanMTOptions
{
[Option('t', "target", Required = true, HelpText = "Target to scan.")]
public string target { get; set; }
[Option('p', "path", Required = true, HelpText = "Share path (without host part, ex: C$\\Users\\user_1).")]
public string Path { get; set; }
[Option('r', "recursiveLevel", Default = 0, HelpText = "How deep the scan should go into the paths.")]
public int RecursiveLevel { get; set; }
[Option('o', "outReport", Required = true, Default = "", HelpText = "The filename of the xlsx report.")]
public string OutReport { get; set; }
[Option('s', "sid", HelpText = "File that contains a list of comma separated SID,name that will be used during report generation to resolve SIDs.")]
public string SIDFileIn { get; set; }
[Option("dns", Default = true, HelpText = "Perform a DNS resolution on host names before scan. If the resolution fails the target will not be scanned. (If the target is an IP address the resolution will not be performed)")]
public bool ResolveHostname { get; set; }
}
[Verb("getACL", HelpText = "Get NTFS ACL.")]
class GetACLOptions : CommonOptions
{
[Option('t', "target", Required = true, HelpText = "Target to scan.")]
public string target { get; set; }
}
[Verb("reporter", HelpText = "Generate report of a previous scan.")]
class ReporterOptions : CommonOptions
{
[Option('t', "scantype", Required = true, Default = "SMB")]
public string ScanType { get; set; }
[Option('i', "inputfile", HelpText = "Serialized result.", Required = true)]
public string InputFile { get; set; }
[Option('o', "outputfile", Required = true, HelpText = "Report filename (without extension).")]
public string OutReport { get; set; }
[Option('s', "sid", HelpText = "File that contains a list of comma separated SID,name that will be used during report generation to resolve SIDs.")]
public string SIDFile { get; set; }
}
[Verb("mergeSMB", HelpText = "Merge two scans data into one file.")]
class MergeSMBOptions : CommonOptions
{
[Option('i', "scan1", Required = true, HelpText = "Serialized result.")]
public string InputFile { get; set; }
[Option('m', "scan2", Required = true, HelpText = "Serialized result to merge to scan1.")]
public string InputFile2 { get; set; }
[Option('x', "outData", Required = true, HelpText = "File path to save the merge result.")]
public string OutFile { get; set; }
}
static void SetCommonOptions(CommonOptions options)
{
Config.Debug = options.Debug;
}
static void SetScanCommonOptions(ScanCommonOptions options)
{
Config.TryResolveHostName = options.ResolveHostname;
Config.RecursiveLevel = options.RecursiveLevel;
if (options.BlackList.Length == 0)
{
Config.SharesRecursiveScanBlackList = new List<string>();
}
if (options.BlackList.Contains(",") || !File.Exists(options.BlackList))
{
Config.SharesRecursiveScanBlackList = new List<string>(options.BlackList.Split(','));
}
else
{
Config.SharesRecursiveScanBlackList = new List<string>(File.ReadAllLines(options.BlackList));
}
if (options.WhiteList.Length == 0)
{
Config.SharesScanWhiteList = new List<string>();
}
else if (options.WhiteList.Contains(",") || !File.Exists(options.WhiteList))
{
Config.SharesScanWhiteList = new List<string>(options.WhiteList.Split(','));
}
else
{
Config.SharesScanWhiteList = new List<string>(File.ReadAllLines(options.WhiteList));
}
}
static void SetMTOptions(MTOptions options)
{
Config.MaxThreads = options.MaxThreads;
Config.ThreadJoinTimeout = options.ThreadJoinTimeout;
Config.ThreadJoinMaxAttempts = options.ThreadJoinMaxAttempts;
}
static void SetDirScanMTOptions(DirScanMTOptions options)
{
Config.DirScanMaxThreads = options.DirScanMaxThreads;
Config.DirScanThreadJoinTimeout = options.DirScanThreadJoinTimeout;
Config.DirScanThreadJoinMaxAttempts = options.DirScanThreadJoinMaxAttempts;
}
static int RunscanSMBVerb(SMBOptions options)
{
Dictionary<string, SMBHost> hosts = new Dictionary<string, SMBHost>();
SetCommonOptions(options);
SetScanCommonOptions(options);
SetMTOptions(options);
SetDirScanMTOptions(options);
if (options.TargetType.ToLower() == "hosts")
{
if (options.MaxThreads > 1)
{
hosts = SharesScanner.MTScanHosts(SharesMapperUtils.AddrParser.ParseTargets(options.Target).ToArray());
}
else
{
hosts = SharesScanner.ScanHosts(SharesMapperUtils.AddrParser.ParseTargets(options.Target).ToArray());
}
}
else if (options.TargetType.ToLower() == "file")
{
if (options.MaxThreads > 1)
{
hosts = SharesScanner.MTScanHosts(options.Target);
}
else
{
hosts = SharesScanner.ScanHosts(options.Target);
}
}
else
{
throw new ArgumentException("Unknown targetType value.");
}
SMBSharesMapperSerializer.SerializeHosts(hosts, options.OutData);
if (options.OutReport.Length > 0)
{
if (File.Exists(options.SIDFileIn))
{
ReportGenerator.XLSXReport.LoadSIDResolutionFile(options.SIDFileIn);
}
ReportGenerator.XLSXReport.GenerateSMBHostsReport(hosts, options.OutReport);
ReportGenerator.XLSXReport.SIDCahe.Clear();
}
return 0;
}
static int RunRescanSMBVerb(RescanSMBOptions options)
{
Dictionary<string, SMBHost> hosts;
SetCommonOptions(options);
SetScanCommonOptions(options);
SetMTOptions(options);
SetDirScanMTOptions(options);
Config.ScanForNewShares = options.ScanForNewShares;
Config.ScanForNewSharesRecusiveLevel = options.RecursiveLevel;
Config.ScanForNewSharesTryResolveHostName = options.ResolveHostname;
if (File.Exists(options.InputFile))
{
hosts = SMBSharesMapperSerializer.DeserializeHosts(options.InputFile);
if (hosts == null)
{
return -1;
}
if (options.AppendHosts != null)
{
SharesScanner.AppendHosts(hosts, options.AppendHosts.Split(','), Config.ScanForNewSharesTryResolveHostName);
}
if (options.AppendHostsFile != null)
{
SharesScanner.AppendHosts(hosts, options.AppendHostsFile, Config.ScanForNewSharesTryResolveHostName);
}
if (options.MaxThreads > 1)
{
SharesScanner.MTReScanHosts(hosts);
}
else
{
SharesScanner.ReScanHosts(hosts);
}
SMBSharesMapperSerializer.SerializeHosts(hosts, options.OutData);
if (options.OutReport.Length > 0)
{
if (File.Exists(options.SIDFileIn))
{
ReportGenerator.XLSXReport.LoadSIDResolutionFile(options.SIDFileIn);
}
ReportGenerator.XLSXReport.GenerateSMBHostsReport(hosts, options.OutReport);
ReportGenerator.XLSXReport.SIDCahe.Clear();
}
}
return 0;
}
static int RunReporterVerb(ReporterOptions options)
{
if (options.ScanType.ToUpper() == "SMB")
{
Dictionary<string, SMBHost> hosts;
SetCommonOptions(options);
if (File.Exists(options.InputFile))
{
hosts = SMBSharesMapperSerializer.DeserializeHosts(options.InputFile);
if (hosts == null)
{
return -1;
}
if (options.OutReport.Length > 0)
{
if (File.Exists(options.SIDFile))
{
ReportGenerator.XLSXReport.LoadSIDResolutionFile(options.SIDFile);
}
ReportGenerator.XLSXReport.GenerateSMBHostsReport(hosts, options.OutReport);
ReportGenerator.XLSXReport.SIDCahe.Clear();
}
}
}
return 0;
}
static int RunGetSMBSharesVerb(GetSMBSharesOptions options)
{
SetCommonOptions(options);
Config.PrintACL = options.PrintACL;
SharesScanner.PreviewHostShares(options.HostName);
return 0;
}
static int RunScanSMBShareDir(ScanSMBShareDirOptions options)
{
SetCommonOptions(options);
SetDirScanMTOptions(options);
Config.TryResolveHostName = options.ResolveHostname;
Config.RecursiveLevel = options.RecursiveLevel;
List<ScanDirectoryResult> result = new List<ScanDirectoryResult>();
foreach (string hostname in SharesMapperUtils.AddrParser.ParseTargets(options.target))
{
if (Config.TryResolveHostName && !SharesScanner.TryResolveHostName(hostname))
{
Console.WriteLine("[-][" + DateTime.Now + "] Could not resolve " + hostname);
continue;
}
result.Add(SharesScanner.ScanShareDirectory("\\\\" + hostname + "\\" + options.Path, Config.RecursiveLevel));
}
if (options.OutReport.Length > 0)
{
if (File.Exists(options.SIDFileIn))
{
ReportGenerator.XLSXReport.LoadSIDResolutionFile(options.SIDFileIn);
}
ReportGenerator.XLSXReport.GenerateSMBDirectoryScanResultReport(result, options.OutReport);
ReportGenerator.XLSXReport.SIDCahe.Clear();
}
return 0;
}
static int RunPrintSMBACLVerb(GetACLOptions options)
{
SetCommonOptions(options);
Config.PrintACL = true;
ShareACLUtils.PrintShareAccesses(ShareACLUtils.GetShareDirectoryACL(options.target));
return 0;
}
static int RunMergeSMBVerb(MergeSMBOptions options)
{
Data.MergeScanResult(options.InputFile, options.InputFile2, options.OutFile);
return 0;
}
static void Main(string[] args)
{
var result = Parser.Default.ParseArguments<SMBOptions, RescanSMBOptions, ReporterOptions, MergeSMBOptions, GetSMBSharesOptions, ScanSMBShareDirOptions, GetACLOptions>(args);
result.MapResult(
(SMBOptions opts) => RunscanSMBVerb(opts),
(RescanSMBOptions opts) => RunRescanSMBVerb(opts),
(ReporterOptions opts) => RunReporterVerb(opts),
(GetSMBSharesOptions opts) => RunGetSMBSharesVerb(opts),
(ScanSMBShareDirOptions opts) => RunScanSMBShareDir(opts),
(MergeSMBOptions opts) => RunMergeSMBVerb(opts),
(GetACLOptions opts) => RunPrintSMBACLVerb(opts),
errs => 1
);
}
}
}
| 31.782511 | 226 | 0.696296 | [
"BSD-3-Clause"
] | dabi0ne/SharesMapper | SharesMapperCLI/Program.cs | 14,177 | C# |
#pragma checksum "C:\Users\FOladiji\Engineering45\Labs\Lab_32_MVC_Core\Views\Products\Details.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "84f2141fcd8dfea176d0eb810441bad643922d95"
// <auto-generated/>
#pragma warning disable 1591
[assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCore.Views_Products_Details), @"mvc.1.0.view", @"/Views/Products/Details.cshtml")]
[assembly:global::Microsoft.AspNetCore.Mvc.Razor.Compilation.RazorViewAttribute(@"/Views/Products/Details.cshtml", typeof(AspNetCore.Views_Products_Details))]
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;
#line 1 "C:\Users\FOladiji\Engineering45\Labs\Lab_32_MVC_Core\Views\_ViewImports.cshtml"
using Lab_32_MVC_Core;
#line default
#line hidden
#line 2 "C:\Users\FOladiji\Engineering45\Labs\Lab_32_MVC_Core\Views\_ViewImports.cshtml"
using Lab_32_MVC_Core.Models;
#line default
#line hidden
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"84f2141fcd8dfea176d0eb810441bad643922d95", @"/Views/Products/Details.cshtml")]
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"dfd9d580fd402b2272faa2b0a344347e651cfca6", @"/Views/_ViewImports.cshtml")]
public class Views_Products_Details : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<Lab_32_MVC_Core.Models.Product>
{
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_0 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-action", "Edit", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_1 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-action", "Index", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
#line hidden
#pragma warning disable 0169
private string __tagHelperStringValueBuffer;
#pragma warning restore 0169
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext __tagHelperExecutionContext;
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner __tagHelperRunner = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner();
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __backed__tagHelperScopeManager = null;
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __tagHelperScopeManager
{
get
{
if (__backed__tagHelperScopeManager == null)
{
__backed__tagHelperScopeManager = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager(StartTagHelperWritingScope, EndTagHelperWritingScope);
}
return __backed__tagHelperScopeManager;
}
}
private global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper;
#pragma warning disable 1998
public async override global::System.Threading.Tasks.Task ExecuteAsync()
{
BeginContext(39, 2, true);
WriteLiteral("\r\n");
EndContext();
#line 3 "C:\Users\FOladiji\Engineering45\Labs\Lab_32_MVC_Core\Views\Products\Details.cshtml"
ViewData["Title"] = "Details";
#line default
#line hidden
BeginContext(84, 121, true);
WriteLiteral("\r\n<h2>Details</h2>\r\n\r\n<div>\r\n <h4>Product</h4>\r\n <hr />\r\n <dl class=\"dl-horizontal\">\r\n <dt>\r\n ");
EndContext();
BeginContext(206, 47, false);
#line 14 "C:\Users\FOladiji\Engineering45\Labs\Lab_32_MVC_Core\Views\Products\Details.cshtml"
Write(Html.DisplayNameFor(model => model.ProductName));
#line default
#line hidden
EndContext();
BeginContext(253, 43, true);
WriteLiteral("\r\n </dt>\r\n <dd>\r\n ");
EndContext();
BeginContext(297, 43, false);
#line 17 "C:\Users\FOladiji\Engineering45\Labs\Lab_32_MVC_Core\Views\Products\Details.cshtml"
Write(Html.DisplayFor(model => model.ProductName));
#line default
#line hidden
EndContext();
BeginContext(340, 43, true);
WriteLiteral("\r\n </dd>\r\n <dt>\r\n ");
EndContext();
BeginContext(384, 44, false);
#line 20 "C:\Users\FOladiji\Engineering45\Labs\Lab_32_MVC_Core\Views\Products\Details.cshtml"
Write(Html.DisplayNameFor(model => model.Category));
#line default
#line hidden
EndContext();
BeginContext(428, 43, true);
WriteLiteral("\r\n </dt>\r\n <dd>\r\n ");
EndContext();
BeginContext(472, 53, false);
#line 23 "C:\Users\FOladiji\Engineering45\Labs\Lab_32_MVC_Core\Views\Products\Details.cshtml"
Write(Html.DisplayFor(model => model.Category.CategoryName));
#line default
#line hidden
EndContext();
BeginContext(525, 43, true);
WriteLiteral("\r\n </dd>\r\n <dt>\r\n ");
EndContext();
BeginContext(569, 51, false);
#line 26 "C:\Users\FOladiji\Engineering45\Labs\Lab_32_MVC_Core\Views\Products\Details.cshtml"
Write(Html.DisplayNameFor(model => model.QuantityPerUnit));
#line default
#line hidden
EndContext();
BeginContext(620, 43, true);
WriteLiteral("\r\n </dt>\r\n <dd>\r\n ");
EndContext();
BeginContext(664, 47, false);
#line 29 "C:\Users\FOladiji\Engineering45\Labs\Lab_32_MVC_Core\Views\Products\Details.cshtml"
Write(Html.DisplayFor(model => model.QuantityPerUnit));
#line default
#line hidden
EndContext();
BeginContext(711, 43, true);
WriteLiteral("\r\n </dd>\r\n <dt>\r\n ");
EndContext();
BeginContext(755, 45, false);
#line 32 "C:\Users\FOladiji\Engineering45\Labs\Lab_32_MVC_Core\Views\Products\Details.cshtml"
Write(Html.DisplayNameFor(model => model.UnitPrice));
#line default
#line hidden
EndContext();
BeginContext(800, 43, true);
WriteLiteral("\r\n </dt>\r\n <dd>\r\n ");
EndContext();
BeginContext(844, 41, false);
#line 35 "C:\Users\FOladiji\Engineering45\Labs\Lab_32_MVC_Core\Views\Products\Details.cshtml"
Write(Html.DisplayFor(model => model.UnitPrice));
#line default
#line hidden
EndContext();
BeginContext(885, 43, true);
WriteLiteral("\r\n </dd>\r\n <dt>\r\n ");
EndContext();
BeginContext(929, 48, false);
#line 38 "C:\Users\FOladiji\Engineering45\Labs\Lab_32_MVC_Core\Views\Products\Details.cshtml"
Write(Html.DisplayNameFor(model => model.UnitsInStock));
#line default
#line hidden
EndContext();
BeginContext(977, 43, true);
WriteLiteral("\r\n </dt>\r\n <dd>\r\n ");
EndContext();
BeginContext(1021, 44, false);
#line 41 "C:\Users\FOladiji\Engineering45\Labs\Lab_32_MVC_Core\Views\Products\Details.cshtml"
Write(Html.DisplayFor(model => model.UnitsInStock));
#line default
#line hidden
EndContext();
BeginContext(1065, 43, true);
WriteLiteral("\r\n </dd>\r\n <dt>\r\n ");
EndContext();
BeginContext(1109, 48, false);
#line 44 "C:\Users\FOladiji\Engineering45\Labs\Lab_32_MVC_Core\Views\Products\Details.cshtml"
Write(Html.DisplayNameFor(model => model.UnitsOnOrder));
#line default
#line hidden
EndContext();
BeginContext(1157, 43, true);
WriteLiteral("\r\n </dt>\r\n <dd>\r\n ");
EndContext();
BeginContext(1201, 44, false);
#line 47 "C:\Users\FOladiji\Engineering45\Labs\Lab_32_MVC_Core\Views\Products\Details.cshtml"
Write(Html.DisplayFor(model => model.UnitsOnOrder));
#line default
#line hidden
EndContext();
BeginContext(1245, 43, true);
WriteLiteral("\r\n </dd>\r\n <dt>\r\n ");
EndContext();
BeginContext(1289, 48, false);
#line 50 "C:\Users\FOladiji\Engineering45\Labs\Lab_32_MVC_Core\Views\Products\Details.cshtml"
Write(Html.DisplayNameFor(model => model.ReorderLevel));
#line default
#line hidden
EndContext();
BeginContext(1337, 43, true);
WriteLiteral("\r\n </dt>\r\n <dd>\r\n ");
EndContext();
BeginContext(1381, 44, false);
#line 53 "C:\Users\FOladiji\Engineering45\Labs\Lab_32_MVC_Core\Views\Products\Details.cshtml"
Write(Html.DisplayFor(model => model.ReorderLevel));
#line default
#line hidden
EndContext();
BeginContext(1425, 43, true);
WriteLiteral("\r\n </dd>\r\n <dt>\r\n ");
EndContext();
BeginContext(1469, 48, false);
#line 56 "C:\Users\FOladiji\Engineering45\Labs\Lab_32_MVC_Core\Views\Products\Details.cshtml"
Write(Html.DisplayNameFor(model => model.Discontinued));
#line default
#line hidden
EndContext();
BeginContext(1517, 43, true);
WriteLiteral("\r\n </dt>\r\n <dd>\r\n ");
EndContext();
BeginContext(1561, 44, false);
#line 59 "C:\Users\FOladiji\Engineering45\Labs\Lab_32_MVC_Core\Views\Products\Details.cshtml"
Write(Html.DisplayFor(model => model.Discontinued));
#line default
#line hidden
EndContext();
BeginContext(1605, 47, true);
WriteLiteral("\r\n </dd>\r\n </dl>\r\n</div>\r\n<div>\r\n ");
EndContext();
BeginContext(1652, 61, false);
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("a", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "e3a8193a3ce64b78ad3542d180a7e592", async() => {
BeginContext(1705, 4, true);
WriteLiteral("Edit");
EndContext();
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Action = (string)__tagHelperAttribute_0.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_0);
if (__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.RouteValues == null)
{
throw new InvalidOperationException(InvalidTagHelperIndexerAssignment("asp-route-id", "Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper", "RouteValues"));
}
BeginWriteTagHelperAttribute();
#line 64 "C:\Users\FOladiji\Engineering45\Labs\Lab_32_MVC_Core\Views\Products\Details.cshtml"
WriteLiteral(Model.ProductID);
#line default
#line hidden
__tagHelperStringValueBuffer = EndWriteTagHelperAttribute();
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.RouteValues["id"] = __tagHelperStringValueBuffer;
__tagHelperExecutionContext.AddTagHelperAttribute("asp-route-id", __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.RouteValues["id"], global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
EndContext();
BeginContext(1713, 8, true);
WriteLiteral(" |\r\n ");
EndContext();
BeginContext(1721, 38, false);
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("a", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "e12e030a682b4902b4249fca171d8be9", async() => {
BeginContext(1743, 12, true);
WriteLiteral("Back to List");
EndContext();
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Action = (string)__tagHelperAttribute_1.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_1);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
EndContext();
BeginContext(1759, 10, true);
WriteLiteral("\r\n</div>\r\n");
EndContext();
}
#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<Lab_32_MVC_Core.Models.Product> Html { get; private set; }
}
}
#pragma warning restore 1591
| 50.731544 | 298 | 0.660934 | [
"MIT"
] | femiola12/Solutions | Lab_32_MVC_Core/obj/Debug/netcoreapp2.1/Razor/Views/Products/Details.cshtml.g.cs | 15,118 | C# |
#pragma warning disable 1591
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace SFA.DAS.EmployerCommitments.Web.Views.Shared
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Web.Helpers;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using System.Web.Mvc.Html;
using System.Web.Optimization;
using System.Web.Routing;
using System.Web.Security;
using System.Web.UI;
using System.Web.WebPages;
using SFA.DAS.EmployerCommitments;
using SFA.DAS.EmployerCommitments.Web.Extensions;
using SFA.DAS.EmployerCommitments.Web.ViewModels.ManageApprenticeships;
[System.CodeDom.Compiler.GeneratedCodeAttribute("RazorGenerator", "2.0.0.0")]
[System.Web.WebPages.PageVirtualPathAttribute("~/Views/Shared/ApprenticeshipUpdate.cshtml")]
public partial class ApprenticeshipUpdate : System.Web.Mvc.WebViewPage<UpdateApprenticeshipViewModel>
{
private static string GetNameChange(ApprenticeshipDetailsViewModel originalApprenticeship, UpdateApprenticeshipViewModel update)
{
var first = !string.IsNullOrWhiteSpace(update.FirstName) ? update.FirstName : originalApprenticeship.FirstName;
var last = !string.IsNullOrWhiteSpace(update.LastName) ? update.LastName : originalApprenticeship.LastName;
return $"{first} {last}";
}
public string FormatCost(string cost)
{
if (!string.IsNullOrEmpty(cost))
{
var dCost = decimal.Parse(cost);
return $"£{dCost:n0}";
}
return string.Empty;
}
public ApprenticeshipUpdate()
{
}
public override void Execute()
{
WriteLiteral("\r\n");
var currentValuHeader = string .IsNullOrEmpty(Model.CurrentTableHeadingText) ? "Current" : Model.CurrentTableHeadingText;
WriteLiteral("\r\n\r\n<table");
WriteLiteral(" class=\"edited-changes\"");
WriteLiteral(">\r\n <thead>\r\n <tr>\r\n <th></th>\r\n <th");
WriteLiteral(" scope=\"col\"");
WriteLiteral(">");
Write(currentValuHeader);
WriteLiteral("</th>\r\n <th");
WriteLiteral(" scope=\"col\"");
WriteLiteral(">Changed to</th>\r\n </tr>\r\n </thead>\r\n <tbody>\r\n");
if (!string.IsNullOrWhiteSpace(Model.FirstName) || !string.IsNullOrWhiteSpace(Model.LastName))
{
WriteLiteral(" <tr>\r\n <td>Name</td>\r\n <td>");
Write(Model.OriginalApprenticeship.FirstName);
WriteLiteral(" ");
Write(Model.OriginalApprenticeship.LastName);
WriteLiteral("</td>\r\n <td>");
Write(GetNameChange(Model.OriginalApprenticeship, Model));
WriteLiteral("</td>\r\n");
WriteLiteral(" ");
Write(Html.Hidden("FirstName", Model.FirstName));
WriteLiteral("\r\n");
WriteLiteral(" ");
Write(Html.Hidden("Lastname", Model.LastName));
WriteLiteral("\r\n </tr>\r\n");
}
WriteLiteral("\r\n");
if (Model.DateOfBirth?.DateTime != null)
{
WriteLiteral(" <tr>\r\n <td>Date of birth</td>\r\n <td>\r\n");
if (Model.OriginalApprenticeship.DateOfBirth.HasValue)
{
Write(Model.OriginalApprenticeship.DateOfBirth.Value.ToGdsFormat());
}
WriteLiteral(" </td>\r\n <td>");
Write(Model.DateOfBirth.DateTime.Value.ToGdsFormat());
WriteLiteral("</td>\r\n");
WriteLiteral(" ");
Write(Html.Hidden("DateOfBirth.Day", Model.DateOfBirth.Day));
WriteLiteral("\r\n");
WriteLiteral(" ");
Write(Html.Hidden("DateOfBirth.Month", Model.DateOfBirth.Month));
WriteLiteral("\r\n");
WriteLiteral(" ");
Write(Html.Hidden("DateOfBirth.Year", Model.DateOfBirth.Year));
WriteLiteral("\r\n </tr>\r\n");
}
WriteLiteral("\r\n");
if (Model.TrainingName != null)
{
WriteLiteral(" <tr>\r\n <td>Apprenticeship training course</td>\r\n <t" +
"d>");
Write(Model.OriginalApprenticeship.TrainingName);
WriteLiteral(" </td>\r\n <td>");
Write(Model.TrainingName);
WriteLiteral("</td>\r\n");
WriteLiteral(" ");
Write(Html.Hidden("TrainingCode", Model.TrainingCode));
WriteLiteral("\r\n");
WriteLiteral(" ");
Write(Html.Hidden("TrainingName", Model.TrainingName));
WriteLiteral("\r\n");
WriteLiteral(" ");
Write(Html.Hidden("TrainingType", Model.TrainingType));
WriteLiteral("\r\n </tr>\r\n");
}
WriteLiteral("\r\n");
if (Model.StartDate?.DateTime != null)
{
WriteLiteral(" <tr>\r\n <td>Planned training start date</td>\r\n <td>");
Write(Model.OriginalApprenticeship.StartDate.Value.ToGdsFormat());
WriteLiteral(" </td>\r\n <td>");
Write(Model.StartDate.DateTime.Value.ToGdsFormat());
WriteLiteral("</td>\r\n");
WriteLiteral(" ");
Write(Html.Hidden("StartDate.Month", Model.StartDate.Month));
WriteLiteral("\r\n");
WriteLiteral(" ");
Write(Html.Hidden("StartDate.Year", Model.StartDate.Year));
WriteLiteral("\r\n </tr>\r\n");
}
WriteLiteral("\r\n");
if (Model.EndDate?.DateTime != null)
{
WriteLiteral(" <tr>\r\n <td>Planned training end date</td>\r\n <td>");
Write(Model.OriginalApprenticeship.EndDate.Value.ToGdsFormat());
WriteLiteral(" </td>\r\n <td>");
Write(Model.EndDate.DateTime.Value.ToGdsFormat());
WriteLiteral("</td>\r\n");
WriteLiteral(" ");
Write(Html.Hidden("EndDate.Month", Model.EndDate.Month));
WriteLiteral("\r\n");
WriteLiteral(" ");
Write(Html.Hidden("EndDate.Year", Model.EndDate.Year));
WriteLiteral("\r\n </tr>\r\n");
}
WriteLiteral("\r\n");
if (!string.IsNullOrEmpty(Model.Cost))
{
WriteLiteral(" <tr>\r\n <td>Cost</td>\r\n <td>");
Write(Model.OriginalApprenticeship.Cost.FormatCost());
WriteLiteral(" </td>\r\n <td>");
Write(FormatCost(Model.Cost));
WriteLiteral("</td>\r\n");
WriteLiteral(" ");
Write(Html.Hidden("Cost", Model.Cost));
WriteLiteral("\r\n </tr>\r\n");
}
WriteLiteral("\r\n");
if (Model.EmployerRef != null)
{
WriteLiteral(" <tr>\r\n <td>Reference</td>\r\n <td>");
Write(Model.OriginalApprenticeship.EmployerReference);
WriteLiteral("</td>\r\n <td>");
Write(Model.EmployerRef);
WriteLiteral("</td>\r\n");
WriteLiteral(" ");
Write(Html.Hidden("EmployerRef", Model.EmployerRef));
WriteLiteral("\r\n </tr>\r\n");
}
WriteLiteral(" </tbody>\r\n</table>\r\n\r\n");
}
}
}
#pragma warning restore 1591
| 24.516129 | 132 | 0.563421 | [
"MIT"
] | SkillsFundingAgency/das-employercommitments | src/SFA.DAS.EAS.Web/Views/Shared/ApprenticeshipUpdate.generated.cs | 7,603 | C# |
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using MyJetWallet.Sdk.Service;
namespace Service.TutorialSecurity
{
public class ApplicationLifetimeManager : ApplicationLifetimeManagerBase
{
private readonly ILogger<ApplicationLifetimeManager> _logger;
public ApplicationLifetimeManager(IHostApplicationLifetime appLifetime, ILogger<ApplicationLifetimeManager> logger)
: base(appLifetime) => _logger = logger;
protected override void OnStarted() => _logger.LogInformation("OnStarted has been called.");
protected override void OnStopping() => _logger.LogInformation("OnStopping has been called.");
protected override void OnStopped() => _logger.LogInformation("OnStopped has been called.");
}
}
| 35.285714 | 117 | 0.805668 | [
"MIT"
] | MyJetEducation/Service.TutorialSecurity | src/Service.TutorialSecurity/ApplicationLifetimeManager.cs | 743 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace System.Reflection.Metadata
{
public struct CustomAttributeTypedArgument<TType>
{
private readonly TType _type;
private readonly object _value;
public CustomAttributeTypedArgument(TType type, object value)
{
_type = type;
_value = value;
}
public TType Type
{
get { return _type; }
}
public object Value
{
get { return _value; }
}
}
}
| 23.142857 | 101 | 0.589506 | [
"MIT"
] | controlflow/srm-extensions | src/System.Reflection.Metadata.Extensions/Decoding/CustomAttributeTypedArgument.cs | 650 | C# |
using System.Collections;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Linq.Expressions;
namespace Orchard.DisplayManagement.Shapes
{
public class Composite : DynamicObject
{
protected readonly IDictionary<object, object> _props = new Dictionary<object, object>();
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
return TryGetMemberImpl(binder.Name, out result);
}
protected virtual bool TryGetMemberImpl(string name, out object result)
{
if (_props.TryGetValue(name, out result))
{
return true;
}
result = null;
return true;
}
public override bool TrySetMember(SetMemberBinder binder, object value)
{
return TrySetMemberImpl(binder.Name, value);
}
protected virtual bool TrySetMemberImpl(string name, object value)
{
_props[name] = value;
return true;
}
public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
{
if (args.Length == 0)
{
return TryGetMemberImpl(binder.Name, out result);
}
// method call with one argument will assign the property
if (args.Length == 1)
{
result = this;
return TrySetMemberImpl(binder.Name, args.First());
}
if (!base.TryInvokeMember(binder, args, out result))
{
if (binder.Name == "ToString")
{
result = string.Empty;
return true;
}
return false;
}
return true;
}
public override bool TryGetIndex(GetIndexBinder binder, object[] indexes, out object result)
{
if (indexes.Length != 1)
{
return base.TryGetIndex(binder, indexes, out result);
}
var index = indexes.First();
if (_props.TryGetValue(index, out result))
{
return true;
}
// try to access an existing member
var strinIndex = index as string;
if (strinIndex != null && TryGetMemberImpl(strinIndex, out result))
{
return true;
}
return base.TryGetIndex(binder, indexes, out result);
}
public override bool TrySetIndex(SetIndexBinder binder, object[] indexes, object value)
{
if (indexes.Length != 1)
{
return base.TrySetIndex(binder, indexes, value);
}
var index = indexes[0];
// try to access an existing member
var strinIndex = index as string;
if (strinIndex != null && TrySetMemberImpl(strinIndex, value))
{
return true;
}
_props[indexes[0]] = value;
return true;
}
public IDictionary<object, object> Properties
{
get { return _props; }
}
public static bool operator ==(Composite a, Nil b)
{
return null == a;
}
public static bool operator !=(Composite a, Nil b)
{
return !(a == b);
}
protected bool Equals(Composite other)
{
return Equals(_props, other._props);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj))
{
return false;
}
if (ReferenceEquals(this, obj))
{
return true;
}
if (obj.GetType() != this.GetType())
{
return false;
}
return Equals((Composite)obj);
}
public override int GetHashCode()
{
return (_props != null ? _props.GetHashCode() : 0);
}
}
public class Nil : DynamicObject
{
static readonly Nil Singleton = new Nil();
public static Nil Instance { get { return Singleton; } }
private Nil()
{
}
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
result = Instance;
return true;
}
public override bool TryGetIndex(GetIndexBinder binder, object[] indexes, out object result)
{
result = Instance;
return true;
}
public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
{
result = Nil.Instance;
return true;
}
public override bool TryBinaryOperation(BinaryOperationBinder binder, object arg, out object result)
{
switch (binder.Operation)
{
case ExpressionType.Equal:
result = ReferenceEquals(arg, Nil.Instance) || (object)arg == null;
return true;
case ExpressionType.NotEqual:
result = !ReferenceEquals(arg, Nil.Instance) && (object)arg != null;
return true;
}
return base.TryBinaryOperation(binder, arg, out result);
}
public static bool operator ==(Nil a, Nil b)
{
return true;
}
public static bool operator !=(Nil a, Nil b)
{
return false;
}
public static bool operator ==(Nil a, object b)
{
return ReferenceEquals(a, b) || (object)b == null;
}
public static bool operator !=(Nil a, object b)
{
return !(a == b);
}
public override bool Equals(object obj)
{
if (obj == null)
{
return true;
}
return ReferenceEquals(obj, Nil.Instance);
}
public override int GetHashCode()
{
return 0;
}
public override bool TryConvert(ConvertBinder binder, out object result)
{
result = null;
return true;
}
public override string ToString()
{
return string.Empty;
}
}
} | 26.378049 | 108 | 0.503159 | [
"BSD-3-Clause"
] | CityOfAuburnAL/orchard2 | src/Orchard.DisplayManagement/Shapes/Composite.cs | 6,491 | C# |
using Application.Common.Interfaces;
using Application.Common.Models;
using Application.Entities;
using MediatR;
namespace Application.Features.URLGroups;
public record CreateUrlGroupCommand(string Name) : IRequest<CQRSResponse>;
public class CreateUrlGroupValidator : IValidator<CreateUrlGroupCommand>
{
public Task<ValidationResult> Validate(CreateUrlGroupCommand request)
{
if (string.IsNullOrWhiteSpace(request.Name))
return Task.FromResult(ValidationResult.Error("Group name is invalid. Enter a valid group name."));
return Task.FromResult(ValidationResult.Success);
}
}
public class CreateUrlGroupCommandHandler : IRequestHandler<CreateUrlGroupCommand, CQRSResponse>
{
private readonly IAppDbContext _context;
public CreateUrlGroupCommandHandler(IAppDbContext context)
{
_context = context;
}
public async Task<CQRSResponse> Handle(CreateUrlGroupCommand request, CancellationToken cancellationToken)
{
var urlGroup = new UrlGroup
{
Name = request.Name
};
await _context.UrlGroups.AddAsync(urlGroup, cancellationToken);
await _context.SaveChangesAsync(cancellationToken);
return CQRSResponse.Success(urlGroup);
}
} | 30.119048 | 111 | 0.743083 | [
"Apache-2.0"
] | andrewtomas/url-shortener | backend/Application/Features/UrlGroups/CreateUrlGroup.cs | 1,267 | C# |
namespace SKIT.FlurlHttpClient.Wechat.Api.Models
{
/// <summary>
/// <para>表示 [GET] /wxaapi/newtmpl/getcategory 接口的请求。</para>
/// </summary>
public class WxaApiNewTemplateGetCategoryRequest : WechatApiRequest, IInferable<WxaApiNewTemplateGetCategoryRequest, WxaApiNewTemplateGetCategoryResponse>
{
}
}
| 32.7 | 158 | 0.740061 | [
"MIT"
] | OrchesAdam/DotNetCore.SKIT.FlurlHttpClient.Wechat | src/SKIT.FlurlHttpClient.Wechat.Api/Models/WxaApi/NewTemplate/WxaApiNewTemplateGetCategoryRequest.cs | 345 | C# |
using System.Collections.Generic;
using System.Globalization;
using Mobet.Dependency;
using Mobet.Localization.Configuration;
using Mobet.Localization.Settings;
namespace Mobet.Localization.Sources
{
/// <summary>
/// Null object pattern for <see cref="ILocalizationSource"/>.
/// </summary>
public class NullLocalizationSource : ILocalizationSource
{
/// <summary>
/// Singleton instance.
/// </summary>
public static NullLocalizationSource Instance { get { return SingletonInstance; } }
private static readonly NullLocalizationSource SingletonInstance = new NullLocalizationSource();
public string Name { get { return null; } }
private readonly IReadOnlyList<LocalizedString> _emptyStringArray = new LocalizedString[0];
private NullLocalizationSource()
{
}
public void Initialize(ILocalizationConfiguration configuration)
{
}
public string GetString(string name)
{
return name;
}
public string GetString(string name, CultureInfo culture)
{
return name;
}
public string GetStringOrNull(string name, bool tryDefaults = true)
{
return null;
}
public string GetStringOrNull(string name, CultureInfo culture, bool tryDefaults = true)
{
return null;
}
public IReadOnlyList<LocalizedString> GetAllStrings(bool includeDefaults = true)
{
return _emptyStringArray;
}
public IReadOnlyList<LocalizedString> GetAllStrings(CultureInfo culture, bool includeDefaults = true)
{
return _emptyStringArray;
}
}
} | 27.734375 | 109 | 0.629296 | [
"Apache-2.0"
] | Mobet/mobet | Mobet-Net/Mobet.Localization/Sources/NullLocalizationSource.cs | 1,775 | C# |
using System;
using System.Collections.Generic;
using Microsoft.ApplicationServer.Caching;
using nz.govt.moe.idp.saml.client.session;
namespace dk.nita.saml20.ext.appfabricsessioncache
{
class AppFabricSession : ISession
{
private static readonly DataCacheFactory CacheFactory = new DataCacheFactory();
public AppFabricSession(Guid sessionId)
{
Id = sessionId;
}
public object this[string key]
{
get
{
DataCache sessions = CacheFactory.GetCache(AppFabricSessions.CacheName);
var session = sessions.Get(Id.ToString()) as IDictionary<string, object>;
if (session != null && session.ContainsKey(key))
return session[key];
return null;
}
set
{
DataCache sessions = CacheFactory.GetCache(AppFabricSessions.CacheName);
var session = sessions.Get(Id.ToString()) as IDictionary<string, object>;
if (session != null)
{
session[key] = value;
sessions.Put(Id.ToString(), session);
}
else
throw new InvalidOperationException("Session with session id: " + Id + " does not exist. Not able to add key: " + key + " and value: " + value +" to session.");
}
}
public void Remove(string key)
{
DataCache sessions = CacheFactory.GetCache(AppFabricSessions.CacheName);
var session = sessions.Get(Id.ToString()) as IDictionary<string, object>;
if (session != null)
{
session.Remove(key);
sessions.Put(Id.ToString(), session);
}
else
throw new InvalidOperationException("Session with session id: " + Id + " does not exist. Not able to remove key: " + key + " from session.");
}
public bool New { get; set; }
public Guid Id { get; private set; }
}
}
| 34.983333 | 177 | 0.545021 | [
"Apache-2.0"
] | nz-govt-moe-skysigal/nz.govt.moe.idp.saml.client.asp.net | _Extra/dk.nita.saml20.ext.AppFabricSessionCache/AppFabricSession.cs | 2,101 | C# |
using System;
using System.IO;
using Xamarin.Forms;
using Notes.Models;
namespace Notes
{
public partial class NoteEntryView : ContentView
{
public NoteEntryView()
{
InitializeComponent();
}
void OnSaveButtonClicked(object sender, EventArgs e)
{
var note = (Note)BindingContext;
if (string.IsNullOrWhiteSpace(note.Filename))
{
// Save
var filename = Path.Combine(App.FolderPath, $"{Path.GetRandomFileName()}.notes.txt");
File.WriteAllText(filename, note.Text);
((Note)BindingContext).Filename = filename;
}
else
{
// Update
File.WriteAllText(note.Filename, note.Text);
}
MainPage.Current.RefreshData();
}
void OnDeleteButtonClicked(object sender, EventArgs e)
{
var note = (Note)BindingContext;
if (File.Exists(note.Filename))
{
File.Delete(note.Filename);
}
BindingContext = new Note();
MainPage.Current.RefreshData();
}
}
}
| 25.208333 | 101 | 0.520661 | [
"MIT"
] | Mahtaran/xamarin-forms-samples | build-2020/step-3/Notes/NoteEntryPage.xaml.cs | 1,212 | C# |
// Copyright (c) 2011-2020 Roland Pheasant. All rights reserved.
// Roland Pheasant licenses this file to you under the MIT license.
// See the LICENSE file in the project root for full license information.
using System;
// ReSharper disable once CheckNamespace
namespace DynamicData
{
/// <summary>
/// Source cache convenience extensions.
/// </summary>
public static class SourceCacheEx
{
/// <summary>
/// Connects to the cache, and casts the object to the specified type
/// Alas, I had to add the converter due to type inference issues.
/// </summary>
/// <typeparam name="TSource">The type of the object.</typeparam>
/// <typeparam name="TKey">The type of the key.</typeparam>
/// <typeparam name="TDestination">The type of the destination.</typeparam>
/// <param name="source">The source.</param>
/// <param name="converter">The conversion factory.</param>
/// <returns>An observable which emits the change set.</returns>
public static IObservable<IChangeSet<TDestination, TKey>> Cast<TSource, TKey, TDestination>(this IObservableCache<TSource, TKey> source, Func<TSource, TDestination> converter)
where TKey : notnull
{
if (source is null)
{
throw new ArgumentNullException(nameof(source));
}
return source.Connect().Cast(converter);
}
}
} | 40.444444 | 183 | 0.638736 | [
"MIT"
] | 1R053/DynamicData | src/DynamicData/Cache/SourceCacheEx.cs | 1,458 | C# |
// <copyright file="Cosmos9Tests.cs" company="Automate The Planet Ltd.">
// Copyright 2018 Automate The Planet Ltd.
// Licensed under the Apache License, Version 2.0 (the "License");
// You may not use this file except in compliance with the License.
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
// <author>Anton Angelov</author>
// <site>https://automatetheplanet.com/</site>
using System;
using System.Threading;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace LoadTestsProject
{
[TestClass]
public class Cosmos9Tests
{
private readonly Random _random = new Random();
[TestMethod]
public void TestMethod0()
{
Thread.Sleep(1000);
}
[TestMethod]
public void TestMethod1()
{
Thread.Sleep(1000);
}
[TestMethod]
public void TestMethod2()
{
Thread.Sleep(1000);
}
[TestMethod]
public void TestMethod3()
{
Thread.Sleep(1000);
}
[TestMethod]
public void TestMethod4()
{
Thread.Sleep(1000);
}
[TestMethod]
public void TestMethod5()
{
Thread.Sleep(1000);
}
[TestMethod]
public void TestMethod6()
{
Thread.Sleep(1000);
}
[TestMethod]
public void TestMethod7()
{
Thread.Sleep(1000);
}
[TestMethod]
public void TestMethod8()
{
Thread.Sleep(1000);
}
[TestMethod]
public void TestMethod9()
{
Thread.Sleep(1000);
}
[TestMethod]
public void TestMethod10()
{
Thread.Sleep(1000);
}
[TestMethod]
public void TestMethod11()
{
Thread.Sleep(1000);
}
[TestMethod]
public void TestMethod12()
{
Thread.Sleep(1000);
}
[TestMethod]
public void TestMethod13()
{
Thread.Sleep(1000);
}
[TestMethod]
public void TestMethod14()
{
Thread.Sleep(1000);
}
[TestMethod]
public void TestMethod15()
{
Thread.Sleep(1000);
}
[TestMethod]
public void TestMethod16()
{
Thread.Sleep(1000);
}
[TestMethod]
public void TestMethod17()
{
Thread.Sleep(1000);
}
[TestMethod]
public void TestMethod18()
{
Thread.Sleep(1000);
}
[TestMethod]
public void TestMethod19()
{
Thread.Sleep(1000);
}
[TestMethod]
public void TestMethod20()
{
Thread.Sleep(1000);
}
[TestMethod]
public void TestMethod21()
{
Thread.Sleep(1000);
}
[TestMethod]
public void TestMethod22()
{
Thread.Sleep(1000);
}
[TestMethod]
public void TestMethod23()
{
Thread.Sleep(1000);
}
[TestMethod]
public void TestMethod24()
{
Thread.Sleep(1000);
}
[TestMethod]
public void TestMethod25()
{
Thread.Sleep(1000);
}
[TestMethod]
public void TestMethod26()
{
Thread.Sleep(1000);
}
[TestMethod]
public void TestMethod27()
{
Thread.Sleep(1000);
}
[TestMethod]
public void TestMethod28()
{
Thread.Sleep(1000);
}
[TestMethod]
public void TestMethod29()
{
Thread.Sleep(1000);
}
[TestMethod]
public void TestMethod30()
{
Thread.Sleep(1000);
}
[TestMethod]
public void TestMethod31()
{
Thread.Sleep(1000);
}
[TestMethod]
public void TestMethod32()
{
Thread.Sleep(1000);
}
[TestMethod]
public void TestMethod33()
{
Thread.Sleep(1000);
}
[TestMethod]
public void TestMethod34()
{
Thread.Sleep(1000);
}
[TestMethod]
public void TestMethod35()
{
Thread.Sleep(1000);
}
[TestMethod]
public void TestMethod36()
{
Thread.Sleep(1000);
}
[TestMethod]
public void TestMethod37()
{
Thread.Sleep(1000);
}
[TestMethod]
public void TestMethod38()
{
Thread.Sleep(1000);
}
[TestMethod]
public void TestMethod39()
{
Thread.Sleep(1000);
}
[TestMethod]
public void TestMethod40()
{
Thread.Sleep(1000);
}
[TestMethod]
public void TestMethod41()
{
Thread.Sleep(1000);
}
[TestMethod]
public void TestMethod42()
{
Thread.Sleep(1000);
}
[TestMethod]
public void TestMethod43()
{
Thread.Sleep(1000);
}
[TestMethod]
public void TestMethod44()
{
Thread.Sleep(1000);
}
[TestMethod]
public void TestMethod45()
{
Thread.Sleep(1000);
}
[TestMethod]
public void TestMethod46()
{
Thread.Sleep(1000);
}
[TestMethod]
public void TestMethod47()
{
Thread.Sleep(1000);
}
[TestMethod]
public void TestMethod48()
{
Thread.Sleep(1000);
}
[TestMethod]
public void TestMethod49()
{
Thread.Sleep(1000);
}
[TestMethod]
public void TestMethod50()
{
Thread.Sleep(1000);
}
[TestMethod]
public void TestMethod51()
{
Thread.Sleep(1000);
}
[TestMethod]
public void TestMethod52()
{
Thread.Sleep(1000);
}
[TestMethod]
public void TestMethod53()
{
Thread.Sleep(1000);
}
[TestMethod]
public void TestMethod54()
{
Thread.Sleep(1000);
}
[TestMethod]
public void TestMethod55()
{
Thread.Sleep(1000);
}
[TestMethod]
public void TestMethod56()
{
Thread.Sleep(1000);
}
[TestMethod]
public void TestMethod57()
{
Thread.Sleep(1000);
}
[TestMethod]
public void TestMethod58()
{
Thread.Sleep(1000);
}
[TestMethod]
public void TestMethod59()
{
Thread.Sleep(1000);
}
[TestMethod]
public void TestMethod60()
{
Thread.Sleep(1000);
}
[TestMethod]
public void TestMethod61()
{
Thread.Sleep(1000);
}
[TestMethod]
public void TestMethod62()
{
Thread.Sleep(1000);
}
[TestMethod]
public void TestMethod63()
{
Thread.Sleep(1000);
}
[TestMethod]
public void TestMethod64()
{
Thread.Sleep(1000);
}
[TestMethod]
public void TestMethod65()
{
Thread.Sleep(1000);
}
[TestMethod]
public void TestMethod66()
{
Thread.Sleep(1000);
}
[TestMethod]
public void TestMethod67()
{
Thread.Sleep(1000);
}
[TestMethod]
public void TestMethod68()
{
Thread.Sleep(1000);
}
[TestMethod]
public void TestMethod69()
{
Thread.Sleep(1000);
}
[TestMethod]
public void TestMethod70()
{
Thread.Sleep(1000);
}
[TestMethod]
public void TestMethod71()
{
Thread.Sleep(1000);
}
[TestMethod]
public void TestMethod72()
{
Thread.Sleep(1000);
}
[TestMethod]
public void TestMethod73()
{
Thread.Sleep(1000);
}
[TestMethod]
public void TestMethod74()
{
Thread.Sleep(1000);
}
[TestMethod]
public void TestMethod75()
{
Thread.Sleep(1000);
}
[TestMethod]
public void TestMethod76()
{
Thread.Sleep(1000);
}
[TestMethod]
public void TestMethod77()
{
Thread.Sleep(1000);
}
[TestMethod]
public void TestMethod78()
{
Thread.Sleep(1000);
}
[TestMethod]
public void TestMethod79()
{
Thread.Sleep(1000);
}
[TestMethod]
public void TestMethod80()
{
Thread.Sleep(1000);
}
[TestMethod]
public void TestMethod81()
{
Thread.Sleep(1000);
}
[TestMethod]
public void TestMethod82()
{
Thread.Sleep(1000);
}
[TestMethod]
public void TestMethod83()
{
Thread.Sleep(1000);
}
[TestMethod]
public void TestMethod84()
{
Thread.Sleep(1000);
}
[TestMethod]
public void TestMethod85()
{
Thread.Sleep(1000);
}
[TestMethod]
public void TestMethod86()
{
Thread.Sleep(1000);
}
[TestMethod]
public void TestMethod87()
{
Thread.Sleep(1000);
}
[TestMethod]
public void TestMethod88()
{
Thread.Sleep(1000);
}
[TestMethod]
public void TestMethod89()
{
Thread.Sleep(1000);
}
[TestMethod]
public void TestMethod90()
{
Thread.Sleep(1000);
}
[TestMethod]
public void TestMethod91()
{
Thread.Sleep(1000);
}
[TestMethod]
public void TestMethod92()
{
Thread.Sleep(1000);
}
[TestMethod]
public void TestMethod93()
{
Thread.Sleep(1000);
}
[TestMethod]
public void TestMethod94()
{
Thread.Sleep(1000);
}
[TestMethod]
public void TestMethod95()
{
Thread.Sleep(1000);
}
[TestMethod]
public void TestMethod96()
{
Thread.Sleep(1000);
}
[TestMethod]
public void TestMethod97()
{
Thread.Sleep(1000);
}
[TestMethod]
public void TestMethod98()
{
Thread.Sleep(1000);
}
[TestMethod]
public void TestMethod99()
{
Thread.Sleep(1000);
}
}
}
| 20.257188 | 85 | 0.4282 | [
"Apache-2.0"
] | AutomateThePlanet/Meissa | CompareRunnersTestsProject/Cosmos9Tests.cs | 12,681 | C# |
#region License
/*
The MIT License
Copyright (c) 2008 Sky Morey
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.
*/
#endregion
#if !CLR4
using System.Collections.Specialized;
using System.Collections;
namespace System.Web
{
/// <summary>
/// HttpContextBase
/// </summary>
//[TypeForwardedFrom("System.Web.Abstractions, Version=3.5.0.0, Culture=Neutral, PublicKeyToken=31bf3856ad364e35")]
public abstract class HttpApplicationStateBase : NameObjectCollectionBase, ICollection, IEnumerable
{
//[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
protected HttpApplicationStateBase() { }
public virtual void Add(string name, object value) { throw new NotImplementedException(); }
public virtual void Clear() { throw new NotImplementedException(); }
public virtual void CopyTo(Array array, int index) { throw new NotImplementedException(); }
public virtual object Get(int index) { throw new NotImplementedException(); }
public virtual object Get(string name) { throw new NotImplementedException(); }
public override IEnumerator GetEnumerator() { throw new NotImplementedException(); }
public virtual string GetKey(int index) { throw new NotImplementedException(); }
public virtual void Lock() { throw new NotImplementedException(); }
public virtual void Remove(string name) { throw new NotImplementedException(); }
public virtual void RemoveAll() { throw new NotImplementedException(); }
public virtual void RemoveAt(int index) { throw new NotImplementedException(); }
public virtual void Set(string name, object value) { throw new NotImplementedException(); }
public virtual void UnLock() { throw new NotImplementedException(); }
public virtual string[] AllKeys
{
get { throw new NotImplementedException(); }
}
public virtual HttpApplicationStateBase Contents
{
get { throw new NotImplementedException(); }
}
public override int Count
{
get { throw new NotImplementedException(); }
}
public virtual bool IsSynchronized
{
get { throw new NotImplementedException(); }
}
public virtual object this[string name]
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
public virtual object this[int index]
{
get { throw new NotImplementedException(); }
}
public virtual HttpStaticObjectsCollectionBase StaticObjects
{
get { throw new NotImplementedException(); }
}
public virtual object SyncRoot
{
get { throw new NotImplementedException(); }
}
}
}
#endif | 45.436782 | 120 | 0.682014 | [
"MIT"
] | BclEx/BclEx-Web | src/System.WebEx/_Unsorted_/zWeb+Abstractions/HttpApplicationStateBase.cs | 3,953 | C# |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="SparkplugApplication.cs" company="Hämmer Electronics">
// The project is licensed under the MIT license.
// </copyright>
// <summary>
// Defines the SparkplugApplication type.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace SparkplugNet.VersionA
{
using System.Collections.Generic;
using Serilog;
using SparkplugNet.Core.Application;
/// <inheritdoc cref="SparkplugApplicationBase{T}"/>
public class SparkplugApplication : SparkplugApplicationBase<Payload.KuraMetric>
{
/// <inheritdoc cref="SparkplugApplicationBase{T}"/>
/// <summary>
/// Initializes a new instance of the <see cref="SparkplugApplication"/> class.
/// </summary>
/// <param name="knownMetrics">The known metrics.</param>
/// <param name="logger">The logger.</param>
public SparkplugApplication(List<Payload.KuraMetric> knownMetrics, ILogger? logger = null) : base(knownMetrics, logger)
{
}
}
} | 38.870968 | 127 | 0.537759 | [
"MIT"
] | BiancoRoyal/SparkplugNet | src/SparkplugNet/VersionA/SparkplugApplication.cs | 1,208 | C# |
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
// Ported from um/winnt.h in the Windows SDK for Windows 10.0.20348.0
// Original source is Copyright © Microsoft. All rights reserved.
using NUnit.Framework;
using System;
using System.Runtime.InteropServices;
namespace TerraFX.Interop.UnitTests
{
/// <summary>Provides validation of the <see cref="XSTATE_CONTEXT" /> struct.</summary>
public static unsafe partial class XSTATE_CONTEXTTests
{
/// <summary>Validates that the <see cref="XSTATE_CONTEXT" /> struct is blittable.</summary>
[Test]
public static void IsBlittableTest()
{
Assert.That(Marshal.SizeOf<XSTATE_CONTEXT>(), Is.EqualTo(sizeof(XSTATE_CONTEXT)));
}
/// <summary>Validates that the <see cref="XSTATE_CONTEXT" /> struct has the right <see cref="LayoutKind" />.</summary>
[Test]
public static void IsLayoutSequentialTest()
{
Assert.That(typeof(XSTATE_CONTEXT).IsLayoutSequential, Is.True);
}
/// <summary>Validates that the <see cref="XSTATE_CONTEXT" /> struct has the correct size.</summary>
[Test]
public static void SizeOfTest()
{
if (Environment.Is64BitProcess)
{
Assert.That(sizeof(XSTATE_CONTEXT), Is.EqualTo(48));
}
else
{
Assert.That(sizeof(XSTATE_CONTEXT), Is.EqualTo(32));
}
}
}
}
| 35.727273 | 145 | 0.631679 | [
"MIT"
] | DaZombieKiller/terrafx.interop.windows | tests/Interop/Windows/um/winnt/XSTATE_CONTEXTTests.cs | 1,574 | C# |
// Copyright Naked Objects Group Ltd, 45 Station Road, Henley on Thames, UK, RG9 1AT
// 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 System.Collections.Immutable;
using System.ComponentModel;
using System.Reflection;
using Microsoft.Extensions.Logging;
using NakedFramework.Architecture.Component;
using NakedFramework.Architecture.Facet;
using NakedFramework.Architecture.FacetFactory;
using NakedFramework.Architecture.Reflect;
using NakedFramework.Architecture.Spec;
using NakedFramework.Architecture.SpecImmutable;
using NakedFramework.Core.Util;
using NakedFramework.Metamodel.Facet;
using NakedFramework.Metamodel.Utils;
namespace NakedObjects.Reflector.FacetFactory {
public sealed class DescribedAsAnnotationFacetFactory : ObjectFacetFactoryProcessor, IAnnotationBasedFacetFactory {
private readonly ILogger<DescribedAsAnnotationFacetFactory> logger;
public DescribedAsAnnotationFacetFactory(IFacetFactoryOrder<DescribedAsAnnotationFacetFactory> order, ILoggerFactory loggerFactory)
: base(order.Order, loggerFactory, FeatureType.Everything) =>
logger = loggerFactory.CreateLogger<DescribedAsAnnotationFacetFactory>();
private void Process(MemberInfo member, ISpecification holder) {
var attribute = member.GetCustomAttribute<DescriptionAttribute>() ?? (Attribute) member.GetCustomAttribute<DescribedAsAttribute>();
FacetUtils.AddFacet(Create(attribute, holder));
}
public override IImmutableDictionary<string, ITypeSpecBuilder> Process(IReflector reflector, Type type, IMethodRemover methodRemover, ISpecificationBuilder specification, IImmutableDictionary<string, ITypeSpecBuilder> metamodel) {
var attribute = type.GetCustomAttribute<DescriptionAttribute>() ?? (Attribute) type.GetCustomAttribute<DescribedAsAttribute>();
FacetUtils.AddFacet(Create(attribute, specification));
return metamodel;
}
public override IImmutableDictionary<string, ITypeSpecBuilder> Process(IReflector reflector, MethodInfo method, IMethodRemover methodRemover, ISpecificationBuilder specification, IImmutableDictionary<string, ITypeSpecBuilder> metamodel) {
Process(method, specification);
return metamodel;
}
public override IImmutableDictionary<string, ITypeSpecBuilder> Process(IReflector reflector, PropertyInfo property, IMethodRemover methodRemover, ISpecificationBuilder specification, IImmutableDictionary<string, ITypeSpecBuilder> metamodel) {
Process(property, specification);
return metamodel;
}
public override IImmutableDictionary<string, ITypeSpecBuilder> ProcessParams(IReflector reflector, MethodInfo method, int paramNum, ISpecificationBuilder holder, IImmutableDictionary<string, ITypeSpecBuilder> metamodel) {
var parameter = method.GetParameters()[paramNum];
var attribute = parameter.GetCustomAttribute<DescriptionAttribute>() ?? (Attribute) parameter.GetCustomAttribute<DescribedAsAttribute>();
FacetUtils.AddFacet(Create(attribute, holder));
return metamodel;
}
private IDescribedAsFacet Create(Attribute attribute, ISpecification holder) =>
attribute switch {
null => null,
DescribedAsAttribute asAttribute => Create(asAttribute, holder),
DescriptionAttribute descriptionAttribute => Create(descriptionAttribute, holder),
_ => throw new ArgumentException(logger.LogAndReturn($"Unexpected attribute type: {attribute.GetType()}"))
};
private static IDescribedAsFacet Create(DescribedAsAttribute attribute, ISpecification holder) => new DescribedAsFacetAnnotation(attribute.Value, holder);
private static IDescribedAsFacet Create(DescriptionAttribute attribute, ISpecification holder) => new DescribedAsFacetAnnotation(attribute.Description, holder);
}
} | 63.056338 | 250 | 0.764574 | [
"Apache-2.0"
] | NakedObjectsGroup/NakedObjectsFramework | NakedObjects/NakedObjects.Reflector/FacetFactory/DescribedAsAnnotationFacetFactory.cs | 4,477 | C# |
#pragma warning disable 108 // new keyword hiding
#pragma warning disable 114 // new keyword hiding
namespace Windows.Security.Cryptography.Certificates
{
#if __ANDROID__ || __IOS__ || NET46 || __WASM__
[global::Uno.NotImplemented]
#endif
public partial class KeyStorageProviderNames
{
#if __ANDROID__ || __IOS__ || NET46 || __WASM__
[global::Uno.NotImplemented]
public static string PlatformKeyStorageProvider
{
get
{
throw new global::System.NotImplementedException("The member string KeyStorageProviderNames.PlatformKeyStorageProvider is not implemented in Uno.");
}
}
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__
[global::Uno.NotImplemented]
public static string SmartcardKeyStorageProvider
{
get
{
throw new global::System.NotImplementedException("The member string KeyStorageProviderNames.SmartcardKeyStorageProvider is not implemented in Uno.");
}
}
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__
[global::Uno.NotImplemented]
public static string SoftwareKeyStorageProvider
{
get
{
throw new global::System.NotImplementedException("The member string KeyStorageProviderNames.SoftwareKeyStorageProvider is not implemented in Uno.");
}
}
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__
[global::Uno.NotImplemented]
public static string PassportKeyStorageProvider
{
get
{
throw new global::System.NotImplementedException("The member string KeyStorageProviderNames.PassportKeyStorageProvider is not implemented in Uno.");
}
}
#endif
// Forced skipping of method Windows.Security.Cryptography.Certificates.KeyStorageProviderNames.PassportKeyStorageProvider.get
// Forced skipping of method Windows.Security.Cryptography.Certificates.KeyStorageProviderNames.SoftwareKeyStorageProvider.get
// Forced skipping of method Windows.Security.Cryptography.Certificates.KeyStorageProviderNames.SmartcardKeyStorageProvider.get
// Forced skipping of method Windows.Security.Cryptography.Certificates.KeyStorageProviderNames.PlatformKeyStorageProvider.get
}
}
| 37.303571 | 153 | 0.778842 | [
"Apache-2.0"
] | nv-ksavaria/Uno | src/Uno.UWP/Generated/3.0.0.0/Windows.Security.Cryptography.Certificates/KeyStorageProviderNames.cs | 2,089 | C# |
using SoundByte.Core.Items.Playlist;
using SoundByte.Core.Items.Podcast;
using SoundByte.Core.Items.Track;
using SoundByte.Core.Items.User;
// ReSharper disable UnusedAutoPropertyAccessor.Global
namespace SoundByte.Core.Items.Generic
{
/// <summary>
/// An item that can be muiltiple things
/// </summary>
public class GroupedItem
{
public ItemType Type { get; set; }
public BaseUser User { get; set; }
public BasePlaylist Playlist { get; set; }
public BaseTrack Track { get; set; }
public BasePodcast Podcast { get; set; }
}
}
| 24.08 | 54 | 0.664452 | [
"MIT"
] | mediabuff/SoundByte | SoundByte.Core/Items/Generic/GroupedItem.cs | 604 | C# |
// =====================================================================
// This file is part of the Microsoft Dynamics CRM SDK code samples.
//
// Copyright (C) Microsoft Corporation. All rights reserved.
//
// This source code is intended only as a supplement to Microsoft
// Development Tools and/or on-line documentation. See these other
// materials for detailed information regarding Microsoft code samples.
//
// THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
// KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
// =====================================================================
//<snippetUserQueryAndSavedQuery>
using System;
using System.Collections.Generic;
using System.IO;
using System.ServiceModel;
using System.Text;
using System.Xml;
// These namespaces are found in the Microsoft.Xrm.Sdk.dll assembly
// located in the SDK\bin folder of the SDK download.
using Microsoft.Xrm.Sdk.Client;
// This namespace is found in Microsoft.Crm.Sdk.Proxy.dll assembly
// found in the SDK\bin folder.
using Microsoft.Crm.Sdk.Messages;
namespace Microsoft.Crm.Sdk.Samples
{
/// <summary>
/// Demonstrates how to execute saved and user queries by id, and how to validate
/// a saved query.
/// </summary>
/// <param name="serverConfig">Contains server connection information.</param>
/// <param name="promptforDelete">When True, the user will be prompted to delete all
/// created entities.</param>
public class UserQueryAndSavedQuery
{
#region Class Level Members
private OrganizationServiceProxy _serviceProxy;
private List<Account> _accounts = new List<Account>();
private SavedQuery _savedQuery;
private UserQuery _userQuery;
#endregion Class Level Members
#region How To Sample Code
/// <summary>
/// This method first creates a series of Accounts to query over, a user query
/// that retrieves the names of all Accounts with a name of 'Coho Winery' and
/// a system query that retrieves all Account names. Then it validates the system
/// query, executes the system query and displays the results, and finally
/// executes the user query and displays the results.
/// </summary>
/// <param name="serverConfig">Contains server connection information.</param>
/// <param name="promptforDelete">When True, the user will be prompted to delete all
/// created entities.</param>
public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete)
{
try
{
//<snippetUserQueryAndSavedQuery1>
// Connect to the Organization service.
// The using statement assures that the service proxy will be properly disposed.
using (_serviceProxy = ServerConnection.GetOrganizationProxy(serverConfig))
{
// This statement is required to enable early-bound type support.
_serviceProxy.EnableProxyTypes();
CreateRequiredRecords();
#region Validate saved query
// Create the request
ValidateSavedQueryRequest validateRequest = new ValidateSavedQueryRequest()
{
FetchXml = _savedQuery.FetchXml,
QueryType = _savedQuery.QueryType.Value
};
// Send the request
Console.WriteLine(" Validating Saved Query");
try
{
// executing the request will throw an exception if the fetch xml is invalid
var validateResponse = (ValidateSavedQueryResponse)_serviceProxy.Execute(validateRequest);
Console.WriteLine(" Saved Query validated successfully");
}
catch (Exception)
{
Console.WriteLine(" Invalid Saved Query");
throw;
}
#endregion
#region Execute saved query
// Create the request
ExecuteByIdSavedQueryRequest executeSavedQueryRequest = new ExecuteByIdSavedQueryRequest()
{
EntityId = _savedQuery.Id
};
// Execute the request
Console.WriteLine(" Executing Saved Query");
ExecuteByIdSavedQueryResponse executeSavedQueryResponse =
(ExecuteByIdSavedQueryResponse)_serviceProxy.Execute(executeSavedQueryRequest);
// Check results
if (String.IsNullOrEmpty(executeSavedQueryResponse.String))
throw new Exception("Saved Query did not return any results");
PrintResults(executeSavedQueryResponse.String);
#endregion
#region Execute user query
// Create the request
ExecuteByIdUserQueryRequest executeUserQuery = new ExecuteByIdUserQueryRequest()
{
EntityId = _userQuery.ToEntityReference()
};
// Send the request
Console.WriteLine(" Executing User Query");
ExecuteByIdUserQueryResponse executeUserQueryResponse =
(ExecuteByIdUserQueryResponse)_serviceProxy.Execute(executeUserQuery);
if (String.IsNullOrEmpty(executeUserQueryResponse.String))
throw new Exception("User Query did not return any results");
// validate results
PrintResults(executeUserQueryResponse.String);
#endregion
DeleteRequiredRecords(promptforDelete);
}
//</snippetUserQueryAndSavedQuery1>
}
// Catch any service fault exceptions that Microsoft Dynamics CRM throws.
catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault>)
{
// You can handle an exception here or pass it back to the calling method.
throw;
}
}
#region Public methods
/// <summary>
/// Creates any entity records that this sample requires.
/// </summary>
public void CreateRequiredRecords()
{
#region Create Accounts to query over
Console.WriteLine(" Creating some sample accounts");
Account account = new Account()
{
Name = "Coho Vineyard"
};
account.Id = _serviceProxy.Create(account);
_accounts.Add(account);
Console.WriteLine(" Created Account {0}", account.Name);
account = new Account()
{
Name = "Coho Winery"
};
account.Id = _serviceProxy.Create(account);
_accounts.Add(account);
Console.WriteLine(" Created Account {0}", account.Name);
account = new Account()
{
Name = "Coho Vineyard & Winery"
};
account.Id = _serviceProxy.Create(account);
_accounts.Add(account);
Console.WriteLine(" Created Account {0}", account.Name);
#endregion
#region Create a Saved Query
Console.WriteLine(" Creating a Saved Query that retrieves all Account ids");
_savedQuery = new SavedQuery()
{
Name = "Fetch all Account ids",
ReturnedTypeCode = Account.EntityLogicalName,
FetchXml = @"
<fetch mapping='logical'>
<entity name='account'>
<attribute name='name' />
</entity>
</fetch>",
QueryType = 0,
};
_savedQuery.Id = _serviceProxy.Create(_savedQuery);
#endregion
#region Create a User Query
Console.WriteLine(
" Creating a User Query that retrieves all Account ids for Accounts with name 'Coho Winery'");
_userQuery = new UserQuery()
{
Name = "Fetch Coho Winery",
ReturnedTypeCode = Account.EntityLogicalName,
FetchXml = @"
<fetch mapping='logical'>
<entity name='account'>
<attribute name='name' />
<filter>
<condition attribute='name' operator='eq' value='Coho Winery' />
</filter>
</entity>
</fetch>",
QueryType = 0
};
_userQuery.Id = _serviceProxy.Create(_userQuery);
#endregion
}
/// <summary>
/// Deletes any entity records that were created for this sample.
/// <param name="prompt">Indicates whether to prompt the user
/// to delete the records created in this sample.</param>
/// </summary>
public void DeleteRequiredRecords(bool prompt)
{
bool toBeDeleted = true;
if (prompt)
{
// Ask the user if the created entities should be deleted.
Console.Write("\nDo you want these entity records deleted? (y/n) [y]: ");
String answer = Console.ReadLine();
if (answer.StartsWith("y") ||
answer.StartsWith("Y") ||
answer == String.Empty)
{
toBeDeleted = true;
}
else
{
toBeDeleted = false;
}
}
if (toBeDeleted)
{
_serviceProxy.Delete(SavedQuery.EntityLogicalName,
_savedQuery.Id);
_serviceProxy.Delete(UserQuery.EntityLogicalName,
_userQuery.Id);
foreach (Account a in _accounts)
_serviceProxy.Delete(Account.EntityLogicalName, a.Id);
Console.WriteLine("Entity records have been deleted.");
}
}
#endregion Public Methods
#region Helper methods
private void PrintResults(String response)
{
// Using XmlReader to format output
StringBuilder output = new StringBuilder();
using (XmlReader reader = XmlReader.Create(new StringReader(response)))
{
XmlWriterSettings settings = new XmlWriterSettings
{
Indent = true,
OmitXmlDeclaration = true
};
using (XmlWriter writer = XmlWriter.Create(output, settings))
{
// Parse the file and display each of the nodes.
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element:
writer.WriteStartElement(reader.Name);
break;
case XmlNodeType.Text:
writer.WriteString(reader.Value);
break;
case XmlNodeType.XmlDeclaration:
case XmlNodeType.ProcessingInstruction:
writer.WriteProcessingInstruction(reader.Name, reader.Value);
break;
case XmlNodeType.Comment:
writer.WriteComment(reader.Value);
break;
case XmlNodeType.EndElement:
writer.WriteFullEndElement();
break;
}
}
}
}
Console.WriteLine(" Result of query:\r\n {0}", output.ToString());
Console.WriteLine();
}
#endregion
#endregion How To Sample Code
#region Main method
/// <summary>
/// Standard Main() method used by most SDK samples.
/// </summary>
/// <param name="args"></param>
static public void Main(string[] args)
{
try
{
// Obtain the target organization's Web address and client logon
// credentials from the user.
ServerConnection serverConnect = new ServerConnection();
ServerConnection.Configuration config = serverConnect.GetServerConfiguration();
UserQueryAndSavedQuery app = new UserQueryAndSavedQuery();
app.Run(config, true);
}
catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault> ex)
{
Console.WriteLine("The application terminated with an error.");
Console.WriteLine("Timestamp: {0}", ex.Detail.Timestamp);
Console.WriteLine("Code: {0}", ex.Detail.ErrorCode);
Console.WriteLine("Message: {0}", ex.Detail.Message);
Console.WriteLine("Plugin Trace: {0}", ex.Detail.TraceText);
Console.WriteLine("Inner Fault: {0}",
null == ex.Detail.InnerFault ? "No Inner Fault" : "Has Inner Fault");
}
catch (System.TimeoutException ex)
{
Console.WriteLine("The application terminated with an error.");
Console.WriteLine("Message: {0}", ex.Message);
Console.WriteLine("Stack Trace: {0}", ex.StackTrace);
Console.WriteLine("Inner Fault: {0}",
null == ex.InnerException.Message ? "No Inner Fault" : ex.InnerException.Message);
}
catch (System.Exception ex)
{
Console.WriteLine("The application terminated with an error.");
Console.WriteLine(ex.Message);
// Display the details of the inner exception.
if (ex.InnerException != null)
{
Console.WriteLine(ex.InnerException.Message);
FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault> fe = ex.InnerException
as FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault>;
if (fe != null)
{
Console.WriteLine("Timestamp: {0}", fe.Detail.Timestamp);
Console.WriteLine("Code: {0}", fe.Detail.ErrorCode);
Console.WriteLine("Message: {0}", fe.Detail.Message);
Console.WriteLine("Plugin Trace: {0}", fe.Detail.TraceText);
Console.WriteLine("Inner Fault: {0}",
null == fe.Detail.InnerFault ? "No Inner Fault" : "Has Inner Fault");
}
}
}
// Additional exceptions to catch: SecurityTokenValidationException, ExpiredSecurityTokenException,
// SecurityAccessDeniedException, MessageSecurityException, and SecurityNegotiationException.
finally
{
Console.WriteLine("Press <Enter> to exit.");
Console.ReadLine();
}
}
#endregion Main method
}
}
//</snippetUserQueryAndSavedQuery> | 39.985075 | 114 | 0.522272 | [
"MIT"
] | Bhaskers-Blu-Org2/Dynamics365-Apps-Samples | samples-from-msdn/Queries/UserQueryAndSavedQuery.cs | 16,076 | C# |
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using static WalletWasabi.Tor.Http.Constants;
namespace WalletWasabi.Tor.Http.Models
{
public class HeaderSection
{
public List<HeaderField> Fields { get; private set; } = new List<HeaderField>();
public string ToString(bool endWithTwoCRLF)
{
StringBuilder sb = new();
foreach (var field in Fields)
{
sb.Append(field.ToString(endWithCRLF: true));
}
if (endWithTwoCRLF)
{
sb.Append(CRLF);
}
return sb.ToString();
}
public override string ToString()
{
return ToString(false);
}
public static async Task<HeaderSection> CreateNewAsync(string headersString)
{
headersString = HeaderField.CorrectObsFolding(headersString);
var hs = new HeaderSection();
if (headersString.EndsWith(CRLF + CRLF))
{
headersString = headersString.TrimEnd(CRLF, StringComparison.Ordinal);
}
using var reader = new StringReader(headersString);
while (true)
{
var field = reader.ReadLine(strictCRLF: true);
if (field is null)
{
break;
}
hs.Fields.Add(await HeaderField.CreateNewAsync(field).ConfigureAwait(false));
}
ValidateAndCorrectHeaders(hs);
return hs;
}
private static void ValidateAndCorrectHeaders(HeaderSection hs)
{
// https://tools.ietf.org/html/rfc7230#section-5.4
// Since the Host field - value is critical information for handling a
// request, a user agent SHOULD generate Host as the first header field
// following the request - line.
HeaderField? hostToCorrect = null;
foreach (var f in hs.Fields)
{
// if we find host
if (f.IsNameEqual("Host"))
{
// if host is not first
if (!hs.Fields.First().IsNameEqual("Host"))
{
// then correct host
hostToCorrect = f;
break;
}
}
}
if (hostToCorrect is { })
{
hs.Fields.Remove(hostToCorrect);
hs.Fields.Insert(0, hostToCorrect);
}
// https://tools.ietf.org/html/rfc7230#section-3.3.2
// If a message is received that has multiple Content-Length header
// fields with field-values consisting of the same decimal value, or a
// single Content-Length header field with a field value containing a
// list of identical decimal values(e.g., "Content-Length: 42, 42"),
// indicating that duplicate Content-Length header fields have been
// generated or combined by an upstream message processor, then the
// recipient MUST either reject the message as invalid or replace the
// duplicated field - values with a single valid Content-Length field
// containing that decimal value prior to determining the message body
// length or forwarding the message.
var allParts = new HashSet<string>();
foreach (var field in hs.Fields)
{
if (field.IsNameEqual("Content-Length"))
{
var parts = field.Value.Trim().Split(',');
foreach (var part in parts)
{
allParts.Add(part.Trim());
}
}
}
if (allParts.Count > 0) // then has Content-Length field
{
if (allParts.Count > 1)
{
throw new InvalidDataException("Invalid Content-Length.");
}
hs.Fields.RemoveAll(x => x.IsNameEqual("Content-Length"));
hs.Fields.Add(new HeaderField("Content-Length", allParts.First()));
}
}
public HttpRequestContentHeaders ToHttpRequestHeaders()
{
using var message = new HttpRequestMessage
{
Content = new ByteArrayContent(Array.Empty<byte>())
};
message.Content.Headers.ContentLength = null;
foreach (var field in Fields)
{
if (field.Name.StartsWith("Content-", StringComparison.OrdinalIgnoreCase))
{
message.Content.Headers.TryAddWithoutValidation(field.Name, field.Value);
}
else
{
message.Headers.TryAddWithoutValidation(field.Name, field.Value);
}
}
return new HttpRequestContentHeaders(message.Headers, message.Content.Headers);
}
public HttpResponseContentHeaders ToHttpResponseHeaders()
{
using var message = new HttpResponseMessage
{
Content = new ByteArrayContent(Array.Empty<byte>())
};
message.Content.Headers.ContentLength = null;
foreach (var field in Fields)
{
if (field.Name.StartsWith("Content-", StringComparison.OrdinalIgnoreCase))
{
message.Content.Headers.TryAddWithoutValidation(field.Name, field.Value);
}
else
{
message.Headers.TryAddWithoutValidation(field.Name, field.Value);
}
}
return new HttpResponseContentHeaders(message.Headers, message.Content.Headers);
}
public static HeaderSection CreateNew(HttpHeaders headers)
{
var hs = new HeaderSection();
foreach (var header in headers)
{
hs.Fields.Add(new HeaderField(header.Key, string.Join(",", header.Value)));
}
// -- Start [SECTION] Crazy VS2017/.NET Core 1.1 bug ---
// The following if branch is needed as is to avoid the craziest VS2017/.NET Core 1.1 bug I have ever seen!
// If this section is not added the Content-Length header will not be set unless...
// - I put a break point at the start of the function
// - And I explicitly expand the "headers" variable
if (headers is HttpContentHeaders contentHeaders && contentHeaders.ContentLength is { } contentLength)
{
if (hs.Fields.All(x => !x.IsNameEqual("Content-Length")))
{
hs.Fields.Add(new HeaderField("Content-Length", contentLength.ToString()));
}
}
// -- End [SECTION] Crazy VS2017/.NET Core 1.1 bug ---
return hs;
}
}
}
| 28.783505 | 110 | 0.684456 | [
"MIT"
] | BTCparadigm/WalletWasabi | WalletWasabi/Tor/Http/Models/HeaderSection.cs | 5,584 | 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 NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Configuration;
using osu.Framework.Configuration.Tracking;
using osu.Framework.Graphics;
using osu.Game.Overlays;
using osu.Game.Overlays.OSD;
namespace osu.Game.Tests.Visual.UserInterface
{
[TestFixture]
public class TestSceneOnScreenDisplay : OsuTestScene
{
[BackgroundDependencyLoader]
private void load()
{
var config = new TestConfigManager();
var osd = new TestOnScreenDisplay();
osd.BeginTracking(this, config);
Add(osd);
AddStep("Display empty osd toast", () => osd.Display(new EmptyToast()));
AddAssert("Toast width is 240", () => osd.Child.Width == 240);
AddStep("Display toast with lengthy text", () => osd.Display(new LengthyToast()));
AddAssert("Toast width is greater than 240", () => osd.Child.Width > 240);
AddRepeatStep("Change toggle (no bind)", () => config.ToggleSetting(TestConfigSetting.ToggleSettingNoKeybind), 2);
AddRepeatStep("Change toggle (with bind)", () => config.ToggleSetting(TestConfigSetting.ToggleSettingWithKeybind), 2);
AddRepeatStep("Change enum (no bind)", () => config.IncrementEnumSetting(TestConfigSetting.EnumSettingNoKeybind), 3);
AddRepeatStep("Change enum (with bind)", () => config.IncrementEnumSetting(TestConfigSetting.EnumSettingWithKeybind), 3);
}
private class TestConfigManager : ConfigManager<TestConfigSetting>
{
public TestConfigManager()
{
InitialiseDefaults();
}
protected override void InitialiseDefaults()
{
SetDefault(TestConfigSetting.ToggleSettingNoKeybind, false);
SetDefault(TestConfigSetting.EnumSettingNoKeybind, EnumSetting.Setting1);
SetDefault(TestConfigSetting.ToggleSettingWithKeybind, false);
SetDefault(TestConfigSetting.EnumSettingWithKeybind, EnumSetting.Setting1);
base.InitialiseDefaults();
}
public void ToggleSetting(TestConfigSetting setting) => SetValue(setting, !Get<bool>(setting));
public void IncrementEnumSetting(TestConfigSetting setting)
{
var nextValue = Get<EnumSetting>(setting) + 1;
if (nextValue > EnumSetting.Setting4)
nextValue = EnumSetting.Setting1;
SetValue(setting, nextValue);
}
public override TrackedSettings CreateTrackedSettings() => new TrackedSettings
{
new TrackedSetting<bool>(TestConfigSetting.ToggleSettingNoKeybind, b => new SettingDescription(b, "toggle setting with no keybind", b ? "enabled" : "disabled")),
new TrackedSetting<EnumSetting>(TestConfigSetting.EnumSettingNoKeybind, v => new SettingDescription(v, "enum setting with no keybind", v.ToString())),
new TrackedSetting<bool>(TestConfigSetting.ToggleSettingWithKeybind, b => new SettingDescription(b, "toggle setting with keybind", b ? "enabled" : "disabled", "fake keybind")),
new TrackedSetting<EnumSetting>(TestConfigSetting.EnumSettingWithKeybind, v => new SettingDescription(v, "enum setting with keybind", v.ToString(), "fake keybind")),
};
protected override void PerformLoad()
{
}
protected override bool PerformSave() => false;
}
private enum TestConfigSetting
{
ToggleSettingNoKeybind,
EnumSettingNoKeybind,
ToggleSettingWithKeybind,
EnumSettingWithKeybind
}
private enum EnumSetting
{
Setting1,
Setting2,
Setting3,
Setting4
}
private class EmptyToast : Toast
{
public EmptyToast()
: base("", "", "")
{
}
}
private class LengthyToast : Toast
{
public LengthyToast()
: base("Toast with a very very very long text", "A very very very very very very long text also", "A very very very very very long shortcut")
{
}
}
private class TestOnScreenDisplay : OnScreenDisplay
{
protected override void DisplayTemporarily(Drawable toDisplay) => toDisplay.FadeIn().ResizeHeightTo(110);
}
}
}
| 40.711864 | 193 | 0.603455 | [
"MIT"
] | 02Naitsirk/osu | osu.Game.Tests/Visual/UserInterface/TestSceneOnScreenDisplay.cs | 4,689 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace TicketShopWebApplication.Pages
{
public class AboutModel : PageModel
{
public string Message { get; set; }
public void OnGet()
{
Message = "Your application description page.";
}
}
}
| 20.631579 | 59 | 0.668367 | [
"MIT"
] | TeknikhogskolanGothenburg/ticketSystem-team-terminator | src/TicketShopWebApplication/Pages/About.cshtml.cs | 394 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class UIPopup_Credit : MonoBehaviour
{
public UIButton btnClose;
internal void Init()
{
this.btnClose.onClick.Add(new EventDelegate(() =>
{
this.gameObject.SetActive(false);
}));
}
internal void Open()
{
this.gameObject.SetActive(true);
}
}
| 16.76 | 57 | 0.627685 | [
"MIT"
] | VontineDev/ProjectA | Dev/AlphaTest/Assets/Scripts/UserInterface/UIPopup_Credit.cs | 421 | C# |
using JetBrains.Annotations;
namespace CGTK.Utilities.Singletons
{
#if ODIN_INSPECTOR
using MonoBehaviour = Sirenix.OdinInspector.SerializedMonoBehaviour;
#else
using MonoBehaviour = UnityEngine.MonoBehaviour;
#endif
//TODO: Check for multiple instances on loading a different scene.
/// <summary> Singleton for <see cref="MonoBehaviour"/>s - If an instance already exists it will use that, if not it'll create one.</summary>
/// <typeparam name="T"> Type of the Singleton. CRTP (the inheritor)</typeparam>
public abstract class MonoBehaviourSingleton_Ensured<T> : MonoBehaviour
where T : MonoBehaviourSingleton_Ensured<T>
{
#region Properties
private static T _internalInstance;
/// <summary> The static reference to the Instance </summary>
[PublicAPI]
public static T Instance
{
get
{
if (InstanceExists) return _internalInstance;
//Debug.Log("Finding Singleton");
_internalInstance = FindObjectOfType<T>();
if (InstanceExists) return _internalInstance;
_internalInstance = CreateSingleton();
//Debug.Log("Creating Singleton");
return _internalInstance;
}
protected set => _internalInstance = value;
}
/// <summary> Whether a Instance of the Singleton exists </summary>
[PublicAPI]
public static bool InstanceExists => (_internalInstance != null);
#endregion
#region Methods
protected virtual void Reset() => Register();
protected virtual void Awake() => Register();
protected virtual void OnEnable() => Register();
protected virtual void OnDisable() => Unregister();
[UsedImplicitly]
private static T CreateSingleton()
{
UnityEngine.GameObject __ownerObject = new UnityEngine.GameObject(name: $"[{typeof(T).Name}]");
T __instance = __ownerObject.AddComponent<T>();
return __instance;
}
/// <summary> Associate Singleton with new instance. </summary>
private void Register()
{
if(InstanceExists && (Instance != this)) //Prefer using already existing Singletons.
{
#if UNITY_EDITOR
if (!UnityEngine.Application.isPlaying)
{
DestroyImmediate(obj: this);
}
else
{
Destroy(obj: this);
}
#else
Destroy(obj: this);
#endif
return;
}
Instance = this as T;
}
/// <summary> Clear Singleton association </summary>
private void Unregister()
{
if (Instance == this)
{
Instance = null;
}
}
#endregion
}
} | 24.32 | 142 | 0.6875 | [
"MIT"
] | Walter-Hulsebos/Utilities.Singletons | Runtime/MonoBehaviour/MonoBehaviourSingleton_Ensured.cs | 2,432 | C# |
//@#$&+
//
//The MIT X11 License
//
//Copyright (c) 2010 - 2017 Icucom Corporation
//
//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 NON-INFRINGEMENT. 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.Collections.Generic;
using System.Collections.ObjectModel;
using System.Reflection;
using System.Security;
using PlatformAgileFramework.Collections;
using PlatformAgileFramework.Collections.ExtensionMethods;
using PlatformAgileFramework.FileAndIO;
using PlatformAgileFramework.FileAndIO.SymbolicDirectories;
using PlatformAgileFramework.Platform;
using PlatformAgileFramework.TypeHandling.TypeExtensionMethods;
using PlatformAgileFramework.TypeHandling.TypeExtensionMethods.Helpers;
namespace PlatformAgileFramework.Manufacturing
{
/// <summary>
/// Helper methods for manufacturing Types in AppDomains. This class is where
/// the system "bootstrapping" actually begins. This class is accessed by
/// other system initialization components to load and scan assemblies. There
/// are several styles of platform coverage supported here, based on the methods
/// and properties on this class. Platform-specific assemblies can be loaded
/// dynamically or they can be linked in statically to the app.
/// This part is Silverlight compatible (single AppDomain).
/// </summary>
/// <history>
/// <contribution>
/// <author> KRM </author>
/// <date> 04nov2017 </date>
/// <desription>
/// <para>
/// Changed to a singleton so we can set static props before use. Moved many functions
/// here from bootstrapper, since bootstrapper is used for service manager and clients
/// want to use another service manager sometimes.
/// </para>
/// </desription>
/// </contribution>
/// <contribution>
/// <author> KRM </author>
/// <date> 02sep2011 </date>
/// <desription>
/// <para>
/// Trying to "morph" our way into the new 4.0 security model and the Silverlight
/// implementation. "SILVERLIGHT" still means the low-security silverlight rules
/// with no possibility of including full-trust stuff, but this file is being made
/// to work in elevated priviledge mode, too.
/// </para>
/// </desription>
/// </contribution>
/// </history>
/// <remarks>
/// <para>
/// Added by KRM - this class does not employ the service manager by design intent.
/// This class must be available at application initialization time in order to
/// locate services dynamically. The other option is to push root services into
/// the manager as statics before the app is started. However, if this class is
/// usable before SM is available, more options are possible.
/// </para>
/// <para>
/// Core only supports loading ONE platform-specific plugin providing logging,
/// storage and UI. It's a good practice to aggregate these functions into a single
/// DLL, anyway.
/// </para>
/// </remarks>
// ReSharper disable PartialTypeWithSinglePart
public partial class ManufacturingUtils
// ReSharper restore PartialTypeWithSinglePart
{
#region Class Fields and Autoproperties
/// <summary>
/// This a thread-safe wrapper for constructing the singleton.
/// </summary>
/// <remarks>
/// Lazy class is thread-safe by default.
/// </remarks>
private static readonly Lazy<ManufacturingUtils> s_Singleton =
new Lazy<ManufacturingUtils>(ConstructManufacturingUtils);
/// <summary>
/// Set when the platform-specific assembly is loaded or an attempt has been
/// made to load it. Or set it to <see langword="true"/> to indicate we don't
/// even want to load any platform-specific assy.
/// </summary>
internal static volatile bool s_IsPlatformAssemblyLoaded;
/// <summary>
/// Platform assy for basic services.
/// </summary>
protected internal static Assembly s_PlatformAssembly;
/// <summary>
/// Container for the assemblies loaded into the current AppDomain. key is the
/// assembly "simple name", in our case, the filename.
/// </summary>
// ReSharper disable once InconsistentNaming
public static IDictionary<string, Assembly> AssembliesLoadedInAppdomain
{
get; [SecurityCritical] set;
}
#region Extension points for static linking
/// <summary>
/// Push this in for loading assemblies on platform. Loads "from" a fileSpec.
/// </summary>
public static Func<string, Assembly> AssemblyLoadFromLoader { get; [SecurityCritical] set; }
/// <summary>
/// Push this in for listing assemblies on platform. Even on platforms where
/// some sort of "GetAssemblies" functionality is not available, the platform
/// assembly can push in itself if it is statically linked. Any assemblies
/// returned from this call are not added if they are already in our collection.
/// The function may return <see langword="null"/>.
/// </summary>
public static Func<IEnumerable<Assembly>> AssemblyLister { get; [SecurityCritical] set; }
#endregion // Extension points for static linking
///// <summary>
///// This one has to be manually set, since there is no reliable way
///// to find out what platform we are on from Microsoft/Xamarin. Used
///// to be able to examine BCL assys, but no more. Too many variations.....
///// </summary>
// public static readonly IPlatformInfo s_CurrentPlatformInfo = new PAF_ECMA4_6_2PlatformInfo();
// // public static readonly IPlatformInfo s_CurrentPlatformInfo = new WinPlatformInfo();
////public static readonly IPlatformInfo s_CurrentPlatformInfo = new MacPlatformInfo();
/// <summary>
/// We need this to do symbolic directory mapping. Set in construction path.
/// </summary>
public static ISymbolicDirectoryMappingDictionary DirectoryMappings
{ get; [SecurityCritical] set; }
/// <summary>
/// We need this to do symbolic directory mapping. Set in construction path.
/// </summary>
internal static ISymbolicDirectoryMappingDictionaryInternal DirectoryMappingsInternal
{ get; set; }
#endregion // Class Fields and Autoproperties
#region Constructors
/// <summary>
/// Create needed collections. Load this assembly
/// into <c>AssembliesLoadedInAppdomain</c>.
/// </summary>
static ManufacturingUtils()
{
AssembliesLoadedInAppdomain = new Dictionary<string, Assembly>();
// Make sure that Platform utils gets loaded when this class gets touched.
// ReSharper disable once UnusedVariable
var platform = PlatformUtils.PlatformInfoInternal;
}
/// <summary>
/// Non-public for testing.
/// </summary>
protected internal ManufacturingUtils()
{
}
#endregion Constructors
#region Properties
/// <summary>
/// Get the singleton instance of the class.
/// </summary>
/// <returns>The singleton.</returns>
public static ManufacturingUtils Instance
{
get
{
return s_Singleton.Value;
}
}
#endregion // Properties
#region Methods
/// <summary>
/// Not quite a constructor - a factory for the lazy construction.
/// </summary>
protected static ManufacturingUtils ConstructManufacturingUtils()
{
var utils = new ManufacturingUtils();
// Just loading the statics, ReSharper...............
// ReSharper disable once UnusedVariable
// Generate an exception here in the constructor so we get it out
// of the way.
var unusedVariable = PlatformUtils.Instance;
// platform statics are loaded, so now we can load the dictionary.
DirectoryMappingsInternal = new SymbolicDirectoryMappingDictionary();
DirectoryMappings = DirectoryMappingsInternal;
// FileUtils must be provisioned with this before SM is released to the public.
PAFFileUtils.SetMappings(DirectoryMappingsInternal);
FindLoadedAssemblies();
return utils;
}
#region Partial Methods
/// <summary>
/// This method is used to find loaded assemblies from a mechanism in a linked-in class.
/// </summary>
/// <param name="assemblies">Collection to add to.</param>
// ReSharper disable UnusedMember.Local
// ReSharper disable PartialMethodWithSinglePart
static partial void FindLoadedAssembliesPartial(ref ICollection<Assembly> assemblies);
// ReSharper restore PartialMethodWithSinglePart
// ReSharper restore UnusedMember.Local
/// <summary>
/// This method is used to load an assembly from a mechanism in a linked-in class.
/// </summary>
/// <param name="assemblyPath">Fully qualified path with assembly name.</param>
/// <param name="assembly">Assembly reference to load into.</param>
// ReSharper disable UnusedMember.Local
// ReSharper disable PartialMethodWithSinglePart
static partial void LoadAssemblyFromFilePartial(string assemblyPath, ref Assembly assembly);
// ReSharper restore PartialMethodWithSinglePart
// ReSharper restore UnusedMember.Local
#endregion // Partial Methods
/// <summary>
/// Standard Type filter for searches. <c>ToString()</c> is performed
/// on criteriaObj to generate a string to match against <c>typeToCheck.FullName</c>.
/// This works out of the box for either <see cref="System.String"/>s or
/// <see cref="System.Type"/>s passed as <paramref name="criteriaObj"/>.
/// </summary>
/// <param name="typeToCheck">
/// <see cref="System.Type"/> to check against the criteria. <see langword="null"/>
/// returns <see langword="false"/>.
/// </param>
/// <param name="criteriaObj">
/// <see langword="null"/> returns <see langword="false"/>.
/// </param>
/// <returns>
/// <see langword="true"/> for a match.
/// </returns>
public static bool DefaultTypeFilter(Type typeToCheck, object criteriaObj)
{
if ((typeToCheck == null) || (criteriaObj == null)) return false;
var stringToCheck = criteriaObj.ToString();
if (criteriaObj.GetType() == typeof(Type)) stringToCheck = ((Type)criteriaObj).FullName;
if (typeToCheck.FullName == stringToCheck)
return true;
return false;
}
#region Partial Method Callers
/// <summary>
/// .Net core cannot find loaded assemblies. They must be pushed in by the
/// platform-specific app. Thus <see cref="AssemblyLister"/> must be present
/// if this assembly is linked with .Net Core. Otherwise it is possible to
/// combine this file with another file which has the implementation of the
/// partial method.
/// </summary>
/// <remarks>
/// Called at application startup time only. No lock needed.
/// </remarks>
protected static void FindLoadedAssemblies()
{
// We always add ourselves.
// ReSharper disable once InconsistentlySynchronizedField
var ourType = typeof(ManufacturingUtils);
var ourselves = ourType.PAFGetAssemblyForType();
var ourName = ourType.PAFGetAssemblySimpleName();
// ReSharper disable once InconsistentlySynchronizedField
AssembliesLoadedInAppdomain.Add(ourName, ourselves);
// try with a lister.
var assys = AssemblyLister?.Invoke();
if (assys != null)
{
foreach (var asm in assys)
{
// ReSharper disable once InconsistentlySynchronizedField
AssembliesLoadedInAppdomain.Add(asm.GetName().FullName, asm);
}
}
var collection = (ICollection<Assembly>)new Collection<Assembly>();
// try with a partial method.
// ReSharper disable once InvocationIsSkipped
FindLoadedAssembliesPartial(ref collection);
foreach (var asm in collection)
{
// ReSharper disable once InconsistentlySynchronizedField
AssembliesLoadedInAppdomain.Add(asm.GetName().FullName, asm);
}
// No name means statically linked.
if (string.IsNullOrEmpty(PlatformUtils.PlatformInfo.CurrentPlatformAssyName)) s_IsPlatformAssemblyLoaded = true;
/////////////////////////////////////////////////////////////////////////////
// Remainder is executed if platform assy is still needed.
if (!s_IsPlatformAssemblyLoaded) return;
// We determine if the platform assy has gotten loaded along the way.
var platformAssembly =
// ReSharper disable once InconsistentlySynchronizedField
PlatformUtils.PlatformInfo.CurrentPlatformAssyName.GetAssemblyFromFullNameKeyedDictionary(AssembliesLoadedInAppdomain);
if (platformAssembly != null)
{
// ReSharper disable once InconsistentlySynchronizedField
s_PlatformAssembly = platformAssembly;
s_IsPlatformAssemblyLoaded = true;
return;
}
// If we pushed in a way to load an assembly, use it.
s_PlatformAssembly = AssemblyLoadFromLoader?.Invoke(PlatformUtils.FormPlatformAssemblyLoadPathWithAssembly());
if (s_PlatformAssembly != null)
{
// ReSharper disable once InconsistentlySynchronizedField
AssembliesLoadedInAppdomain.Add(s_PlatformAssembly.GetAssemblySimpleName(), s_PlatformAssembly);
}
s_PlatformAssembly = LoadPlatformAssembly();
// TODO krm exception here.
// This was the last chance, so we must complain.
}
/// <summary>
/// Call this to load platform-specific assembly.
/// </summary>
/// <remarks>
/// Separated out mostly to support tests not involving the service manager.
/// </remarks>
protected internal static Assembly LoadPlatformAssembly()
{
if (s_IsPlatformAssemblyLoaded) return s_PlatformAssembly;
s_IsPlatformAssemblyLoaded = true;
var platformAssemblyLoadPath = PlatformUtils.FormPlatformAssemblyLoadPathWithAssembly();
// LoadFrom is OK, since we ONLY bind to interfaces.
s_PlatformAssembly = LoadAssembly(platformAssemblyLoadPath);
if (s_PlatformAssembly != null)
AddAssemblyToAssembliesLoadedInternal(s_PlatformAssembly);
return s_PlatformAssembly;
}
/// <summary>
/// Will return <see langword="null"/> if partial class implementation is not present.
/// </summary>
/// <exceptions>
/// None caught, none thrown. Load exceptions are typically generated.
/// </exceptions>
public static Assembly LoadAssembly(string assemblyPath)
{
var assembly = LoadAssemblyFromFile(assemblyPath);
if (assembly != null)
return assembly;
var pathParts = PAFFileUtils.SeparateDirectoryFromFile(assemblyPath);
return Assembly.Load(new AssemblyName(pathParts[1]));
}
private static Assembly LoadAssemblyFromFile(string assemblyPath)
{
Assembly assembly = null;
// ReSharper disable once InvocationIsSkipped
LoadAssemblyFromFilePartial(assemblyPath, ref assembly);
// ReSharper disable once ExpressionIsAlwaysNull
return assembly;
}
#endregion Partial Method Callers
/// <summary>
/// This utility method is needed since listing assemblies is done
/// differently in Silverlight and other platforms.
/// </summary>
/// <returns>
/// Set of assemblies in the current "AppDomain".
/// </returns>
public virtual IEnumerable<Assembly> GetAppDomainAssemblies()
{
IEnumerable<Assembly> col;
lock (AssembliesLoadedInAppdomain)
{
col = new List<Assembly>(AssembliesLoadedInAppdomain.Values);
}
return col;
}
/// <summary>
/// Locates a <see cref="Type"/> in assemblies loaded in an
/// "AppDomain". This method will optionally find a
/// <see cref="Type"/> implementing an interface. Uses
/// <see cref="LocateReflectionTypeInAssembly"/> to find the Type.
/// See that method for details.
/// </summary>
/// <param name="typeName">
/// This is a fully-qualified type name such as "System.Drawing.Size"
/// or <see cref="System.IComparable"/>. See <see cref="LocateReflectionTypeInAssembly"/>
/// for details. If <paramref name="typeNameSpace"/> is specified, this parameter
/// should be a simple name (no namespace).
/// </param>
/// <param name="typeNameSpace">
/// This is a NameSpace such as "System.Drawing" or <see cref="System"/>.
/// If this string is not <see langword="null"/>, it is prepended to the typeName.
/// If the search is for an interface only, (<paramref name="typeName"/> is null),
/// Only Types within the given namespace will be searched for the interface
/// implementation. This is useful in cases where services may be implemented
/// by several different Types in an assembly, but the Types are organized so
/// that only one Type within a given namespace implements an interface.
/// An example of this is <c>System.Data.OleDb.OleDbConnection</c>
/// versus <c>System.Data.SqlClient.SqlClientConnection</c>. Both Types
/// implement <c>System.Data.IDbConnection</c> and live in the same assembly,
/// but in different namespaces.
/// </param>
/// <param name="interfaceName">
/// This is a fully-qualified type name such as <see cref="System.IComparable"/>.
/// See <see cref="LocateReflectionTypeInAssembly"/> for details.
/// </param>
/// <param name="assemblyList">
/// The array of <see cref="Assembly"/>'s to search. These will be searched
/// in order to find the Type. If this parameter is <see langword="null"/>, all assemblies
/// in the current "AppDomain" will be searched.
/// </param>
/// <returns>
/// If the <see cref="Type"/> is found in any assemblies searched, it is
/// returned. If not, <see langword="null"/> is returned without any exceptions.
/// </returns>
/// <remarks>
/// If both <paramref name="typeName"/> and <paramref name="interfaceName"/>
/// are blank or <see langword="null"/>, <see langword="null"/> is returned.
/// </remarks>
public virtual Type LocateReflectionType(string typeName, string typeNameSpace,
string interfaceName, IEnumerable<Assembly> assemblyList = null)
{
if (assemblyList == null) assemblyList = GetAppDomainAssemblies();
// Try to load from any assembly.
// ReSharper disable LoopCanBeConvertedToQuery
foreach (var asm in assemblyList)
// ReSharper restore LoopCanBeConvertedToQuery
{
var type = LocateReflectionTypeInAssembly(asm, typeName, typeNameSpace, interfaceName);
if (type != null) return type;
}
// Fall-through returns null.
return null;
}
/// <summary>
/// Locates a <see cref="Type"/> in a single assembly. This just takes the
/// first type returned from <see cref="LocateReflectionTypesInAssembly"/>.
/// If the client needs to respond to multiple returned types (e.g. an exception),
/// use <see cref="LocateReflectionTypesInAssembly"/>.
/// </summary>
/// <param name="assemblyToSearch">
/// See <see cref="LocateReflectionTypesInAssembly"/>.
/// </param>
/// <param name="typeName">
/// See <see cref="LocateReflectionTypesInAssembly"/>.
/// </param>
/// <param name="typeNameSpace">
/// See <see cref="LocateReflectionTypesInAssembly"/>.
/// </param>
/// <param name="interfaceName">
/// See <see cref="LocateReflectionTypesInAssembly"/>.
/// </param>
/// <param name="typeFilter">
/// See <see cref="LocateReflectionTypesInAssembly"/>.
/// </param>
/// <returns>
/// If the <see cref="Type"/> is found in the assemblies searched, it is
/// returned. If not, <see langword="null"/> is returned without any exceptions. If
/// multiple <see cref="Type"/>s are found that meet the criteria, only
/// the first is returned.
/// </returns>
/// <remarks>
/// If both <paramref name="typeName"/> and <paramref name="interfaceName"/> are
/// blank or <see langword="null"/>, <see langword="null"/> is returned.
/// </remarks>
public virtual Type LocateReflectionTypeInAssembly(Assembly assemblyToSearch,
string typeName, string typeNameSpace = null, string interfaceName = null,
IPAFTypeFilter typeFilter = null)
{
var col = LocateReflectionTypesInAssembly(assemblyToSearch, typeName,
typeNameSpace, interfaceName, typeFilter);
if ((col != null) && (col.Count > 0)) return col.GetFirstElement();
return null;
}
/// <summary>
/// Locates a <see cref="Type"/> in a single assembly.
/// </summary>
/// <param name="assemblyToSearch">
/// A specific assembly to search for. Cannot be <see langword="null"/>.
/// </param>
/// <param name="typeName">
/// This is a fully-qualified type name such as "System.Drawing.Size"
/// or <see cref="System.IComparable"/> or an unqualified type name such as
/// "Size". If this string is <see langword="null"/> or blank, the first
/// non-interface Type implementing the specified interface is returned.
/// If <paramref name="typeNameSpace"/> is specified, this parameter should be an
/// unqualified name (no namespace). In the case of an unqualified type name,
/// with no namespace specified, the first conforming type in the assembly is
/// returned.
/// </param>
/// <param name="typeNameSpace">
/// This is a NameSpace such as "System.Drawing" or <see cref="System"/>.
/// If this string is not <see langword="null"/>, it is prepended to the typeName.
/// If the search is for an interface only, (<paramref name="typeName"/> is null),
/// only Types within the given namespace will be searched for the interface
/// implementation. This is useful in cases where services may be implemented
/// by several different Types in an assembly, but the Types are organized so
/// that only one Type within a given namespace implements an interface.
/// An example of this is <c>System.Data.OleDb.OleDbConnection</c>
/// versus <c>System.Data.SqlClient.SqlClientConnection</c>. Both Types
/// implement <c>System.Data.IDbConnection</c> and live in the same assembly,
/// but in different namespaces. If the namespace is not specified, the FIRST
/// type with the correct <paramref name="typeName"/> is returned. Note that
/// if a <paramref name="typeName"/> and <paramref name="typeNameSpace"/> are both
/// specified, a maximum of one (1) type should ever be returned.
/// </param>
/// <param name="interfaceName">
/// This is a fully-qualified type name such as <see cref="System.IComparable"/>.
/// If this string is <see langword="null"/> or blank, the <paramref name="typeName"/> is used
/// to find the <see cref="System.Type"/> without any regard to implemented
/// interfaces. If the Type name is blank or <see langword="null"/>, the method will
/// only return a Type if it is constructable (not an abstract Type and not an
/// interface).
/// </param>
/// <param name="typeFilter">
/// An optional filter that will eliminate unsuitable types from the search.
/// Default = <see langword="null"/>.
/// </param>
/// <returns>
/// If one or more <see cref="Type"/>s meeting all requirements are found, they are
/// returned. If not, <see langword="null"/> is returned without any exceptions.
/// </returns>
/// <remarks>
/// If both <paramref name="typeName"/> and <paramref name="interfaceName"/> are
/// blank or <see langword="null"/>, <see langword="null"/> is returned.
/// <see langword="null"/> is returned if both <paramref name="typeName"/>
/// and <paramref name="typeNameSpace"/> are <see langword="null"/>.
/// </remarks>
public virtual ICollection<Type> LocateReflectionTypesInAssembly(Assembly assemblyToSearch,
string typeName = null, string typeNameSpace = null, string interfaceName = null,
IPAFTypeFilter typeFilter = null)
{
// Safety valve.
if ((string.IsNullOrEmpty(typeName) && string.IsNullOrEmpty(interfaceName)))
return null;
// This tells us if we are searching for an implementation of an interface
// without regard to implementation type.
var isInterfaceSearch = string.IsNullOrEmpty(typeName);
// If we had a definate Type/Types, things are relatively easy. All we have
// to do is see if it implements the interface.
if (!isInterfaceSearch)
{
// If namespace is not null, prepend it. This condition
// results in return of a single type.
if (typeNameSpace != null)
{
typeName = typeNameSpace + "." + typeName;
var type = assemblyToSearch.GetType(typeName);
// Can't go further if nothing here.
if (type == null) return null;
// Kill it if it's not right.
if (typeFilter != null)
if (!typeFilter.FilteringDelegate(type, typeFilter.FilterAuxiliaryData)) return null;
var retval = new Collection<Type> { type };
return retval;
}
// Next try to locate by unqualified name. This results in multiple types.
var returnedTypes = new Collection<Type>();
var types = assemblyToSearch.PAFGetAccessibleTypes();
foreach (var aType in types)
{
// First apply client filter.
if (typeFilter != null)
{
if (!typeFilter.FilteringDelegate(aType, typeFilter.FilterAuxiliaryData)) continue;
}
if (!aType.UnqualifiedNamesMatch(typeName)) continue;
// Interface present - check it.
if (!string.IsNullOrEmpty(interfaceName))
{
if (aType.FindConformingInterfaces(DefaultTypeFilter, interfaceName) == null)
continue;
}
returnedTypes.Add(aType);
}
if (returnedTypes.Count == 0) return null;
return returnedTypes;
}
return LocateReflectionInterfacesInAssembly(assemblyToSearch, interfaceName,
typeNameSpace, typeFilter);
}
/// <summary>
/// Locates a set of <see cref="Type"/>'s in a single assembly. These
/// types are constrained to implement an interface and are filtered
/// by other OPTIONAL criteria. Since this method works with an
/// <see cref="Assembly"/> instance, it operates locally, finding
/// services already in the current "AppDomain".
/// </summary>
/// <param name="assemblyToSearch">
/// A specific assembly to search for. <see langword="null"/> returns <see langword="null"/>.
/// </param>
/// <param name="interfaceName">
/// This is a fully-qualified type name such as <see cref="System.IComparable"/>.
/// The method will only return a Type if it is constructable (not an abstract
/// Type and not an interface). <see langword="null"/> returns <see langword="null"/>.
/// </param>
/// <param name="typeNameSpace">
/// This is a NameSpace such as "System.Drawing" or <see cref="System"/>.
/// If this string is not <see langword="null"/>, it is used as a filter on returned types.
/// Only Types within the given namespace will be checked for the interface
/// implementation. This is useful in cases where services may be implemented
/// by several different Types in an assembly, but the Types are organized so
/// that only one Type within a given namespace implements an interface.
/// An example of this is <c>System.Data.OleDb.OleDbConnection</c>
/// versus <c>System.Data.SqlClient.SqlClientConnection</c>. Both Types
/// implement <c>System.Data.IDbConnection</c> and live in the same assembly,
/// but in different namespaces. Default = <see langword="null"/>.
/// </param>
/// <param name="typeFilter">
/// An optional <see cref="IPAFTypeFilter"/> delegate that will
/// eliminate unsuitable types from the search. This can be used to operate
/// on attributes or anything else on a <see cref="Type"/>. Default = <see langword="null"/>.
/// </param>
/// <returns>
/// If any conforming <see cref="Type"/>s are found in the assemblies searched,
/// they are returned. If not, <see langword="null"/> is returned without any exceptions.
/// </returns>
public virtual ICollection<Type> LocateReflectionInterfacesInAssembly(
Assembly assemblyToSearch, string interfaceName, string typeNameSpace = null,
IPAFTypeFilter typeFilter = null)
{
// Safety valve.
if ((assemblyToSearch == null) || (string.IsNullOrEmpty(interfaceName)))
return null;
// Loop through all Types and figure out if any implement the interface.
var types = assemblyToSearch.PAFGetAccessibleTypes();
var col = new Collection<Type>();
foreach (var aType in types)
{
// Apply the client's filter.
if (typeFilter != null)
{
if (!typeFilter.FilteringDelegate(aType, typeFilter.FilterAuxiliaryData)) continue;
}
// Filter on namespace if the caller specfied one.
// ReSharper disable PossibleNullReferenceException
if ((string.IsNullOrEmpty(typeNameSpace))
&& (!(aType.FullName.Contains(typeNameSpace + ".")))) continue;
// ReSharper restore PossibleNullReferenceException
// Use DefaultTypeFilter for the interface name only.
var interfaceTypes = aType.FindConformingInterfaces(DefaultTypeFilter, interfaceName);
if ((interfaceTypes != null) && (interfaceTypes.GetFirstElement() != null))
{
col.Add(aType);
}
}
return col.Count == 0 ? null : col;
}
/// <summary>
/// Locates a <see cref="Type"/> in assemblies loaded in an
/// "AppDomain". This method will optionally find a
/// <see cref="Type"/> implementing an interface. Uses
/// <see cref="LocateReflectionTypeInAssembly"/> to find the Type.
/// See that method for details.
/// </summary>
/// <param name="interfaceName">
/// This is a fully-qualified type name such as <see cref="System.IComparable"/>.
/// See <see cref="LocateReflectionTypeInAssembly"/> for details.
/// </param>
/// <param name="typeNameSpace">
/// This is a NameSpace such as "System.Drawing" or <see cref="System"/>.
/// If this string is not <see langword="null"/>, it is prepended to the typeName.
/// If the search is for an interface only, (<paramref name="typeName"/> is null),
/// Only Types within the given namespace will be searched for the interface
/// implementation. This is useful in cases where services may be implemented
/// by several different Types in an assembly, but the Types are organized so
/// that only one Type within a given namespace implements an interface.
/// An example of this is <c>System.Data.OleDb.OleDbConnection</c>
/// versus <c>System.Data.SqlClient.SqlClientConnection</c>. Both Types
/// implement <c>System.Data.IDbConnection</c> and live in the same assembly,
/// but in different namespaces.
/// </param>
/// <param name="typeName">
/// This can be a fully-qualified type name such as "System.Drawing.Size".
/// See <see cref="LocateReflectionTypeInAssembly"/> for details. If
/// <paramref name="typeNameSpace"/> is specified, this parameter should
/// be a simple name (no namespace).
/// </param>
/// <param name="typeFilter">
/// See <see cref="LocateReflectionTypesInAssembly"/>.
/// </param>
/// <param name="assemblyList">
/// The array of <see cref="Assembly"/>'s to search. These will be searched
/// in order to find the Type. If this parameter is <see langword="null"/>, all assemblies
/// in the current "AppDomain" will be searched.
/// </param>
/// <returns>
/// If the <see cref="Type"/> is found in any assemblies searched, it is
/// returned. If not, <see langword="null"/> is returned without any exceptions.
/// </returns>
/// <remarks>
/// If both <paramref name="typeName"/> and <paramref name="interfaceName"/>
/// are blank or <see langword="null"/>, <see langword="null"/> is returned.
/// </remarks>
public virtual ICollection<Type> LocateReflectionServices(string interfaceName,
string typeNameSpace = null, string typeName = null,
IPAFTypeFilter typeFilter = null,
IEnumerable<Assembly> assemblyList = null)
{
if (assemblyList == null) assemblyList = GetAppDomainAssemblies();
// Try to load from any assembly.
var outCol = new Collection<Type>();
// ReSharper disable LoopCanBeConvertedToQuery
foreach (var asm in assemblyList)
// ReSharper restore LoopCanBeConvertedToQuery
{
var col = LocateReflectionServicesInAssembly(asm, interfaceName, typeNameSpace,
typeName, typeFilter);
if (col != null) outCol.AddItems(col);
}
if ((outCol.Count == 0))
return null;
return outCol;
}
/// <summary>
/// This method works exactly the same as <see cref="LocateReflectionTypesInAssembly"/>
/// with the added restriction on returned <see cref="Type"/>s that they be instantiable.
/// The check is made for an abstract class or a pure interface type and those types are
/// culled from the returned set. This is intended to produce a set of implementing types
/// that can be built and run. No check is made for the presence of any particular
/// constructor. It is up to the client to do this in their installed filter.
/// </summary>
/// <param name="assemblyToSearch">
/// See <see cref="LocateReflectionInterfacesInAssembly"/>.
/// </param>
/// <param name="interfaceName">
/// See <see cref="LocateReflectionTypesInAssembly"/>.
/// The method will only return a Type if it is constructable (not an abstract
/// Type and not an interface). <see langword="null"/> returns <see langword="null"/>.
/// </param>
/// <param name="typeNameSpace">
/// See <see cref="LocateReflectionTypesInAssembly"/>.
/// </param>
/// <param name="typeName">
/// See <see cref="LocateReflectionTypesInAssembly"/>.
/// </param>
/// <param name="typeFilter">
/// See <see cref="LocateReflectionTypesInAssembly"/>.
/// </param>
/// <returns>
/// If any conforming <see cref="Type"/>s are found in the assemblies searched,
/// they are returned. If not, <see langword="null"/> is returned without any exceptions.
/// </returns>
public virtual ICollection<Type> LocateReflectionServicesInAssembly(Assembly assemblyToSearch,
string interfaceName, string typeNameSpace = null, string typeName = null,
IPAFTypeFilter typeFilter = null)
{
// We wish to apply a filter that culls out interfaces and abstract classes.
var filterContainer = new PAFTypeFilter(TypeExtensions.IsTypeInstantiable);
// We must combine the filter with the one the client has provided, if any.
var filterAggregator = new PAFTypeFilterAggregator();
filterAggregator.AddFilter(filterContainer);
if (typeFilter != null)
{
filterAggregator.AddFilter(typeFilter);
}
var outCol = LocateReflectionTypesInAssembly(assemblyToSearch, typeName,
typeNameSpace, interfaceName, filterAggregator);
if ((outCol == null) || (outCol.Count == 0)) return null;
return outCol;
}
#region Internal/Secure Methods for Framework Extenders
/// <summary>
/// Adds an assembly into the collection of loaded assemblies.
/// </summary>
/// <param name="assembly">Assembly to add.</param>
/// <returns>
/// <see langword="false"/> if the assembly was already in the collection.
/// </returns>
/// <threadsafety>
/// Made thread-safe through a monitor. Not a high-traffic zone, so this
/// is fine.
/// </threadsafety>
internal static bool AddAssemblyToAssembliesLoadedInternal(Assembly assembly)
{
lock (AssembliesLoadedInAppdomain)
{
if (AssembliesLoadedInAppdomain.ContainsKey(assembly.GetName().Name)) return false;
AssembliesLoadedInAppdomain.Add(assembly.GetName().Name, assembly);
return true;
}
}
/// <summary>
/// Elevated-trust entry into <see cref="AddAssemblyToAssembliesLoadedInternal"/>.
/// </summary>
/// <see cref="AddAssemblyToAssembliesLoadedInternal"/>.
/// <returns>
/// <see cref="AddAssemblyToAssembliesLoadedInternal"/>.
/// </returns>
/// <threadsafety>
/// <see cref="AddAssemblyToAssembliesLoadedInternal"/>.
/// </threadsafety>
[SecurityCritical]
public static bool AddAssemblyToAssembliesLoaded(Assembly assembly)
{
return AddAssemblyToAssembliesLoadedInternal(assembly);
}
#endregion // Internal/Secure Methods for Framework Extenders
#endregion //Methods
}
}
| 43.530733 | 124 | 0.689956 | [
"MIT"
] | Platform-Agile-Software/PAF-Community | PlatformAgileFrameworkCore/PlatformAgileFrameworkCoreStandard/Manufacturing/Core_ManufacturingUtils.cs | 36,827 | C# |
using System.Text;
using Spectre.Console;
namespace ThemesOfDotNet.Indexing;
public static class GitHubActions
{
public struct Group : IDisposable
{
public void Dispose()
{
EndGroup();
}
}
public static bool SeenErrors { get; private set; }
public static bool IsRunningInside
{
get => Environment.GetEnvironmentVariable("GITHUB_ACTIONS") == "true";
}
public static Group BeginGroup(string title)
{
if (IsRunningInside)
Console.WriteLine($"::group::{title}");
return new Group();
}
public static void EndGroup()
{
if (IsRunningInside)
Console.WriteLine($"::endgroup::");
}
public static void Notice(string message,
string? fileName = null,
int? line = null,
int? endLine = null,
int? column = null,
int? endColumn = null)
{
Message("notice", message, fileName, line, endLine, column, endColumn);
}
public static void Warning(string message,
string? fileName = null,
int? line = null,
int? endLine = null,
int? column = null,
int? endColumn = null)
{
Message("warning", message, fileName, line, endLine, column, endColumn);
}
public static void Error(Exception exception)
{
if (!IsRunningInside)
{
AnsiConsole.WriteException(exception);
}
else
{
Error(exception.ToString());
}
}
public static void Error(string message,
string? fileName = null,
int? line = null,
int? endLine = null,
int? column = null,
int? endColumn = null)
{
Message("error", message, fileName, line, endLine, column, endColumn);
}
private static void Message(string kind,
string message,
string? fileName = null,
int? line = null,
int? endLine = null,
int? column = null,
int? endColumn = null)
{
ArgumentNullException.ThrowIfNull(kind);
ArgumentNullException.ThrowIfNull(message);
if (kind == "error")
SeenErrors = true;
if (!IsRunningInside)
{
var sb = new StringBuilder();
if (kind == "error")
sb.Append("[red]");
else if (kind == "warning")
sb.Append("[yellow]");
sb.Append(kind);
sb.Append(": ");
if (fileName is not null)
{
sb.Append(fileName);
sb.Append(": ");
}
sb.Append(message.EscapeMarkup());
if (kind == "error" || kind == "warning")
sb.Append("[/]");
AnsiConsole.MarkupLine(sb.ToString());
}
else
{
var sb = new StringBuilder();
sb.Append($"::{kind}");
if (fileName is not null)
{
sb.Append($" file={fileName}");
if (line is not null)
sb.Append($",line={line}");
if (endLine is not null)
sb.Append($",endLine={endLine}");
if (column is not null)
sb.Append($",col={column}");
if (endColumn is not null)
sb.Append($",endCol={endColumn}");
}
sb.Append($"::{message}");
Console.WriteLine(sb.ToString());
Console.WriteLine(sb.ToString().Substring(2));
}
}
}
| 27.598639 | 80 | 0.441952 | [
"MIT"
] | terrajobst/themesof.net | src/ThemesOfDotNet.Indexing/GitHubActions.cs | 4,057 | C# |
//
// System.Collections.Generic.List
//
// Authors:
// Ben Maurer (bmaurer@ximian.com)
// Martin Baulig (martin@ximian.com)
// Carlos Alberto Cortez (calberto.cortez@gmail.com)
// David Waite (mass@akuma.org)
//
// Copyright (C) 2004-2005 Novell, Inc (http://www.novell.com)
// Copyright (C) 2005 David Waite
//
// 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.
//
#if NET_2_0
using System.Collections.ObjectModel;
using System.Runtime.InteropServices;
namespace System.Collections.Generic {
[Serializable]
public class List <T> : IList <T>, IList, ICollection {
T [] _items;
int _size;
int _version;
static readonly T [] EmptyArray = new T [0];
const int DefaultCapacity = 4;
public List ()
{
_items = EmptyArray;
}
public List (IEnumerable <T> collection)
{
CheckCollection (collection);
// initialize to needed size (if determinable)
ICollection <T> c = collection as ICollection <T>;
if (c == null)
{
_items = EmptyArray;
AddEnumerable (collection);
}
else
{
_items = new T [c.Count];
AddCollection (c);
}
}
public List (int capacity)
{
if (capacity < 0)
throw new ArgumentOutOfRangeException ("capacity");
_items = new T [capacity];
}
internal List (T [] data, int size)
{
_items = data;
_size = size;
}
public void Add (T item)
{
// If we check to see if we need to grow before trying to grow
// we can speed things up by 25%
if (_size == _items.Length)
GrowIfNeeded (1);
_items [_size ++] = item;
_version++;
}
void GrowIfNeeded (int newCount)
{
int minimumSize = _size + newCount;
if (minimumSize > _items.Length)
Capacity = Math.Max (Math.Max (Capacity * 2, DefaultCapacity), minimumSize);
}
void CheckRange (int idx, int count)
{
if (idx < 0)
throw new ArgumentOutOfRangeException ("index");
if (count < 0)
throw new ArgumentOutOfRangeException ("count");
if ((uint) idx + (uint) count > (uint) _size)
throw new ArgumentException ("index and count exceed length of list");
}
void AddCollection (ICollection <T> collection)
{
int collectionCount = collection.Count;
GrowIfNeeded (collectionCount);
collection.CopyTo (_items, _size);
_size += collectionCount;
}
void AddEnumerable (IEnumerable <T> enumerable)
{
foreach (T t in enumerable)
{
Add (t);
}
}
public void AddRange (IEnumerable <T> collection)
{
//Console.WriteLine(collection);
CheckCollection (collection);
ICollection <T> c = collection as ICollection <T>;
if (c != null)
AddCollection (c);
else
AddEnumerable (collection);
_version++;
}
public ReadOnlyCollection <T> AsReadOnly ()
{
return new ReadOnlyCollection <T> (this);
}
public int BinarySearch (T item)
{
return Array.BinarySearch <T> (_items, 0, _size, item);
}
public int BinarySearch (T item, IComparer <T> comparer)
{
return Array.BinarySearch <T> (_items, 0, _size, item, comparer);
}
public int BinarySearch (int index, int count, T item, IComparer <T> comparer)
{
CheckRange (index, count);
return Array.BinarySearch <T> (_items, index, count, item, comparer);
}
public void Clear ()
{
Array.Clear (_items, 0, _items.Length);
_size = 0;
_version++;
}
public bool Contains (T item)
{
return Array.IndexOf<T>(_items, item, 0, _size) != -1;
}
public List <TOutput> ConvertAll <TOutput> (Converter <T, TOutput> converter)
{
if (converter == null)
throw new ArgumentNullException ("converter");
List <TOutput> u = new List <TOutput> (_size);
for (int i = 0; i < _size; i++)
u._items[i] = converter(_items[i]);
u._size = _size;
return u;
}
public void CopyTo (T [] array)
{
Array.Copy (_items, 0, array, 0, _size);
}
public void CopyTo (T [] array, int arrayIndex)
{
Array.Copy (_items, 0, array, arrayIndex, _size);
}
public void CopyTo (int index, T [] array, int arrayIndex, int count)
{
CheckRange (index, count);
Array.Copy (_items, index, array, arrayIndex, count);
}
public bool Exists (Predicate <T> match)
{
CheckMatch(match);
return GetIndex(0, _size, match) != -1;
}
public T Find (Predicate <T> match)
{
CheckMatch(match);
int i = GetIndex(0, _size, match);
return (i != -1) ? _items [i] : default (T);
}
static void CheckMatch (Predicate <T> match)
{
if (match == null)
throw new ArgumentNullException ("match");
}
#if NOT_PFX
public List <T> FindAll (Predicate <T> match)
{
CheckMatch (match);
if (this._size <= 0x10000) // <= 8 * 1024 * 8 (8k in stack)
return this.FindAllStackBits (match);
else
return this.FindAllList (match);
}
private List <T> FindAllStackBits (Predicate <T> match)
{
unsafe
{
uint *bits = stackalloc uint [(this._size / 32) + 1];
uint *ptr = bits;
int found = 0;
uint bitmask = 0x80000000;
for (int i = 0; i < this._size; i++)
{
if (match (this._items [i]))
{
(*ptr) = (*ptr) | bitmask;
found++;
}
bitmask = bitmask >> 1;
if (bitmask == 0)
{
ptr++;
bitmask = 0x80000000;
}
}
T [] results = new T [found];
bitmask = 0x80000000;
ptr = bits;
int j = 0;
for (int i = 0; i < this._size && j < found; i++)
{
if (((*ptr) & bitmask) == bitmask)
results [j++] = this._items [i];
bitmask = bitmask >> 1;
if (bitmask == 0)
{
ptr++;
bitmask = 0x80000000;
}
}
return new List <T> (results, found);
}
}
#endif
private List <T> FindAllList (Predicate <T> match)
{
List <T> results = new List <T> ();
for (int i = 0; i < this._size; i++)
if (match (this._items [i]))
results.Add (this._items [i]);
return results;
}
public int FindIndex (Predicate <T> match)
{
CheckMatch (match);
return GetIndex (0, _size, match);
}
public int FindIndex (int startIndex, Predicate <T> match)
{
CheckMatch (match);
CheckIndex (startIndex);
return GetIndex (startIndex, _size - startIndex, match);
}
public int FindIndex (int startIndex, int count, Predicate <T> match)
{
CheckMatch (match);
CheckRange (startIndex, count);
return GetIndex (startIndex, count, match);
}
int GetIndex (int startIndex, int count, Predicate <T> match)
{
int end = startIndex + count;
for (int i = startIndex; i < end; i ++)
if (match (_items [i]))
return i;
return -1;
}
public T FindLast (Predicate <T> match)
{
CheckMatch (match);
int i = GetLastIndex (0, _size, match);
return i == -1 ? default (T) : this [i];
}
public int FindLastIndex (Predicate <T> match)
{
CheckMatch (match);
return GetLastIndex (0, _size, match);
}
public int FindLastIndex (int startIndex, Predicate <T> match)
{
CheckMatch (match);
CheckIndex (startIndex);
return GetLastIndex (0, startIndex + 1, match);
}
public int FindLastIndex (int startIndex, int count, Predicate <T> match)
{
CheckMatch (match);
int start = startIndex - count + 1;
CheckRange (start, count);
return GetLastIndex (start, count, match);
}
int GetLastIndex (int startIndex, int count, Predicate <T> match)
{
// unlike FindLastIndex, takes regular params for search range
for (int i = startIndex + count; i != startIndex;)
if (match (_items [--i]))
return i;
return -1;
}
public void ForEach (Action <T> action)
{
if (action == null)
throw new ArgumentNullException ("action");
for(int i=0; i < _size; i++)
action(_items[i]);
}
public Enumerator GetEnumerator ()
{
return new Enumerator (this);
}
public List <T> GetRange (int index, int count)
{
CheckRange (index, count);
T [] tmpArray = new T [count];
Array.Copy (_items, index, tmpArray, 0, count);
return new List <T> (tmpArray, count);
}
public int IndexOf (T item)
{
return Array.IndexOf<T> (_items, item, 0, _size);
}
public int IndexOf (T item, int index)
{
CheckIndex (index);
return Array.IndexOf<T> (_items, item, index, _size - index);
}
public int IndexOf (T item, int index, int count)
{
if (index < 0)
throw new ArgumentOutOfRangeException ("index");
if (count < 0)
throw new ArgumentOutOfRangeException ("count");
if ((uint) index + (uint) count > (uint) _size)
throw new ArgumentOutOfRangeException ("index and count exceed length of list");
return Array.IndexOf<T> (_items, item, index, count);
}
void Shift (int start, int delta)
{
if (delta < 0)
start -= delta;
if (start < _size)
Array.Copy (_items, start, _items, start + delta, _size - start);
_size += delta;
}
void CheckIndex (int index)
{
if (index < 0 || (uint) index > (uint) _size)
throw new ArgumentOutOfRangeException ("index");
}
public void Insert (int index, T item)
{
CheckIndex (index);
if (_size == _items.Length)
GrowIfNeeded (1);
Shift (index, 1);
_items[index] = item;
_version++;
}
void CheckCollection (IEnumerable <T> collection)
{
if (collection == null)
throw new ArgumentNullException ("collection");
}
public void InsertRange (int index, IEnumerable <T> collection)
{
CheckCollection (collection);
CheckIndex (index);
if (collection == this) {
T[] buffer = new T[_size];
CopyTo (buffer, 0);
GrowIfNeeded (_size);
Shift (index, buffer.Length);
Array.Copy (buffer, 0, _items, index, buffer.Length);
} else {
ICollection <T> c = collection as ICollection <T>;
if (c != null)
InsertCollection (index, c);
else
InsertEnumeration (index, collection);
}
_version++;
}
void InsertCollection (int index, ICollection <T> collection)
{
int collectionCount = collection.Count;
GrowIfNeeded (collectionCount);
Shift (index, collectionCount);
collection.CopyTo (_items, index);
}
void InsertEnumeration (int index, IEnumerable <T> enumerable)
{
foreach (T t in enumerable)
Insert (index++, t);
}
public int LastIndexOf (T item)
{
return Array.LastIndexOf<T> (_items, item, _size - 1, _size);
}
public int LastIndexOf (T item, int index)
{
CheckIndex (index);
return Array.LastIndexOf<T> (_items, item, index, index + 1);
}
public int LastIndexOf (T item, int index, int count)
{
if (index < 0)
throw new ArgumentOutOfRangeException ("index", index, "index is negative");
if (count < 0)
throw new ArgumentOutOfRangeException ("count", count, "count is negative");
if (index - count + 1 < 0)
throw new ArgumentOutOfRangeException ("cound", count, "count is too large");
return Array.LastIndexOf<T> (_items, item, index, count);
}
public bool Remove (T item)
{
int loc = IndexOf (item);
if (loc != -1)
RemoveAt (loc);
return loc != -1;
}
public int RemoveAll (Predicate <T> match)
{
CheckMatch(match);
int i = 0;
int j = 0;
// Find the first item to remove
for (i = 0; i < _size; i++)
if (match(_items[i]))
break;
if (i == _size)
return 0;
_version++;
// Remove any additional items
for (j = i + 1; j < _size; j++)
{
if (!match(_items[j]))
_items[i++] = _items[j];
}
_size = i;
return (j - i);
}
public void RemoveAt (int index)
{
if (index < 0 || (uint)index >= (uint)_size)
throw new ArgumentOutOfRangeException("index");
Shift (index, -1);
Array.Clear (_items, _size, 1);
_version++;
}
public void RemoveRange (int index, int count)
{
CheckRange (index, count);
if (count > 0) {
Shift (index, -count);
Array.Clear (_items, _size, count);
_version++;
}
}
public void Reverse ()
{
Array.Reverse (_items, 0, _size);
_version++;
}
public void Reverse (int index, int count)
{
CheckRange (index, count);
Array.Reverse (_items, index, count);
_version++;
}
public void Sort ()
{
Array.Sort<T> (_items, 0, _size, Comparer <T>.Default);
_version++;
}
public void Sort (IComparer <T> comparer)
{
Array.Sort<T> (_items, 0, _size, comparer);
_version++;
}
public void Sort (Comparison <T> comparison)
{
Array.Sort<T> (_items, _size, comparison);
_version++;
}
public void Sort (int index, int count, IComparer <T> comparer)
{
CheckRange (index, count);
Array.Sort<T> (_items, index, count, comparer);
_version++;
}
public T [] ToArray ()
{
T [] t = new T [_size];
Array.Copy (_items, t, _size);
return t;
}
public void TrimExcess ()
{
Capacity = _size;
}
public bool TrueForAll (Predicate <T> match)
{
CheckMatch (match);
for (int i = 0; i < _size; i++)
if (!match(_items[i]))
return false;
return true;
}
public int Capacity {
get {
return _items.Length;
}
set {
if ((uint) value < (uint) _size)
throw new ArgumentOutOfRangeException ();
Array.Resize (ref _items, value);
}
}
public int Count {
get { return _size; }
}
public T this [int index] {
get {
if ((uint) index >= (uint) _size)
throw new ArgumentOutOfRangeException ("index");
return _items [index];
}
set {
CheckIndex (index);
if ((uint) index == (uint) _size)
throw new ArgumentOutOfRangeException ("index");
_items [index] = value;
}
}
#region Interface implementations.
IEnumerator <T> IEnumerable <T>.GetEnumerator ()
{
return GetEnumerator ();
}
void ICollection.CopyTo (Array array, int arrayIndex)
{
Array.Copy (_items, 0, array, arrayIndex, _size);
}
IEnumerator IEnumerable.GetEnumerator ()
{
return GetEnumerator ();
}
int IList.Add (object item)
{
try {
Add ((T) item);
} catch (InvalidCastException) {
throw new ArgumentException("item");
}
return _size - 1;
}
bool IList.Contains (object item)
{
try {
return Contains ((T) item);
} catch (InvalidCastException) {
return false;
}
}
int IList.IndexOf (object item)
{
try {
return IndexOf((T) item);
} catch (InvalidCastException) {
return -1;
}
}
void IList.Insert (int index, object item)
{
// We need to check this first because, even if the
// item is null or not the correct type, we need to
// return an ArgumentOutOfRange exception if the
// index is out of range
CheckIndex (index);
try {
Insert (index, (T) item);
} catch (InvalidCastException) {
throw new ArgumentException("item");
}
}
void IList.Remove (object item)
{
try {
Remove ((T) item);
} catch (InvalidCastException) {
// Swallow the exception--if we
// can't cast to the correct type
// then we've already "succeeded"
// in removing the item from the
// List.
}
}
bool ICollection <T>.IsReadOnly {
get { return false; }
}
bool ICollection.IsSynchronized {
get { return false; }
}
object ICollection.SyncRoot {
get { return this; }
}
bool IList.IsFixedSize {
get { return false; }
}
bool IList.IsReadOnly {
get { return false; }
}
object IList.this [int index] {
get { return this [index]; }
set { this [index] = (T) value; }
}
#endregion
[Serializable]
public struct Enumerator : IEnumerator <T>, IDisposable {
const int NOT_STARTED = -2;
// this MUST be -1, because we depend on it in move next.
// we just decr the size, so, 0 - 1 == FINISHED
const int FINISHED = -1;
List <T> l;
int idx;
int ver;
internal Enumerator (List <T> l)
{
this.l = l;
idx = NOT_STARTED;
ver = l._version;
}
// for some fucked up reason, MSFT added a useless dispose to this class
// It means that in foreach, we must still do a try/finally. Broken, very
// broken.
public void Dispose ()
{
idx = NOT_STARTED;
}
public bool MoveNext ()
{
if (ver != l._version)
throw new InvalidOperationException ("Collection was modified;"
+ "enumeration operation may not execute.");
if (idx == NOT_STARTED)
idx = l._size;
return idx != FINISHED && -- idx != FINISHED;
}
public T Current {
get {
if (idx < 0)
throw new InvalidOperationException ();
return l._items [l._size - 1 - idx];
}
}
void IEnumerator.Reset ()
{
if (ver != l._version)
throw new InvalidOperationException ("Collection was modified;"
+ "enumeration operation may not execute.");
idx = NOT_STARTED;
}
object IEnumerator.Current {
get { return Current; }
}
}
}
}
#endif
| 23.537688 | 85 | 0.588439 | [
"MIT"
] | GrapeCity/pagefx | mono/mcs/class/corlib/System.Collections.Generic/List.cs | 18,736 | C# |
namespace Phenix.Unity.AI.BT
{
[TaskIcon("TaskIcons/Idle.png")]
public class Idle : Action<IdleImpl> { }
[System.Serializable]
public class IdleImpl : ActionImpl
{
/*public float time = 0;
float _startTimer = 0;
public override void OnTurnBegin()
{
base.OnTurnBegin();
_startTimer = Time.timeSinceLevelLoad;
}
public override void OnTurnEnd()
{
base.OnTurnEnd();
}*/
public override TaskStatus Run()
{
/*if (time > 0 && _startTimer + time <= Time.timeSinceLevelLoad)
{
return TaskStatus.Success;
}*/
return TaskStatus.RUNNING;
}
}
} | 22.727273 | 76 | 0.521333 | [
"MIT"
] | phenix1021/PhenixDotNet | PhenixUnity/src/AI/BT/Actions/Idle.cs | 752 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("BolwtimEscolar")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("BolwtimEscolar")]
[assembly: AssemblyCopyright("Copyright © 2019")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("1d214a4b-dc62-4e83-bdd0-488735d5c910")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.702703 | 84 | 0.749104 | [
"MIT"
] | AnnaGalvao/Boletim | BolwtimEscolar/Properties/AssemblyInfo.cs | 1,396 | C# |
using UnityEngine;
using Unity.MLAgents;
using Unity.MLAgents.Actuators;
using Unity.MLAgentsExamples;
using Unity.MLAgents.Sensors;
[RequireComponent(typeof(JointDriveController))] // Required to set joint forces
public class WormAgent : Agent
{
const float m_MaxWalkingSpeed = 10; //The max walking speed
[Header("Target Prefabs")] public Transform TargetPrefab; //Target prefab to use in Dynamic envs
private Transform m_Target; //Target the agent will walk towards during training.
[Header("Body Parts")] public Transform bodySegment0;
public Transform bodySegment1;
public Transform bodySegment2;
public Transform bodySegment3;
//This will be used as a stabilized model space reference point for observations
//Because ragdolls can move erratically during training, using a stabilized reference transform improves learning
OrientationCubeController m_OrientationCube;
//The indicator graphic gameobject that points towards the target
DirectionIndicator m_DirectionIndicator;
JointDriveController m_JdController;
private Vector3 m_StartingPos; //starting position of the agent
public override void Initialize()
{
SpawnTarget(TargetPrefab, transform.position); //spawn target
m_StartingPos = bodySegment0.position;
m_OrientationCube = GetComponentInChildren<OrientationCubeController>();
m_DirectionIndicator = GetComponentInChildren<DirectionIndicator>();
m_JdController = GetComponent<JointDriveController>();
UpdateOrientationObjects();
//Setup each body part
m_JdController.SetupBodyPart(bodySegment0);
m_JdController.SetupBodyPart(bodySegment1);
m_JdController.SetupBodyPart(bodySegment2);
m_JdController.SetupBodyPart(bodySegment3);
}
/// <summary>
/// Spawns a target prefab at pos
/// </summary>
/// <param name="prefab"></param>
/// <param name="pos"></param>
void SpawnTarget(Transform prefab, Vector3 pos)
{
m_Target = Instantiate(prefab, pos, Quaternion.identity, transform.parent);
}
/// <summary>
/// Loop over body parts and reset them to initial conditions.
/// </summary>
public override void OnEpisodeBegin()
{
foreach (var bodyPart in m_JdController.bodyPartsList)
{
bodyPart.Reset(bodyPart);
}
//Random start rotation to help generalize
bodySegment0.rotation = Quaternion.Euler(0, Random.Range(0.0f, 360.0f), 0);
UpdateOrientationObjects();
}
/// <summary>
/// Add relevant information on each body part to observations.
/// </summary>
public void CollectObservationBodyPart(BodyPart bp, VectorSensor sensor)
{
//GROUND CHECK
sensor.AddObservation(bp.groundContact.touchingGround ? 1 : 0); // Whether the bp touching the ground
//Get velocities in the context of our orientation cube's space
//Note: You can get these velocities in world space as well but it may not train as well.
sensor.AddObservation(m_OrientationCube.transform.InverseTransformDirection(bp.rb.velocity));
sensor.AddObservation(m_OrientationCube.transform.InverseTransformDirection(bp.rb.angularVelocity));
if (bp.rb.transform != bodySegment0)
{
//Get position relative to hips in the context of our orientation cube's space
sensor.AddObservation(
m_OrientationCube.transform.InverseTransformDirection(bp.rb.position - bodySegment0.position));
sensor.AddObservation(bp.rb.transform.localRotation);
}
if (bp.joint)
sensor.AddObservation(bp.currentStrength / m_JdController.maxJointForceLimit);
}
public override void CollectObservations(VectorSensor sensor)
{
RaycastHit hit;
float maxDist = 10;
if (Physics.Raycast(bodySegment0.position, Vector3.down, out hit, maxDist))
{
sensor.AddObservation(hit.distance / maxDist);
}
else
sensor.AddObservation(1);
var cubeForward = m_OrientationCube.transform.forward;
var velGoal = cubeForward * m_MaxWalkingSpeed;
sensor.AddObservation(m_OrientationCube.transform.InverseTransformDirection(velGoal));
sensor.AddObservation(Quaternion.Angle(m_OrientationCube.transform.rotation,
m_JdController.bodyPartsDict[bodySegment0].rb.rotation) / 180);
sensor.AddObservation(Quaternion.FromToRotation(bodySegment0.forward, cubeForward));
//Add pos of target relative to orientation cube
sensor.AddObservation(m_OrientationCube.transform.InverseTransformPoint(m_Target.transform.position));
foreach (var bodyPart in m_JdController.bodyPartsList)
{
CollectObservationBodyPart(bodyPart, sensor);
}
}
/// <summary>
/// Agent touched the target
/// </summary>
public void TouchedTarget()
{
AddReward(1f);
}
public override void OnActionReceived(ActionBuffers actionBuffers)
{
// The dictionary with all the body parts in it are in the jdController
var bpDict = m_JdController.bodyPartsDict;
var i = -1;
var continuousActions = actionBuffers.ContinuousActions;
// Pick a new target joint rotation
bpDict[bodySegment0].SetJointTargetRotation(continuousActions[++i], continuousActions[++i], 0);
bpDict[bodySegment1].SetJointTargetRotation(continuousActions[++i], continuousActions[++i], 0);
bpDict[bodySegment2].SetJointTargetRotation(continuousActions[++i], continuousActions[++i], 0);
// Update joint strength
bpDict[bodySegment0].SetJointStrength(continuousActions[++i]);
bpDict[bodySegment1].SetJointStrength(continuousActions[++i]);
bpDict[bodySegment2].SetJointStrength(continuousActions[++i]);
//Reset if Worm fell through floor;
if (bodySegment0.position.y < m_StartingPos.y - 2)
{
EndEpisode();
}
}
void FixedUpdate()
{
UpdateOrientationObjects();
var velReward =
GetMatchingVelocityReward(m_OrientationCube.transform.forward * m_MaxWalkingSpeed,
m_JdController.bodyPartsDict[bodySegment0].rb.velocity);
//Angle of the rotation delta between cube and body.
//This will range from (0, 180)
var rotAngle = Quaternion.Angle(m_OrientationCube.transform.rotation,
m_JdController.bodyPartsDict[bodySegment0].rb.rotation);
//The reward for facing the target
var facingRew = 0f;
//If we are within 30 degrees of facing the target
if (rotAngle < 30)
{
//Set normalized facingReward
//Facing the target perfectly yields a reward of 1
facingRew = 1 - (rotAngle / 180);
}
//Add the product of these two rewards
AddReward(velReward * facingRew);
}
/// <summary>
/// Normalized value of the difference in actual speed vs goal walking speed.
/// </summary>
public float GetMatchingVelocityReward(Vector3 velocityGoal, Vector3 actualVelocity)
{
//distance between our actual velocity and goal velocity
var velDeltaMagnitude = Mathf.Clamp(Vector3.Distance(actualVelocity, velocityGoal), 0, m_MaxWalkingSpeed);
//return the value on a declining sigmoid shaped curve that decays from 1 to 0
//This reward will approach 1 if it matches perfectly and approach zero as it deviates
return Mathf.Pow(1 - Mathf.Pow(velDeltaMagnitude / m_MaxWalkingSpeed, 2), 2);
}
/// <summary>
/// Update OrientationCube and DirectionIndicator
/// </summary>
void UpdateOrientationObjects()
{
m_OrientationCube.UpdateOrientation(bodySegment0, m_Target);
if (m_DirectionIndicator)
{
m_DirectionIndicator.MatchOrientation(m_OrientationCube.transform);
}
}
}
| 38.929245 | 118 | 0.667273 | [
"Apache-2.0"
] | pengzhi1998/ml-agents | Project/Assets/ML-Agents/Examples/Worm/Scripts/WormAgent.cs | 8,253 | C# |
using System;
using System.Linq;
using System.Collections.Generic;
namespace WizardCastle {
internal static partial class Game {
public static void RevealMapCell(State state, MapPos loc) =>
state.Map[loc].Known = true;
public static void HideMapCell(State state, MapPos loc) =>
state.Map[loc].Known = false;
public static void RevealMapArea(State state, MapPos loc) {
var neighbors = new MapPos[] {
new MapPos(row: -1, col: -1),
new MapPos(row: -1, col: 0),
new MapPos(row: -1, col: 1),
new MapPos(row: 0, col: -1),
new MapPos(row: 0, col: 1),
new MapPos(row: 1, col: -1),
new MapPos(row: 1, col: 0),
new MapPos(row: 1, col: 1)
}
.Select(x => x + loc)
.Where(x => state.Map.ValidPos(x));
foreach(var p in neighbors) {
RevealMapCell(state, p);
}
}
public static void DisplayLevel(State state) {
state.Map.Traverse((map, p) => {
if (p == state.Player.Location) {
state.SetBgColor(ConsoleColor.DarkMagenta).Write(" * ");
} else if (!map[p].Known) {
state.SetColor(ConsoleColor.White).Write(" X ");
} else {
var content = map[p].Content;
// if (map[player.location[0], j, k] == "Zot") { roomValue = "W";
if (content == null) {
state.SetColor(ConsoleColor.White).Write(" - ");
} else if (content is IMonster) {
state.SetColor(ConsoleColor.White).Write(" M ");
} else {
state.Write($" {content.Symbol} ");
}
}
state.ResetColors();
if (p.Col == map.Cols - 1) { state.WriteLine(); }
}, state.Player.Location.Level);
}
/*
public static MapPos RandEmptyMapPos(State state) => state.Map.RandEmptyPos();
public static IEnumerable<(Map.Cell cell, MapPos pos)> SearchMap(State state, Func<Map.Cell, MapPos, bool> pred) =>
state.Map.Search(pred);
public static IEnumerable<(Map.Cell cell, MapPos pos)> SearchMap(State state, IHasName item) =>
SearchMap(state, item);
*/
}
} | 33.613333 | 123 | 0.482745 | [
"MIT"
] | Baavgai/Wizards-Castle-40th-Anniversary-CSharp-Edition | Reorg/Game/Map.cs | 2,523 | C# |
namespace Miruken.Mvc.Console
{
using System;
public abstract class FrameworkElement
{
public Size Size { get; set; }
public Size DesiredSize { get; set; }
public Size ActualSize { get; set; }
public Thickness Margin { get; set; }
public Thickness Border { get; set; }
public Thickness Padding { get; set; }
public Point Point { get; set; }
public VerticalAlignment VerticalAlignment { get; set; }
public HorizontalAlignment HorizontalAlignment { get; set; }
public Boundry ContentBoundry { get; set; }
protected FrameworkElement()
{
Point = Point.Default;
Margin = Thickness.Default;
Border = Thickness.Default;
Padding = Thickness.Default;
}
public virtual void Initialize()
{
}
public virtual void Measure(Size availableSize)
{
if (Size == null)
{
DesiredSize = new Size(availableSize);
return;
}
var height = Size.Height > availableSize.Height
? availableSize.Height
: Size.Height;
var width = Size.Width > availableSize.Width
? availableSize.Width
: Size.Width;
DesiredSize = new Size(Math.Max(0, width), Math.Max(0, height));
}
public virtual void Arrange(Rectangle rectangle)
{
Point = rectangle.Location;
var availableSize = rectangle.Size;
var height = DesiredSize.Height > availableSize.Height
? availableSize.Height
: DesiredSize.Height;
var width = DesiredSize.Width > availableSize.Width
? availableSize.Width
: DesiredSize.Width;
ActualSize = new Size(Math.Max(width, 0), Math.Max(height, 0));
}
public virtual void Render(Cells cells)
{
new RenderElement().Handle(this, cells);
}
public virtual void KeyPressed(ConsoleKeyInfo keyInfo)
{
}
public virtual Boundry Boundry
{
get
{
var x2 = Point.X + ActualSize.Width;
var y2 = Point.Y + ActualSize.Height;
return new Boundry(new Point(Point), new Point(x2, y2));
}
}
}
}
| 32.353659 | 77 | 0.492273 | [
"MIT"
] | Miruken-DotNet/miruken.mvc | Source/Miruken.Mvc.Console/FrameworkElement/FrameworkElement.cs | 2,655 | C# |
using MediatR;
using System.Threading;
using System.Threading.Tasks;
using DAS_Capture_The_Flag.Application.Models.GameModels;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.AspNetCore.Identity;
using DAS_Capture_The_Flag.Data;
using System.Linq;
namespace DAS_Capture_The_Flag.Web.Handlers.GetPlayerDetails
{
public class GetPlayerDetailsHandler : IRequestHandler<GetPlayerDetailsRequest, PlayerDetails>
{
private readonly ApplicationDbContext _db;
public GetPlayerDetailsHandler(ApplicationDbContext db)
{
_db = db;
}
public async Task<PlayerDetails> Handle(GetPlayerDetailsRequest request, CancellationToken cancellationToken)
{
var user = _db.Users.FirstOrDefault(user => user.Id == request.Id.ToString());
return new PlayerDetails(user.UserName);
}
}
}
| 31.62069 | 117 | 0.740458 | [
"MIT"
] | SkillsFundingAgency/das-apprentice-learning | src/SFA.DAS.CaptureTheFlag.Web/Handlers/GetPlayerDetails/GetPlayerDetailsHandler.cs | 919 | C# |
using Diga.WebView2.Interop;
using System;
using Diga.WebView2.Wrapper.EventArguments;
namespace Diga.WebView2.Wrapper.Handler
{
public class MoveFocusRequestedEventHandler : ICoreWebView2MoveFocusRequestedEventHandler
{
public event EventHandler<MoveFocusRequestedEventArgs> MoveFocusRequested;
protected virtual void OnMoveFocusRequested(MoveFocusRequestedEventArgs e)
{
MoveFocusRequested?.Invoke(this, e);
}
#if V9488
public void Invoke(ICoreWebView2Controller sender, ICoreWebView2MoveFocusRequestedEventArgs args)
{
OnMoveFocusRequested(new MoveFocusRequestedEventArgs(args));
}
#else
public void Invoke(ICoreWebView2Host sender, ICoreWebView2MoveFocusRequestedEventArgs args)
{
OnMoveFocusRequested(new MoveFocusRequestedEventArgs(args));
}
#endif
}
} | 29.733333 | 105 | 0.732063 | [
"MIT"
] | ITAgnesmeyer/Diga.WebView2 | Archive/V9430/Diga.WebView2.Wrapper.V9430/Handler/MoveFocusRequestedEventHandler.cs | 894 | 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\IEntityWithReferenceRequest.cs.tt
namespace Microsoft.Graph
{
using System;
using System.IO;
using System.Net.Http;
using System.Threading;
using System.Linq.Expressions;
/// <summary>
/// The interface IItemAnalyticsWithReferenceRequest.
/// </summary>
public partial interface IItemAnalyticsWithReferenceRequest : IBaseRequest
{
/// <summary>
/// Gets the specified ItemAnalytics.
/// </summary>
/// <returns>The ItemAnalytics.</returns>
System.Threading.Tasks.Task<ItemAnalytics> GetAsync();
/// <summary>
/// Gets the specified ItemAnalytics.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The ItemAnalytics.</returns>
System.Threading.Tasks.Task<ItemAnalytics> GetAsync(CancellationToken cancellationToken);
/// <summary>
/// Creates the specified ItemAnalytics using POST.
/// </summary>
/// <param name="itemAnalyticsToCreate">The ItemAnalytics to create.</param>
/// <returns>The created ItemAnalytics.</returns>
System.Threading.Tasks.Task<ItemAnalytics> CreateAsync(ItemAnalytics itemAnalyticsToCreate); /// <summary>
/// Creates the specified ItemAnalytics using POST.
/// </summary>
/// <param name="itemAnalyticsToCreate">The ItemAnalytics to create.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The created ItemAnalytics.</returns>
System.Threading.Tasks.Task<ItemAnalytics> CreateAsync(ItemAnalytics itemAnalyticsToCreate, CancellationToken cancellationToken);
/// <summary>
/// Updates the specified ItemAnalytics using PATCH.
/// </summary>
/// <param name="itemAnalyticsToUpdate">The ItemAnalytics to update.</param>
/// <returns>The updated ItemAnalytics.</returns>
System.Threading.Tasks.Task<ItemAnalytics> UpdateAsync(ItemAnalytics itemAnalyticsToUpdate);
/// <summary>
/// Updates the specified ItemAnalytics using PATCH.
/// </summary>
/// <param name="itemAnalyticsToUpdate">The ItemAnalytics 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 ItemAnalytics.</returns>
System.Threading.Tasks.Task<ItemAnalytics> UpdateAsync(ItemAnalytics itemAnalyticsToUpdate, CancellationToken cancellationToken);
/// <summary>
/// Deletes the specified ItemAnalytics.
/// </summary>
/// <returns>The task to await.</returns>
System.Threading.Tasks.Task DeleteAsync();
/// <summary>
/// Deletes the specified ItemAnalytics.
/// </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>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="value">The expand value.</param>
/// <returns>The request object to send.</returns>
IItemAnalyticsWithReferenceRequest 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>
IItemAnalyticsWithReferenceRequest Expand(Expression<Func<ItemAnalytics, 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>
IItemAnalyticsWithReferenceRequest 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>
IItemAnalyticsWithReferenceRequest Select(Expression<Func<ItemAnalytics, object>> selectExpression);
}
}
| 47.157407 | 153 | 0.644021 | [
"MIT"
] | OfficeGlobal/msgraph-beta-sdk-dotnet | src/Microsoft.Graph/Requests/Generated/IItemAnalyticsWithReferenceRequest.cs | 5,093 | 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.
// The Regex class represents a single compiled instance of a regular
// expression.
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Threading;
namespace System.Text.RegularExpressions
{
/// <summary>
/// Represents an immutable, compiled regular expression. Also
/// contains static methods that allow use of regular expressions without instantiating
/// a Regex explicitly.
/// </summary>
public class Regex
{
protected internal string pattern; // The string pattern provided
protected internal RegexOptions roptions; // the top-level options from the options string
// *********** Match timeout fields { ***********
// We need this because time is queried using Environment.TickCount for performance reasons
// (Environment.TickCount returns milliseconds as an int and cycles):
private static readonly TimeSpan MaximumMatchTimeout = TimeSpan.FromMilliseconds(Int32.MaxValue - 1);
// InfiniteMatchTimeout specifies that match timeout is switched OFF. It allows for faster code paths
// compared to simply having a very large timeout.
// We do not want to ask users to use System.Threading.Timeout.InfiniteTimeSpan as a parameter because:
// (1) We do not want to imply any relation between having using a RegEx timeout and using multi-threading.
// (2) We do not want to require users to take ref to a contract assembly for threading just to use RegEx.
// There may in theory be a SKU that has RegEx, but no multithreading.
// We create a public Regex.InfiniteMatchTimeout constant, which for consistency uses the save underlying
// value as Timeout.InfiniteTimeSpan creating an implementation detail dependency only.
public static readonly TimeSpan InfiniteMatchTimeout = Timeout.InfiniteTimeSpan;
protected internal TimeSpan internalMatchTimeout; // timeout for the execution of this regex
// DefaultMatchTimeout specifies the match timeout to use if no other timeout was specified
// by one means or another. Typically, it is set to InfiniteMatchTimeout.
internal static readonly TimeSpan DefaultMatchTimeout = InfiniteMatchTimeout;
// *********** } match timeout fields ***********
protected internal RegexRunnerFactory factory;
internal Dictionary<int, int> _caps; // if captures are sparse, this is the hashtable capnum->index
internal Dictionary<string, int> _capnames; // if named captures are used, this maps names->index
protected internal String[] capslist; // if captures are sparse or named captures are used, this is the sorted list of names
protected internal int capsize; // the size of the capture array
protected IDictionary Caps
{
get
{
return _caps;
}
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
_caps = value as Dictionary<int, int>;
if (_caps == null)
{
_caps = new Dictionary<int, int>(value.Count);
foreach (DictionaryEntry entry in value)
{
_caps.Add((int)entry.Key, (int)entry.Value);
}
}
}
}
protected IDictionary CapNames
{
get
{
return _capnames;
}
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
_capnames = value as Dictionary<string, int>;
if (_capnames == null)
{
_capnames = new Dictionary<string, int>(value.Count);
foreach (DictionaryEntry entry in value)
{
_capnames.Add((string)entry.Key, (int)entry.Value);
}
}
}
}
internal ExclusiveReference _runnerref; // cached runner
internal SharedReference _replref; // cached parsed replacement pattern
internal RegexCode _code; // if interpreted, this is the code for RegexInterpreter
internal bool _refsInitialized = false;
internal static LinkedList<CachedCodeEntry> s_livecode = new LinkedList<CachedCodeEntry>();// the cache of code and factories that are currently loaded
internal static int s_cacheSize = 15;
internal const int MaxOptionShift = 10;
protected Regex()
{
internalMatchTimeout = DefaultMatchTimeout;
}
/// <summary>
/// Creates and compiles a regular expression object for the specified regular
/// expression.
/// </summary>
public Regex(String pattern)
: this(pattern, RegexOptions.None, DefaultMatchTimeout, false)
{
}
/// <summary>
/// Creates and compiles a regular expression object for the
/// specified regular expression with options that modify the pattern.
/// </summary>
public Regex(String pattern, RegexOptions options)
: this(pattern, options, DefaultMatchTimeout, false)
{
}
public Regex(String pattern, RegexOptions options, TimeSpan matchTimeout)
: this(pattern, options, matchTimeout, false)
{
}
private Regex(String pattern, RegexOptions options, TimeSpan matchTimeout, bool useCache)
{
RegexTree tree;
CachedCodeEntry cached = null;
string cultureKey = null;
if (pattern == null)
throw new ArgumentNullException(nameof(pattern));
if (options < RegexOptions.None || (((int)options) >> MaxOptionShift) != 0)
throw new ArgumentOutOfRangeException(nameof(options));
if ((options & RegexOptions.ECMAScript) != 0
&& (options & ~(RegexOptions.ECMAScript |
RegexOptions.IgnoreCase |
RegexOptions.Multiline |
RegexOptions.CultureInvariant
#if DEBUG
| RegexOptions.Debug
#endif
)) != 0)
throw new ArgumentOutOfRangeException(nameof(options));
ValidateMatchTimeout(matchTimeout);
// Try to look up this regex in the cache. We do this regardless of whether useCache is true since there's
// really no reason not to.
if ((options & RegexOptions.CultureInvariant) != 0)
cultureKey = CultureInfo.InvariantCulture.ToString(); // "English (United States)"
else
cultureKey = CultureInfo.CurrentCulture.ToString();
var key = new CachedCodeEntryKey(options, cultureKey, pattern);
cached = LookupCachedAndUpdate(key);
this.pattern = pattern;
roptions = options;
internalMatchTimeout = matchTimeout;
if (cached == null)
{
// Parse the input
tree = RegexParser.Parse(pattern, roptions);
// Extract the relevant information
_capnames = tree._capnames;
capslist = tree._capslist;
_code = RegexWriter.Write(tree);
_caps = _code._caps;
capsize = _code._capsize;
InitializeReferences();
tree = null;
if (useCache)
cached = CacheCode(key);
}
else
{
_caps = cached._caps;
_capnames = cached._capnames;
capslist = cached._capslist;
capsize = cached._capsize;
_code = cached._code;
_runnerref = cached._runnerref;
_replref = cached._replref;
_refsInitialized = true;
}
}
// Note: "<" is the XML entity for smaller ("<").
/// <summary>
/// Validates that the specified match timeout value is valid.
/// The valid range is <code>TimeSpan.Zero < matchTimeout <= Regex.MaximumMatchTimeout</code>.
/// </summary>
/// <param name="matchTimeout">The timeout value to validate.</param>
/// <exception cref="System.ArgumentOutOfRangeException">If the specified timeout is not within a valid range.
/// </exception>
protected internal static void ValidateMatchTimeout(TimeSpan matchTimeout)
{
if (InfiniteMatchTimeout == matchTimeout)
return;
// Change this to make sure timeout is not longer then Environment.Ticks cycle length:
if (TimeSpan.Zero < matchTimeout && matchTimeout <= MaximumMatchTimeout)
return;
throw new ArgumentOutOfRangeException(nameof(matchTimeout));
}
/// <summary>
/// Escapes a minimal set of metacharacters (\, *, +, ?, |, {, [, (, ), ^, $, ., #, and
/// whitespace) by replacing them with their \ codes. This converts a string so that
/// it can be used as a constant within a regular expression safely. (Note that the
/// reason # and whitespace must be escaped is so the string can be used safely
/// within an expression parsed with x mode. If future Regex features add
/// additional metacharacters, developers should depend on Escape to escape those
/// characters as well.)
/// </summary>
public static String Escape(String str)
{
if (str == null)
throw new ArgumentNullException(nameof(str));
return RegexParser.Escape(str);
}
/// <summary>
/// Unescapes any escaped characters in the input string.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Unescape", Justification = "Already shipped since v1 - can't fix without causing a breaking change")]
public static String Unescape(String str)
{
if (str == null)
throw new ArgumentNullException(nameof(str));
return RegexParser.Unescape(str);
}
[SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "Reviewed for thread-safety")]
public static int CacheSize
{
get
{
return s_cacheSize;
}
set
{
if (value < 0)
throw new ArgumentOutOfRangeException(nameof(value));
s_cacheSize = value;
if (s_livecode.Count > s_cacheSize)
{
lock (s_livecode)
{
while (s_livecode.Count > s_cacheSize)
s_livecode.RemoveLast();
}
}
}
}
/// <summary>
/// Returns the options passed into the constructor
/// </summary>
public RegexOptions Options
{
get { return roptions; }
}
/// <summary>
/// The match timeout used by this Regex instance.
/// </summary>
public TimeSpan MatchTimeout
{
get { return internalMatchTimeout; }
}
/// <summary>
/// Indicates whether the regular expression matches from right to left.
/// </summary>
public bool RightToLeft
{
get
{
return UseOptionR();
}
}
/// <summary>
/// Returns the regular expression pattern passed into the constructor
/// </summary>
public override string ToString()
{
return pattern;
}
/*
* Returns an array of the group names that are used to capture groups
* in the regular expression. Only needed if the regex is not known until
* runtime, and one wants to extract captured groups. (Probably unusual,
* but supplied for completeness.)
*/
/// <summary>
/// Returns the GroupNameCollection for the regular expression. This collection contains the
/// set of strings used to name capturing groups in the expression.
/// </summary>
public String[] GetGroupNames()
{
String[] result;
if (capslist == null)
{
int max = capsize;
result = new String[max];
for (int i = 0; i < max; i++)
{
result[i] = Convert.ToString(i, CultureInfo.InvariantCulture);
}
}
else
{
result = new String[capslist.Length];
System.Array.Copy(capslist, 0, result, 0, capslist.Length);
}
return result;
}
/*
* Returns an array of the group numbers that are used to capture groups
* in the regular expression. Only needed if the regex is not known until
* runtime, and one wants to extract captured groups. (Probably unusual,
* but supplied for completeness.)
*/
/// <summary>
/// Returns the integer group number corresponding to a group name.
/// </summary>
public int[] GetGroupNumbers()
{
int[] result;
if (_caps == null)
{
int max = capsize;
result = new int[max];
for (int i = 0; i < max; i++)
{
result[i] = i;
}
}
else
{
result = new int[_caps.Count];
foreach (KeyValuePair<int, int> kvp in _caps)
{
result[kvp.Value] = kvp.Key;
}
}
return result;
}
/*
* Given a group number, maps it to a group name. Note that numbered
* groups automatically get a group name that is the decimal string
* equivalent of its number.
*
* Returns null if the number is not a recognized group number.
*/
/// <summary>
/// Retrieves a group name that corresponds to a group number.
/// </summary>
public String GroupNameFromNumber(int i)
{
if (capslist == null)
{
if (i >= 0 && i < capsize)
return i.ToString(CultureInfo.InvariantCulture);
return String.Empty;
}
else
{
if (_caps != null)
{
if (!_caps.TryGetValue(i, out i))
return String.Empty;
}
if (i >= 0 && i < capslist.Length)
return capslist[i];
return String.Empty;
}
}
/*
* Given a group name, maps it to a group number. Note that numbered
* groups automatically get a group name that is the decimal string
* equivalent of its number.
*
* Returns -1 if the name is not a recognized group name.
*/
/// <summary>
/// Returns a group number that corresponds to a group name.
/// </summary>
public int GroupNumberFromName(String name)
{
int result = -1;
if (name == null)
throw new ArgumentNullException(nameof(name));
// look up name if we have a hashtable of names
if (_capnames != null)
{
if (!_capnames.TryGetValue(name, out result))
return -1;
return result;
}
// convert to an int if it looks like a number
result = 0;
for (int i = 0; i < name.Length; i++)
{
char ch = name[i];
if (ch > '9' || ch < '0')
return -1;
result *= 10;
result += (ch - '0');
}
// return int if it's in range
if (result >= 0 && result < capsize)
return result;
return -1;
}
/*
* Static version of simple IsMatch call
*/
/// <summary>
/// Searches the input string for one or more occurrences of the text supplied in the given pattern.
/// </summary>
public static bool IsMatch(String input, String pattern)
{
return IsMatch(input, pattern, RegexOptions.None, DefaultMatchTimeout);
}
/*
* Static version of simple IsMatch call
*/
/// <summary>
/// Searches the input string for one or more occurrences of the text
/// supplied in the pattern parameter with matching options supplied in the options
/// parameter.
/// </summary>
public static bool IsMatch(String input, String pattern, RegexOptions options)
{
return IsMatch(input, pattern, options, DefaultMatchTimeout);
}
public static bool IsMatch(String input, String pattern, RegexOptions options, TimeSpan matchTimeout)
{
return new Regex(pattern, options, matchTimeout, true).IsMatch(input);
}
/*
* Returns true if the regex finds a match within the specified string
*/
/// <summary>
/// Searches the input string for one or more matches using the previous pattern,
/// options, and starting position.
/// </summary>
public bool IsMatch(String input)
{
if (input == null)
throw new ArgumentNullException(nameof(input));
return IsMatch(input, UseOptionR() ? input.Length : 0);
}
/*
* Returns true if the regex finds a match after the specified position
* (proceeding leftward if the regex is leftward and rightward otherwise)
*/
/// <summary>
/// Searches the input string for one or more matches using the previous pattern and options,
/// with a new starting position.
/// </summary>
public bool IsMatch(String input, int startat)
{
if (input == null)
throw new ArgumentNullException(nameof(input));
return (null == Run(true, -1, input, 0, input.Length, startat));
}
/*
* Static version of simple Match call
*/
/// <summary>
/// Searches the input string for one or more occurrences of the text
/// supplied in the pattern parameter.
/// </summary>
public static Match Match(String input, String pattern)
{
return Match(input, pattern, RegexOptions.None, DefaultMatchTimeout);
}
/*
* Static version of simple Match call
*/
/// <summary>
/// Searches the input string for one or more occurrences of the text
/// supplied in the pattern parameter. Matching is modified with an option
/// string.
/// </summary>
public static Match Match(String input, String pattern, RegexOptions options)
{
return Match(input, pattern, options, DefaultMatchTimeout);
}
public static Match Match(String input, String pattern, RegexOptions options, TimeSpan matchTimeout)
{
return new Regex(pattern, options, matchTimeout, true).Match(input);
}
/*
* Finds the first match for the regular expression starting at the beginning
* of the string (or at the end of the string if the regex is leftward)
*/
/// <summary>
/// Matches a regular expression with a string and returns
/// the precise result as a RegexMatch object.
/// </summary>
public Match Match(String input)
{
if (input == null)
throw new ArgumentNullException(nameof(input));
return Match(input, UseOptionR() ? input.Length : 0);
}
/*
* Finds the first match, starting at the specified position
*/
/// <summary>
/// Matches a regular expression with a string and returns
/// the precise result as a RegexMatch object.
/// </summary>
public Match Match(String input, int startat)
{
if (input == null)
throw new ArgumentNullException(nameof(input));
return Run(false, -1, input, 0, input.Length, startat);
}
/*
* Finds the first match, restricting the search to the specified interval of
* the char array.
*/
/// <summary>
/// Matches a regular expression with a string and returns the precise result as a
/// RegexMatch object.
/// </summary>
public Match Match(String input, int beginning, int length)
{
if (input == null)
throw new ArgumentNullException(nameof(input));
return Run(false, -1, input, beginning, length, UseOptionR() ? beginning + length : beginning);
}
/*
* Static version of simple Matches call
*/
/// <summary>
/// Returns all the successful matches as if Match were called iteratively numerous times.
/// </summary>
public static MatchCollection Matches(String input, String pattern)
{
return Matches(input, pattern, RegexOptions.None, DefaultMatchTimeout);
}
/*
* Static version of simple Matches call
*/
/// <summary>
/// Returns all the successful matches as if Match were called iteratively numerous times.
/// </summary>
public static MatchCollection Matches(String input, String pattern, RegexOptions options)
{
return Matches(input, pattern, options, DefaultMatchTimeout);
}
public static MatchCollection Matches(String input, String pattern, RegexOptions options, TimeSpan matchTimeout)
{
return new Regex(pattern, options, matchTimeout, true).Matches(input);
}
/*
* Finds the first match for the regular expression starting at the beginning
* of the string Enumerator(or at the end of the string if the regex is leftward)
*/
/// <summary>
/// Returns all the successful matches as if Match was called iteratively numerous times.
/// </summary>
public MatchCollection Matches(String input)
{
if (input == null)
throw new ArgumentNullException(nameof(input));
return Matches(input, UseOptionR() ? input.Length : 0);
}
/*
* Finds the first match, starting at the specified position
*/
/// <summary>
/// Returns all the successful matches as if Match was called iteratively numerous times.
/// </summary>
public MatchCollection Matches(String input, int startat)
{
if (input == null)
throw new ArgumentNullException(nameof(input));
return new MatchCollection(this, input, 0, input.Length, startat);
}
/// <summary>
/// Replaces all occurrences of the pattern with the <paramref name="replacement"/> pattern, starting at
/// the first character in the input string.
/// </summary>
public static String Replace(String input, String pattern, String replacement)
{
return Replace(input, pattern, replacement, RegexOptions.None, DefaultMatchTimeout);
}
/// <summary>
/// Replaces all occurrences of
/// the <paramref name="pattern "/>with the <paramref name="replacement "/>
/// pattern, starting at the first character in the input string.
/// </summary>
public static String Replace(String input, String pattern, String replacement, RegexOptions options)
{
return Replace(input, pattern, replacement, options, DefaultMatchTimeout);
}
public static String Replace(String input, String pattern, String replacement, RegexOptions options, TimeSpan matchTimeout)
{
return new Regex(pattern, options, matchTimeout, true).Replace(input, replacement);
}
/// <summary>
/// Replaces all occurrences of the previously defined pattern with the
/// <paramref name="replacement"/> pattern, starting at the first character in the
/// input string.
/// </summary>
public String Replace(String input, String replacement)
{
if (input == null)
throw new ArgumentNullException(nameof(input));
return Replace(input, replacement, -1, UseOptionR() ? input.Length : 0);
}
/// <summary>
/// Replaces all occurrences of the previously defined pattern with the
/// <paramref name="replacement"/> pattern, starting at the first character in the
/// input string.
/// </summary>
public String Replace(String input, String replacement, int count)
{
if (input == null)
throw new ArgumentNullException(nameof(input));
return Replace(input, replacement, count, UseOptionR() ? input.Length : 0);
}
/// <summary>
/// Replaces all occurrences of the previously defined pattern with the
/// <paramref name="replacement"/> pattern, starting at the character position
/// <paramref name="startat"/>.
/// </summary>
public String Replace(String input, String replacement, int count, int startat)
{
if (input == null)
throw new ArgumentNullException(nameof(input));
if (replacement == null)
throw new ArgumentNullException(nameof(replacement));
// a little code to grab a cached parsed replacement object
RegexReplacement repl = (RegexReplacement)_replref.Get();
if (repl == null || !repl.Pattern.Equals(replacement))
{
repl = RegexParser.ParseReplacement(replacement, _caps, capsize, _capnames, roptions);
_replref.Cache(repl);
}
return repl.Replace(this, input, count, startat);
}
/// <summary>
/// Replaces all occurrences of the <paramref name="pattern"/> with the recent
/// replacement pattern.
/// </summary>
public static String Replace(String input, String pattern, MatchEvaluator evaluator)
{
return Replace(input, pattern, evaluator, RegexOptions.None, DefaultMatchTimeout);
}
/// <summary>
/// Replaces all occurrences of the <paramref name="pattern"/> with the recent
/// replacement pattern, starting at the first character.
/// </summary>
public static String Replace(String input, String pattern, MatchEvaluator evaluator, RegexOptions options)
{
return Replace(input, pattern, evaluator, options, DefaultMatchTimeout);
}
public static String Replace(String input, String pattern, MatchEvaluator evaluator, RegexOptions options, TimeSpan matchTimeout)
{
return new Regex(pattern, options, matchTimeout, true).Replace(input, evaluator);
}
/// <summary>
/// Replaces all occurrences of the previously defined pattern with the recent
/// replacement pattern, starting at the first character position.
/// </summary>
public String Replace(String input, MatchEvaluator evaluator)
{
if (input == null)
throw new ArgumentNullException(nameof(input));
return Replace(input, evaluator, -1, UseOptionR() ? input.Length : 0);
}
/// <summary>
/// Replaces all occurrences of the previously defined pattern with the recent
/// replacement pattern, starting at the first character position.
/// </summary>
public String Replace(String input, MatchEvaluator evaluator, int count)
{
if (input == null)
throw new ArgumentNullException(nameof(input));
return Replace(input, evaluator, count, UseOptionR() ? input.Length : 0);
}
/// <summary>
/// Replaces all occurrences of the previously defined pattern with the recent
/// replacement pattern, starting at the character position
/// <paramref name="startat"/>.
/// </summary>
public String Replace(String input, MatchEvaluator evaluator, int count, int startat)
{
if (input == null)
throw new ArgumentNullException(nameof(input));
return RegexReplacement.Replace(evaluator, this, input, count, startat);
}
/// <summary>
/// Splits the <paramref name="input "/>string at the position defined
/// by <paramref name="pattern"/>.
/// </summary>
public static String[] Split(String input, String pattern)
{
return Split(input, pattern, RegexOptions.None, DefaultMatchTimeout);
}
/// <summary>
/// Splits the <paramref name="input "/>string at the position defined by <paramref name="pattern"/>.
/// </summary>
public static String[] Split(String input, String pattern, RegexOptions options)
{
return Split(input, pattern, options, DefaultMatchTimeout);
}
public static String[] Split(String input, String pattern, RegexOptions options, TimeSpan matchTimeout)
{
return new Regex(pattern, options, matchTimeout, true).Split(input);
}
/// <summary>
/// Splits the <paramref name="input"/> string at the position defined by a
/// previous pattern.
/// </summary>
public String[] Split(String input)
{
if (input == null)
throw new ArgumentNullException(nameof(input));
return Split(input, 0, UseOptionR() ? input.Length : 0);
}
/// <summary>
/// Splits the <paramref name="input"/> string at the position defined by a
/// previous pattern.
/// </summary>
public String[] Split(String input, int count)
{
if (input == null)
throw new ArgumentNullException(nameof(input));
return RegexReplacement.Split(this, input, count, UseOptionR() ? input.Length : 0);
}
/// <summary>
/// Splits the <paramref name="input"/> string at the position defined by a
/// previous pattern.
/// </summary>
public String[] Split(String input, int count, int startat)
{
if (input == null)
throw new ArgumentNullException(nameof(input));
return RegexReplacement.Split(this, input, count, startat);
}
protected void InitializeReferences()
{
if (_refsInitialized)
throw new NotSupportedException(SR.OnlyAllowedOnce);
_refsInitialized = true;
_runnerref = new ExclusiveReference();
_replref = new SharedReference();
}
/*
* Internal worker called by all the public APIs
*/
internal Match Run(bool quick, int prevlen, String input, int beginning, int length, int startat)
{
Match match;
RegexRunner runner = null;
if (startat < 0 || startat > input.Length)
throw new ArgumentOutOfRangeException("start", SR.BeginIndexNotNegative);
if (length < 0 || length > input.Length)
throw new ArgumentOutOfRangeException(nameof(length), SR.LengthNotNegative);
// There may be a cached runner; grab ownership of it if we can.
runner = (RegexRunner)_runnerref.Get();
// Create a RegexRunner instance if we need to
if (runner == null)
{
if (factory != null)
runner = factory.CreateInstance();
else
runner = new RegexInterpreter(_code, UseOptionInvariant() ? CultureInfo.InvariantCulture : CultureInfo.CurrentCulture);
}
try
{
// Do the scan starting at the requested position
match = runner.Scan(this, input, beginning, beginning + length, startat, prevlen, quick, internalMatchTimeout);
}
finally
{
// Release or fill the cache slot
_runnerref.Release(runner);
}
#if DEBUG
if (Debug && match != null)
match.Dump();
#endif
return match;
}
/*
* Find code cache based on options+pattern
*/
private static CachedCodeEntry LookupCachedAndUpdate(CachedCodeEntryKey key)
{
lock (s_livecode)
{
for (LinkedListNode<CachedCodeEntry> current = s_livecode.First; current != null; current = current.Next)
{
if (current.Value._key == key)
{
// If we find an entry in the cache, move it to the head at the same time.
s_livecode.Remove(current);
s_livecode.AddFirst(current);
return current.Value;
}
}
}
return null;
}
/*
* Add current code to the cache
*/
private CachedCodeEntry CacheCode(CachedCodeEntryKey key)
{
CachedCodeEntry newcached = null;
lock (s_livecode)
{
// first look for it in the cache and move it to the head
for (LinkedListNode<CachedCodeEntry> current = s_livecode.First; current != null; current = current.Next)
{
if (current.Value._key == key)
{
s_livecode.Remove(current);
s_livecode.AddFirst(current);
return current.Value;
}
}
// it wasn't in the cache, so we'll add a new one. Shortcut out for the case where cacheSize is zero.
if (s_cacheSize != 0)
{
newcached = new CachedCodeEntry(key, _capnames, capslist, _code, _caps, capsize, _runnerref, _replref);
s_livecode.AddFirst(newcached);
if (s_livecode.Count > s_cacheSize)
s_livecode.RemoveLast();
}
}
return newcached;
}
/*
* True if the L option was set
*/
internal bool UseOptionR()
{
return (roptions & RegexOptions.RightToLeft) != 0;
}
internal bool UseOptionInvariant()
{
return (roptions & RegexOptions.CultureInvariant) != 0;
}
#if DEBUG
/*
* True if the regex has debugging enabled
*/
internal bool Debug
{
get
{
return (roptions & RegexOptions.Debug) != 0;
}
}
#endif
}
/*
* Callback class
*/
public delegate String MatchEvaluator(Match match);
/*
* Used as a key for CacheCodeEntry
*/
internal struct CachedCodeEntryKey : IEquatable<CachedCodeEntryKey>
{
private readonly RegexOptions _options;
private readonly string _cultureKey;
private readonly string _pattern;
internal CachedCodeEntryKey(RegexOptions options, string cultureKey, string pattern)
{
_options = options;
_cultureKey = cultureKey;
_pattern = pattern;
}
public override bool Equals(object obj)
{
return obj is CachedCodeEntryKey && Equals((CachedCodeEntryKey)obj);
}
public bool Equals(CachedCodeEntryKey other)
{
return this == other;
}
public static bool operator ==(CachedCodeEntryKey left, CachedCodeEntryKey right)
{
return left._options == right._options && left._cultureKey == right._cultureKey && left._pattern == right._pattern;
}
public static bool operator !=(CachedCodeEntryKey left, CachedCodeEntryKey right)
{
return !(left == right);
}
public override int GetHashCode()
{
return ((int)_options) ^ _cultureKey.GetHashCode() ^ _pattern.GetHashCode();
}
}
/*
* Used to cache byte codes
*/
internal sealed class CachedCodeEntry
{
internal CachedCodeEntryKey _key;
internal RegexCode _code;
internal Dictionary<Int32, Int32> _caps;
internal Dictionary<string, int> _capnames;
internal String[] _capslist;
internal int _capsize;
internal ExclusiveReference _runnerref;
internal SharedReference _replref;
internal CachedCodeEntry(CachedCodeEntryKey key, Dictionary<string, int> capnames, String[] capslist, RegexCode code, Dictionary<Int32, Int32> caps, int capsize, ExclusiveReference runner, SharedReference repl)
{
_key = key;
_capnames = capnames;
_capslist = capslist;
_code = code;
_caps = caps;
_capsize = capsize;
_runnerref = runner;
_replref = repl;
}
}
/*
* Used to cache one exclusive runner reference
*/
internal sealed class ExclusiveReference
{
private RegexRunner _ref;
private Object _obj;
private int _locked;
/*
* Return an object and grab an exclusive lock.
*
* If the exclusive lock can't be obtained, null is returned;
* if the object can't be returned, the lock is released.
*
*/
internal Object Get()
{
// try to obtain the lock
if (0 == Interlocked.Exchange(ref _locked, 1))
{
// grab reference
Object obj = _ref;
// release the lock and return null if no reference
if (obj == null)
{
_locked = 0;
return null;
}
// remember the reference and keep the lock
_obj = obj;
return obj;
}
return null;
}
/*
* Release an object back to the cache
*
* If the object is the one that's under lock, the lock
* is released.
*
* If there is no cached object, then the lock is obtained
* and the object is placed in the cache.
*
*/
internal void Release(Object obj)
{
if (obj == null)
throw new ArgumentNullException(nameof(obj));
// if this reference owns the lock, release it
if (_obj == obj)
{
_obj = null;
_locked = 0;
return;
}
// if no reference owns the lock, try to cache this reference
if (_obj == null)
{
// try to obtain the lock
if (0 == Interlocked.Exchange(ref _locked, 1))
{
// if there's really no reference, cache this reference
if (_ref == null)
_ref = (RegexRunner)obj;
// release the lock
_locked = 0;
return;
}
}
}
}
/*
* Used to cache a weak reference in a threadsafe way
*/
internal sealed class SharedReference
{
private WeakReference _ref = new WeakReference(null);
private int _locked;
/*
* Return an object from a weakref, protected by a lock.
*
* If the exclusive lock can't be obtained, null is returned;
*
* Note that _ref.Target is referenced only under the protection
* of the lock. (Is this necessary?)
*/
internal Object Get()
{
if (0 == Interlocked.Exchange(ref _locked, 1))
{
Object obj = _ref.Target;
_locked = 0;
return obj;
}
return null;
}
/*
* Suggest an object into a weakref, protected by a lock.
*
* Note that _ref.Target is referenced only under the protection
* of the lock. (Is this necessary?)
*/
internal void Cache(Object obj)
{
if (0 == Interlocked.Exchange(ref _locked, 1))
{
_ref.Target = obj;
_locked = 0;
}
}
}
}
| 34.965203 | 218 | 0.5497 | [
"MIT"
] | OceanYan/corefx | src/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Regex.cs | 42,203 | C# |
using Microsoft.Extensions.Configuration;
using MongoDB.Driver;
using SkillSearchAPI.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace SkillSearchAPI.Data
{
public class SkillSearchContext : ISkillSearchContext
{
public SkillSearchContext(IConfiguration configuration)
{
var client = new MongoClient(configuration.GetValue<string>("DatabaseSettings:ConnectionString"));
var database = client.GetDatabase(configuration.GetValue<string>("DatabaseSettings:DatabaseName"));
AssociateSkills = database.GetCollection<AssociateSkill>(configuration.GetValue<string>("DatabaseSettings:AssociateCollectionName"));
Skills = database.GetCollection<Skill>(configuration.GetValue<string>("DatabaseSettings:SkillCollectionName"));
SeedInitialData.SeedData(AssociateSkills, Skills);
}
public IMongoCollection<AssociateSkill> AssociateSkills { get; }
public IMongoCollection<Skill> Skills { get; }
}
}
| 36.1 | 145 | 0.735919 | [
"MIT"
] | LokeOnFire/SkillTracker | src/SkillSearch/SkillSearchAPI/Data/SkillSearchContext.cs | 1,085 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace CpsDbg
{
using System;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using Microsoft.Diagnostics.Runtime;
using Microsoft.Diagnostics.Runtime.Interop;
internal class DebuggerContext
{
private const string ClrMD = "Microsoft.Diagnostics.Runtime";
/// <summary>
/// The singleton instance used in a debug session.
/// </summary>
private static DebuggerContext? instance;
static DebuggerContext()
{
AppDomain.CurrentDomain.AssemblyResolve += ResolveAssembly;
}
private DebuggerContext(IDebugClient debugClient, DataTarget dataTarget, ClrRuntime runtime, DebuggerOutput output)
{
this.DebugClient = debugClient;
this.DataTarget = dataTarget;
this.Runtime = runtime;
this.Output = output;
}
internal ClrRuntime Runtime { get; }
internal DebuggerOutput Output { get; }
internal IDebugClient DebugClient { get; }
internal IDebugControl DebugControl => (IDebugControl)this.DebugClient;
private DataTarget DataTarget { get; }
internal static DebuggerContext? GetDebuggerContext(IntPtr ptrClient)
{
// On our first call to the API:
// 1. Store a copy of IDebugClient in DebugClient.
// 2. Replace Console's output stream to be the debugger window.
// 3. Create an instance of DataTarget using the IDebugClient.
if (instance is null)
{
object client = Marshal.GetUniqueObjectForIUnknown(ptrClient);
var debugClient = (IDebugClient)client;
var output = new DebuggerOutput(debugClient);
#pragma warning disable CA2000 // Dispose objects before losing scope
var dataTarget = DataTarget.CreateFromDbgEng(ptrClient);
#pragma warning restore CA2000 // Dispose objects before losing scope
ClrRuntime? runtime = null;
// If our ClrRuntime instance is null, it means that this is our first call, or
// that the dac wasn't loaded on any previous call. Find the dac loaded in the
// process (the user must use .cordll), then construct our runtime from it.
// Just find a module named mscordacwks and assume it's the one the user
// loaded into windbg.
Process p = Process.GetCurrentProcess();
foreach (ProcessModule module in p.Modules)
{
if (module.FileName.ToUpperInvariant().Contains("MSCORDACWKS"))
{
// TODO: This does not support side-by-side CLRs.
runtime = dataTarget.ClrVersions.Single().CreateRuntime(module.FileName);
break;
}
}
// Otherwise, the user didn't run .cordll.
if (runtime is null)
{
output.WriteLine("Mscordacwks.dll not loaded into the debugger.");
output.WriteLine("Run .cordll to load the dac before running this command.");
}
if (runtime is object)
{
instance = new DebuggerContext(debugClient, dataTarget, runtime, output);
}
}
else
{
// If we already had a runtime, flush it for this use. This is ONLY required
// for a live process or iDNA trace. If you use the IDebug* apis to detect
// that we are debugging a crash dump you may skip this call for better perf.
// instance.Runtime.Flush();
}
return instance;
}
private static Assembly? ResolveAssembly(object sender, ResolveEventArgs args)
{
if (args.Name.Contains(ClrMD))
{
string codebase = Assembly.GetExecutingAssembly().CodeBase;
if (codebase.StartsWith("file://", StringComparison.OrdinalIgnoreCase))
{
codebase = codebase.Substring(8).Replace('/', '\\');
}
string directory = Path.GetDirectoryName(codebase);
string path = Path.Combine(directory, ClrMD) + ".dll";
return Assembly.LoadFile(path);
}
return null;
}
}
}
| 37.590551 | 123 | 0.576875 | [
"MIT"
] | AArnott/vs-threading | src/SosThreadingTools/DebuggerContext.cs | 4,776 | C# |
using Abp;
using System;
using System.Collections.Generic;
using System.Linq;
namespace FuelWerx.MultiTenancy.Demo
{
public static class MyRandomHelper
{
public static List<T> GenerateRandomizedList<T>(IEnumerable<T> items)
{
List<T> ts = new List<T>(items);
List<T> ts1 = new List<T>();
while (ts.Any<T>())
{
int random = RandomHelper.GetRandom(0, ts.Count);
ts1.Add(ts[random]);
ts.RemoveAt(random);
}
return ts1;
}
}
} | 20.043478 | 71 | 0.668113 | [
"MIT"
] | zberg007/fuelwerx | src/FuelWerx.Core/MultiTenancy/Demo/MyRandomHelper.cs | 461 | C# |
using Microsoft.EntityFrameworkCore;
using YoutubeWithFriends.Db.Models;
namespace YoutubeWithFriends.Api.Data {
public class DbApiContext : DbContext {
public DbApiContext(DbContextOptions<DbApiContext> options)
: base(options) {
}
public DbSet<Room> Rooms { get; set; }
public DbSet<User> Users { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder) {
modelBuilder.ApplyConfiguration(new RoomConfiguration());
modelBuilder.ApplyConfiguration(new UserConfiguration());
}
}
} | 29.95 | 76 | 0.677796 | [
"MIT"
] | PapyrusCompendium/YoutubeWithFriends | backend/YoutubeWithFriends.Db/Data/DbApiContext.cs | 601 | C# |
namespace ContosoUniversity.Web.ViewModels
{
public class ChangePasswordViewModel
{
[Required]
[DataType(DataType.Password)]
[Display(Name = "Current Password")]
public string OldPassword { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "New Password")]
public string NewPassword { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm new password")]
[Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match")]
public string ConfirmPassword { get; set; }
}
} | 36.666667 | 125 | 0.633766 | [
"MIT"
] | DanielPHobbs/Contoso-University | ContosoUniversity.Web/ViewModels/ChangePasswordViewModel.cs | 772 | C# |
using System;
using System.IO;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Renci.SshNet.Sftp;
namespace Renci.SshNet.Tests.Classes.Sftp
{
[TestClass]
public class SftpFileStreamTest_Ctor_FileModeCreate_FileAccessRead : SftpFileStreamTestBase
{
private Random _random;
private string _path;
private FileMode _fileMode;
private FileAccess _fileAccess;
private int _bufferSize;
private ArgumentException _actualException;
protected override void SetupData()
{
base.SetupData();
_random = new Random();
_path = _random.Next().ToString();
_fileMode = FileMode.Create;
_fileAccess = FileAccess.Read;
_bufferSize = _random.Next(5, 1000);
}
protected override void SetupMocks()
{
}
protected override void Act()
{
try
{
new SftpFileStream(SftpSessionMock.Object, _path, _fileMode, _fileAccess, _bufferSize);
Assert.Fail();
}
catch (ArgumentException ex)
{
_actualException = ex;
}
}
[TestMethod]
public void CtorShouldHaveThrownArgumentException()
{
Assert.IsNotNull(_actualException);
Assert.IsNull(_actualException.InnerException);
Assert.AreEqual(string.Format("Combining {0}: {1} with {2}: {3} is invalid.", typeof(FileMode).Name, _fileMode, typeof(FileAccess).Name, _fileAccess), _actualException.Message);
Assert.IsNull(_actualException.ParamName);
}
}
}
| 30.035714 | 189 | 0.602854 | [
"MIT"
] | 0xced/SSH.NET | src/Renci.SshNet.Tests/Classes/Sftp/SftpFileStreamTest_Ctor_FileModeCreate_FileAccessRead.cs | 1,684 | C# |
using System;
using FashiShop.Core.Entity;
namespace FashiShop.Model
{
public class OrderDetail
{
public OrderDetail()
{
Cancelled=false;
Discount=0;
}
public int OrderID { get; set; }
public int ProductID { get; set; }
public short Quantity { get; set; }
public double Discount { get; set; }
public bool Cancelled { get; set; }
public string Note { get; set; }
//Mapping
public virtual Order Order { get; set; }
public virtual Product Product { get; set; }
}
}
| 24.8 | 53 | 0.537097 | [
"MIT"
] | saidahmetbayrak/FashiShop | FashiShop.Model/OrderDetail.cs | 620 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Storage;
using System.Windows.Forms;
using System.Threading;
namespace FancyTool
{
class Program
{
static void Main(string[] args)
{
string pipeName = $"Sessions\\{Process.GetCurrentProcess().SessionId}\\AppContainerNamedObjects\\{ApplicationData.Current.LocalSettings.Values["PackageSid"]}\\NurseryPipe";
Console.WriteLine(pipeName);
Console.ReadKey();
}
}
}
| 23.64 | 184 | 0.697124 | [
"MIT"
] | MoeexT/FancyToys | Tools/FancyTool/Program.cs | 591 | C# |
using System.Collections.Generic;
// Auto-generated file from T4 template.
using System;
using System.Numerics;
namespace Urho3DNet.InputEvents
{
#region Touchscreen touch
public partial interface IInputListener
{
/// <summary>
/// Called when a Touchscreen touch begin event has occurred.
/// </summary>
/// <param name="sender">Touch event source.</param>
/// <param name="args">Touch event arguments.</param>
void OnTouchscreenTouchBegin(object sender, TouchEventArgs args);
/// <summary>
/// Called when a Touchscreen touch end event has occurred.
/// </summary>
/// <param name="sender">Touch event source.</param>
/// <param name="args">Touch event arguments.</param>
void OnTouchscreenTouchEnd(object sender, TouchEventArgs args);
/// <summary>
/// Called when a Touchscreen touch moved event has occurred.
/// </summary>
/// <param name="sender">Touch event source.</param>
/// <param name="args">Touch event arguments.</param>
void OnTouchscreenTouchMoved(object sender, TouchEventArgs args);
/// <summary>
/// Called when a Touchscreen touch canceled event has occurred.
/// </summary>
/// <param name="sender">Touch event source.</param>
/// <param name="args">Touch event arguments.</param>
void OnTouchscreenTouchCanceled(object sender, TouchEventArgs args);
}
public partial class AbstractInputListener
{
/// <summary>
/// Called when a Touchscreen touch begin event has occurred.
/// </summary>
/// <param name="sender">Touch event source.</param>
/// <param name="args">Touch event arguments.</param>
public virtual void OnTouchscreenTouchBegin(object sender, TouchEventArgs args)
{
((IInputListener)_inputProxy)?.OnTouchscreenTouchBegin(sender, args);
}
/// <summary>
/// Called when a Touchscreen touch end event has occurred.
/// </summary>
/// <param name="sender">Touch event source.</param>
/// <param name="args">Touch event arguments.</param>
public virtual void OnTouchscreenTouchEnd(object sender, TouchEventArgs args)
{
((IInputListener)_inputProxy)?.OnTouchscreenTouchEnd(sender, args);
}
/// <summary>
/// Called when a Touchscreen touch moved event has occurred.
/// </summary>
/// <param name="sender">Touch event source.</param>
/// <param name="args">Touch event arguments.</param>
public virtual void OnTouchscreenTouchMoved(object sender, TouchEventArgs args)
{
((IInputListener)_inputProxy)?.OnTouchscreenTouchMoved(sender, args);
}
/// <summary>
/// Called when a Touchscreen touch canceled event has occurred.
/// </summary>
/// <param name="sender">Touch event source.</param>
/// <param name="args">Touch event arguments.</param>
public virtual void OnTouchscreenTouchCanceled(object sender, TouchEventArgs args)
{
((IInputListener)_inputProxy)?.OnTouchscreenTouchCanceled(sender, args);
}
}
public partial class InputDemultiplexer
{
/// <summary>
/// Called when a Touchscreen touch begin event has occurred.
/// </summary>
/// <param name="sender">Touch event source.</param>
/// <param name="args">Touch event arguments.</param>
void IInputListener.OnTouchscreenTouchBegin(object sender, TouchEventArgs args)
{
foreach (var inputListener in _listeners)
{
inputListener?.OnTouchscreenTouchBegin(sender, args);
}
}
/// <summary>
/// Called when a Touchscreen touch end event has occurred.
/// </summary>
/// <param name="sender">Touch event source.</param>
/// <param name="args">Touch event arguments.</param>
void IInputListener.OnTouchscreenTouchEnd(object sender, TouchEventArgs args)
{
foreach (var inputListener in _listeners)
{
inputListener?.OnTouchscreenTouchEnd(sender, args);
}
}
/// <summary>
/// Called when a Touchscreen touch moved event has occurred.
/// </summary>
/// <param name="sender">Touch event source.</param>
/// <param name="args">Touch event arguments.</param>
void IInputListener.OnTouchscreenTouchMoved(object sender, TouchEventArgs args)
{
foreach (var inputListener in _listeners)
{
inputListener?.OnTouchscreenTouchMoved(sender, args);
}
}
/// <summary>
/// Called when a Touchscreen touch canceled event has occurred.
/// </summary>
/// <param name="sender">Touch event source.</param>
/// <param name="args">Touch event arguments.</param>
void IInputListener.OnTouchscreenTouchCanceled(object sender, TouchEventArgs args)
{
foreach (var inputListener in _listeners)
{
inputListener?.OnTouchscreenTouchCanceled(sender, args);
}
}
}
public partial class EventEmitter
{
public event EventHandler<TouchEventArgs> TouchscreenTouchBegin;
void IInputListener.OnTouchscreenTouchBegin(object sender, TouchEventArgs args)
{
TouchscreenTouchBegin?.Invoke(sender, args);
}
public event EventHandler<TouchEventArgs> TouchscreenTouchEnd;
void IInputListener.OnTouchscreenTouchEnd(object sender, TouchEventArgs args)
{
TouchscreenTouchEnd?.Invoke(sender, args);
}
public event EventHandler<TouchEventArgs> TouchscreenTouchMoved;
void IInputListener.OnTouchscreenTouchMoved(object sender, TouchEventArgs args)
{
TouchscreenTouchMoved?.Invoke(sender, args);
}
public event EventHandler<TouchEventArgs> TouchscreenTouchCanceled;
void IInputListener.OnTouchscreenTouchCanceled(object sender, TouchEventArgs args)
{
TouchscreenTouchCanceled?.Invoke(sender, args);
}
}
#endregion //Touchscreen touch
}
| 38.756098 | 90 | 0.62146 | [
"MIT"
] | gleblebedev/Urho3DNet.Extras | src/Urho3DNet.InputEvents/Touch.cs | 6,358 | C# |
// This code has been based from the sample repository "cecil": https://github.com/jbevain/cecil
// Copyright (c) 2020 - 2021 Faber Leonardo. All Rights Reserved. https://github.com/FaberSanZ
// This code is licensed under the MIT license (MIT) (http://opensource.org/licenses/MIT)
using System;
namespace LSharp.IL
{
public abstract class MemberReference : IMetadataTokenProvider {
string name;
TypeReference declaring_type;
internal MetadataToken token;
internal object projection;
public virtual string Name {
get { return name; }
set {
if (IsWindowsRuntimeProjection && value != name)
throw new InvalidOperationException ();
name = value;
}
}
public abstract string FullName {
get;
}
public virtual TypeReference DeclaringType {
get { return declaring_type; }
set { declaring_type = value; }
}
public MetadataToken MetadataToken {
get { return token; }
set { token = value; }
}
public bool IsWindowsRuntimeProjection {
get { return projection != null; }
}
internal bool HasImage {
get {
var module = Module;
if (module == null)
return false;
return module.HasImage;
}
}
public virtual ModuleDefinition Module {
get { return declaring_type != null ? declaring_type.Module : null; }
}
public virtual bool IsDefinition {
get { return false; }
}
public virtual bool ContainsGenericParameter {
get { return declaring_type != null && declaring_type.ContainsGenericParameter; }
}
internal MemberReference ()
{
}
internal MemberReference (string name)
{
this.name = name ?? string.Empty;
}
internal string MemberFullName ()
{
if (declaring_type == null)
return name;
return declaring_type.FullName + "::" + name;
}
public IMemberDefinition Resolve ()
{
return ResolveDefinition ();
}
protected abstract IMemberDefinition ResolveDefinition ();
public override string ToString ()
{
return FullName;
}
}
}
| 20.121212 | 96 | 0.685241 | [
"MIT"
] | FaberSanZ/L-Sharp | Src/LSharp.IL/MemberReference.cs | 1,992 | C# |
// -----------------------------------------------------------------------------
// 让 .NET 开发更简单,更通用,更流行。
// Copyright © 2020-2021 Furion, 百小僧, Baiqian Co.,Ltd.
//
// 框架名称:Furion
// 框架作者:百小僧
// 框架版本:2.9.4
// 源码地址:Gitee: https://gitee.com/dotnetchina/Furion
// Github:https://github.com/monksoul/Furion
// 开源协议:Apache-2.0(https://gitee.com/dotnetchina/Furion/blob/master/LICENSE)
// -----------------------------------------------------------------------------
using Furion;
using Furion.DependencyInjection;
using Furion.EventBus;
using System;
using System.Linq;
using System.Reflection;
namespace Microsoft.Extensions.DependencyInjection
{
/// <summary>
/// 轻量级事件总线服务拓展
/// </summary>
[SkipScan]
public static class EventBusServiceCollectionExtensions
{
/// <summary>
/// 添加轻量级事件总线服务拓展
/// </summary>
/// <param name="services"></param>
/// <returns></returns>
public static IServiceCollection AddSimpleEventBus(this IServiceCollection services)
{
// 查找所有贴了 [SubscribeMessage] 特性的方法,并且含有两个参数,第一个参数为 string messageId,第二个参数为 object payload
var typeMethods = App.EffectiveTypes
// 查询符合条件的订阅类型
.Where(u => u.IsClass && !u.IsInterface && !u.IsAbstract && typeof(ISubscribeHandler).IsAssignableFrom(u))
// 查询符合条件的订阅方法
.SelectMany(u =>
u.GetMethods(BindingFlags.Public | BindingFlags.Instance)
.Where(m => m.IsDefined(typeof(SubscribeMessageAttribute), false)
&& m.GetParameters().Length == 2
&& m.GetParameters()[0].ParameterType == typeof(string)
&& m.GetParameters()[1].ParameterType == typeof(object)
&& m.ReturnType == typeof(void))
.GroupBy(m => m.DeclaringType));
if (!typeMethods.Any()) return services;
// 遍历所有订阅类型
foreach (var item in typeMethods)
{
if (!item.Any()) continue;
// 创建订阅类对象
var typeInstance = Activator.CreateInstance(item.Key);
foreach (var method in item)
{
// 创建委托类型
var action = (Action<string, object>)Delegate.CreateDelegate(typeof(Action<string, object>), typeInstance, method.Name);
// 获取所有消息特性
var subscribeMessageAttributes = method.GetCustomAttributes<SubscribeMessageAttribute>();
// 注册订阅
foreach (var subscribeMessageAttribute in subscribeMessageAttributes)
{
if (string.IsNullOrWhiteSpace(subscribeMessageAttribute.MessageId)) continue;
InternalMessageCenter.Instance.Subscribe(item.Key, subscribeMessageAttribute.MessageId, action);
}
}
}
return services;
}
}
} | 39.6125 | 140 | 0.513411 | [
"Apache-2.0"
] | lxhcnblogscom/Furion | framework/Furion/EventBus/Extensions/EventBusServiceCollectionExtensions.cs | 3,498 | C# |
using AdventHelper;
using Day4;
AdventTextReader reader = new AdventTextReader();
string inputLocation = $"data.txt";
var bingoGame = reader.GetListFromFile(inputLocation);
string numbers = bingoGame.First();
bingoGame.RemoveAt(0);
Bingo bingo = new Bingo(numbers);
var boards = bingo.SetupBoards(bingoGame);
bingo.PlayGame(boards);
| 25.846154 | 54 | 0.779762 | [
"MIT"
] | SamA21/AdventOfCode2021 | AdventOfCode2021/Day4/Program.cs | 338 | C# |
/*Write a program that finds the most frequent number in an array. Example:
{4, 1, 1, 4, 2, 3, 4, 4, 1, 2, 4, 9, 3} 4 (5 times)
*/
using System;
class MostFrequentNumber
{
static void Main()
{
int[] array = { 4, 1, 1, 4, 2, 3, 4, 4, 1, 2, 4, 9, 3 };
int start = 1;
int end = 1;
int sum = 0;
int maxSum = 0;
for (int i = 0; i < array.Length - 1; i++)
{
for (int j = 1 + i; j < array.Length; j++)
{
if (array[i] == array[j])
{
sum = array[i];
start++;
}
if (start > end)
{
maxSum = sum;
end = start;
}
}
start = 1;
}
Console.WriteLine("The most frequend number is {0} --> {1} times", maxSum, end);
}
}
| 24.131579 | 89 | 0.371865 | [
"MIT"
] | froddo/CSharp-More | Arrays/MostFrequentNumber/MostFrequentNumber.cs | 921 | C# |
using Unity.Entities;
using Unity.Animation;
using Unity.DataFlowGraph;
using Unity.Mathematics;
using Unity.Transforms;
public struct RigRemapSetup : ISampleSetup
{
public BlobAssetReference<Clip> SrcClip;
public BlobAssetReference<RigDefinition> SrcRig;
public BlobAssetReference<RigRemapTable> RemapTable;
};
public struct RigRemapData : ISampleData
{
public NodeHandle<ConvertDeltaTimeToFloatNode> DeltaTimeNode;
public NodeHandle<ClipPlayerNode> ClipPlayerNode;
public NodeHandle<RigRemapperNode> RemapperNode;
public NodeHandle<ComponentNode> EntityNode;
public NodeHandle<ComponentNode> DebugEntityNode;
}
[UpdateBefore(typeof(DefaultAnimationSystemGroup))]
public class RigRemapGraphSystem : SampleSystemBase<
RigRemapSetup,
RigRemapData,
ProcessDefaultAnimationGraph
>
{
protected override RigRemapData CreateGraph(Entity entity, ref Rig rig, ProcessDefaultAnimationGraph graphSystem, ref RigRemapSetup setup)
{
var set = graphSystem.Set;
var debugEntity = RigUtils.InstantiateDebugRigEntity(
setup.SrcRig,
EntityManager,
new BoneRendererProperties { BoneShape = BoneRendererUtils.BoneShape.Line, Color = new float4(0f, 1f, 0f, 0.5f), Size = 1f }
);
PostUpdateCommands.AddComponent(debugEntity, new LocalToParent { Value = float4x4.identity });
PostUpdateCommands.AddComponent(debugEntity, new Parent { Value = entity });
var data = new RigRemapData();
data.DeltaTimeNode = set.Create<ConvertDeltaTimeToFloatNode>();
data.ClipPlayerNode = set.Create<ClipPlayerNode>();
data.RemapperNode = set.Create<RigRemapperNode>();
data.EntityNode = set.CreateComponentNode(entity);
data.DebugEntityNode = set.CreateComponentNode(debugEntity);
set.SetData(data.ClipPlayerNode, ClipPlayerNode.KernelPorts.Speed, 1.0f);
// Connect kernel ports
set.Connect(data.DeltaTimeNode, ConvertDeltaTimeToFloatNode.KernelPorts.Output, data.ClipPlayerNode, ClipPlayerNode.KernelPorts.DeltaTime);
set.Connect(data.ClipPlayerNode, ClipPlayerNode.KernelPorts.Output, data.RemapperNode, RigRemapperNode.KernelPorts.Input);
// Connect EntityNode
set.Connect(data.EntityNode, data.DeltaTimeNode, ConvertDeltaTimeToFloatNode.KernelPorts.Input);
set.Connect(data.RemapperNode, RigRemapperNode.KernelPorts.Output, data.EntityNode, NodeSet.ConnectionType.Feedback);
// Connect DebugEntityNode
set.Connect(data.ClipPlayerNode, ClipPlayerNode.KernelPorts.Output, data.DebugEntityNode);
// Send messages
set.SendMessage(data.ClipPlayerNode, ClipPlayerNode.SimulationPorts.Configuration, new ClipConfiguration { Mask = ClipConfigurationMask.LoopTime });
set.SendMessage(data.ClipPlayerNode, ClipPlayerNode.SimulationPorts.Rig, new Rig { Value = setup.SrcRig });
set.SendMessage(data.ClipPlayerNode, ClipPlayerNode.SimulationPorts.Clip, setup.SrcClip);
set.SendMessage(data.RemapperNode, RigRemapperNode.SimulationPorts.SourceRig, new Rig { Value = setup.SrcRig });
set.SendMessage(data.RemapperNode, RigRemapperNode.SimulationPorts.DestinationRig, rig);
set.SendMessage(data.RemapperNode, RigRemapperNode.SimulationPorts.RemapTable, setup.RemapTable);
return data;
}
protected override void DestroyGraph(Entity entity, ProcessDefaultAnimationGraph graphSystem, ref RigRemapData data)
{
var set = graphSystem.Set;
set.Destroy(data.DeltaTimeNode);
set.Destroy(data.ClipPlayerNode);
set.Destroy(data.RemapperNode);
set.Destroy(data.EntityNode);
set.Destroy(data.DebugEntityNode);
}
}
| 44.294118 | 156 | 0.742098 | [
"MIT"
] | Steven9Smith/Mixamo-For-Unity-DOTS | Assets/Scenes/Advanced/AnimationRigRemap/RigRemapGraphSystem.cs | 3,765 | 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("AutoFacDependancyInjectionFrameworks")]
[assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")]
[assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")]
[assembly: System.Reflection.AssemblyProductAttribute("AutoFacDependancyInjectionFrameworks")]
[assembly: System.Reflection.AssemblyTitleAttribute("AutoFacDependancyInjectionFrameworks")]
[assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")]
// Generated by the MSBuild WriteCodeFragment class.
| 44.083333 | 94 | 0.672968 | [
"MIT"
] | PeterPartridge/DependancyInjectionFrameworks | AutoFacDependancyInjectionFrameworks/obj/Debug/netcoreapp2.1/AutoFacDependancyInjectionFrameworks.AssemblyInfo.cs | 1,058 | C# |
using DataStructuresLib.Sequences.Periodic1D;
using EuclideanGeometryLib.BasicMath.Tuples;
using EuclideanGeometryLib.BasicMath.Tuples.Immutable;
namespace MeshComposerLib.Geometry.PointsPath.Space3D
{
public sealed class PlanarXyPointsPath3D
: PSeqMapped1D<ITuple2D, ITuple3D>, IPointsPath3D
{
public double ValueZ { get; set; }
public PlanarXyPointsPath3D(IPointsPath2D xyPath)
: base(xyPath)
{
ValueZ = 0;
}
public PlanarXyPointsPath3D(IPointsPath2D xyPath, double valueZ)
: base(xyPath)
{
ValueZ = valueZ;
}
protected override ITuple3D MappingFunction(ITuple2D xyPoint)
{
return new Tuple3D(
xyPoint.X,
xyPoint.Y,
ValueZ
);
}
}
} | 24.571429 | 72 | 0.598837 | [
"MIT"
] | ga-explorer/GMac | MeshComposerLib/MeshComposerLib/Geometry/PointsPath/Space3D/PlanarXyPointsPath3D.cs | 862 | C# |
using global::System;
using NUnit.Framework;
using NUnit.Framework.TUnit;
using Tizen.NUI.Components;
using Tizen.NUI.BaseComponents;
namespace Tizen.NUI.Devel.Tests
{
using tlog = Tizen.Log;
[TestFixture]
[Description("internal/Common/FontMetrics")]
public class InternalFontMetricsTest
{
private const string tag = "NUITEST";
[SetUp]
public void Init()
{
tlog.Info(tag, "Init() is called!");
}
[TearDown]
public void Destroy()
{
tlog.Info(tag, "Destroy() is called!");
}
[Test]
[Category("P1")]
[Description("FontMetrics constructor.")]
[Property("SPEC", "Tizen.NUI.FontMetrics.FontMetrics C")]
[Property("SPEC_URL", "-")]
[Property("CRITERIA", "CONSTR")]
[Property("AUTHOR", "guowei.wang@samsung.com")]
public void FontMetricsConstructor()
{
tlog.Debug(tag, $"FontMetricsConstructor START");
var testingTarget = new FontMetrics();
Assert.IsNotNull(testingTarget, "Can't create success object FontMetrics.");
Assert.IsInstanceOf<FontMetrics>(testingTarget, "Should return FontMetrics instance.");
testingTarget.Dispose();
tlog.Debug(tag, $"FontMetricsConstructor END (OK)");
}
[Test]
[Category("P1")]
[Description("FontMetrics constructor.")]
[Property("SPEC", "Tizen.NUI.FontMetrics.FontMetrics C")]
[Property("SPEC_URL", "-")]
[Property("CRITERIA", "CONSTR")]
[Property("AUTHOR", "guowei.wang@samsung.com")]
public void FontMetricsConstructorWithFloats()
{
tlog.Debug(tag, $"FontMetricsConstructorWithFloats START");
var testingTarget = new FontMetrics(0.3f, 0.1f, 0.5f, 0.9f, 0.0f);
Assert.IsNotNull(testingTarget, "Can't create success object FontMetrics.");
Assert.IsInstanceOf<FontMetrics>(testingTarget, "Should return FontMetrics instance.");
testingTarget.UnderlineThickness = 0.3f;
tlog.Debug(tag, "UnderlineThickness :" + testingTarget.UnderlineThickness);
testingTarget.Dispose();
tlog.Debug(tag, $"FontMetricsConstructorWithFloats END (OK)");
}
[Test]
[Category("P1")]
[Description("FontMetrics Ascender.")]
[Property("SPEC", "Tizen.NUI.FontMetrics.Ascender A")]
[Property("SPEC_URL", "-")]
[Property("CRITERIA", "PRW")]
[Property("AUTHOR", "guowei.wang@samsung.com")]
public void FontMetricsAscender()
{
tlog.Debug(tag, $"FontMetricsAscender START");
var testingTarget = new FontMetrics();
Assert.IsNotNull(testingTarget, "Can't create success object FontMetrics.");
Assert.IsInstanceOf<FontMetrics>(testingTarget, "Should return FontMetrics instance.");
testingTarget.Ascender = 0.3f;
Assert.AreEqual(0.3f, testingTarget.Ascender, "Should be equal!");
testingTarget.Dispose();
tlog.Debug(tag, $"FontMetricsAscender END (OK)");
}
[Test]
[Category("P1")]
[Description("FontMetrics Descender.")]
[Property("SPEC", "Tizen.NUI.FontMetrics.Descender A")]
[Property("SPEC_URL", "-")]
[Property("CRITERIA", "PRW")]
[Property("AUTHOR", "guowei.wang@samsung.com")]
public void FontMetricsDescender()
{
tlog.Debug(tag, $"FontMetricsDescender START");
var testingTarget = new FontMetrics();
Assert.IsNotNull(testingTarget, "Can't create success object FontMetrics.");
Assert.IsInstanceOf<FontMetrics>(testingTarget, "Should return FontMetrics instance.");
testingTarget.Descender = 0.3f;
Assert.AreEqual(0.3f, testingTarget.Descender, "Should be equal!");
testingTarget.Dispose();
tlog.Debug(tag, $"FontMetricsDescender END (OK)");
}
[Test]
[Category("P1")]
[Description("FontMetrics Height.")]
[Property("SPEC", "Tizen.NUI.FontMetrics.Height A")]
[Property("SPEC_URL", "-")]
[Property("CRITERIA", "PRW")]
[Property("AUTHOR", "guowei.wang@samsung.com")]
public void FontMetricsHeight()
{
tlog.Debug(tag, $"FontMetricsHeight START");
var testingTarget = new FontMetrics();
Assert.IsNotNull(testingTarget, "Can't create success object FontMetrics.");
Assert.IsInstanceOf<FontMetrics>(testingTarget, "Should return FontMetrics instance.");
testingTarget.Height = 0.3f;
Assert.AreEqual(0.3f, testingTarget.Height, "Should be equal!");
testingTarget.Dispose();
tlog.Debug(tag, $"FontMetricsHeight END (OK)");
}
[Test]
[Category("P1")]
[Description("FontMetrics UnderlinePosition.")]
[Property("SPEC", "Tizen.NUI.FontMetrics.UnderlinePosition A")]
[Property("SPEC_URL", "-")]
[Property("CRITERIA", "PRW")]
[Property("AUTHOR", "guowei.wang@samsung.com")]
public void FontMetricsUnderlinePosition()
{
tlog.Debug(tag, $"FontMetricsUnderlinePosition START");
var testingTarget = new FontMetrics();
Assert.IsNotNull(testingTarget, "Can't create success object FontMetrics.");
Assert.IsInstanceOf<FontMetrics>(testingTarget, "Should return FontMetrics instance.");
testingTarget.UnderlinePosition = 0.3f;
Assert.AreEqual(0.3f, testingTarget.UnderlinePosition, "Should be equal!");
testingTarget.Dispose();
tlog.Debug(tag, $"FontMetricsUnderlinePosition END (OK)");
}
[Test]
[Category("P1")]
[Description("FontMetrics UnderlineThickness.")]
[Property("SPEC", "Tizen.NUI.FontMetrics.UnderlineThickness A")]
[Property("SPEC_URL", "-")]
[Property("CRITERIA", "PRW")]
[Property("AUTHOR", "guowei.wang@samsung.com")]
public void FontMetricsUnderlineThickness()
{
tlog.Debug(tag, $"FontMetricsUnderlineThickness START");
var testingTarget = new FontMetrics();
Assert.IsNotNull(testingTarget, "Can't create success object FontMetrics.");
Assert.IsInstanceOf<FontMetrics>(testingTarget, "Should return FontMetrics instance.");
testingTarget.UnderlinePosition = 0.1f;
Assert.AreEqual(0.1f, testingTarget.UnderlinePosition, "Should be equal!");
testingTarget.Dispose();
tlog.Debug(tag, $"FontMetricsUnderlineThickness END (OK)");
}
}
}
| 37.447514 | 99 | 0.605488 | [
"Apache-2.0",
"MIT"
] | Inhong/TizenFX | test/Tizen.NUI.Tests/Tizen.NUI.Devel.Tests/testcase/internal/Common/TSFontMetrics.cs | 6,780 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Enochian.UnitTests
{
public static class AssertUtils
{
public static void NoErrors(IConfigurable obj)
{
if (obj.Errors != null)
{
var message = string.Join(", ", obj.Errors.Select(er => er.Message));
if (!string.IsNullOrWhiteSpace(message))
Assert.Fail(message);
}
}
public static void WithErrors(Action<IList<string>> act, Action assert, string expectedError = null)
{
WithErrors(null, act, assert, expectedError);
}
public static void WithErrors(Action arrange, Action<IList<string>> act, Action assert, string expectedError = null)
{
arrange?.Invoke();
var errors = new List<string>();
act?.Invoke(errors);
if (string.IsNullOrWhiteSpace(expectedError))
{
if (errors.Any())
throw new AssertFailedException(string.Format("errors: {0}", string.Join(", ", errors)));
assert?.Invoke();
}
else
{
var found = errors.Any(e => e.Contains(expectedError));
Assert.IsTrue(found,
string.Format("did not find expected error {0}: {1}",
expectedError, string.Join(", ", errors)));
}
}
public static void SequenceEquals<T>(IEnumerable<T> expected, IEnumerable<T> actual)
{
if (expected == null) throw new ArgumentNullException(nameof(expected));
if (actual == null) throw new ArgumentNullException(nameof(actual));
if (!expected.SequenceEqual(actual))
throw new AssertFailedException("sequences are not equal");
}
}
}
| 34.298246 | 124 | 0.558568 | [
"MIT"
] | kulibali/enochian | source/Enochian.UnitTests/AssertUtils.cs | 1,957 | C# |
using ApprovalTests;
using ArteLogico.GisGlue.Contracts;
using Newtonsoft.Json;
using NUnit.Framework;
using System.IO;
namespace ArteLogico.GisGlue.Tests.Contracts
{
[TestFixture]
public class ExtentConverterTests
{
[Test]
public void WriteJson_WhenSerializingAnExtent_ThenTheFormatMatchesTheExample()
{
var extent = new Extent { X1 = 100, Y1 = 200, X2 = 1000, Y2 = 2000 };
var serializer = JsonHelper.CreateSerializer();
string result;
using (var writer = new StringWriter())
using (var jsonWriter = new JsonTextWriter(writer))
{
jsonWriter.Formatting = Formatting.Indented;
serializer.Serialize(jsonWriter, extent);
result = writer.ToString();
}
Approvals.Verify(result);
}
}
} | 29.2 | 86 | 0.610731 | [
"Apache-2.0"
] | jcarrascal/ArcGisJsonSharp | ArteLogico.GisGlue.Tests/Contracts/ExtentConverterTests.cs | 878 | C# |
using BaZic.Core.ComponentModel.Assemblies;
using BaZic.Core.Tests.Mocks;
using BaZic.Runtime.BaZic.Code.AbstractSyntaxTree;
using BaZic.Runtime.BaZic.Code.Parser;
using BaZic.Runtime.BaZic.Runtime;
using BaZic.Runtime.BaZic.Runtime.Debugger.Exceptions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace BaZic.Runtime.Tests.BaZic.Runtime
{
[TestClass]
public class BaZicInterpreterTest
{
[TestInitialize]
public void Initialize()
{
TestUtilities.InitializeLogs();
}
[TestMethod]
public async Task BaZicInterpreterLifeCycle()
{
var parser = new BaZicParser();
var inputCode =
@"EXTERN FUNCTION Main(args[])
VARIABLE var1 = 1
VARIABLE Var1 = 2
RETURN var1 + Var1
END FUNCTION";
var interpreter = new BaZicInterpreter(parser.Parse(inputCode, true).Program);
await interpreter.StartDebugAsync(true);
Assert.AreEqual(BaZicInterpreterState.Ready, interpreter.StateChangedHistory[0].State);
Assert.AreEqual(BaZicInterpreterState.Preparing, interpreter.StateChangedHistory[1].State);
Assert.AreEqual(BaZicInterpreterState.Running, interpreter.StateChangedHistory[12].State);
Assert.AreEqual(BaZicInterpreterState.Idle, interpreter.StateChangedHistory.Last().State);
await TestUtilities.TestAllRunningMode("3", inputCode);
}
[TestMethod]
public async Task BaZicInterpreterAssembliesLoad()
{
var program = new BaZicProgram();
program.WithAssemblies("FakeAssembly, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");
var interpreter = new BaZicInterpreter(program);
await interpreter.StartDebugAsync(true);
var exception = (LoadAssemblyException)interpreter.Error.Exception;
Assert.AreEqual("FakeAssembly, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", exception.AssemblyPath);
Assert.AreEqual("Could not load file or assembly 'FakeAssembly, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' or one of its dependencies. The system cannot find the file specified.", exception.InnerException.Message);
}
[TestMethod]
public async Task BaZicInterpreterStepInto()
{
var parser = new BaZicParser();
var inputCode =
@"EXTERN FUNCTION Main(args[])
VARIABLE var1 = 0
BREAKPOINT
var1 = 1
var1 = 2
var1 = 3
RETURN var1
END FUNCTION";
var interpreter = new BaZicInterpreter(parser.Parse(inputCode, false).Program);
var t = interpreter.StartDebugAsync(true);
await Task.Delay(3000);
var expectedLogs = @"[State] Ready
[State] Preparing
[Log] Reference assembly 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' loaded in the application domain.
[Log] Reference assembly 'System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' loaded in the application domain.
[Log] Reference assembly 'System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' loaded in the application domain.
[Log] Reference assembly 'System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' loaded in the application domain.
[Log] Reference assembly 'Microsoft.CSharp, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' loaded in the application domain.
[Log] Reference assembly 'PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' loaded in the application domain.
[Log] Reference assembly 'PresentationCore, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' loaded in the application domain.
[Log] Reference assembly 'WindowsBase, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' loaded in the application domain.
[Log] Declaring global variables.
[Log] Program's entry point detected.
[State] Running
[Log] Preparing to invoke the method 'Main'.
[Log] Executing the argument values of the method.
[Log] Executing an expression of type 'ArrayCreationExpression'.
[Log] The expression returned the value 'BaZicProgramReleaseMode.ObservableDictionary' (BaZicProgramReleaseMode.ObservableDictionary (length: 0)).
[Log] Invoking the synchronous method 'Main'.
[Log] Variable 'args' declared. Default value : {Null}
[Log] Variable 'args' value set to : BaZicProgramReleaseMode.ObservableDictionary (BaZicProgramReleaseMode.ObservableDictionary (length: 0))
[Log] Registering labels.
[Log] Executing a statement of type 'VariableDeclaration'.
[Log] Executing an expression of type 'PrimitiveExpression'.
[Log] The expression returned the value '0' (System.Int32).
[Log] Variable 'var1' declared. Default value : 0 (System.Int32)
[Log] Executing a statement of type 'BreakpointStatement'.
[Log] A Breakpoint has been intercepted.
[State] Pause
";
Assert.AreEqual(expectedLogs, interpreter.GetStateChangedHistoryString());
Assert.AreEqual(BaZicInterpreterState.Pause, interpreter.State);
interpreter.NextStep();
await Task.Delay(1000);
Assert.AreEqual(BaZicInterpreterState.Pause, interpreter.State);
interpreter.NextStep();
await Task.Delay(1000);
expectedLogs = @"[State] Ready
[State] Preparing
[Log] Reference assembly 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' loaded in the application domain.
[Log] Reference assembly 'System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' loaded in the application domain.
[Log] Reference assembly 'System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' loaded in the application domain.
[Log] Reference assembly 'System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' loaded in the application domain.
[Log] Reference assembly 'Microsoft.CSharp, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' loaded in the application domain.
[Log] Reference assembly 'PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' loaded in the application domain.
[Log] Reference assembly 'PresentationCore, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' loaded in the application domain.
[Log] Reference assembly 'WindowsBase, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' loaded in the application domain.
[Log] Declaring global variables.
[Log] Program's entry point detected.
[State] Running
[Log] Preparing to invoke the method 'Main'.
[Log] Executing the argument values of the method.
[Log] Executing an expression of type 'ArrayCreationExpression'.
[Log] The expression returned the value 'BaZicProgramReleaseMode.ObservableDictionary' (BaZicProgramReleaseMode.ObservableDictionary (length: 0)).
[Log] Invoking the synchronous method 'Main'.
[Log] Variable 'args' declared. Default value : {Null}
[Log] Variable 'args' value set to : BaZicProgramReleaseMode.ObservableDictionary (BaZicProgramReleaseMode.ObservableDictionary (length: 0))
[Log] Registering labels.
[Log] Executing a statement of type 'VariableDeclaration'.
[Log] Executing an expression of type 'PrimitiveExpression'.
[Log] The expression returned the value '0' (System.Int32).
[Log] Variable 'var1' declared. Default value : 0 (System.Int32)
[Log] Executing a statement of type 'BreakpointStatement'.
[Log] A Breakpoint has been intercepted.
[State] Pause
[State] Running
[Log] Executing a statement of type 'AssignStatement'.
[Log] Assign 'var1' to ''1' (type:System.Int32)'.
[Log] Executing an expression of type 'PrimitiveExpression'.
[Log] The expression returned the value '1' (System.Int32).
[Log] Variable 'var1' value set to : 1 (System.Int32)
[Log] 'var1' is now equal to '1'(type:System.Int32)
[State] Pause
[State] Running
[Log] Executing a statement of type 'AssignStatement'.
[Log] Assign 'var1' to ''2' (type:System.Int32)'.
[Log] Executing an expression of type 'PrimitiveExpression'.
[Log] The expression returned the value '2' (System.Int32).
[Log] Variable 'var1' value set to : 2 (System.Int32)
[Log] 'var1' is now equal to '2'(type:System.Int32)
[State] Pause
";
Assert.AreEqual(expectedLogs, interpreter.GetStateChangedHistoryString());
Assert.AreEqual(BaZicInterpreterState.Pause, interpreter.State);
await interpreter.Stop();
await Task.Delay(1000);
expectedLogs = @"[State] Ready
[State] Preparing
[Log] Reference assembly 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' loaded in the application domain.
[Log] Reference assembly 'System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' loaded in the application domain.
[Log] Reference assembly 'System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' loaded in the application domain.
[Log] Reference assembly 'System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' loaded in the application domain.
[Log] Reference assembly 'Microsoft.CSharp, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' loaded in the application domain.
[Log] Reference assembly 'PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' loaded in the application domain.
[Log] Reference assembly 'PresentationCore, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' loaded in the application domain.
[Log] Reference assembly 'WindowsBase, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' loaded in the application domain.
[Log] Declaring global variables.
[Log] Program's entry point detected.
[State] Running
[Log] Preparing to invoke the method 'Main'.
[Log] Executing the argument values of the method.
[Log] Executing an expression of type 'ArrayCreationExpression'.
[Log] The expression returned the value 'BaZicProgramReleaseMode.ObservableDictionary' (BaZicProgramReleaseMode.ObservableDictionary (length: 0)).
[Log] Invoking the synchronous method 'Main'.
[Log] Variable 'args' declared. Default value : {Null}
[Log] Variable 'args' value set to : BaZicProgramReleaseMode.ObservableDictionary (BaZicProgramReleaseMode.ObservableDictionary (length: 0))
[Log] Registering labels.
[Log] Executing a statement of type 'VariableDeclaration'.
[Log] Executing an expression of type 'PrimitiveExpression'.
[Log] The expression returned the value '0' (System.Int32).
[Log] Variable 'var1' declared. Default value : 0 (System.Int32)
[Log] Executing a statement of type 'BreakpointStatement'.
[Log] A Breakpoint has been intercepted.
[State] Pause
[State] Running
[Log] Executing a statement of type 'AssignStatement'.
[Log] Assign 'var1' to ''1' (type:System.Int32)'.
[Log] Executing an expression of type 'PrimitiveExpression'.
[Log] The expression returned the value '1' (System.Int32).
[Log] Variable 'var1' value set to : 1 (System.Int32)
[Log] 'var1' is now equal to '1'(type:System.Int32)
[State] Pause
[State] Running
[Log] Executing a statement of type 'AssignStatement'.
[Log] Assign 'var1' to ''2' (type:System.Int32)'.
[Log] Executing an expression of type 'PrimitiveExpression'.
[Log] The expression returned the value '2' (System.Int32).
[Log] Variable 'var1' value set to : 2 (System.Int32)
[Log] 'var1' is now equal to '2'(type:System.Int32)
[State] Pause
[Log] The user requests to stop the interpreter as soon as possible.
[State] Stopped
";
Assert.AreEqual(expectedLogs, interpreter.GetStateChangedHistoryString());
Assert.AreEqual(BaZicInterpreterState.Stopped, interpreter.State);
}
[TestMethod]
public async Task BaZicInterpreterDebugInformation()
{
var parser = new BaZicParser();
var inputCode =
@"
VARIABLE globVar = ""Hello""
EXTERN FUNCTION Main(args[])
RETURN SimpleRecursivity(5)
END FUNCTION
FUNCTION SimpleRecursivity(num)
IF num < 1 THEN
BREAKPOINT
RETURN num
ELSE
RETURN SimpleRecursivity(num - 1)
END IF
END FUNCTION";
var interpreter = new BaZicInterpreter(parser.Parse(inputCode, true).Program);
var t = interpreter.StartDebugAsync(true);
await Task.Delay(2000);
var debugInfo = interpreter.DebugInfos;
Assert.IsNull(debugInfo);
Assert.AreEqual(BaZicInterpreterState.Pause, interpreter.State);
interpreter = new BaZicInterpreter(parser.Parse(inputCode, false).Program);
t = interpreter.StartDebugAsync(true);
Assert.IsNull(interpreter.DebugInfos);
await Task.Delay(2000);
debugInfo = interpreter.DebugInfos;
Assert.IsNotNull(debugInfo);
Assert.AreEqual(BaZicInterpreterState.Pause, interpreter.State);
Assert.AreEqual(7, debugInfo.CallStack.Count);
Assert.AreEqual(1, debugInfo.GlobalVariables.Count);
Assert.AreEqual("SimpleRecursivity", debugInfo.CallStack.First().InvokeMethodExpression.MethodName.Identifier);
Assert.AreEqual("num", debugInfo.CallStack.First().Variables.Single().Name);
Assert.AreEqual(0, debugInfo.CallStack.First().Variables.Single().Value);
Assert.AreEqual(5, debugInfo.CallStack[5].Variables.Single().Value);
}
[TestMethod]
public async Task BaZicInterpreterDebugInformationAsync()
{
var parser = new BaZicParser();
var inputCode =
@"
VARIABLE globVar = ""Hello""
EXTERN FUNCTION Main(args[])
RETURN SimpleRecursivity(5)
END FUNCTION
ASYNC FUNCTION SimpleRecursivity(num)
IF num < 1 THEN
BREAKPOINT
RETURN num
ELSE
RETURN SimpleRecursivity(num - 1)
END IF
END FUNCTION";
var interpreter = new BaZicInterpreter(parser.Parse(inputCode, false).Program);
var t = interpreter.StartDebugAsync(true);
Assert.IsNull(interpreter.DebugInfos);
await Task.Delay(5000);
var debugInfo = interpreter.DebugInfos;
Assert.IsNotNull(debugInfo);
Assert.AreEqual("Hello", debugInfo.GlobalVariables.Single().Value);
Assert.AreEqual(BaZicInterpreterState.Pause, interpreter.State);
Assert.AreEqual(1, debugInfo.GlobalVariables.Count);
Assert.AreEqual("SimpleRecursivity", debugInfo.CallStack.First().InvokeMethodExpression.MethodName.Identifier);
Assert.AreEqual("num", debugInfo.CallStack.First().Variables.Single().Name);
Assert.AreEqual(0, debugInfo.CallStack.First().Variables.Single().Value);
Assert.IsNull(debugInfo.CallStack[1]);
inputCode =
@"
VARIABLE globVar = ""Hello""
EXTERN FUNCTION Main(args[])
RETURN AWAIT SimpleRecursivity(5)
END FUNCTION
ASYNC FUNCTION SimpleRecursivity(num)
IF num < 1 THEN
BREAKPOINT
RETURN num
ELSE
IF num % 2 = 0 THEN
RETURN SimpleRecursivity(num - 1)
ELSE
RETURN AWAIT SimpleRecursivity(num - 1)
END IF
END IF
END FUNCTION";
interpreter = new BaZicInterpreter(parser.Parse(inputCode, false).Program);
t = interpreter.StartDebugAsync(true);
Assert.IsNull(interpreter.DebugInfos);
await Task.Delay(5000);
debugInfo = interpreter.DebugInfos;
Assert.IsNotNull(debugInfo);
Assert.AreEqual(BaZicInterpreterState.Pause, interpreter.State);
Assert.AreEqual(7, debugInfo.CallStack.Count);
Assert.AreEqual(1, debugInfo.GlobalVariables.Count);
Assert.AreEqual("SimpleRecursivity", debugInfo.CallStack.First().InvokeMethodExpression.MethodName.Identifier);
Assert.AreEqual("num", debugInfo.CallStack.First().Variables.Single().Name);
Assert.AreEqual(0, debugInfo.CallStack.First().Variables.Single().Value);
Assert.AreEqual("SimpleRecursivity", debugInfo.CallStack[1].InvokeMethodExpression.MethodName.Identifier);
Assert.AreEqual("num", debugInfo.CallStack[1].Variables.Single().Name);
Assert.AreEqual(1, debugInfo.CallStack[1].Variables.Single().Value);
Assert.IsNull(debugInfo.CallStack[2]);
Assert.IsNull(debugInfo.CallStack[3]);
Assert.IsNull(debugInfo.CallStack[4]);
Assert.IsNull(debugInfo.CallStack[5]);
Assert.IsNull(debugInfo.CallStack[6]);
}
[TestMethod]
public async Task BaZicInterpreterSecurity()
{
var parser = new BaZicParser();
var inputCode =
@"EXTERN FUNCTION Main(args[])
VARIABLE var1 = Localization.L.BaZic.AbstractSyntaxTree.InvalidNamespace
RETURN var1
END FUNCTION";
var interpreter = new BaZicInterpreter(parser.Parse(inputCode, false).Program);
await interpreter.StartDebugAsync(true);
var expectedLogs = @"[State] Ready
[State] Preparing
[Log] Reference assembly 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' loaded in the application domain.
[Log] Reference assembly 'System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' loaded in the application domain.
[Log] Reference assembly 'System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' loaded in the application domain.
[Log] Reference assembly 'System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' loaded in the application domain.
[Log] Reference assembly 'Microsoft.CSharp, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' loaded in the application domain.
[Log] Reference assembly 'PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' loaded in the application domain.
[Log] Reference assembly 'PresentationCore, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' loaded in the application domain.
[Log] Reference assembly 'WindowsBase, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' loaded in the application domain.
[Log] Declaring global variables.
[Log] Program's entry point detected.
[State] Running
[Log] Preparing to invoke the method 'Main'.
[Log] Executing the argument values of the method.
[Log] Executing an expression of type 'ArrayCreationExpression'.
[Log] The expression returned the value 'BaZicProgramReleaseMode.ObservableDictionary' (BaZicProgramReleaseMode.ObservableDictionary (length: 0)).
[Log] Invoking the synchronous method 'Main'.
[Log] Variable 'args' declared. Default value : {Null}
[Log] Variable 'args' value set to : BaZicProgramReleaseMode.ObservableDictionary (BaZicProgramReleaseMode.ObservableDictionary (length: 0))
[Log] Registering labels.
[Log] Executing a statement of type 'VariableDeclaration'.
[Log] Executing an expression of type 'PropertyReferenceExpression'.
[Log] Getting the property 'Localization.L.BaZic.AbstractSyntaxTree.InvalidNamespace'.
[Log] Executing an expression of type 'ClassReferenceExpression'.
[Error] Unexpected and unmanaged error has been detected : Unable to load the type 'Localization.L.BaZic.AbstractSyntaxTree'. Does an assembly is missing?
";
Assert.AreEqual(expectedLogs, interpreter.GetStateChangedHistoryString());
}
[TestMethod]
public async Task BaZicCompile()
{
var inputCode =
@"EXTERN FUNCTION Main(args[])
VARIABLE var1 = 1
VARIABLE Var1 = 2
VARIABLE result = var1 + Var1
System.Console.WriteLine(result.ToString())
RETURN result
END FUNCTION";
using (var interpreter = new BaZicInterpreter(inputCode, false))
{
var mscorlib = AssemblyInfoHelper.GetAssemblyDetailsFromNameOrLocation(typeof(object).Assembly.FullName);
var baZicCoreTest = AssemblyInfoHelper.GetAssemblyDetailsFromNameOrLocation(typeof(LogMock).Assembly.Location);
interpreter.SetDependencies(mscorlib, baZicCoreTest);
var tempFile = Path.Combine(Path.GetTempPath(), "BaZic_Bin", Path.GetFileNameWithoutExtension(Path.GetTempFileName()) + ".exe");
var errors = await interpreter.Build(Core.Enums.BaZicCompilerOutputType.ConsoleApp, tempFile);
Assert.IsNull(errors);
Assert.IsTrue(File.Exists(tempFile));
Assert.IsTrue(File.Exists(tempFile.Replace(".exe", ".pdb")));
Assert.IsTrue(File.Exists(Path.Combine(Path.GetTempPath(), "BaZic_Bin", "BaZic.Core.Tests.dll")));
File.Delete(tempFile);
File.Delete(tempFile.Replace(".exe", ".pdb"));
File.Delete(Path.Combine(Path.GetTempPath(), "BaZic_Bin", "BaZic.Core.Tests.dll"));
Directory.Delete(Path.Combine(Path.GetTempPath(), @"BaZic_Bin"), true);
}
}
[TestMethod]
public async Task BaZicCompileWithUI()
{
var inputCode =
@"
EXTERN FUNCTION Main(args[])
END FUNCTION
EVENT FUNCTION Window1_Closed()
RETURN ""Result of Window.Close""
END FUNCTION
EVENT FUNCTION Window1_Loaded()
VARIABLE var1 = Button1.Content
IF var1 = ""Hello"" THEN
Button1.Content = ""Hello World""
var1 = Button1.Content
IF var1 = ""Hello World"" THEN
RETURN TRUE
END IF
END IF
END FUNCTION
# The XAML will be provided separatly";
var xamlCode = @"
<Window xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation"" Name=""Window1"">
<StackPanel>
<Button Name=""Button1"" Content=""Hello""/>
</StackPanel>
</Window>";
using (var interpreter = new BaZicInterpreter(inputCode, xamlCode, optimize: false))
{
var tempFile = Path.Combine(Path.GetTempPath(), "BaZic_Bin", Path.GetFileNameWithoutExtension(Path.GetTempFileName()) + ".exe");
var errors = await interpreter.Build(Core.Enums.BaZicCompilerOutputType.WindowsApp, tempFile);
Assert.IsNull(errors);
Assert.IsTrue(File.Exists(tempFile));
Assert.IsTrue(File.Exists(tempFile.Replace(".exe", ".pdb")));
File.Delete(tempFile);
File.Delete(tempFile.Replace(".exe", ".pdb"));
Directory.Delete(Path.Combine(Path.GetTempPath(), @"BaZic_Bin"), true);
}
}
}
}
| 46.13442 | 250 | 0.712696 | [
"MIT"
] | Acidburn0zzz/BaZic | Tests/BaZic.Runtime.Tests/BaZic/Runtime/BaZicInterpreterTest.cs | 22,654 | C# |
// <copyright file="SendingNotificationDataRepository.cs" company="Microsoft">
// Copyright (c) Microsoft. All rights reserved.
// </copyright>
namespace Microsoft.Teams.Apps.CompanyCommunicator.Common.Repositories.NotificationData
{
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
/// <summary>
/// Repository for the sending notification data in the table storage.
/// </summary>
public class SendingNotificationDataRepository : BaseRepository<SendingNotificationDataEntity>, ISendingNotificationDataRepository
{
/// <summary>
/// Initializes a new instance of the <see cref="SendingNotificationDataRepository"/> class.
/// </summary>
/// <param name="logger">The logging service.</param>
/// <param name="repositoryOptions">Options used to create the repository.</param>
public SendingNotificationDataRepository(
ILogger<SendingNotificationDataRepository> logger,
IOptions<RepositoryOptions> repositoryOptions)
: base(
logger,
storageAccountConnectionString: repositoryOptions.Value.StorageAccountConnectionString,
tableName: NotificationDataTableNames.TableName,
defaultPartitionKey: NotificationDataTableNames.SendingNotificationsPartition,
ensureTableExists: repositoryOptions.Value.EnsureTableExists)
{
}
}
}
| 44.393939 | 134 | 0.697611 | [
"MIT"
] | Brasoftware-Inovacao/microsoft-teams-apps-company-communicator | Source/Microsoft.Teams.Apps.CompanyCommunicator.Common/Repositories/NotificationData/SendingNotificationDataRepository.cs | 1,467 | C# |
using System;
using System.Net;
using System.Net.Sockets;
using Lib;
namespace RemoteTaskManagerConsoleServer
{
internal class Program
{
private static readonly TcpListener _serverSocket = new TcpListener(IPAddress.Any, NetworkSettings.ServerPort);
private static TcpClient _clientSocket = default(TcpClient);
private static void Main(string[] args)
{
while (true)
{
try
{
_serverSocket.Start();
_clientSocket = _serverSocket.AcceptTcpClient();
Console.WriteLine("connected!");
var broadcastStream = _clientSocket.GetStream();
var bytes = GlobalMethods.SerializeMessageToBytes(WmiManager.GetProcessList());
broadcastStream.Write(bytes, 0, bytes.Length);
broadcastStream.Flush();
broadcastStream.Dispose();
_serverSocket.Stop();
_clientSocket.Close();
}
catch
{
_serverSocket.Stop();
_clientSocket.Close();
}
}
}
}
} | 22.095238 | 113 | 0.699353 | [
"CC0-1.0"
] | 23S163PR/network-programming | Shevchuk-Yuganets.Andrew/RemoteTaskManager/RemoteTaskManagerConsoleServer/Program.cs | 930 | C# |
using IdentityServer4.EntityFramework.Options;
using Microsoft.AspNetCore.ApiAuthorization.IdentityServer;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using WorldCities.Data.Models;
namespace WorldCities.Data
{
public class ApplicationDbContext : ApiAuthorizationDbContext<ApplicationUser>
{
public ApplicationDbContext(
DbContextOptions options,
IOptions<OperationalStoreOptions> operationalStoreOptions)
: base(options, operationalStoreOptions)
{
}
public DbSet<City> Cities { get; set; }
public DbSet<Country> Countries { get; set; }
}
}
| 30.045455 | 82 | 0.723147 | [
"MIT"
] | FlorianMeinhart/ASP.NET-Core-5-and-Angular | Chapter_11/WorldCities/Data/ApplicationDbContext.cs | 663 | C# |
namespace IconsReminder.DAL
{
using Model;
using System;
using System.Collections.ObjectModel;
using System.Linq;
public class DataSource
{
public static ObservableCollection<IItem> IconsItems { get; set; } = new ObservableCollection<IItem>();
public static ObservableCollection<IItem> SubscribedItems { get; set; } = new ObservableCollection<IItem>();
public static ObservableCollection<IItem> ReminderItems { get; set; } = new ObservableCollection<IItem>();
public static ObservableCollection<IItem> PastReminderItems { get; set; } = new ObservableCollection<IItem>();
private static ItemService _itemService = new ItemService(new FileService(), new ItemJsonParser());
public DataSource()
{
IconsItems = _itemService.GetTheIconsItems();
SubscribedItems = _itemService.GetTheSubscribedItemList();
ReminderItems = _itemService.GetTheRedminderList();
PastReminderItems =
new ObservableCollection<IItem>(_itemService.GetThePastRedminderList().Take<IItem>(50));
}
public static void AddSusbcribedItemToDataStorage(IItem item)
{
_itemService.AddSubscribedItem(item);
}
public static void AddReminderItemToDataStorage(IItem item)
{
_itemService.AddReminderItem(item);
}
public static void AddPastReminderItemToDataStorage(IItem item)
{
_itemService.AddPastReminderItem(item);
}
public static void SaveSusbcribedItemsToDataStorage()
{
_itemService.SaveSubscribedList(SubscribedItems);
}
public static void SaveReminderItemsToDataStorage()
{
_itemService.SaveReminderList(ReminderItems);
}
public static void SavePastReminderItemsToDataStorage()
{
_itemService.SavePastReminderList(PastReminderItems);
}
}
}
| 34.807018 | 118 | 0.664315 | [
"MIT"
] | SudeepPradhan/Reminder-with-Icons | IconsReminder/IconsReminder.DAL/DataSource.cs | 1,986 | C# |
using UnityEngine;
namespace BDFramework.Editor.Tools
{
static public class EditorGUIHelper
{
readonly static public GUIStyle TitleStyle =new GUIStyle()
{
fontSize = 25,
normal = new GUIStyleState()
{
textColor = Color.red
}
};
readonly static public GUIStyle OnGUITitleStyle =new GUIStyle()
{
fontSize = 25,
normal = new GUIStyleState()
{
textColor = Color.red
}
};
}
} | 20.892857 | 71 | 0.478632 | [
"Apache-2.0"
] | HugoFang/BDFramework.Core | Assets/Code/BDFramework/Editor/Tools/EditorGUIHelper.cs | 585 | C# |
using System;
namespace OrmBasics
{
public class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
}
| 15.076923 | 47 | 0.494898 | [
"MIT"
] | cailyngallup/OrmBasics | src/OrmBasics/Program.cs | 198 | C# |
namespace AuthApi.Contracts
{
using MongoDB.Bson;
/// <summary>
/// Specifies the data of a database user.
/// </summary>
public interface IDatabaseUser : IUser
{
/// <summary>
/// Gets the mongodb id.
/// </summary>
ObjectId Id { get; }
}
} | 18.4 | 46 | 0.586957 | [
"MIT"
] | MichaelDiers/micro-frontend | backend/AuthApi/AuthApi/Contracts/IDatabaseUser.cs | 278 | C# |
using Improbable;
using Improbable.Worker;
using ItemGenerator;
using ItemGenerator.Resources;
using RogueFleet.Asteroids;
using RogueFleet.Core;
using RogueFleet.Items;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Threading.Tasks;
using Xoshiro.Base;
using Xoshiro.PRNG32;
namespace AsteroidWorker.ECS
{
public static class ResourceGeneratorSystem
{
static readonly Dispatcher dispatcher = new Dispatcher();
static ResourceGeneratorSystem()
{
dispatcher.OnCommandRequest(Harvestable.Commands.GenerateResource.Metaclass, OnGenerateResourceRequest);
}
internal static void ProccessOpList(OpList opList)
{
dispatcher.Process(opList);
}
static readonly ConcurrentQueue<CommandRequestOp<Harvestable.Commands.GenerateResource, ResourceGenerationRequest>> generateResourceRequestOps = new ConcurrentQueue<CommandRequestOp<Harvestable.Commands.GenerateResource, ResourceGenerationRequest>>();
static void OnGenerateResourceRequest(CommandRequestOp<Harvestable.Commands.GenerateResource, ResourceGenerationRequest> op)
{
generateResourceRequestOps.Enqueue(op);
}
static TimeSpan frameRate = TimeSpan.FromMilliseconds(100);
static readonly Stopwatch stopwatch = new Stopwatch();
internal static void UpdateLoop()
{
while (true)
{
stopwatch.Restart();
Update();
stopwatch.Stop();
var frameTime = frameRate - stopwatch.Elapsed;
if (frameTime > TimeSpan.Zero)
{
Task.Delay(frameTime).Wait();
}
else
{
//connection.SendLogMessage(LogLevel.Warn, "Game Loop", string.Format("Frame Time {0}ms", frameTime.TotalMilliseconds.ToString("N0")));
}
}
}
static readonly DateTime centuryBegin = new DateTime(2001, 1, 1, 0, 0, 0, DateTimeKind.Utc);
static void Update()
{
ProccessGenerateResourceOps();
}
static void ProccessGenerateResourceOps()
{
while (generateResourceRequestOps.TryDequeue(out var op))
{
var asteroidEntityId = op.EntityId.Id;
var response = new ResourceGenerationReponse();
if (ResourcesInventorySystem.TryGetResourceInfo(asteroidEntityId, 0, out var resourceInfo))
{
response.databaseId = resourceInfo.databaseId;
response.type = resourceInfo.type;
response.quantity = resourceInfo.quantity;
}
else
{
var position = PositionsSystem.GetComponent(asteroidEntityId).coords;
var time = (long)(DateTime.Now.ToUniversalTime() - centuryBegin).TotalSeconds;
var lowSample = ProbabilityMap.EvaluateLowSample(position.x, position.y, position.z, time);
var medSample = ProbabilityMap.EvaluateMedSample(position.x, position.y, position.z, time);
var highSample = ProbabilityMap.EvaluateHighSample(position.x, position.y, position.z, time);
var sample = ProbabilityMap.LayeringSample(lowSample, medSample, highSample);
var seed = asteroidEntityId ^ BitConverter.ToInt64(Encoding.UTF8.GetBytes(op.Request.userDatabaseId), 0);
IRandomU prng = new XoShiRo128starstar(seed);
var scanner = op.Request.scanner;
var quantity = QuantityGenerator.Sample(sample, prng, scanner);
if (quantity > 0)
{
response.quantity = quantity;
var scannerResource = scanner.speciality;
if (scannerResource == ResourceType.Random)
{
scannerResource = (ResourceType)prng.Next(1, (int)ResourceType.Count);
}
response.type = scannerResource;
var resourceDBId = Helpers.GenerateCloudFireStoreRandomDocumentId(prng);
var asteroidDBId = Helpers.GenerateCloudFireStoreRandomDocumentId(prng);
response.databaseId = resourceDBId;
SpatialOSConnectionSystem.addPersistenceOps.Enqueue(
new AddComponentOp<PersistenceData>
{
EntityId = op.EntityId,
Data = new PersistenceData()
});
var addComponentOp = new AddComponentOp<IdentificationData>
{
EntityId = op.EntityId,
Data = new IdentificationData
{
entityDatabaseId = asteroidDBId,
}
};
IdentificationsSystem.OnComponentAdded(addComponentOp);
SpatialOSConnectionSystem.addIdentificationOps.Enqueue(addComponentOp);
ResourcesInventorySystem.QueueAddResourceOp(asteroidEntityId, resourceInfo.databaseId, new Resource(resourceInfo.type, resourceInfo.quantity));
var asteroidRef = CloudFirestoreInfo.Database.Collection(CloudFirestoreInfo.AsteroidsCollection).Document(asteroidDBId);
asteroidRef.CreateAsync(new Dictionary<string, object> { { CloudFirestoreInfo.CoordinatesField, new double[3] { position.x, position.y, position.z } } });
}
}
SpatialOSConnectionSystem.responseGenerateResourceOps.Enqueue(
new CommandResponseOp<Harvestable.Commands.GenerateResource, ResourceGenerationReponse>//just using CommandResponseOp as container for request raw id and response
{
EntityId = new EntityId(),
RequestId = new RequestId<OutgoingCommandRequest<Harvestable.Commands.GenerateResource>>(op.RequestId.Id),
Response = response,
});
}
}
}
}
| 41.398734 | 259 | 0.580492 | [
"MIT"
] | SionoiS/AsteroidWorker | ECS/ResourceGeneratorSystem.cs | 6,543 | C# |
using Amazon.JSII.Runtime.Deputy;
#pragma warning disable CS0672,CS0809,CS1591
namespace aws
{
[JsiiInterface(nativeType: typeof(IWafv2WebAclRuleStatementAndStatementStatementSqliMatchStatementFieldToMatchSingleQueryArgument), fullyQualifiedName: "aws.Wafv2WebAclRuleStatementAndStatementStatementSqliMatchStatementFieldToMatchSingleQueryArgument")]
public interface IWafv2WebAclRuleStatementAndStatementStatementSqliMatchStatementFieldToMatchSingleQueryArgument
{
[JsiiProperty(name: "name", typeJson: "{\"primitive\":\"string\"}")]
string Name
{
get;
}
[JsiiTypeProxy(nativeType: typeof(IWafv2WebAclRuleStatementAndStatementStatementSqliMatchStatementFieldToMatchSingleQueryArgument), fullyQualifiedName: "aws.Wafv2WebAclRuleStatementAndStatementStatementSqliMatchStatementFieldToMatchSingleQueryArgument")]
internal sealed class _Proxy : DeputyBase, aws.IWafv2WebAclRuleStatementAndStatementStatementSqliMatchStatementFieldToMatchSingleQueryArgument
{
private _Proxy(ByRefValue reference): base(reference)
{
}
[JsiiProperty(name: "name", typeJson: "{\"primitive\":\"string\"}")]
public string Name
{
get => GetInstanceProperty<string>()!;
}
}
}
}
| 43.419355 | 262 | 0.733284 | [
"MIT"
] | scottenriquez/cdktf-alpha-csharp-testing | resources/.gen/aws/aws/IWafv2WebAclRuleStatementAndStatementStatementSqliMatchStatementFieldToMatchSingleQueryArgument.cs | 1,346 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.ComponentModel;
using EasyGenerator.Studio.PropertyTools;
using EasyGenerator.Studio.Utils;
using System.Xml.Serialization;
namespace EasyGenerator.Studio.Model.UI
{
[Serializable()]
[DefaultPropertyAttribute("Name")]
[UiNode(ImageIndex=3)]
[XmlRoot("GUIModule")]
public class GUIModule : ContextObject,ICloneable
{
//private string name;
//private string caption;
//private string description;
public GUIModule(ContextObject owner)
: base(owner)
{
Windows=new ContextObjectList<GUIWindow>(this);
}
[CategoryAttribute("界面")]
[UiNodeInvisibleAttribute()]
[XmlElement("Name")]
public string Name
{
get;
set;
}
[CategoryAttribute("界面")]
[UiNodeInvisibleAttribute()]
[XmlElement("Caption")]
public string Caption
{
get;
set;
}
[CategoryAttribute("界面")]
[UiNodeInvisibleAttribute()]
[XmlElement("Description")]
public string Description
{
get;
set;
}
[BrowsableAttribute(false)]
[ReadOnly(true)]
[XmlElement("Windows")]
public List<GUIWindow> Windows
{
get;
set;
}
public override string ToString()
{
return this.Caption;
}
public object Clone()
{
return this.MemberwiseClone();
}
}
}
| 22.653333 | 59 | 0.562095 | [
"CC0-1.0"
] | Pinckyang/easygenerator | EasyGenerator/EasyGenerator.Studio/Model/UI/GUIModule.cs | 1,713 | C# |
using System.Collections.Generic;
using ZedSharp.Models.Enums;
namespace ZedSharp.Models.Leagues
{
public class LeagueList
{
public string Name { get; set; }
public Tier Tier { get; set; }
public Queue Queue { get; set; }
public List<LeagueEntry> Entries { get; set; }
}
}
| 22.785714 | 54 | 0.633229 | [
"MIT"
] | NitashEU/ZedSharp | ZedSharp/Models/Leagues/LeagueList.cs | 321 | C# |
//Problem 8. Extract sentences
//Write a program that extracts from a given text all sentences containing given word.
//Example:
//The word is: in
//The text is: We are living in a yellow submarine. We don't have anything else.
//Inside the submarine is very tight. So we are drinking all the day. We will move out of it in 5 days.
//The expected result is: We are living in a yellow submarine. We will move out of it in 5 days.
//Consider that the sentences are separated by . and the words – by non-letter symbols.
using System;
class ExtractSentences
{
static void Main()
{
string text = Text();
int index = 0;
int secuenceIndex = 0;
string[] sentenceBySentence = text.Split('.');
foreach (var sentence in sentenceBySentence)
{
if (sentence.Contains(" in "))
{
Console.Write("{0}.",sentence);
}
}
Console.WriteLine();
}
static string Text()
{
string text = @"We are living in a yellow submarine. We don't have anything else.\nInside the submarine is very tight. So we are drinking all the day. We will move out of it in 5 days.";
return text;
}
}
| 26.326087 | 194 | 0.633361 | [
"MIT"
] | Gecata-/CSharp--Part2-Telerik | StringsAndTextProcessing/08.ExtractSentences/08.ExtractSentences.cs | 1,215 | C# |
using System;
using Microsoft.Extensions.DependencyInjection;
namespace EasyNetQ.DI.Microsoft
{
/// <inheritdoc />
public class ServiceCollectionAdapter : IServiceRegister
{
private readonly IServiceCollection serviceCollection;
/// <summary>
/// Creates an adapter on top of IServiceCollection
/// </summary>
public ServiceCollectionAdapter(IServiceCollection serviceCollection)
{
this.serviceCollection = serviceCollection;
this.serviceCollection.AddSingleton<IServiceResolver, ServiceProviderAdapter>();
}
/// <inheritdoc />
public IServiceRegister Register<TService, TImplementation>(Lifetime lifetime = Lifetime.Singleton) where TService : class where TImplementation : class, TService
{
switch (lifetime)
{
case Lifetime.Transient:
serviceCollection.AddTransient<TService, TImplementation>();
break;
case Lifetime.Singleton:
serviceCollection.AddSingleton<TService, TImplementation>();
break;
default:
throw new ArgumentOutOfRangeException(nameof(lifetime), lifetime, null);
}
return this;
}
/// <inheritdoc />
public IServiceRegister Register<TService>(TService instance) where TService : class
{
serviceCollection.AddSingleton(instance);
return this;
}
/// <inheritdoc />
public IServiceRegister Register<TService>(Func<IServiceResolver, TService> factory, Lifetime lifetime = Lifetime.Singleton) where TService : class
{
switch (lifetime)
{
case Lifetime.Transient:
serviceCollection.AddTransient(x => factory(x.GetService<IServiceResolver>()));
break;
case Lifetime.Singleton:
serviceCollection.AddSingleton(x => factory(x.GetService<IServiceResolver>()));
break;
default:
throw new ArgumentOutOfRangeException(nameof(lifetime), lifetime, null);
}
return this;
}
private class ServiceProviderAdapter : IServiceResolver
{
private readonly IServiceProvider serviceProvider;
public ServiceProviderAdapter(IServiceProvider serviceProvider)
{
this.serviceProvider = serviceProvider;
}
public TService Resolve<TService>() where TService : class
{
return serviceProvider.GetService<TService>();
}
public IServiceResolverScope CreateScope()
{
return new MicrosoftServiceResolverScope(serviceProvider);
}
}
private class MicrosoftServiceResolverScope : IServiceResolverScope
{
private readonly IServiceScope serviceScope;
public MicrosoftServiceResolverScope(IServiceProvider serviceProvider)
{
serviceScope = serviceProvider.CreateScope();
}
public IServiceResolverScope CreateScope()
{
return new MicrosoftServiceResolverScope(serviceScope.ServiceProvider);
}
public void Dispose()
{
serviceScope?.Dispose();
}
public TService Resolve<TService>() where TService : class
{
return serviceScope.ServiceProvider.GetService<TService>();
}
}
}
}
| 33.709091 | 170 | 0.582794 | [
"MIT"
] | EasyNetQ/EasyNetQ | Source/EasyNetQ.DI.Microsoft/ServiceCollectionAdapter.cs | 3,708 | C# |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ViewModelBase.cs" company="">
//
// </copyright>
// <summary>
// Defines the ViewModelBase type.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace PdfCutter
{
using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;
using System.Windows.Markup;
public class BoolToVisibilityConverter : ConverterBase<BoolToVisibilityConverter>
{
public override object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return value is bool
? ((bool)value ? Visibility.Visible : Visibility.Collapsed)
: Visibility.Collapsed;
}
}
public abstract class ConverterBase<T> : MarkupExtension, IValueConverter
where T : class, new()
{
private static T converter;
public abstract object Convert(object value, Type targetType, object parameter, CultureInfo culture);
public virtual object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
#region MarkupExtension members
public override object ProvideValue(IServiceProvider serviceProvider)
{
return converter ?? (converter = new T());
}
#endregion
}
public class NotBoolOperatorConverter : ConverterBase<NotBoolOperatorConverter>
{
public override object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (object.ReferenceEquals(value, null))
{
return null;
}
return !(bool)value;
}
public override object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (object.ReferenceEquals(value, null))
{
return null;
}
return !(bool)value;
}
}
} | 31.819444 | 133 | 0.555216 | [
"Apache-2.0"
] | EfimKR/PdfCutter | PdfCutter/Helpers.cs | 2,291 | C# |
// This file is part of CycloneDX BOM Repository Server
//
// 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.
//
// SPDX-License-Identifier: Apache-2.0
// Copyright (c) OWASP Foundation. All Rights Reserved.
using System;
using System.Collections.Generic;
namespace CycloneDX.BomRepoServer.Models
{
public class BomIdentifier : IComparable<BomIdentifier>
{
public string SerialNumber { get; }
public int Version { get; }
public BomIdentifier(string serialNumber, int version)
{
SerialNumber = serialNumber;
Version = version;
}
public int CompareTo(BomIdentifier other) => SerialNumber == other.SerialNumber
? Version.CompareTo(other.Version)
: SerialNumber.CompareTo(other.SerialNumber);
}
} | 34.368421 | 87 | 0.70291 | [
"Apache-2.0"
] | CycloneDX/cyclonedx-bom-repo-server | src/CycloneDX.BomRepoServer/Models/BomIdentifier.cs | 1,314 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace DAnTE.Inferno
{
partial class frmMADPar
{
/// <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
private Button mbtnOK;
private Button mbtnCancel;
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(frmMADPar));
this.mbtnOK = new System.Windows.Forms.Button();
this.mbtnCancel = new System.Windows.Forms.Button();
this.label2 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.niceLine2 = new DAnTE.ExtraControls.NiceLine();
this.niceLine1 = new DAnTE.ExtraControls.NiceLine();
this.mlblDataName = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this.mcmbBoxFactors = new System.Windows.Forms.ComboBox();
this.mchkBoxMeanAdj = new System.Windows.Forms.CheckBox();
this.SuspendLayout();
//
// mbtnOK
//
this.mbtnOK.Location = new System.Drawing.Point(60, 177);
this.mbtnOK.Name = "mbtnOK";
this.mbtnOK.Size = new System.Drawing.Size(75, 23);
this.mbtnOK.TabIndex = 2;
this.mbtnOK.Text = "OK";
this.mbtnOK.UseVisualStyleBackColor = true;
this.mbtnOK.Click += new System.EventHandler(this.mbtnOK_Click);
//
// mbtnCancel
//
this.mbtnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.mbtnCancel.Location = new System.Drawing.Point(197, 177);
this.mbtnCancel.Name = "mbtnCancel";
this.mbtnCancel.Size = new System.Drawing.Size(75, 23);
this.mbtnCancel.TabIndex = 3;
this.mbtnCancel.Text = "Cancel";
this.mbtnCancel.UseVisualStyleBackColor = true;
this.mbtnCancel.Click += new System.EventHandler(this.mbtnCancel_Click);
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(21, 43);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(70, 13);
this.label2.TabIndex = 16;
this.label2.Text = "Data Source:";
//
// label3
//
this.label3.AutoSize = true;
this.label3.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label3.Location = new System.Drawing.Point(12, 9);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(198, 13);
this.label3.TabIndex = 20;
this.label3.Text = "Median Absolute Deviation (MAD)";
//
// niceLine2
//
this.niceLine2.Location = new System.Drawing.Point(12, 25);
this.niceLine2.Name = "niceLine2";
this.niceLine2.Size = new System.Drawing.Size(315, 15);
this.niceLine2.TabIndex = 21;
//
// niceLine1
//
this.niceLine1.Location = new System.Drawing.Point(12, 156);
this.niceLine1.Name = "niceLine1";
this.niceLine1.Size = new System.Drawing.Size(315, 15);
this.niceLine1.TabIndex = 4;
//
// mlblDataName
//
this.mlblDataName.AutoSize = true;
this.mlblDataName.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.mlblDataName.Location = new System.Drawing.Point(94, 43);
this.mlblDataName.Name = "mlblDataName";
this.mlblDataName.Size = new System.Drawing.Size(41, 13);
this.mlblDataName.TabIndex = 55;
this.mlblDataName.Text = "label8";
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(21, 80);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(82, 13);
this.label1.TabIndex = 56;
this.label1.Text = "Within a Factor:";
//
// mcmbBoxFactors
//
this.mcmbBoxFactors.FormattingEnabled = true;
this.mcmbBoxFactors.Location = new System.Drawing.Point(109, 77);
this.mcmbBoxFactors.Name = "mcmbBoxFactors";
this.mcmbBoxFactors.Size = new System.Drawing.Size(127, 21);
this.mcmbBoxFactors.TabIndex = 57;
//
// mchkBoxMeanAdj
//
this.mchkBoxMeanAdj.AutoSize = true;
this.mchkBoxMeanAdj.Location = new System.Drawing.Point(24, 122);
this.mchkBoxMeanAdj.Name = "mchkBoxMeanAdj";
this.mchkBoxMeanAdj.Size = new System.Drawing.Size(197, 17);
this.mchkBoxMeanAdj.TabIndex = 58;
this.mchkBoxMeanAdj.Text = "Mean of the Datasets is around zero";
this.mchkBoxMeanAdj.UseVisualStyleBackColor = true;
//
// frmMADPar
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(341, 213);
this.Controls.Add(this.mchkBoxMeanAdj);
this.Controls.Add(this.label1);
this.Controls.Add(this.mcmbBoxFactors);
this.Controls.Add(this.mlblDataName);
this.Controls.Add(this.niceLine2);
this.Controls.Add(this.label3);
this.Controls.Add(this.label2);
this.Controls.Add(this.niceLine1);
this.Controls.Add(this.mbtnCancel);
this.Controls.Add(this.mbtnOK);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "frmMADPar";
this.ShowInTaskbar = false;
this.Text = "MAD";
this.ResumeLayout(false);
this.PerformLayout();
}
private ExtraControls.NiceLine niceLine1;
#endregion
private Label label2;
private Label label3;
private ExtraControls.NiceLine niceLine2;
private Label mlblDataName;
private Label label1;
private ComboBox mcmbBoxFactors;
private CheckBox mchkBoxMeanAdj;
}
} | 42.227778 | 171 | 0.579529 | [
"Apache-2.0"
] | ashokapol/Inferno4Proteomics | Inferno/Data/frmMADPar.Designer.cs | 7,601 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Text;
namespace Pollster.Models
{
public class PollDefinition
{
public const string POLL_STATE_UNSCHEDULE = "Unscheduled";
public const string POLL_STATE_SCHEDULE = "Scheduled";
public const string POLL_STATE_ACTIVE = "Active";
public const string POLL_STATE_EXPIRED = "Expired";
public PollDefinition()
{
this.State = POLL_STATE_UNSCHEDULE;
}
public string Id { get; set; }
public string AuthorEmail { get; set; }
[Required]
public string Title { get; set; }
[Required]
public string Question { get; set; }
[Required]
public Dictionary<string, Option> Options { get; set; }
[Required]
public DateTime StartTime { get; set; }
[Required]
public DateTime EndTime { get; set; }
public string State { get; set; }
public class Option
{
public Option()
{
}
public Option(string text)
{
this.Text = text;
}
[Required]
public string Text { get; set; }
public int Votes { get; set; }
}
}
public class ActivePoll
{
public string Id { get; set; }
public DateTime ActivatedTime { get; set; }
}
}
| 23.238095 | 66 | 0.556011 | [
"Apache-2.0"
] | Doug-AWS/aws-sdk-net-samples | Talks/ndcoslo-2017/Pollster/Pollster/Models/PollDefinition.cs | 1,466 | C# |
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.PowerShell.EditorServices.Utility;
namespace Microsoft.PowerShell.EditorServices.Console
{
internal class WindowsConsoleOperations : IConsoleOperations
{
private ConsoleKeyInfo? _bufferedKey;
private SemaphoreSlim _readKeyHandle = AsyncUtils.CreateSimpleLockingSemaphore();
public int GetCursorLeft() => System.Console.CursorLeft;
public int GetCursorLeft(CancellationToken cancellationToken) => System.Console.CursorLeft;
public Task<int> GetCursorLeftAsync() => Task.FromResult(System.Console.CursorLeft);
public Task<int> GetCursorLeftAsync(CancellationToken cancellationToken) => Task.FromResult(System.Console.CursorLeft);
public int GetCursorTop() => System.Console.CursorTop;
public int GetCursorTop(CancellationToken cancellationToken) => System.Console.CursorTop;
public Task<int> GetCursorTopAsync() => Task.FromResult(System.Console.CursorTop);
public Task<int> GetCursorTopAsync(CancellationToken cancellationToken) => Task.FromResult(System.Console.CursorTop);
public async Task<ConsoleKeyInfo> ReadKeyAsync(bool intercept, CancellationToken cancellationToken)
{
await _readKeyHandle.WaitAsync(cancellationToken);
try
{
return
_bufferedKey.HasValue
? _bufferedKey.Value
: await Task.Factory.StartNew(
() => (_bufferedKey = System.Console.ReadKey(intercept)).Value);
}
finally
{
_readKeyHandle.Release();
// Throw if we're cancelled so the buffered key isn't cleared.
cancellationToken.ThrowIfCancellationRequested();
_bufferedKey = null;
}
}
public ConsoleKeyInfo ReadKey(bool intercept, CancellationToken cancellationToken)
{
_readKeyHandle.Wait(cancellationToken);
try
{
return
_bufferedKey.HasValue
? _bufferedKey.Value
: (_bufferedKey = System.Console.ReadKey(intercept)).Value;
}
finally
{
_readKeyHandle.Release();
// Throw if we're cancelled so the buffered key isn't cleared.
cancellationToken.ThrowIfCancellationRequested();
_bufferedKey = null;
}
}
}
}
| 35.896104 | 127 | 0.625543 | [
"MIT"
] | Benny1007/PowerShellEditorServices | src/PowerShellEditorServices/Console/WindowsConsoleOperations.cs | 2,764 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using MixedRealityExtension.Core;
using MixedRealityExtension.Core.Types;
using MixedRealityExtension.Patching.Types;
using MixedRealityExtension.Util;
using Godot;
using MRECollisionDetectionMode = MixedRealityExtension.Core.Interfaces.CollisionDetectionMode;
using MRERigidBodyConstraints = MixedRealityExtension.Core.Interfaces.RigidBodyConstraints;
//using MRELight = MixedRealityExtension.Core.Light;
//using UnityCollisionDetectionMode = UnityEngine.CollisionDetectionMode;
//using UnityRigidBodyConstraints = UnityEngine.RigidbodyConstraints;
using UnityLight = Godot.Light;
using MixedRealityExtension.Util.GodotHelper;
namespace MixedRealityExtension.Patching
{
internal static class PatchingUtilMethods
{
public static T? GeneratePatch<T>(T _old, T _new) where T : struct
{
T? ret = null;
if (!_old.Equals(_new))
{
ret = _new;
}
return ret;
}
public static T[] GeneratePatch<T>(T[] _old, T[] _new) where T : struct
{
if ((_old == null && _new != null) || _new != null)
{
return _new;
}
else
{
return null;
}
}
public static string GeneratePatch(string _old, string _new)
{
if (_old == null && _new != null)
{
return _new;
}
else if (_new == null)
{
return null;
}
if (_old != _new)
{
return _new;
}
else
{
return null;
}
}
public static Vector3Patch GeneratePatch(MWVector3 _old, Vector3 _new)
{
if (_old == null && _new != null)
{
return new Vector3Patch(_new);
}
else if (_new == null)
{
return null;
}
var patch = new Vector3Patch()
{
X = _old.X != _new.x ? (float?)_new.x : null,
Y = _old.Y != _new.y ? (float?)_new.y : null,
Z = _old.Z != _new.z ? (float?)_new.z : null
};
if (patch.IsPatched())
{
return patch;
}
else
{
return null;
}
}
public static QuaternionPatch GeneratePatch(MWQuaternion _old, Quat _new)
{
if (_old == null && _new != null)
{
return new QuaternionPatch(_new);
}
else if (_new == null)
{
return null;
}
var patch = new QuaternionPatch()
{
X = _old.X != _new.x ? (float?)_new.x : null,
Y = _old.Y != _new.y ? (float?)_new.y : null,
Z = _old.Z != _new.z ? (float?)_new.z : null,
W = _old.W != _new.w ? (float?)_new.w : null
};
if (patch.IsPatched())
{
return patch;
}
else
{
return null;
}
}
public static TransformPatch GenerateAppTransformPatch(MWTransform _old, Spatial _new, Spatial appRoot)
{
if (_old == null && _new != null)
{
return new TransformPatch()
{
Position = GeneratePatch(null, appRoot.ToLocal(_new.GlobalTransform.origin)),
Rotation = GeneratePatch(null, new Quat(appRoot.GlobalTransform.basis.Inverse() * _new.GlobalTransform.basis)),
};
}
else if (_new == null)
{
return null;
}
TransformPatch transform = new TransformPatch()
{
Position = GeneratePatch(_old.Position, appRoot.ToLocal(_new.GlobalTransform.origin)),
Rotation = GeneratePatch(_old.Rotation, new Quat(appRoot.GlobalTransform.basis.Inverse() * _new.GlobalTransform.basis)),
};
return transform.IsPatched() ? transform : null;
}
public static ScaledTransformPatch GenerateLocalTransformPatch(MWScaledTransform _old, Spatial _new)
{
if (_old == null && _new != null)
{
return new ScaledTransformPatch()
{
Position = GeneratePatch(null, _new.Transform.origin),
Rotation = GeneratePatch(null, new Quat(_new.Transform.basis)),
Scale = GeneratePatch(null, _new.Scale)
};
}
else if (_new == null)
{
return null;
}
ScaledTransformPatch transform = new ScaledTransformPatch()
{
Position = GeneratePatch(_old.Position, _new.Transform.origin),
Rotation = GeneratePatch(_old.Rotation, new Quat(_new.Transform.basis)),
Scale = GeneratePatch(_old.Scale, _new.Scale)
};
return transform.IsPatched() ? transform : null;
}
public static ColorPatch GeneratePatch(MWColor _old, Color _new)
{
if (_old == null && _new != null)
{
return new ColorPatch(_new);
}
else if (_new == null)
{
return null;
}
var patch = new ColorPatch()
{
R = _old.R != _new.r ? (float?)_new.r : null,
G = _old.G != _new.g ? (float?)_new.g : null,
B = _old.B != _new.b ? (float?)_new.b : null,
A = _old.A != _new.a ? (float?)_new.a : null
};
if (patch.IsPatched())
{
return patch;
}
else
{
return null;
}
}
public static RigidBodyPatch GeneratePatch(MixedRealityExtension.Core.RigidBody _old, Godot.RigidBody _new,
Spatial sceneRoot, bool addVelocities)
{
if (_old == null && _new != null)
{
return new RigidBodyPatch(_new, sceneRoot);
}
else if (_new == null)
{
return null;
}
var patch = new RigidBodyPatch()
{
// Do not include Position or Rotation in the patch.
// we add velocities only if there is an explicit subscription for it, since it might cause significant bandwidth
Velocity = ((addVelocities) ?
GeneratePatch(_old.Velocity, sceneRoot.ToLocal(_new.LinearVelocity)) : null),
AngularVelocity = ((addVelocities) ?
GeneratePatch(_old.AngularVelocity, sceneRoot.ToLocal(_new.AngularVelocity)) : null),
CollisionDetectionMode = GeneratePatch(
_old.CollisionDetectionMode,
_new.ContinuousCd switch
{
true => MRECollisionDetectionMode.Continuous,
false => MRECollisionDetectionMode.Discrete
}),
ConstraintFlags = GeneratePatch(_old.ConstraintFlags, _new.GetMRERigidBodyConstraints()),
DetectCollisions = GeneratePatch(_old.DetectCollisions, !_new.GetChild<CollisionShape>()?.Disabled ?? false),
Mass = GeneratePatch(_old.Mass, _new.Mass),
UseGravity = GeneratePatch(_old.UseGravity, !Mathf.IsZeroApprox(_new.GravityScale)),
};
if (patch.IsPatched())
{
return patch;
}
else
{
return null;
}
}
/*FIXME
public static LightPatch GeneratePatch(MRELight _old, UnityLight _new)
{
if (_old == null && _new != null)
{
return new LightPatch(_new);
}
else if (_new == null)
{
return null;
}
var patch = new LightPatch()
{
Enabled = _new.enabled,
Type = UtilMethods.ConvertEnum<Core.Interfaces.LightType, UnityEngine.LightType>(_new.type),
Color = new ColorPatch(_new.color),
Range = _new.range,
Intensity = _new.intensity,
SpotAngle = _new.spotAngle
};
if (patch.IsPatched())
{
return patch;
}
else
{
return null;
}
}
*/
}
public static class PatchingUtilsExtensions
{
public static T ApplyPatch<T>(this T _this, T? patch) where T : struct
{
if (patch.HasValue)
{
_this = patch.Value;
}
return _this;
}
public static string ApplyPatch(this string _this, string patch)
{
if (patch != null)
{
_this = patch;
}
return _this;
}
public static MWVector2 ApplyPatch(this MWVector2 _this, Vector2Patch vector)
{
if (vector == null)
{
return _this;
}
if (vector.X != null)
{
_this.X = vector.X.Value;
}
if (vector.Y != null)
{
_this.Y = vector.Y.Value;
}
return _this;
}
public static MWVector3 ApplyPatch(this MWVector3 _this, Vector3Patch vector)
{
if (vector == null)
{
return _this;
}
if (vector.X != null)
{
_this.X = vector.X.Value;
}
if (vector.Y != null)
{
_this.Y = vector.Y.Value;
}
if (vector.Z != null)
{
_this.Z = vector.Z.Value;
}
return _this;
}
public static MWQuaternion ApplyPatch(this MWQuaternion _this, QuaternionPatch quaternion)
{
if (quaternion == null)
{
return _this;
}
if (quaternion.W != null)
{
_this.W = quaternion.W.Value;
}
if (quaternion.X != null)
{
_this.X = quaternion.X.Value;
}
if (quaternion.Y != null)
{
_this.Y = quaternion.Y.Value;
}
if (quaternion.Z != null)
{
_this.Z = quaternion.Z.Value;
}
return _this;
}
public static MWColor ApplyPatch(this MWColor _this, ColorPatch color)
{
if (color == null)
{
return _this;
}
if (color.A != null)
{
_this.A = color.A.Value;
}
if (color.R != null)
{
_this.R = color.R.Value;
}
if (color.G != null)
{
_this.G = color.G.Value;
}
if (color.B != null)
{
_this.B = color.B.Value;
}
return _this;
}
public static void ApplyLocalPatch(this Spatial _this, MWScaledTransform current, ScaledTransformPatch patch)
{
var localPosition = _this.Transform.origin;
var localRotation = _this.Transform.basis.RotationQuat();
var localScale = _this.Transform.basis.Scale;
if (patch.Position != null)
{
localPosition = localPosition.GetPatchApplied(current.Position.ApplyPatch(patch.Position));
localPosition.z *= -1;
}
if (patch.Rotation != null)
{
localRotation = localRotation.GetPatchApplied(current.Rotation.ApplyPatch(patch.Rotation));
localRotation.x *= -1;
localRotation.y *= -1;
}
if (patch.Scale != null)
{
localScale = localScale.GetPatchApplied(current.Scale.ApplyPatch(patch.Scale));
}
var basis = new Basis(localRotation);
basis.Scale = localScale;
_this.Transform = new Transform(basis, localPosition);
}
public static void ApplyAppPatch(this Spatial _this, Spatial appRoot, MWTransform current, TransformPatch patch)
{
var globalPosition = _this.GlobalTransform.origin;
var globalRotation = _this.GlobalTransform.basis.RotationQuat();
var globalScale = _this.GlobalTransform.basis.Scale;
if (patch.Position != null)
{
globalPosition = appRoot.ToLocal(_this.GlobalTransform.origin).GetPatchApplied(current.Position.ApplyPatch(patch.Position));
globalPosition = appRoot.ToGlobal(globalPosition);
globalPosition.z *= -1;
}
if (patch.Rotation != null)
{
var appRotation = appRoot.GlobalTransform.basis.RotationQuat();
var currAppRotation = appRotation.Inverse() * globalRotation;
var newAppRotation = currAppRotation.GetPatchApplied(current.Rotation.ApplyPatch(patch.Rotation));
globalRotation = appRotation * newAppRotation;
globalRotation.x *= -1;
globalRotation.y *= -1;
}
var basis = new Basis(globalRotation);
basis.Scale = globalScale;
_this.Transform = new Transform(basis, globalPosition);
}
}
}
| 22.714903 | 128 | 0.649235 | [
"MIT"
] | Samsung/mixed-reality-extension-godot | MREGodotRuntimeLib/Patching/PatchingUtils.cs | 10,517 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.