content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2 values |
|---|---|---|---|---|---|---|---|---|
using System;
using System.Collections.Generic;
using System.Collections;
namespace OmiyaGames.Settings
{
///-----------------------------------------------------------------------
/// <copyright file="SingleSettingsGeneratorArgs.cs" company="Omiya Games">
/// The MIT License (MIT)
///
/// Copyright (c) 2014-2017 Omiya Games
///
/// 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.
/// </copyright>
/// <author>Taro Omiya</author>
/// <date>5/29/2017</date>
///-----------------------------------------------------------------------
/// <summary>
/// Arguments providing a collection of <see cref="IGenerator"/>
/// </summary>
/// <seealso cref="GameSettings"/>
public class SettingsGeneratorArgs : EventArgs, IEnumerable<KeyValuePair<int, ICollection<SettingsGeneratorArgs.SingleSettingsInfo>>>
{
public struct SingleSettingsInfo
{
public readonly int versionArrayIndex;
public readonly IGenerator generator;
public readonly bool isStoredSetting;
public SingleSettingsInfo(int versionArrayIndex, IGenerator generator)
{
this.versionArrayIndex = versionArrayIndex;
this.generator = generator;
isStoredSetting = (generator is IStoredSetting);
}
public string propertyName
{
get
{
return generator.PropertyName;
}
}
}
readonly Dictionary<string, SingleSettingsInfo> allProperties = new Dictionary<string, SingleSettingsInfo>();
readonly HashSet<string> allPropertyNames = new HashSet<string>();
public bool AddSetting(int versionArrayIndex, IGenerator generator, out string errorMessage)
{
bool returnFlag = false;
errorMessage = null;
if (string.IsNullOrEmpty(generator.Key) == true)
{
errorMessage = "Key from generator is null or empty. Please populate them.";
}
else if (string.IsNullOrEmpty(generator.PropertyName) == true)
{
errorMessage = "PropertyName from generator is null or empty. Please populate them.";
}
else if (allProperties.ContainsKey(generator.Key) == true)
{
errorMessage = "Key \"" + generator.Key + "\" is already in the arguments. Consider using ModifySetting(ISingleGenerator, out string) instead.";
}
else if (allPropertyNames.Contains(generator.PropertyName) == true)
{
errorMessage = "Property/Function \"" + generator.PropertyName + "\" is already in the arguments. Provide a unique property name, instead.";
}
else
{
allProperties.Add(generator.Key, new SingleSettingsInfo(versionArrayIndex, generator));
allPropertyNames.Add(generator.PropertyName);
returnFlag = true;
}
return returnFlag;
}
public bool RemoveSetting(string generatorKey, out string errorMessage)
{
bool returnFlag = false;
errorMessage = null;
if (string.IsNullOrEmpty(generatorKey) == true)
{
errorMessage = "Key is null or empty.";
}
else if(RemoveSettings(generatorKey) == false)
{
errorMessage = "Key \"" + generatorKey + "\" is not in the arguments.";
}
else
{
returnFlag = true;
}
return returnFlag;
}
public IEnumerator<KeyValuePair<int, ICollection<SingleSettingsInfo>>> GetEnumerator()
{
return GroupedInfo.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GroupedInfo.GetEnumerator();
}
#region Helper Methods
private SortedDictionary<int, ICollection<SingleSettingsInfo>> GroupedInfo
{
get
{
SortedDictionary<int, ICollection<SingleSettingsInfo>> groupedInfo = new SortedDictionary<int, ICollection<SingleSettingsInfo>>();
ICollection<SingleSettingsInfo> infoGroup = null;
foreach (SingleSettingsInfo info in allProperties.Values)
{
if(groupedInfo.TryGetValue(info.versionArrayIndex, out infoGroup) == false)
{
infoGroup = new List<SingleSettingsInfo>();
groupedInfo.Add(info.versionArrayIndex, infoGroup);
}
infoGroup.Add(info);
}
return groupedInfo;
}
}
private bool RemoveSettings(string key)
{
bool returnFlag = false;
SingleSettingsInfo generator;
if (allProperties.TryGetValue(key, out generator) == true)
{
allPropertyNames.Remove(generator.propertyName);
allProperties.Remove(key);
returnFlag = true;
}
return returnFlag;
}
#endregion
}
}
| 41.06875 | 161 | 0.561406 | [
"MIT"
] | OmiyaGames/everybody-plays-golf | Assets/Omiya Games/Scripts/Singleton/Settings/FileGenerators/SettingsGeneratorArgs.cs | 6,573 | C# |
namespace Examples.ElasticSearch.Consumer
{
using Examples.ElasticSearch.Consumer.Consumers;
using MassTransit;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Hosting;
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
} | 24.56 | 64 | 0.760586 | [
"MIT"
] | thorstenalpers/.Net-Examples | ElasticSearch/Consumer/Program.cs | 614 | C# |
using System;
namespace MultiPlayer.Games.TicTacToe
{
public class Mark : Move
{
public int X { get; set; }
public int Y { get; set; }
public Field Marking { get; set; }
public Mark(int x, int y, Field marking)
{
X = x;
Y = y;
Marking = marking;
}
public override void Execute(GameState gameState)
{
(gameState as TTTGameState).Board.board[X,Y] = Marking;
}
public override bool Equals(Move other)
{
var mark = other as Mark;
return mark.Marking == Marking && mark.X == X && mark.Y == Y;
}
}
}
| 22.633333 | 73 | 0.500736 | [
"MIT"
] | andszk/MultiPlayer | MultiPlayer/Games/TicTacToe/Mark.cs | 681 | C# |
using System;
using System.Drawing;
using System.Windows.Forms;
using Johnny.Library.Helper;
using Johnny.CodeGenerator.Core;
namespace Johnny.CodeGenerator.Controls.VSTempTree
{
/// <summary>
/// Summary description for Nodes.
/// </summary>
public class BaseNode : TreeNode {
public NodeType NodeType;
public BaseNode(){}
public BaseNode(string nodename)
{
NodeType = NodeType.Base;
this.Text = nodename;
this.ImageIndex = DataConvert.GetInt32(IconType.VsTemplates);
this.SelectedImageIndex = DataConvert.GetInt32(IconType.VsTemplates);
}
}
public class VsVersionNode : BaseNode
{
public VsTemplateInfo VsVersion;
public VsVersionNode() { }
public VsVersionNode(string nodename)
{
NodeType = NodeType.VsVersion;
this.Text = nodename;
this.ImageIndex = DataConvert.GetInt32(IconType.VsVersion);
this.SelectedImageIndex = DataConvert.GetInt32(IconType.VsVersion);
}
}
public class SolutionNode : BaseNode
{
public SolutionInfo Solution;
public SolutionNode() { }
public SolutionNode(string nodename)
{
NodeType = NodeType.Solution;
this.Text = nodename;
this.ImageIndex = DataConvert.GetInt32(IconType.Solution);
this.SelectedImageIndex = DataConvert.GetInt32(IconType.Solution);
}
}
public class ProjectNode : BaseNode
{
public ProjectInfo Project;
public ProjectNode(){}
public ProjectNode(string nodename)
{
NodeType = NodeType.Project;
this.Text = nodename;
this.ImageIndex = DataConvert.GetInt32(IconType.Project);
this.SelectedImageIndex = DataConvert.GetInt32(IconType.Project);
}
}
}
| 27.289855 | 81 | 0.631439 | [
"MIT"
] | SammyEnigma/code-generator-winform | Johnny.CodeGenerator.Controls/VSTempTree/Nodes.cs | 1,883 | C# |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
namespace NotificationService.UnitTests.Controllers.V1.MeetingInviteController
{
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Threading.Tasks;
using Moq;
using NotificationService.BusinessLibrary;
using NotificationService.BusinessLibrary.Interfaces;
using NotificationService.Common.Logger;
using NotificationService.Contracts;
using NotificationService.Contracts.Models;
using NotificationService.Controllers;
using NUnit.Framework;
/// <summary>
/// Tests for SendEmailNotifications method of Email Controller.
/// </summary>
[ExcludeFromCodeCoverage]
public class SendMeetingNotificationsTest
{
private readonly string applicationName = "TestApp";
private readonly MeetingNotificationItem[] meetingInvitesItem = new MeetingNotificationItem[]
{
new MeetingNotificationItem() { From = "user@contoso.com", RequiredAttendees = "test@contoso.com" },
};
private Mock<IEmailServiceManager> emailServiceManager;
private ILogger logger;
/// <summary>
/// Initialization for the tests.
/// </summary>
[SetUp]
public void Setup()
{
this.emailServiceManager = new Mock<IEmailServiceManager>();
this.logger = new Mock<ILogger>().Object;
}
/// <summary>
/// Tests for SendEmailNotifications method for valid inputs.
/// </summary>
[Test]
public void SendEmailNotificationsTestValidInput()
{
MeetingInviteController meetingInviteController = new MeetingInviteController(this.emailServiceManager.Object, this.logger);
IList<NotificationResponse> responses = new List<NotificationResponse>();
_ = this.emailServiceManager
.Setup(emailServiceManager => emailServiceManager.SendMeetingInvites(It.IsAny<string>(), It.IsAny<MeetingNotificationItem[]>()))
.Returns(Task.FromResult(responses));
var result = meetingInviteController.SendMeetingInvites(this.applicationName, this.meetingInvitesItem);
Assert.AreEqual(result.Status.ToString(), "RanToCompletion");
this.emailServiceManager.Verify(mgr => mgr.SendMeetingInvites(It.IsAny<string>(), It.IsAny<MeetingNotificationItem[]>()), Times.Once);
Assert.Pass();
}
/// <summary>
/// Tests for SendEmailNotifications method for invalid inputs.
/// </summary>
[Test]
public void SendEmailNotificationsTestInvalidInput()
{
MeetingInviteController meetingInviteController = new MeetingInviteController(this.emailServiceManager.Object, this.logger);
_ = Assert.ThrowsAsync<ArgumentException>(async () => await meetingInviteController.SendMeetingInvites(null, this.meetingInvitesItem));
_ = Assert.ThrowsAsync<ArgumentNullException>(async () => await meetingInviteController.SendMeetingInvites(this.applicationName, null));
}
}
}
| 41.75 | 148 | 0.686101 | [
"MIT"
] | tech4GT/notification-provider | NotificationService/NotificationService.UnitTests/Controllers/V1/MeetingInviteController/SendMeetingNotificationsTest.cs | 3,175 | C# |
using Microsoft.Extensions.Configuration;
using DtpCore.Workflows;
using DtpStampCore.Extensions;
using DtpStampCore.Interfaces;
using MediatR;
using DtpCore.Repository;
using DtpCore.Model;
using DtpCore.Extensions;
using Microsoft.Extensions.Logging;
using System.Collections.Generic;
using DtpCore.Interfaces;
using DtpCore.Enumerations;
using System;
using System.ComponentModel;
using DtpStampCore.Commands;
using Microsoft.EntityFrameworkCore;
using System.Linq;
using DtpCore.Model.Database;
using System.Net;
using System.Text;
namespace DtpStampCore.Workflows
{
[DisplayName("Create Proof for timestamps")]
[Description("Calculated the Timestamps sources into a merke tree and put the root on the blockchain")]
public class CreateProofWorkflow : WorkflowContext
{
//private ITimestampWorkflowService _timestampWorkflowService;
private readonly IMediator _mediator;
private TrustDBContext _db;
private IConfiguration _configuration;
private ILogger<CreateProofWorkflow> _logger;
//public BlockchainProof CurrentProof { get; private set; }
private IMerkleTree _merkleTree;
private IBlockchainServiceFactory _blockchainServiceFactory;
private IKeyValueService _keyValueService;
private readonly IDTPApiService _apiService;
public CreateProofWorkflow(IMediator mediator, TrustDBContext db, IConfiguration configuration, ILogger<CreateProofWorkflow> logger, IMerkleTree merkleTree, IBlockchainServiceFactory blockchainServiceFactory, IKeyValueService keyValueService, IDTPApiService apiService)
{
_mediator = mediator;
_db = db;
_configuration = configuration;
_logger = logger;
_merkleTree = merkleTree;
_blockchainServiceFactory = blockchainServiceFactory;
_keyValueService = keyValueService;
_apiService = apiService;
}
public override void Execute()
{
// Getting the current aggregator for timestamps
var proof = new BlockchainProof();
// TODO: Support more than one blockchain type!!
proof.Timestamps = _db.Timestamps.Where(p => p.ProofDatabaseID == null).ToList();
if (proof.Timestamps.Count == 0)
{
CombineLog(_logger, $"No timestamps found");
Wait(_configuration.TimestampInterval()); // Default 10 min
return; // Exit workflow succesfully
}
// Ensure a new Proof object!
try
{
Merkle(proof);
// If funding key is available then use, local timestamping.
if (IsFundingAvailable(proof))
LocalTimestamp(proof);
else
RemoteTimestamp(proof);
proof.Status = ProofStatusType.Waiting.ToString();
_db.Proofs.Add(proof);
// Otherwise use the remote timestamp from trust.dance.
}
catch (Exception ex)
{
proof.Status = ProofStatusType.Failed.ToString();
CombineLog(_logger, $"Error in proof ID:{proof.DatabaseID} " + ex.Message+":"+ex.StackTrace);
}
finally
{
var result = _db.SaveChangesAsync().GetAwaiter().GetResult();
_logger.LogTrace($"CreateProofWorkflow save with result code: {result}");
}
Wait(_configuration.ConfirmationWait(_configuration.Blockchain()));
}
private bool IsFundingAvailable(BlockchainProof proof)
{
return !string.IsNullOrEmpty(_configuration.FundingKey(proof.Blockchain));
}
public void Merkle(BlockchainProof proof)
{
foreach (var item in proof.Timestamps)
_merkleTree.Add(item);
proof.MerkleRoot = _merkleTree.Build().Hash;
CombineLog(_logger, $"Proof ID:{proof.DatabaseID} Timestamp found {proof.Timestamps.Count} - Merkleroot: {proof.MerkleRoot.ConvertToHex()}");
}
public void LocalTimestamp(BlockchainProof proof)
{
var _fundingKeyWIF = _configuration.FundingKey(proof.Blockchain);
var _blockchainService = _blockchainServiceFactory.GetService(proof.Blockchain);
var fundingKey = _blockchainService.DerivationStrategy.KeyFromString(_fundingKeyWIF);
var tempTxKey = proof.Blockchain + "_previousTx";
var previousTx = _keyValueService.Get(tempTxKey);
var previousTxList = (previousTx != null) ? new List<Byte[]> { previousTx } : null;
var OutTx = _blockchainService.Send(proof.MerkleRoot, fundingKey, previousTxList);
//OutTX needs to go to a central store for that blockchain
_keyValueService.Set(tempTxKey, OutTx[0]);
var merkleRootKey = _blockchainService.DerivationStrategy.GetKey(proof.MerkleRoot);
proof.Address = _blockchainService.DerivationStrategy.GetAddress(merkleRootKey);
CombineLog(_logger, $"Proof ID:{proof.DatabaseID} Merkle root: {proof.MerkleRoot.ConvertToHex()} has been timestamped with address: {proof.Address}");
}
public void RemoteTimestamp(BlockchainProof proof)
{
var uri = _configuration.RemoteServer().Append("/api/timestamp");
var timestamp = _apiService.UploadData<Timestamp>(uri, proof.MerkleRoot).GetAwaiter().GetResult();
proof.Receipt = timestamp.Path;
}
}
}
| 38.155405 | 277 | 0.650257 | [
"MIT"
] | DigitalTrustProtocol/DtpSolution | DtpStampCore/Workflows/CreateProofWorkflow.cs | 5,649 | C# |
// Copyright (c) Imazen LLC.
// No part of this project, including this file, may be copied, modified,
// propagated, or distributed except as permitted in COPYRIGHT.txt.
// Licensed under the Apache License, Version 2.0.
using System;
using System.Collections.Generic;
using System.Text;
using ImageResizer.Resizing;
using System.Web.Hosting;
using ImageResizer.Configuration;
using System.Text.RegularExpressions;
using System.Collections.Specialized;
using ImageResizer.ExtensionMethods;
using ImageResizer.Util;
namespace ImageResizer.Plugins.Basic {
/// <summary>
/// Redirects image 404 errors to a querystring-specified server-local location,
/// while maintaining querystring values (by default) so layout isn't disrupted.
/// </summary>
/// <remarks>
/// <para>
/// The image to use in place of missing images can be specified by the "404"
/// parameter in the querystring. The "404" value can also refer to a named
/// value in the <plugins>/<Image404> setting in Web.config.
/// </para>
/// </remarks>
/// <example>
/// <para>
/// Using <c><img src="missingimage.jpg?404=image.jpg&width=200" /></c>
/// with the default setting (<c><image404 baseDir="~/" /></c>) will
/// redirect to <c>~/image.jpg?width=200</c>.
/// </para>
/// <para>
/// You may also configure 'variables', which is the recommended approach.
/// For example, <c><image404 propertyImageDefault="~/images/nophoto.png" /></c>
/// in the config file, and <c><img src="missingimage.jpg?404=propertyImageDefault&width=200" /></c>
/// will result in a redirect to <c>~/images/nophoto.png?width=200</c>.
/// Any querystring values in the config variable take precedence over
/// querystring values in the image querystring. For example,
/// <c><image404 propertyImageDefault="~/images/nophoto.png?format=png" /></c>
/// in the config file and
/// <c><img src="missingimage.jpg?format=jpg&404=propertImageDefault&width=200" /></c>
/// will result in a redirect to <c>~/images/nophoto.png?format=png&width=200</c>.
/// </para>
/// </example>
public class Image404:IQuerystringPlugin,IPlugin {
public enum FilterMode
{
IncludeUnknownCommands,
ExcludeUnknownCommands,
IncludeAllCommands,
ExcludeAllCommands,
}
readonly static MatcherCollection DefaultWhitelist = new MatcherCollection(
// deterministic sizing and color -- copied by default
new Matcher("maxwidth"),
new Matcher("maxheight"),
new Matcher("width"),
new Matcher("height"),
new Matcher("w"),
new Matcher("h"),
new Matcher(delegate (string name, string value) { // crop=auto
return string.Equals(name, "crop", StringComparison.OrdinalIgnoreCase) &&
string.Equals(value, "auto", StringComparison.OrdinalIgnoreCase); }),
new Matcher("mode"),
new Matcher("anchor"),
new Matcher("scale"),
new Matcher("zoom"),
new Matcher("bgcolor"),
new Matcher("paddingWidth"),
new Matcher("paddingColor"),
new Matcher("borderWidth"),
new Matcher("borderColor"),
new Matcher("shadowWidth"),
new Matcher("shadowOffset"),
new Matcher("shadowColor"),
new Matcher("margin"),
new Matcher("dpi"),
// output size, format -- copied by default
new Matcher("format"),
new Matcher("quality"),
new Matcher("colors"),
new Matcher("subsampling"),
new Matcher("dither"),
new Matcher("speed"),
new Matcher("ignoreicc"),
// visual filters (simple and advanced), post-processing -- copied by default
new Matcher(delegate(string name) { return name.StartsWith("s.", StringComparison.OrdinalIgnoreCase);}),
new Matcher(delegate(string name) { return name.StartsWith("a.", StringComparison.OrdinalIgnoreCase);}),
new Matcher("flip"),
new Matcher("rotate"));
readonly static MatcherCollection DefaultBlacklist = new MatcherCollection(
// not useful -- excluded by default
new Matcher("watermark"),
new Matcher("cache"),
new Matcher("process"),
new Matcher("builder"),
new Matcher("decoder"),
new Matcher("encoder"),
// unlikely to need -- excluded by default
new Matcher("sflip"),
new Matcher("srotate"),
new Matcher("autorotate"),
new Matcher(delegate (string name, string value) { // crop=anything-other-than-auto
return string.Equals(name, "crop", StringComparison.OrdinalIgnoreCase) &&
!string.Equals(value, "auto", StringComparison.OrdinalIgnoreCase); }),
new Matcher("cropxunits"),
new Matcher("cropyyunits"),
new Matcher("trim.threshold"),
new Matcher("trim.percentpadding"),
// never want to copy -- excluded by default
new Matcher("hmac"),
new Matcher("urlb64"),
new Matcher("frame"),
new Matcher("page"),
new Matcher("color1"),
new Matcher("color2"));
Config c;
private FilterMode filterMode = FilterMode.ExcludeUnknownCommands;
private MatcherCollection except = MatcherCollection.Empty;
// To support configurable include/exclude modes and exceptions, uncomment
// this constructor.
////public Image404(NameValueCollection args) {
//// this.filterMode = NameValueCollectionExtensions.Get(args, "mode", FilterMode.ExcludeUnknownCommands);
//// this.except = MatcherCollection.Parse(args["except"]);
//// }
public IPlugin Install(Configuration.Config c) {
this.c = c;
if (c.Plugins.Has<Image404>()) throw new InvalidOperationException();
c.Pipeline.ImageMissing += new Configuration.UrlEventHandler(Pipeline_ImageMissing);
c.Plugins.add_plugin(this);
return this;
}
void Pipeline_ImageMissing(System.Web.IHttpModule sender, System.Web.HttpContext context, Configuration.IUrlEventArgs e) {
if (!string.IsNullOrEmpty(e.QueryString["404"])) {
//Resolve the path to virtual or app-relative for
string path = resolve404Path(e.QueryString["404"]);
//Resolve to virtual path
path = Util.PathUtils.ResolveAppRelative(path);
// Merge commands from the 404 querystring with ones from the
// original image. We start by sanitizing the querystring from
// the image.
ResizeSettings imageQuery = new ResizeSettings(e.QueryString);
imageQuery.Normalize();
// Use the configured settings by default.
var filterMode = this.filterMode;
var except = this.except;
// To support querystring-specifiable filter mode and exceptions,
// uncomment the if block below.
////// If the imageQuery includes specific 404 command-filtering,
////// (*either* of the values), use those instead of the
////// configured defaults.
////if (!string.IsNullOrEmpty(e.QueryString["404.filterMode"]) ||
//// !string.IsNullOrEmpty(e.QueryString["404.except"]))
////{
//// filterMode = NameValueCollectionExtensions.Get(e.QueryString, "404.filterMode", FilterMode.ExcludeUnknownCommands);
//// except = MatcherCollection.Parse(e.QueryString["404.except"]);
////}
// remove all of the commands we're supposed to remove... we
// clone the list of keys so that we're not modifying the collection
// while we enumerate it.
var shouldRemove = CreateRemovalMatcher(filterMode, except);
var names = new List<string>(imageQuery.AllKeys);
foreach (var name in names)
{
if (shouldRemove(name, imageQuery[name]))
{
imageQuery.Remove(name);
}
}
// Always remove the '404', '404.filterMode', and '404.except' settings.
imageQuery.Remove("404");
imageQuery.Remove("404.filterMode");
imageQuery.Remove("404.except");
ResizeSettings i404Query = new ResizeSettings(Util.PathUtils.ParseQueryString(path));
i404Query.Normalize();
//Overwrite new with old
foreach (string key in i404Query.Keys)
if (key != null) imageQuery[key] = i404Query[key];
path = PathUtils.AddQueryString(PathUtils.RemoveQueryString(path), PathUtils.BuildQueryString(imageQuery));
//Redirect
context.Response.Redirect(path, true);
}
}
private static Matcher.NameAndValue CreateRemovalMatcher(FilterMode filterMode, MatcherCollection except)
{
Matcher.NameAndValue shouldRemove = null;
switch (filterMode)
{
case FilterMode.IncludeUnknownCommands:
// To include unknown commands, we remove blacklisted
// and 'except' commands.
shouldRemove = delegate(string name, string value)
{
return DefaultBlacklist.IsMatch(name, value) ||
except.IsMatch(name, value);
};
break;
case FilterMode.ExcludeUnknownCommands:
// To exclude unknown commands, we *keep* whitelisted
// and 'except' commands.
shouldRemove = delegate(string name, string value)
{
return !(DefaultWhitelist.IsMatch(name, value) ||
except.IsMatch(name, value));
};
break;
case FilterMode.IncludeAllCommands:
// To include all commands, we remove any of the 'except'
// commands.
shouldRemove = delegate(string name, string value)
{
return except.IsMatch(name, value);
};
break;
case FilterMode.ExcludeAllCommands:
// To exclude all commands, we only keep the 'except'
// commands.
shouldRemove = delegate(string name, string value)
{
return !except.IsMatch(name, value);
};
break;
}
return shouldRemove;
}
protected string resolve404Path(string path) {
//1 If it starts with 'http(s)://' throw an exception.
if (path.StartsWith("http", StringComparison.OrdinalIgnoreCase) || path.StartsWith("//")) throw new ImageProcessingException("Image 404 redirects must be server-local. Received " + path);
//2 If it starts with a slash, use as-is
if (path.StartsWith("/", StringComparison.OrdinalIgnoreCase)) return path;
//3 If it starts with a tilde, use as-is.
if (path.StartsWith("~", StringComparison.OrdinalIgnoreCase)) return path;
//3 If it doesn't have a slash or a period, see if it is a attribute of <image404>.
if (new Regex("^[a-zA-Z][a-zA-Z0-9]*$").IsMatch(path)) {
string val = c.get("image404." + path,null);
if (val != null) return val;
}
//4 Otherwise, join with image404.basedir or the application root
string baseDir = c.get("image404.basedir","~/");
path = baseDir.TrimEnd('/') + '/' + path.TrimStart('/');
return path;
}
public bool Uninstall(Configuration.Config c) {
c.Pipeline.ImageMissing -= Pipeline_ImageMissing;
c.Plugins.remove_plugin(this);
return true;
}
public IEnumerable<string> GetSupportedQuerystringKeys() {
return new string[] { "404" };
}
private class MatcherCollection
{
private Matcher[] matchers;
public static MatcherCollection Empty = new MatcherCollection();
public static MatcherCollection Parse(string commandList)
{
if (string.IsNullOrEmpty(commandList))
{
return MatcherCollection.Empty;
}
var commands = commandList.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
var matchers = new Matcher[commands.Length];
for (var i = 0; i < commands.Length; i++)
{
matchers[i] = new Matcher(commands[i]);
}
return new MatcherCollection(matchers);
}
public MatcherCollection(params Matcher[] matchers)
{
this.matchers = matchers;
}
public bool IsMatch(string name, string value)
{
foreach (var matcher in this.matchers)
{
if (matcher.IsMatch(name, value))
{
return true;
}
}
return false;
}
}
private class Matcher
{
public delegate bool NameOnly(string name);
public delegate bool NameAndValue(string name, string value);
private string name;
private NameOnly nameTest;
private NameAndValue nameAndValueTest;
public Matcher(string name)
{
this.name = name;
}
public Matcher(NameOnly nameTest)
{
this.nameTest = nameTest;
}
public Matcher(NameAndValue nameAndValueTest)
{
this.nameAndValueTest = nameAndValueTest;
}
public bool IsMatch(string name, string value)
{
if (this.name != null)
{
return string.Equals(this.name, name, StringComparison.OrdinalIgnoreCase);
}
if (this.nameTest != null)
{
return this.nameTest(name);
}
if (this.nameAndValueTest != null)
{
return this.nameAndValueTest(name, value);
}
return false;
}
}
}
}
| 40.660477 | 199 | 0.549547 | [
"MIT"
] | jiangshide/resizer | Core/Plugins/Basic/Image404.cs | 15,331 | C# |
namespace MeasureUnitManagement.Infrastructure.Query.Models
{
public class FormulatedMeasureUnitResponse
{
public string Symbol { get; set; }
public string Title { get; set; }
public string TitleSlug { get; set; }
public string ConvertFormulaFromBasicUnit { get; set; }
public string ConvertFormulaToBasicUnit { get; set; }
}
}
| 31.75 | 63 | 0.674541 | [
"MIT"
] | MohammadrezaTaghipour/MeasureUnitManagement | Code/Src/MeasureUnitManagement/Infrastructure/Query/Models/FormulatedMeasureUnitResponse.cs | 383 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNative.Network.V20190601
{
/// <summary>
/// ExpressRoute gateway resource.
/// </summary>
[AzureNativeResourceType("azure-native:network/v20190601:ExpressRouteGateway")]
public partial class ExpressRouteGateway : Pulumi.CustomResource
{
/// <summary>
/// Configuration for auto scaling.
/// </summary>
[Output("autoScaleConfiguration")]
public Output<Outputs.ExpressRouteGatewayPropertiesResponseAutoScaleConfiguration?> AutoScaleConfiguration { get; private set; } = null!;
/// <summary>
/// A unique read-only string that changes whenever the resource is updated.
/// </summary>
[Output("etag")]
public Output<string> Etag { get; private set; } = null!;
/// <summary>
/// List of ExpressRoute connections to the ExpressRoute gateway.
/// </summary>
[Output("expressRouteConnections")]
public Output<ImmutableArray<Outputs.ExpressRouteConnectionResponse>> ExpressRouteConnections { get; private set; } = null!;
/// <summary>
/// Resource location.
/// </summary>
[Output("location")]
public Output<string?> Location { get; private set; } = null!;
/// <summary>
/// Resource name.
/// </summary>
[Output("name")]
public Output<string> Name { get; private set; } = null!;
/// <summary>
/// The provisioning state of the resource.
/// </summary>
[Output("provisioningState")]
public Output<string> ProvisioningState { get; private set; } = null!;
/// <summary>
/// Resource tags.
/// </summary>
[Output("tags")]
public Output<ImmutableDictionary<string, string>?> Tags { get; private set; } = null!;
/// <summary>
/// Resource type.
/// </summary>
[Output("type")]
public Output<string> Type { get; private set; } = null!;
/// <summary>
/// The Virtual Hub where the ExpressRoute gateway is or will be deployed.
/// </summary>
[Output("virtualHub")]
public Output<Outputs.VirtualHubIdResponse> VirtualHub { get; private set; } = null!;
/// <summary>
/// Create a ExpressRouteGateway resource with the given unique name, arguments, and options.
/// </summary>
///
/// <param name="name">The unique name of the resource</param>
/// <param name="args">The arguments used to populate this resource's properties</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public ExpressRouteGateway(string name, ExpressRouteGatewayArgs args, CustomResourceOptions? options = null)
: base("azure-native:network/v20190601:ExpressRouteGateway", name, args ?? new ExpressRouteGatewayArgs(), MakeResourceOptions(options, ""))
{
}
private ExpressRouteGateway(string name, Input<string> id, CustomResourceOptions? options = null)
: base("azure-native:network/v20190601:ExpressRouteGateway", name, null, MakeResourceOptions(options, id))
{
}
private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id)
{
var defaultOptions = new CustomResourceOptions
{
Version = Utilities.Version,
Aliases =
{
new Pulumi.Alias { Type = "azure-nextgen:network/v20190601:ExpressRouteGateway"},
new Pulumi.Alias { Type = "azure-native:network:ExpressRouteGateway"},
new Pulumi.Alias { Type = "azure-nextgen:network:ExpressRouteGateway"},
new Pulumi.Alias { Type = "azure-native:network/v20180801:ExpressRouteGateway"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20180801:ExpressRouteGateway"},
new Pulumi.Alias { Type = "azure-native:network/v20181001:ExpressRouteGateway"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20181001:ExpressRouteGateway"},
new Pulumi.Alias { Type = "azure-native:network/v20181101:ExpressRouteGateway"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20181101:ExpressRouteGateway"},
new Pulumi.Alias { Type = "azure-native:network/v20181201:ExpressRouteGateway"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20181201:ExpressRouteGateway"},
new Pulumi.Alias { Type = "azure-native:network/v20190201:ExpressRouteGateway"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20190201:ExpressRouteGateway"},
new Pulumi.Alias { Type = "azure-native:network/v20190401:ExpressRouteGateway"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20190401:ExpressRouteGateway"},
new Pulumi.Alias { Type = "azure-native:network/v20190701:ExpressRouteGateway"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20190701:ExpressRouteGateway"},
new Pulumi.Alias { Type = "azure-native:network/v20190801:ExpressRouteGateway"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20190801:ExpressRouteGateway"},
new Pulumi.Alias { Type = "azure-native:network/v20190901:ExpressRouteGateway"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20190901:ExpressRouteGateway"},
new Pulumi.Alias { Type = "azure-native:network/v20191101:ExpressRouteGateway"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20191101:ExpressRouteGateway"},
new Pulumi.Alias { Type = "azure-native:network/v20191201:ExpressRouteGateway"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20191201:ExpressRouteGateway"},
new Pulumi.Alias { Type = "azure-native:network/v20200301:ExpressRouteGateway"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20200301:ExpressRouteGateway"},
new Pulumi.Alias { Type = "azure-native:network/v20200401:ExpressRouteGateway"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20200401:ExpressRouteGateway"},
new Pulumi.Alias { Type = "azure-native:network/v20200501:ExpressRouteGateway"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20200501:ExpressRouteGateway"},
new Pulumi.Alias { Type = "azure-native:network/v20200601:ExpressRouteGateway"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20200601:ExpressRouteGateway"},
new Pulumi.Alias { Type = "azure-native:network/v20200701:ExpressRouteGateway"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20200701:ExpressRouteGateway"},
new Pulumi.Alias { Type = "azure-native:network/v20200801:ExpressRouteGateway"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20200801:ExpressRouteGateway"},
new Pulumi.Alias { Type = "azure-native:network/v20201101:ExpressRouteGateway"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20201101:ExpressRouteGateway"},
},
};
var merged = CustomResourceOptions.Merge(defaultOptions, options);
// Override the ID if one was specified for consistency with other language SDKs.
merged.Id = id ?? merged.Id;
return merged;
}
/// <summary>
/// Get an existing ExpressRouteGateway resource's state with the given name, ID, and optional extra
/// properties used to qualify the lookup.
/// </summary>
///
/// <param name="name">The unique name of the resulting resource.</param>
/// <param name="id">The unique provider ID of the resource to lookup.</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public static ExpressRouteGateway Get(string name, Input<string> id, CustomResourceOptions? options = null)
{
return new ExpressRouteGateway(name, id, options);
}
}
public sealed class ExpressRouteGatewayArgs : Pulumi.ResourceArgs
{
/// <summary>
/// Configuration for auto scaling.
/// </summary>
[Input("autoScaleConfiguration")]
public Input<Inputs.ExpressRouteGatewayPropertiesAutoScaleConfigurationArgs>? AutoScaleConfiguration { get; set; }
/// <summary>
/// The name of the ExpressRoute gateway.
/// </summary>
[Input("expressRouteGatewayName")]
public Input<string>? ExpressRouteGatewayName { get; set; }
/// <summary>
/// Resource ID.
/// </summary>
[Input("id")]
public Input<string>? Id { get; set; }
/// <summary>
/// Resource location.
/// </summary>
[Input("location")]
public Input<string>? Location { get; set; }
/// <summary>
/// The name of the resource group.
/// </summary>
[Input("resourceGroupName", required: true)]
public Input<string> ResourceGroupName { get; set; } = null!;
[Input("tags")]
private InputMap<string>? _tags;
/// <summary>
/// Resource tags.
/// </summary>
public InputMap<string> Tags
{
get => _tags ?? (_tags = new InputMap<string>());
set => _tags = value;
}
/// <summary>
/// The Virtual Hub where the ExpressRoute gateway is or will be deployed.
/// </summary>
[Input("virtualHub", required: true)]
public Input<Inputs.VirtualHubIdArgs> VirtualHub { get; set; } = null!;
public ExpressRouteGatewayArgs()
{
}
}
}
| 48.943396 | 151 | 0.610833 | [
"Apache-2.0"
] | sebtelko/pulumi-azure-native | sdk/dotnet/Network/V20190601/ExpressRouteGateway.cs | 10,376 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AudioManager : MonoBehaviour
{
public AudioSource audioSource;
public List<AudioClip> songs;
int index;
public bool canPlay;
private void Update() {
if(!audioSource.isPlaying && canPlay){
audioSource.PlayOneShot(songs[index]);
index ++;
if(index == songs.Count){
index = 0;
}
}
}
public void SetVolume(float amount){
audioSource.volume = amount;
AudioDontDestroy.I.source.volume = amount;
}
}
| 22.851852 | 50 | 0.606159 | [
"MIT"
] | Vandermaesenpi/gameoff2020 | Unity Project/Assets/SCRIPT/AudioManager.cs | 619 | C# |
namespace Maquina
{
public enum LogEntryLevel
{
Info,
Warning,
Error
}
}
| 11 | 29 | 0.5 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | FranklinDM/Maquina | src/LogEntryLevel.cs | 112 | C# |
namespace State
{
class Water
{
public IWaterState State { get; set; }
public Water(IWaterState ws)
{
State = ws;
}
public void Heat()
{
State.Heat(this);
}
public void Frost()
{
State.Frost(this);
}
}
}
| 15.227273 | 46 | 0.414925 | [
"MIT"
] | Kropisha/DesignPatterns | State/Water.cs | 337 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace QuanLyKho.Model
{
using QuanLyKho.ViewModel;
using System;
using System.Collections.Generic;
public partial class Unit: BaseViewModel
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Unit()
{
this.Objects = new HashSet<Object>();
}
public int Id { get; set; }
private string _DisplayName;
public string DisplayName { get => _DisplayName; set { _DisplayName = value; OnPropertyChanged(); } }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Object> Objects { get; set; }
}
}
| 37.6875 | 128 | 0.588723 | [
"MIT"
] | TruyenLam/C-WPF | QuanLyKho/QuanLyKho/QuanLyKho/Model/Unit.cs | 1,206 | C# |
using System.Data;
using Accord.Statistics.Analysis;
namespace Webyneter.ComponentsAnalysis.Core.Analysis
{
public interface IAnalysisOptions
{
DataTable InputData { get; }
AnalysisAlgorithm Algorithm { get; }
AnalysisMethod Method { get; }
}
} | 20.285714 | 52 | 0.690141 | [
"MIT"
] | webyneter/Components-Analysis | Core/Analysis/IAnalysisOptions.cs | 286 | C# |
namespace NHS111.Web.Authentication
{
using System;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Web.Mvc;
public class BasicAuthenticationAttribute
: ActionFilterAttribute
{
public string Realm { get; set; }
public BasicAuthenticationAttribute(string username, string password, string realm = "NHS111")
{
Realm = realm;
_username = username;
_password = password;
}
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
// Allow requests even when not authenticated to actions with the AllowAnonymousAccess attribute present. see below.
if (filterContext.ActionDescriptor.GetCustomAttributes(typeof(AllowAnonymousAccess), false).Any())
{
return;
}
var credentials = filterContext.HttpContext.Request.DecodeBasicAuthCredentials();
if (!credentials.Validate(_username, _password))
filterContext.HttpContext.Response.IssueAuthChallenge(Realm);
}
private readonly string _username;
private readonly string _password;
}
internal static class NetworkCredentialsExtensions
{
public static bool Validate(this NetworkCredential credentials, string username, string password)
{
return credentials.UserName == username &&
credentials.Password == password;
}
}
internal static class HttpResponseBaseExtensions
{
public static void IssueAuthChallenge(this HttpResponseBase response, string realm)
{
if (response.HeadersWritten)
return;
response.StatusCode = 401;
response.AddHeader("WWW-Authenticate", string.Format("Basic realm=\"{0}\"", realm));
response.End();
}
}
internal static class HttpRequestBaseExtensions
{
public static NetworkCredential DecodeBasicAuthCredentials(this HttpRequestBase request)
{
var authHeader = request.Headers["Authorization"];
if (string.IsNullOrEmpty(authHeader))
return new NetworkCredential();
try
{
var encodedCredentials = authHeader.Replace("Basic ", "");
var bytes = Convert.FromBase64String(encodedCredentials);
var decodedAuthHeader = Encoding.ASCII.GetString(bytes);
var credentials = decodedAuthHeader.Split(':');
return new NetworkCredential(credentials[0], credentials[1]);
}
catch (Exception e)
{
throw new FormatException("The provided basic auth header was not in the expected format", e);
}
}
}
/// <summary>
// Attribute to mark a controller as accessible regarding of authentication requirement
// Source: https://stackoverflow.com/a/9963113/1537195
/// </summary>
public class AllowAnonymousAccess : Attribute
{
}
}
| 31.686869 | 128 | 0.620657 | [
"Apache-2.0"
] | 111Online/web-stack | NHS111/NHS111.Web/Authentication/BasicAuthenticationModule.cs | 3,139 | C# |
namespace Entity
{
public class Users
{
#region "Consteractor"
public Users()
{ }
public Users(string _User, string _Pass)
{
User = _User;
Pass = _Pass;
}
#endregion
#region "Property"
public string User { get; set; }
public string Pass { get; set; }
#endregion
}
}
| 17.863636 | 48 | 0.475827 | [
"MIT"
] | Sabermotamedi/DentistCRUD | Entity/Users.cs | 395 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Peg.Samples;
using Peg.Base;
using System.IO;
using System.Diagnostics;
namespace BERTree
{
class BERConvertDefiniteLength : IParserPostProcessor
{
#region Data members
TreeContext context_;
Dictionary<PegNode, uint> dictLength= new Dictionary<PegNode,uint>();
byte[] lengthBuffer = new byte[5];
#endregion Data members
#region Helper classes
class TreeContext
{
internal PegNode root_;
internal byte[] byteSrc_;
internal TextWriter errOut_;
internal ParserPostProcessParams generatorParams_;
internal string sErrorPrefix;
internal TreeContext(ParserPostProcessParams generatorParams)
{
generatorParams_ = generatorParams;
root_ = generatorParams.root_;
byteSrc_ = generatorParams.byteSrc_;
errOut_ = generatorParams.errOut_;
sErrorPrefix = "<BER_DEFINITE_CONVERTER> FILE:'" + generatorParams_.grammarFileName_ + "' ";
}
}
#endregion Helper classes
#region IParserPostProcessor Members
string IParserPostProcessor.ShortDesc
{
get { return "-> Definite Length Form"; }
}
string IParserPostProcessor.ShortestDesc
{
get { return "Definite"; }
}
string IParserPostProcessor.DetailDesc
{
get
{
return "Convert to definite length form (usally smaller files)";
}
}
void IParserPostProcessor.Postprocess(ParserPostProcessParams postProcessorParams)
{
context_ = new TreeContext(postProcessorParams);
string outDir =PUtils.MakeFileName("", context_.generatorParams_.outputDirectory_, "DefiniteLengthForm");
if (!Directory.Exists(outDir))
{
Directory.CreateDirectory(outDir);
}
string outFile= PUtils.MakeFileName(context_.generatorParams_.sourceFileTitle_,outDir);
using (BinaryWriter rw = new BinaryWriter(File.Open(outFile, FileMode.Create)))
{
WriteDefinite(rw, context_.generatorParams_.root_);
context_.generatorParams_.errOut_.WriteLine("INFO from <BER_DEFINITE_ENCODER> {0} bytes written to '{1}'",
rw.BaseStream.Position,outFile);
}
}
#endregion IParserPostProcessor Members
#region WriteDefinite method and helpers
private void WriteDefinite(BinaryWriter rw, PegNode pegNode)
{
PegNode child;
if (pegNode == null) return;
WriteTag(rw, pegNode);
WriteLength(rw, pegNode);
if (IsComposite(pegNode, out child))
{
WriteDefinite(rw, child);
}
else
{
Debug.Assert(pegNode.child_ != null && pegNode.child_.next_ != null && pegNode.child_.next_.next_ != null);
WriteContent(rw, pegNode.child_.next_.next_);
}
WriteDefinite(rw, pegNode.next_);
}
private bool IsComposite(PegNode pegNode,out PegNode child)
{
Debug.Assert(pegNode.child_ != null && pegNode.child_.next_ != null && pegNode.child_.next_.next_!=null);
child = pegNode.child_.next_.next_;
bool bIsComposite= child.id_ == (int)EBERTree.ConstructedDelimValue ||
child.id_ == (int)EBERTree.ConstructedValue;
if (bIsComposite) child = child.child_;
return bIsComposite;
}
private void WriteTag(BinaryWriter rw, PegNode pegNode)
{
Debug.Assert(pegNode.child_ != null);
PegNode tagNode = pegNode.child_;
Debug.Assert(tagNode.id_== (int)EBERTree.OneOctetTag || tagNode.id_==(int)EBERTree.MultiOctetTag);
rw.Write(context_.byteSrc_, tagNode.match_.posBeg_, tagNode.match_.posEnd_ - tagNode.match_.posBeg_);
}
private void WriteLength(BinaryWriter rw, PegNode pegNode)
{
Debug.Assert(pegNode.child_ != null && pegNode.child_.next_ != null);
PegNode lengthNode = pegNode.child_.next_;
uint length = GetLength(lengthNode.next_);
int bytesToWrite= GetLengthEncodingLength(length);
if (bytesToWrite == 1)
{
lengthBuffer[0] = (byte)length;
}
else
{
lengthBuffer[0] = (byte)((bytesToWrite - 1) | 0x80);
int j=1;
for (int i = bytesToWrite - 1; i>0; i--)
{
byte @byte = (byte)((length & (0xFF << 8 * (i - 1) )) >> 8 * (i - 1));
lengthBuffer[j++] = @byte;
}
}
rw.Write(lengthBuffer, 0,bytesToWrite);
}
private uint GetLength(PegNode pegNode)
{
if (dictLength.ContainsKey(pegNode)) return dictLength[pegNode];
if (pegNode.id_ == (int)EBERTree.ConstructedDelimValue ||
pegNode.id_ == (int)EBERTree.ConstructedValue)
{
uint length = 0;
for (PegNode child = pegNode.child_; child != null; child = child.next_)
{
length += GetLength(child);
}
dictLength.Add(pegNode, length);
return length;
}
else if (pegNode.id_ == (int)EBERTree.PrimitiveValue)
{
uint length= (uint)(pegNode.match_.posEnd_ - pegNode.match_.posBeg_);
dictLength.Add(pegNode, length);
return length;
}
else if (pegNode.id_ == (int)EBERTree.TLV)
{
Debug.Assert(pegNode.child_ != null && pegNode.child_.next_ != null);
PegNode tag = pegNode.child_, content = tag.next_.next_;
uint length= (uint)(pegNode.child_.match_.posEnd_ - pegNode.child_.match_.posBeg_)
+ (uint)GetLengthEncodingLength(GetLength(content))
+ GetLength(content);
dictLength.Add(pegNode, length);
return length;
}
else
{
Debug.Assert(false);
return 0;
}
}
private int GetLengthEncodingLength(uint length)
{
if (length < 127) return 1;
else
{
if ((length & 0xFF000000) != 0) return 5;
else if ((length & 0xFFFF0000) != 0) return 4;
else if ((length & 0xFFFFFF00) != 0) return 3;
else return 2;
}
}
private void WriteContent(BinaryWriter rw, PegNode pegNode)
{
Debug.Assert(pegNode.id_ == (int)EBERTree.PrimitiveValue);
rw.Write(context_.byteSrc_, pegNode.match_.posBeg_, pegNode.match_.posEnd_ - pegNode.match_.posBeg_);
}
#endregion WriteDefinite method and helpers
}
class BERConvertIndefiniteLength : IParserPostProcessor
{
#region Data members
TreeContext context_;
Dictionary<PegNode, uint> dictLength = new Dictionary<PegNode, uint>();
byte[] lengthBuffer = new byte[5];
#endregion Data members
#region Helper classes
class TreeContext
{
internal PegNode root_;
internal byte[] byteSrc_;
internal TextWriter errOut_;
internal ParserPostProcessParams generatorParams_;
internal string sErrorPrefix;
internal TreeContext(ParserPostProcessParams generatorParams)
{
generatorParams_ = generatorParams;
root_ = generatorParams.root_;
byteSrc_ = generatorParams.byteSrc_;
errOut_ = generatorParams.errOut_;
sErrorPrefix = "<BER_INDEFINITE_CONVERTER> FILE:'" + generatorParams_.grammarFileName_ + "' ";
}
}
#endregion Helper classes
#region IParserPostProcessor Members
string IParserPostProcessor.ShortDesc
{
get { return "-> Indefinite Length Form"; }
}
string IParserPostProcessor.ShortestDesc
{
get { return "Indefinite"; }
}
string IParserPostProcessor.DetailDesc
{
get
{
return "Convert to indefinite length form (usally bigger files)";
}
}
void IParserPostProcessor.Postprocess(ParserPostProcessParams postProcessorParams)
{
context_ = new TreeContext(postProcessorParams);
string outDir = PUtils.MakeFileName("", context_.generatorParams_.outputDirectory_, "IndefiniteLengthForm");
if (!Directory.Exists(outDir))
{
Directory.CreateDirectory(outDir);
}
string outFile = PUtils.MakeFileName(context_.generatorParams_.sourceFileTitle_, outDir);
using (BinaryWriter rw = new BinaryWriter(File.Open(outFile, FileMode.Create)))
{
WriteInDefinite(rw, context_.generatorParams_.root_);
context_.generatorParams_.errOut_.WriteLine("INFO from <BER_INDEFINITE_ENCODER> {0} bytes written to '{1}'",
rw.BaseStream.Position, outFile);
}
}
#endregion IParserPostProcessor Members
#region WriteDefinite method and helpers
private void WriteInDefinite(BinaryWriter rw, PegNode pegNode)
{
PegNode child;
if (pegNode == null) return;
bool bIsComposite = IsComposite(pegNode, out child);
WriteTag(rw, pegNode);
WriteLength(rw, pegNode,bIsComposite);
if (bIsComposite)
{
for(;child!=null;child= child.next_)
{
WriteInDefinite(rw, child);
}
rw.Write((ushort)0x0000);
}
else
{
Debug.Assert(pegNode.child_ != null && pegNode.child_.next_ != null && pegNode.child_.next_.next_ != null);
WriteContent(rw, pegNode.child_.next_.next_);
}
}
private bool IsComposite(PegNode pegNode, out PegNode child)
{
Debug.Assert(pegNode.child_ != null && pegNode.child_.next_ != null && pegNode.child_.next_.next_ != null);
child = pegNode.child_.next_.next_;
bool bIsComposite = child.id_ == (int)EBERTree.ConstructedDelimValue ||
child.id_ == (int)EBERTree.ConstructedValue;
if (bIsComposite) child = child.child_;
return bIsComposite;
}
private void WriteTag(BinaryWriter rw, PegNode pegNode)
{
Debug.Assert(pegNode.child_ != null);
PegNode tagNode = pegNode.child_;
Debug.Assert(tagNode.id_ == (int)EBERTree.OneOctetTag || tagNode.id_ == (int)EBERTree.MultiOctetTag);
rw.Write(context_.byteSrc_, tagNode.match_.posBeg_, tagNode.match_.posEnd_ - tagNode.match_.posBeg_);
}
private void WriteLength(BinaryWriter rw, PegNode pegNode,bool bIsComposite)
{
Debug.Assert(pegNode.child_ != null && pegNode.child_.next_ != null);
if (bIsComposite)
{
rw.Write((byte)0x80);
}
else {
PegNode lengthNode = pegNode.child_.next_;
uint length = GetLength(lengthNode.next_);
int bytesToWrite = GetLengthEncodingLength(length);
if (bytesToWrite == 1)
{
lengthBuffer[0] = (byte)length;
}
else
{
lengthBuffer[0] = (byte)((bytesToWrite - 1) | 0x80);
int j = 1;
for (int i = bytesToWrite - 1; i > 0; i--)
{
byte @byte = (byte)((length & (0xFF << 8 * (i - 1))) >> 8 * (i - 1));
lengthBuffer[j++] = @byte;
}
}
rw.Write(lengthBuffer, 0, bytesToWrite);
}
}
private uint GetLength(PegNode pegNode)
{
uint length = (uint)(pegNode.match_.posEnd_ - pegNode.match_.posBeg_);
return length;
}
private int GetLengthEncodingLength(uint length)
{
if (length < 127) return 1;
else
{
if ((length & 0xFF000000) != 0) return 5;
else if ((length & 0xFFFF0000) != 0) return 4;
else if ((length & 0xFFFFFF00) != 0) return 3;
else return 2;
}
}
private void WriteContent(BinaryWriter rw, PegNode pegNode)
{
Debug.Assert(pegNode.id_ == (int)EBERTree.PrimitiveValue);
rw.Write(context_.byteSrc_, pegNode.match_.posBeg_, pegNode.match_.posEnd_ - pegNode.match_.posBeg_);
}
#endregion WriteDefinite method and helpers
}
}
| 38.231638 | 125 | 0.544702 | [
"Apache-2.0"
] | JamieDixon/dotless | lib/PEG_GrammarExplorer/PEG_GrammarExplorer/PegSamples/BasicEncodingRules/BERConvert.cs | 13,536 | C# |
using Confluent.Kafka;
namespace Coretech9.Kafkas;
/// <summary>
/// Context for each consume operation
/// </summary>
/// <typeparam name="TMessage">Type of the consuming message</typeparam>
public class ConsumeContext<TMessage>
{
/// <summary>
/// Consuming message
/// </summary>
public TMessage Message { get; }
/// <summary>
/// Topic and partition information of the message
/// </summary>
public TopicPartition Partition { get; }
/// <summary>
/// Offset information for the message
/// </summary>
public TopicPartitionOffset Offset { get; }
/// <summary>
/// Message total retry count
/// </summary>
public int RetryCount { get; set; }
/// <summary>
/// Creates new consume context
/// </summary>
/// <param name="message">Consuming message</param>
/// <param name="partition">Topic and partition information of the message</param>
/// <param name="offset">Offset information for the message</param>
/// <param name="retryCount">Message total retry count</param>
public ConsumeContext(TMessage message, TopicPartition partition, TopicPartitionOffset offset, int retryCount)
{
Message = message;
Partition = partition;
Offset = offset;
RetryCount = retryCount;
}
} | 29.466667 | 114 | 0.641026 | [
"Apache-2.0"
] | coretech9/kafkas | Coretech9.Kafkas/ConsumeContext.cs | 1,328 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Telerik.Charting;
using Telerik.Core;
using Telerik.UI.Xaml.Controls.Chart;
using Telerik.UI.Xaml.Controls.Chart.Primitives;
using Windows.Devices.Input;
using Windows.Foundation;
using Windows.UI;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Shapes;
namespace Telerik.UI.Xaml.Controls.Chart
{
/// <summary>
/// Represents a behavior that adds two lines in <see cref="RadChartBase"/>'s render surface. The two lines intersect at the center of the closest data point found.
/// </summary>
public class ChartTrackBallBehavior : ChartBehavior
{
/// <summary>
/// Identifies the <see cref="LineStyle"/> property.
/// </summary>
public static readonly DependencyProperty LineStyleProperty =
DependencyProperty.Register(nameof(LineStyle), typeof(Style), typeof(ChartTrackBallBehavior), new PropertyMetadata(null, OnLineStylePropertyChanged));
/// <summary>
/// Identifies the <see cref="InfoStyle"/> property.
/// </summary>
public static readonly DependencyProperty InfoStyleProperty =
DependencyProperty.Register(nameof(InfoStyle), typeof(Style), typeof(ChartTrackBallBehavior), null);
/// <summary>
/// Identifies the <see cref="IntersectionTemplateProperty"/> dependency property.
/// </summary>
public static readonly DependencyProperty IntersectionTemplateProperty =
DependencyProperty.RegisterAttached("IntersectionTemplate", typeof(DataTemplate), typeof(ChartTrackBallBehavior), new PropertyMetadata(null));
/// <summary>
/// Identifies the <see cref="TrackInfoTemplateProperty"/> dependency property.
/// </summary>
public static readonly DependencyProperty TrackInfoTemplateProperty =
DependencyProperty.RegisterAttached("TrackInfoTemplate", typeof(DataTemplate), typeof(ChartTrackBallBehavior), new PropertyMetadata(null));
internal List<ContentPresenter> individualTrackInfos;
private static readonly Style DefaultLineStyle;
private TrackBallLineControl lineControl;
private TrackBallSnapMode snapMode;
private bool showInfo = true;
private bool showIntersectionPoints;
private bool visualsDisplayed;
private Point position;
private TrackInfoMode infoMode = TrackInfoMode.Individual;
private TrackBallInfoControl trackInfoControl;
private List<ContentPresenter> intersectionPoints;
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline", Justification = "The static DefaultLineStyle field requires additional initialization.")]
static ChartTrackBallBehavior()
{
DefaultLineStyle = new Style(typeof(Polyline));
DefaultLineStyle.Setters.Add(new Setter(Polyline.StrokeThicknessProperty, 2));
DefaultLineStyle.Setters.Add(new Setter(Polyline.StrokeProperty, new SolidColorBrush(Colors.Gray)));
}
/// <summary>
/// Initializes a new instance of the <see cref="ChartTrackBallBehavior"/> class.
/// </summary>
public ChartTrackBallBehavior()
{
this.lineControl = new TrackBallLineControl();
this.snapMode = TrackBallSnapMode.ClosestPoint;
this.trackInfoControl = new TrackBallInfoControl(this);
this.intersectionPoints = new List<ContentPresenter>(4);
this.individualTrackInfos = new List<ContentPresenter>(4);
}
/// <summary>
/// Occurs when a track info is updated, just before the UI that represents it is updated.
/// Allows custom information to be displayed.
/// </summary>
public event EventHandler<TrackBallInfoEventArgs> TrackInfoUpdated;
/// <summary>
/// Gets or sets the <see cref="Style"/> that defines the appearance of the line displayed by a <see cref="ChartTrackBallBehavior"/> instance.
/// The style should target the <see cref="Windows.UI.Xaml.Shapes.Polyline"/> type.
/// </summary>
public Style LineStyle
{
get
{
return this.GetValue(LineStyleProperty) as Style;
}
set
{
this.SetValue(LineStyleProperty, value);
}
}
/// <summary>
/// Gets or sets the <see cref="Style"/> that defines the appearance of the TrackInfo control displayed by a <see cref="ChartTrackBallBehavior"/> instance.
/// The style should target the <see cref="Telerik.UI.Xaml.Controls.Chart.Primitives.TrackBallInfoControl"/> type.
/// </summary>
public Style InfoStyle
{
get
{
return this.GetValue(InfoStyleProperty) as Style;
}
set
{
this.SetValue(InfoStyleProperty, value);
}
}
/// <summary>
/// Gets or sets a value indicating whether a visual information for all the closest data points will be displayed.
/// </summary>
public bool ShowInfo
{
get
{
return this.showInfo;
}
set
{
this.showInfo = value;
}
}
/// <summary>
/// Gets or sets a value indicating whether a visual representation for all the intersection points will be displayed.
/// </summary>
public bool ShowIntersectionPoints
{
get
{
return this.showIntersectionPoints;
}
set
{
this.showIntersectionPoints = value;
}
}
/// <summary>
/// Gets or sets the how this behavior should snap to the closest to a physical location data points.
/// </summary>
public TrackBallSnapMode SnapMode
{
get
{
return this.snapMode;
}
set
{
this.snapMode = value;
}
}
/// <summary>
/// Gets or sets a value indicating the track information displayed by the behavior.
/// </summary>
public TrackInfoMode InfoMode
{
get
{
return this.infoMode;
}
set
{
this.infoMode = value;
}
}
/// <summary>
/// Gets the control used to display Polyline shape that renders the trackball line. Exposed for testing purposes.
/// </summary>
internal TrackBallLineControl LineControl
{
get
{
return this.lineControl;
}
}
/// <summary>
/// Gets the control used to display the track information. Exposed for testing purposes.
/// </summary>
internal TrackBallInfoControl InfoControl
{
get
{
return this.trackInfoControl;
}
}
/// <summary>
/// Gets the list with all the content presenters used to visualize intersection points. Exposed for testing purposes.
/// </summary>
internal List<ContentPresenter> IntersectionPoints
{
get
{
return this.intersectionPoints;
}
}
/// <summary>
/// Gets the position of the track ball. Exposed for testing purposes.
/// </summary>
internal Point Position
{
get
{
return this.position;
}
}
internal override ManipulationModes DesiredManipulationMode
{
get
{
return ManipulationModes.TranslateX | ManipulationModes.TranslateY;
}
}
/// <summary>
/// Gets the <see cref="DataTemplate"/> instance for the specified object instance.
/// </summary>
/// <remarks>
/// This template is used to highlight the intersection point of each <see cref="ChartSeries"/> instance with the trackball line.
/// </remarks>
public static DataTemplate GetIntersectionTemplate(DependencyObject instance)
{
if (instance == null)
{
throw new ArgumentNullException();
}
return instance.GetValue(IntersectionTemplateProperty) as DataTemplate;
}
/// <summary>
/// Sets the <see cref="DataTemplate"/> instance for the specified object instance.
/// </summary>
/// <remarks>
/// This template is used to highlight the intersection point of each <see cref="ChartSeries"/> instance with the trackball line.
/// </remarks>
/// <param name="instance">The object instance to apply the template to.</param>
/// <param name="value">The specified <see cref="DataTemplate"/> instance.</param>
public static void SetIntersectionTemplate(DependencyObject instance, DataTemplate value)
{
if (instance == null)
{
throw new ArgumentNullException();
}
instance.SetValue(IntersectionTemplateProperty, value);
}
/// <summary>
/// Gets the <see cref="DataTemplate"/> instance for the provided object instance.
/// </summary>
/// <remarks>
/// This template defines the appearance of the information for the currently hit data point of each <see cref="ChartSeries"/>.
/// </remarks>
public static DataTemplate GetTrackInfoTemplate(DependencyObject instance)
{
if (instance == null)
{
throw new ArgumentNullException(nameof(instance));
}
return instance.GetValue(TrackInfoTemplateProperty) as DataTemplate;
}
/// <summary>
/// Gets the specified <see cref="DataTemplate"/> instance to the provided object instance.
/// </summary>
/// <remarks>
/// This template defines the appearance of the information for the currently hit data point of each <see cref="ChartSeries"/>.
/// </remarks>
public static void SetTrackInfoTemplate(DependencyObject instance, DataTemplate value)
{
if (instance == null)
{
throw new ArgumentNullException();
}
instance.SetValue(TrackInfoTemplateProperty, value);
}
/// <summary>
/// Exposed for testing purposes.
/// </summary>
internal void HandleDrag(Point currentPosition)
{
if (currentPosition.X > this.chart.PlotAreaDecorationSlot.X
&& currentPosition.X < (this.chart.PlotAreaDecorationSlot.X + this.chart.PlotAreaDecorationSlot.Width))
{
this.position = currentPosition;
if (!this.visualsDisplayed)
{
this.PrepareVisuals();
}
this.UpdateVisuals();
}
}
/// <summary>
/// Handles the <see cref="E:RadChartBase.PointerEntered"/> event of the owning <see cref="RadChartBase"/> instance.
/// </summary>
protected internal override void OnPointerEntered(PointerRoutedEventArgs args)
{
base.OnPointerEntered(args);
if (args == null)
{
throw new ArgumentNullException(nameof(args));
}
this.HandleDrag(args.GetCurrentPoint(this.chart).Position);
args.Handled = true;
}
/// <summary>
/// Handles the <see cref="E:RadChartBase.PointerMoved"/> event of the owning <see cref="RadChartBase"/> instance.
/// </summary>
protected internal override void OnPointerMoved(PointerRoutedEventArgs args)
{
base.OnPointerMoved(args);
if (args == null)
{
throw new ArgumentNullException(nameof(args));
}
if (args.Pointer.IsInContact)
{
return;
}
this.HandleDrag(args.GetCurrentPoint(this.chart).Position);
args.Handled = true;
}
/// <summary>
/// Handles the <see cref="E:RadChartBase.PointerPressed"/> event of the owning <see cref="RadChartBase"/> instance.
/// </summary>
protected internal override void OnPointerPressed(PointerRoutedEventArgs args)
{
base.OnPointerPressed(args);
if (args == null)
{
throw new ArgumentNullException(nameof(args));
}
if (args.Pointer.PointerDeviceType != PointerDeviceType.Touch)
{
this.EndTrack();
}
}
/// <summary>
/// Handles the <see cref="E:RadChartBase.PointerExited"/> event of the owning <see cref="RadChartBase"/> instance.
/// </summary>
protected internal override void OnPointerExited(PointerRoutedEventArgs args)
{
base.OnPointerExited(args);
this.EndTrack();
}
/// <summary>
/// Handles the <see cref="E:RadChartBase.HoldCompleted"/> event of the owning <see cref="RadChartBase"/> instance.
/// </summary>
protected internal override void OnHoldCompleted(HoldingRoutedEventArgs args)
{
base.OnHoldCompleted(args);
this.EndTrack();
}
/// <summary>
/// Handles the <see cref="E:RadChartBase.PointerReleased"/> event of the owning <see cref="RadChartBase"/> instance.
/// </summary>
protected internal override void OnPointerReleased(PointerRoutedEventArgs args)
{
base.OnPointerReleased(args);
if (args == null)
{
throw new ArgumentNullException(nameof(args));
}
this.EndTrack();
}
/// <summary>
/// Handles the <see cref="E:RadChartBase.HoldStarted"/> event of the owning <see cref="RadChartBase"/> instance.
/// </summary>
protected internal override void OnHoldStarted(HoldingRoutedEventArgs args)
{
base.OnHoldStarted(args);
if (args == null)
{
throw new ArgumentNullException(nameof(args));
}
this.HandleDrag(args.GetPosition(this.chart));
args.Handled = true;
}
/// <summary>
/// Handles the <see cref="E:RadChartBase.ManipulationDelta"/> event of the owning <see cref="RadChartBase"/> instance.
/// </summary>
protected internal override void OnManipulationDelta(ManipulationDeltaRoutedEventArgs args)
{
base.OnManipulationDelta(args);
if (args == null)
{
throw new ArgumentNullException(nameof(args));
}
if (!this.chart.isInHold || args.IsInertial)
{
return;
}
this.HandleDrag(args.Position);
args.Handled = true;
}
/// <summary>
/// A callback from the owning <see cref="RadChartBase"/> instance that notifies for a completed UpdateUI pass.
/// </summary>
protected internal override void OnChartUIUpdated()
{
base.OnChartUIUpdated();
if (this.visualsDisplayed)
{
this.UpdateVisuals();
}
}
/// <summary>
/// This method is called when this behavior is removed from the chart.
/// </summary>
protected override void OnDetached()
{
base.OnDetached();
this.chart.adornerLayer.LayoutUpdated -= this.OnAdornerLayerLayoutUpdated;
if (this.chart.adornerLayer.Children.Contains(this.lineControl))
{
this.chart.adornerLayer.Children.Remove(this.lineControl);
}
if (this.chart.adornerLayer.Children.Contains(this.trackInfoControl))
{
this.chart.adornerLayer.Children.Remove(this.trackInfoControl);
}
foreach (ContentPresenter presenter in this.intersectionPoints)
{
this.chart.adornerLayer.Children.Remove(presenter);
}
}
private static void OnLineStylePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
ChartTrackBallBehavior behavior = d as ChartTrackBallBehavior;
behavior.lineControl.LineStyle = e.NewValue as Style;
}
private void HideVisuals()
{
this.visualsDisplayed = false;
this.lineControl.Visibility = Visibility.Collapsed;
this.lineControl.Line.Points.Clear();
this.trackInfoControl.Visibility = Visibility.Collapsed;
foreach (ContentPresenter presenter in this.intersectionPoints)
{
presenter.Visibility = Visibility.Collapsed;
}
foreach (ContentPresenter presenter in this.individualTrackInfos)
{
presenter.Visibility = Visibility.Collapsed;
}
}
private void PrepareVisuals()
{
this.visualsDisplayed = true;
this.lineControl.Visibility = Visibility.Visible;
if (!this.chart.adornerLayer.Children.Contains(this.lineControl))
{
this.chart.adornerLayer.Children.Add(this.lineControl);
}
if (!this.showInfo)
{
return;
}
this.AdornerLayer.LayoutUpdated += this.OnAdornerLayerLayoutUpdated;
if (this.infoMode == TrackInfoMode.Individual)
{
return;
}
Style style = this.InfoStyle;
if (style != null)
{
this.trackInfoControl.Style = style;
}
if (!this.chart.adornerLayer.Children.Contains(this.trackInfoControl))
{
this.chart.adornerLayer.Children.Add(this.trackInfoControl);
this.trackInfoControl.SetValue(Canvas.ZIndexProperty, this.trackInfoControl.DefaultZIndex);
}
this.trackInfoControl.Visibility = Visibility.Visible;
}
private void UpdateVisuals()
{
ChartDataContext context = this.GetDataContext(this.position, true);
if (context.ClosestDataPoint != null)
{
var point = context.ClosestDataPoint.DataPoint as CategoricalDataPoint;
if (point != null)
{
List<DataPointInfo> points = null;
if (point.Category == null)
{
points = context.DataPoints.Where(c => c.DataPoint is CategoricalDataPoint &&
((CategoricalDataPoint)c.DataPoint).Category == null).ToList();
}
else
{
// select points only with the same category. TODO: Refactor this.
points = context.DataPoints.Where(c =>
c.DataPoint is CategoricalDataPoint &&
point.Category.Equals(((CategoricalDataPoint)c.DataPoint).Category)).ToList();
}
context = new ChartDataContext(points, context.ClosestDataPoint);
}
}
if (context.ClosestDataPoint != null
&& context.ClosestDataPoint.DataPoint.LayoutSlot.X > this.chart.PlotAreaClip.X
&& context.ClosestDataPoint.DataPoint.LayoutSlot.X < (this.chart.PlotAreaClip.X + this.chart.PlotAreaClip.Width))
{
this.UpdateLine(context);
this.UpdateIntersectionPoints(context);
this.UpdateTrackInfo(context);
}
else
{
this.HideVisuals();
}
}
private void UpdateTrackInfo(ChartDataContext context)
{
if (!this.showInfo)
{
return;
}
// arrange the track content
if (this.lineControl.Line.Points.Count == 0)
{
Debug.Assert(false, "Must have line points initialized.");
return;
}
TrackBallInfoEventArgs args = new TrackBallInfoEventArgs(context);
if (this.TrackInfoUpdated != null)
{
this.TrackInfoUpdated(this, args);
}
if (this.infoMode == TrackInfoMode.Multiple)
{
this.trackInfoControl.Update(args);
}
else
{
this.BuildIndividualTrackInfos(context);
}
}
private void UpdateLine(ChartDataContext context)
{
this.lineControl.Line.Points.Clear();
Point plotOrigin = this.chart.PlotOrigin;
if (this.snapMode == TrackBallSnapMode.AllClosePoints)
{
Point[] points = new Point[context.DataPoints.Count];
int index = 0;
foreach (DataPointInfo info in context.DataPoints)
{
Point center = info.DataPoint.Center();
center.X += plotOrigin.X;
center.Y += plotOrigin.Y;
points[index++] = center;
}
Array.Sort(points, new PointYComparer());
foreach (Point point in points)
{
this.lineControl.Line.Points.Add(point);
}
}
else if (this.snapMode == TrackBallSnapMode.ClosestPoint && context.ClosestDataPoint != null)
{
Point center = context.ClosestDataPoint.DataPoint.Center();
center.X += plotOrigin.X;
center.Y += plotOrigin.Y;
// Temporary fix for NAN values. Remove when the chart starts to support null values.
if (double.IsNaN(center.X))
{
center.X = 0;
}
if (double.IsNaN(center.Y))
{
center.Y = this.chart.chartArea.plotArea.layoutSlot.Bottom;
}
this.lineControl.Line.Points.Add(center);
}
RadRect plotArea = this.chart.chartArea.plotArea.layoutSlot;
Point topPoint;
Point bottomPoint;
if (this.lineControl.Line.Points.Count > 0)
{
topPoint = new Point(this.lineControl.Line.Points[0].X, plotArea.Y);
bottomPoint = new Point(this.lineControl.Line.Points[this.lineControl.Line.Points.Count - 1].X, plotArea.Bottom);
}
else
{
topPoint = new Point(this.position.X, plotArea.Y);
bottomPoint = new Point(this.position.X, plotArea.Bottom);
}
this.lineControl.Line.Points.Insert(0, topPoint);
this.lineControl.Line.Points.Insert(this.lineControl.Line.Points.Count, bottomPoint);
}
private void UpdateIntersectionPoints(ChartDataContext context)
{
if (!this.showIntersectionPoints)
{
return;
}
int index = 0;
Point plotOrigin = this.chart.PlotOrigin;
foreach (ContentPresenter presenter in this.intersectionPoints)
{
presenter.Visibility = Visibility.Collapsed;
}
foreach (DataPointInfo info in context.DataPoints)
{
DataTemplate template = GetIntersectionTemplate(info.Series);
if (template == null)
{
continue;
}
ContentPresenter presenter = this.GetIntersectionPointPresenter(index);
presenter.Visibility = Visibility.Visible;
presenter.Content = info;
presenter.ContentTemplate = template;
presenter.Measure(RadChartBase.InfinitySize);
Point center = info.DataPoint.Center();
Size desiredSize = presenter.DesiredSize;
Canvas.SetLeft(presenter, center.X - Math.Abs(plotOrigin.X) - (desiredSize.Width / 2));
Canvas.SetTop(presenter, center.Y - Math.Abs(plotOrigin.Y) - (desiredSize.Height / 2));
index++;
}
}
private ContentPresenter GetIntersectionPointPresenter(int index)
{
if (index < this.intersectionPoints.Count)
{
return this.intersectionPoints[index];
}
ContentPresenter visual = new ContentPresenter();
this.chart.adornerLayer.Children.Add(visual);
this.intersectionPoints.Add(visual);
return visual;
}
private void OnAdornerLayerLayoutUpdated(object sender, object args)
{
if (this.lineControl.Line.Points.Count == 0)
{
return;
}
if (this.infoMode == TrackInfoMode.Multiple)
{
// fit the info control into the plot area
RadRect plotArea = this.chart.chartArea.plotArea.layoutSlot;
Point topPoint = new Point(this.lineControl.Line.Points[0].X, plotArea.Y);
double left = topPoint.X - (int)(this.trackInfoControl.ActualWidth / 2);
left = Math.Min(left, this.chart.ActualWidth - this.trackInfoControl.ActualWidth);
left = Math.Max(0, left);
Canvas.SetLeft(this.trackInfoControl, left);
Canvas.SetTop(this.trackInfoControl, topPoint.Y);
// update the top line point to reach the bottom edge of the track info
topPoint.Y += this.trackInfoControl.ActualHeight;
this.lineControl.Line.Points[0] = topPoint;
}
else
{
this.ArrangeIndividualTrackInfos();
}
}
private void BuildIndividualTrackInfos(ChartDataContext context)
{
int index = 0;
List<DataPointInfo> infos = new List<DataPointInfo>(context.DataPoints);
infos.Sort(new DataPointInfoYComparer());
foreach (DataPointInfo info in infos)
{
ContentPresenter presenter;
if (this.individualTrackInfos.Count > index)
{
presenter = this.individualTrackInfos[index];
presenter.Visibility = Visibility.Visible;
}
else
{
presenter = new ContentPresenter();
this.individualTrackInfos.Add(presenter);
this.chart.adornerLayer.Children.Add(presenter);
}
presenter.Content = info;
presenter.ContentTemplate = GetTrackInfoTemplate(info.Series);
index++;
}
while (index < this.individualTrackInfos.Count)
{
this.individualTrackInfos[index].Visibility = Visibility.Collapsed;
index++;
}
}
private void ArrangeIndividualTrackInfos()
{
int index = 0;
Point plotOrigin = this.chart.PlotOrigin;
foreach (ContentPresenter presenter in this.individualTrackInfos)
{
if (presenter.Visibility == Visibility.Collapsed)
{
continue;
}
DataPointInfo info = presenter.Content as DataPointInfo;
RadRect layoutSlot = info.DataPoint.layoutSlot;
Size size = presenter.DesiredSize;
HorizontalAlignment horizontalAlign = index % 2 == 0 ? HorizontalAlignment.Left : HorizontalAlignment.Right;
double x = 0;
switch (horizontalAlign)
{
case HorizontalAlignment.Left:
x = layoutSlot.X - size.Width;
break;
case HorizontalAlignment.Center:
x = layoutSlot.Center.X - size.Width / 2;
break;
case HorizontalAlignment.Right:
x = layoutSlot.Right;
break;
}
double y = layoutSlot.Center.Y - size.Height / 2;
Canvas.SetLeft(presenter, x + plotOrigin.X);
Canvas.SetTop(presenter, y + plotOrigin.Y);
index++;
}
}
private void EndTrack()
{
this.chart.adornerLayer.LayoutUpdated -= this.OnAdornerLayerLayoutUpdated;
this.HideVisuals();
}
private class PointYComparer : IComparer<Point>
{
public int Compare(Point x, Point y)
{
return x.Y.CompareTo(y.Y);
}
}
private class DataPointInfoYComparer : IComparer<DataPointInfo>
{
public int Compare(DataPointInfo x, DataPointInfo y)
{
if (x == null || y == null)
{
return 0;
}
return x.DataPoint.layoutSlot.Center.Y.CompareTo(y.DataPoint.layoutSlot.Center.Y);
}
}
}
}
| 34.938728 | 223 | 0.552578 | [
"Apache-2.0"
] | ChristianGutman/UI-For-UWP | Controls/Chart/Chart.UWP/Visualization/Behaviors/Trackball/ChartTrackBallBehavior.cs | 30,222 | C# |
// <copyright file="TypeHandlerFactory.cs" company="Fubar Development Junker">
// Copyright (c) 2016 Fubar Development Junker. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// </copyright>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BeanIO.Config;
using BeanIO.Types;
using BeanIO.Types.Xml;
using JetBrains.Annotations;
namespace BeanIO.Internal.Util
{
/// <summary>
/// A factory class used to get a <see cref="ITypeHandler"/> for parsing field text
/// into field objects, and for formatting field objects into field text.
/// </summary>
/// <remarks>
/// <para>A <see cref="ITypeHandler"/> is registered and retrieved by class, type alias, or name. If a stream
/// format is specified when registering a type handler by class or type alias, the type handler
/// will only be returned when the same format is queried for.
/// In most cases, registering a type handler by type alias has the same effect as registering the
/// type handler using the target class associated with the alias.</para>
/// <para>If a registered type handler implements the <see cref="IConfigurableTypeHandler"/> interface,
/// handler properties can be overridden using a <see cref="IDictionary{TKey,TValue}"/> object. When the type handler
/// is retrieved, the factory calls <see cref="IConfigurableTypeHandler.Configure"/> to
/// allow the type handler to return a customized version of itself.</para>
/// <para>By default, a <see cref="TypeHandlerFactory"/> holds a reference to a parent
/// factory. If a factory cannot find a type handler, its parent will be checked
/// recursively until there is no parent left to check.</para>
/// </remarks>
internal class TypeHandlerFactory
{
private const string NameKey = "name:";
private const string TypeKey = "type:";
private static readonly TypeHandlerFactory _defaultFactory;
private readonly Dictionary<string, Func<ITypeHandler>> _handlerMap = new Dictionary<string, Func<ITypeHandler>>(StringComparer.OrdinalIgnoreCase);
private readonly TypeHandlerFactory _parent;
static TypeHandlerFactory()
{
_defaultFactory = new TypeHandlerFactory(null);
_defaultFactory.RegisterHandlerFor(typeof(char), () => new CharacterTypeHandler());
_defaultFactory.RegisterHandlerFor(typeof(string), () => new StringTypeHandler());
_defaultFactory.RegisterHandlerFor(typeof(sbyte), () => new NumberTypeHandler(typeof(sbyte)));
_defaultFactory.RegisterHandlerFor(typeof(short), () => new NumberTypeHandler(typeof(short)));
_defaultFactory.RegisterHandlerFor(typeof(int), () => new NumberTypeHandler(typeof(int)));
_defaultFactory.RegisterHandlerFor(typeof(long), () => new NumberTypeHandler(typeof(long)));
_defaultFactory.RegisterHandlerFor(typeof(byte), () => new NumberTypeHandler(typeof(byte)));
_defaultFactory.RegisterHandlerFor(typeof(ushort), () => new NumberTypeHandler(typeof(ushort)));
_defaultFactory.RegisterHandlerFor(typeof(uint), () => new NumberTypeHandler(typeof(uint)));
_defaultFactory.RegisterHandlerFor(typeof(ulong), () => new NumberTypeHandler(typeof(ulong)));
_defaultFactory.RegisterHandlerFor(typeof(float), () => new SingleTypeHandler());
_defaultFactory.RegisterHandlerFor(typeof(double), () => new DoubleTypeHandler());
_defaultFactory.RegisterHandlerFor(typeof(decimal), () => new NumberTypeHandler(typeof(decimal)));
_defaultFactory.RegisterHandlerFor(typeof(bool), () => new BooleanTypeHandler());
_defaultFactory.RegisterHandlerFor(typeof(Guid), () => new GuidTypeHandler());
_defaultFactory.RegisterHandlerFor(typeof(Uri), () => new UrlTypeHandler());
_defaultFactory.RegisterHandlerFor(typeof(Version), () => new VersionTypeHandler());
_defaultFactory.RegisterHandlerFor(typeof(Encoding), () => new EncodingTypeHandler());
_defaultFactory.RegisterHandlerFor("datetime", () => new DateTimeTypeHandler());
_defaultFactory.RegisterHandlerFor("datetimeoffset", () => new DateTimeOffsetTypeHandler());
_defaultFactory.RegisterHandlerFor("date", () => new DateTypeHandler());
_defaultFactory.RegisterHandlerFor("time", () => new TimeTypeHandler());
_defaultFactory.RegisterHandlerFor(typeof(bool), () => new XmlBooleanTypeHandler(), "xml");
_defaultFactory.RegisterHandlerFor("datetime", () => new XmlDateTimeTypeHandler(), "xml");
_defaultFactory.RegisterHandlerFor("datetimeoffset", () => new XmlDateTimeOffsetTypeHandler(), "xml");
_defaultFactory.RegisterHandlerFor("date", () => new XmlDateTypeHandler(), "xml");
_defaultFactory.RegisterHandlerFor("time", () => new XmlTimeTypeHandler(), "xml");
}
/// <summary>
/// Initializes a new instance of the <see cref="TypeHandlerFactory"/> class.
/// </summary>
public TypeHandlerFactory()
: this(Default)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="TypeHandlerFactory"/> class.
/// </summary>
/// <param name="parent">The parent <see cref="TypeHandlerFactory"/></param>
public TypeHandlerFactory(TypeHandlerFactory parent)
{
_parent = parent;
}
/// <summary>
/// Gets the default <see cref="TypeHandlerFactory"/>
/// </summary>
public static TypeHandlerFactory Default => _defaultFactory;
/// <summary>
/// Returns a named type handler, or <code>null</code> if there is no type handler configured
/// for the given name in this factory or any of its ancestors.
/// </summary>
/// <param name="name">the name of type handler was registered under</param>
/// <returns>the type handler, or <code>null</code> if there is no configured type handler
/// registered for the name</returns>
public ITypeHandler GetTypeHandler([NotNull] string name)
{
return GetTypeHandler(name, null);
}
/// <summary>
/// Returns a named type handler, or <code>null</code> if there is no type handler configured
/// for the given name in this factory or any of its ancestors.
/// </summary>
/// <param name="name">the name of type handler was registered under</param>
/// <param name="properties">the custom properties for configuring the type handler</param>
/// <returns>the type handler, or <code>null</code> if there is no configured type handler
/// registered for the name</returns>
public ITypeHandler GetTypeHandler([NotNull] string name, Properties properties)
{
if (name == null)
throw new ArgumentNullException(nameof(name));
return GetHandler(NameKey + name, null, properties);
}
/// <summary>
/// Returns the type handler for the given type, or <code>null</code> if there is no type
/// handler configured for the type in this factory or any of its ancestors.
/// </summary>
/// <param name="typeName">the class name or type alias</param>
/// <returns>the type handler, or <code>null</code> if there is no configured type handler
/// registered for the type</returns>
public ITypeHandler GetTypeHandlerFor([NotNull] string typeName)
{
return GetTypeHandlerFor(typeName, null, null);
}
/// <summary>
/// Returns the type handler for the given type, or <code>null</code> if there is no type
/// handler configured for the type in this factory or any of its ancestors.
/// </summary>
/// <param name="typeName">the class name or type alias</param>
/// <param name="format">the stream format, or if null, format specific handlers will not be returned</param>
/// <returns>the type handler, or <code>null</code> if there is no configured type handler
/// registered for the type</returns>
public ITypeHandler GetTypeHandlerFor([NotNull] string typeName, string format)
{
return GetTypeHandlerFor(typeName, format, null);
}
/// <summary>
/// Returns the type handler for the given type, or <code>null</code> if there is no type
/// handler configured for the type in this factory or any of its ancestors.
/// </summary>
/// <param name="typeName">the class name or type alias</param>
/// <param name="format">the stream format, or if null, format specific handlers will not be returned</param>
/// <param name="properties">the custom properties for configuring the type handler</param>
/// <returns>the type handler, or <code>null</code> if there is no configured type handler
/// registered for the type</returns>
public ITypeHandler GetTypeHandlerFor([NotNull] string typeName, string format, Properties properties)
{
if (typeName == null)
throw new ArgumentNullException(nameof(typeName));
var type = typeName.ToType();
if (type == null)
return null;
return GetTypeHandlerFor(type, format, properties);
}
/// <summary>
/// Returns a type handler for a class, or <code>null</code> if there is no type
/// handler configured for the class in this factory or any of its ancestors
/// </summary>
/// <param name="type">the target class to find a type handler for</param>
/// <returns>the type handler, or null if the class is not supported</returns>
public ITypeHandler GetTypeHandlerFor([NotNull] Type type)
{
return GetTypeHandlerFor(type, null, null);
}
/// <summary>
/// Returns a type handler for a class, or <code>null</code> if there is no type
/// handler configured for the class in this factory or any of its ancestors
/// </summary>
/// <param name="type">the target class to find a type handler for</param>
/// <param name="format">the stream format, or if null, format specific handlers will not be returned</param>
/// <returns>the type handler, or null if the class is not supported</returns>
public ITypeHandler GetTypeHandlerFor([NotNull] Type type, [NotNull] string format)
{
return GetTypeHandlerFor(type, format, null);
}
/// <summary>
/// Returns a type handler for a class, or <code>null</code> if there is no type
/// handler configured for the class in this factory or any of its ancestors
/// </summary>
/// <param name="type">the target class to find a type handler for</param>
/// <param name="format">the stream format, or if null, format specific handlers will not be returned</param>
/// <param name="properties">the custom properties for configuring the type handler</param>
/// <returns>the type handler, or null if the class is not supported</returns>
public ITypeHandler GetTypeHandlerFor([NotNull] Type type, string format, Properties properties)
{
if (type == null)
throw new ArgumentNullException(nameof(type));
// Ensure that we "unbox" a nullable type
type = Nullable.GetUnderlyingType(type) ?? type;
var handler = GetHandler(TypeKey + type.FullName, format, properties);
if (handler == null && typeof(Enum).IsAssignableFromThis(type))
return GetEnumHandler(type, properties);
return handler;
}
/// <summary>
/// Registers a type handler in this factory
/// </summary>
/// <param name="name">the name to register the type handler under</param>
/// <param name="createHandler">the type handler creation function to register</param>
public void RegisterHandler([NotNull] string name, [NotNull] Func<ITypeHandler> createHandler)
{
if (name == null)
throw new ArgumentNullException(nameof(name));
if (createHandler == null)
throw new ArgumentNullException(nameof(createHandler));
_handlerMap[NameKey + name] = createHandler;
}
/// <summary>
/// Registers a type handler in this factory by class type for all stream formats
/// </summary>
/// <param name="name">the fully qualified class name or type alias to register the type handler for</param>
/// <param name="createHandler">the type handler creation function to register</param>
public void RegisterHandlerFor([NotNull] string name, [NotNull] Func<ITypeHandler> createHandler)
{
RegisterHandlerFor(name, createHandler, null);
}
/// <summary>
/// Registers a type handler in this factory by class type for a specific stream format
/// </summary>
/// <param name="name">the fully qualified class name or type alias to register the type handler for</param>
/// <param name="createHandler">the type handler creation function to register</param>
/// <param name="format">the stream format to register the type handler for, or if null the type handler may be returned for any format</param>
public void RegisterHandlerFor([NotNull] string name, [NotNull] Func<ITypeHandler> createHandler, string format)
{
if (name == null)
throw new ArgumentNullException(nameof(name));
var type = name.ToType();
if (type == null)
throw new ArgumentException($"Invalid type or type alias '{name}'", nameof(name));
RegisterHandlerFor(format, type.FullName, type, createHandler);
}
/// <summary>
/// Registers a type handler in this factory for any stream format.
/// </summary>
/// <param name="type">the target class to register the type handler for</param>
/// <param name="createHandler">the type handler creation function to register</param>
public void RegisterHandlerFor([NotNull] Type type, [NotNull] Func<ITypeHandler> createHandler)
{
RegisterHandlerFor(type, createHandler, null);
}
/// <summary>
/// Registers a type handler in this factory for a specific stream format
/// </summary>
/// <param name="type">the target class to register the type handler for</param>
/// <param name="createHandler">the type handler creation function to register</param>
/// <param name="format">the stream format to register the type handler for, or if null the type handler may be returned for any format</param>
public void RegisterHandlerFor([NotNull] Type type, [NotNull] Func<ITypeHandler> createHandler, string format)
{
if (type == null)
throw new ArgumentNullException(nameof(type));
RegisterHandlerFor(format, type.FullName, type, createHandler);
}
private void RegisterHandlerFor([CanBeNull] string format, [NotNull] string typeName, [NotNull] Type expectedClass, [NotNull] Func<ITypeHandler> createHandler)
{
var testInstance = createHandler();
if (!expectedClass.IsAssignableFromThis(testInstance.TargetType))
{
throw new ArgumentException(
$"Type handler of type '{testInstance.TargetType}' is not assignable from configured type '{expectedClass}'");
}
if (format != null)
{
_handlerMap[string.Concat(format, ".", TypeKey, typeName)] = createHandler;
}
else
{
_handlerMap[string.Concat(TypeKey, typeName)] = createHandler;
}
}
private ITypeHandler GetEnumHandler([NotNull] Type enumType, Properties properties)
{
var handler = new EnumTypeHandler(enumType);
if (properties != null)
handler.Configure(properties);
return handler;
}
private ITypeHandler GetHandler([NotNull] string key, string format, Properties properties)
{
var factory = this;
while (factory != null)
{
Func<ITypeHandler> createHandler;
if (format != null && factory._handlerMap.TryGetValue(format + "." + key, out createHandler))
return GetHandler(createHandler, properties);
if (factory._handlerMap.TryGetValue(key, out createHandler))
return GetHandler(createHandler, properties);
factory = factory._parent;
}
return null;
}
private ITypeHandler GetHandler([NotNull] Func<ITypeHandler> createHandler, Properties properties)
{
var handler = createHandler();
if (properties != null && properties.Count != 0)
{
var configurableHandler = handler as IConfigurableTypeHandler;
if (configurableHandler == null)
{
throw new BeanIOConfigurationException(
$"'{properties.First().Key}' setting not supported by type handler with target type '{handler.TargetType}'");
}
configurableHandler.Configure(properties);
}
return handler;
}
}
}
| 49.788301 | 167 | 0.634721 | [
"MIT"
] | FubarDevelopment/beanio-net | src/FubarDev.BeanIO/Internal/Util/TypeHandlerFactory.cs | 17,874 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace DsubGui.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "15.9.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default {
get {
return defaultInstance;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("COM3")]
public string ComPort {
get {
return ((string)(this["ComPort"]));
}
set {
this["ComPort"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("9600")]
public int BaudRate {
get {
return ((int)(this["BaudRate"]));
}
set {
this["BaudRate"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("None")]
public global::System.IO.Ports.Parity Parity {
get {
return ((global::System.IO.Ports.Parity)(this["Parity"]));
}
set {
this["Parity"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("8")]
public int DataBits {
get {
return ((int)(this["DataBits"]));
}
set {
this["DataBits"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("One")]
public global::System.IO.Ports.StopBits StopBits {
get {
return ((global::System.IO.Ports.StopBits)(this["StopBits"]));
}
set {
this["StopBits"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("None")]
public global::System.IO.Ports.Handshake Handshake {
get {
return ((global::System.IO.Ports.Handshake)(this["Handshake"]));
}
set {
this["Handshake"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("\\r")]
public string NewLine {
get {
return ((string)(this["NewLine"]));
}
set {
this["NewLine"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute(",")]
public string FieldDelimiter {
get {
return ((string)(this["FieldDelimiter"]));
}
set {
this["FieldDelimiter"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("False")]
public bool ConnectOnStartup {
get {
return ((bool)(this["ConnectOnStartup"]));
}
set {
this["ConnectOnStartup"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("500")]
public int ReadTimeout {
get {
return ((int)(this["ReadTimeout"]));
}
set {
this["ReadTimeout"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("500")]
public int WriteTimeout {
get {
return ((int)(this["WriteTimeout"]));
}
set {
this["WriteTimeout"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("False")]
public bool DtrEnable {
get {
return ((bool)(this["DtrEnable"]));
}
set {
this["DtrEnable"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("False")]
public bool RtsEnable {
get {
return ((bool)(this["RtsEnable"]));
}
set {
this["RtsEnable"] = value;
}
}
}
}
| 36.786885 | 151 | 0.548425 | [
"MIT"
] | swvincent/dsub | DsubGui/Properties/Settings.Designer.cs | 6,734 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UniRx;
namespace Game.Components
{
[Game]
public class SnakePosition : Entitas.IComponent
{
public List<Vector2> positions;
}
} | 18.307692 | 51 | 0.718487 | [
"MIT"
] | mmatvein/snake | Snake/Assets/Game/Scripts/Game/Components/SnakePosition.cs | 240 | C# |
using System.Collections.Generic;
namespace PrincipleStudios.OpenApi.Transformations
{
public interface ISourceProvider
{
IEnumerable<SourceEntry> GetSources(OpenApiTransformDiagnostic diagnostic);
}
} | 24.777778 | 83 | 0.780269 | [
"BSD-2-Clause"
] | mdekrey/principle-studios-openapi-generators | lib/PrincipleStudios.OpenApi.Transformations/ISourceProvider.cs | 225 | C# |
namespace MassTransit.ActiveMqTransport.Topology.Entities
{
using MassTransit.Topology.Entities;
public interface QueueHandle :
EntityHandle
{
Queue Queue { get; }
}
}
| 17.75 | 58 | 0.638498 | [
"ECL-2.0",
"Apache-2.0"
] | Aerodynamite/MassTrans | src/Transports/MassTransit.ActiveMqTransport/Topology/Entities/QueueHandle.cs | 213 | 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: Microsoft.AspNetCore.Mvc.ApplicationParts.ProvideApplicationPartFactoryAttribute("Microsoft.AspNetCore.Mvc.ApplicationParts.CompiledRazorAssemblyApplicationPartFac" +
"tory, Microsoft.AspNetCore.Mvc.Razor")]
[assembly: System.Reflection.AssemblyCompanyAttribute("AdvancePhonebook")]
[assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")]
[assembly: System.Reflection.AssemblyProductAttribute("AdvancePhonebook")]
[assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")]
[assembly: System.Reflection.AssemblyTitleAttribute("AdvancePhonebook.Views")]
[assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")]
// Generated by the MSBuild WriteCodeFragment class.
| 47.192308 | 177 | 0.691932 | [
"MIT"
] | miladxandi/AdvancesPhonebook | AdvancePhonebook/obj/Debug/netcoreapp3.1/AdvancePhonebook.RazorTargetAssemblyInfo.cs | 1,227 | C# |
using System;
using Commands;
using Messages;
using NServiceBus;
public class CommandSender
{
public static void Start(IBus bus)
{
Console.WriteLine("Press 'C' to send a command");
Console.WriteLine("Press 'R' to send a request");
Console.WriteLine("Press 'E' to send a message that is marked as Express");
Console.WriteLine("Press 'D' to send a large message that is marked to be sent using Data Bus");
Console.WriteLine("Press 'X' to send a message that is marked with expiration time.");
Console.WriteLine("Press any key to exit");
while (true)
{
var key = Console.ReadKey();
Console.WriteLine();
switch (key.Key)
{
case ConsoleKey.C:
SendCommand(bus);
continue;
case ConsoleKey.R:
SendRequest(bus);
continue;
case ConsoleKey.E:
Express(bus);
continue;
case ConsoleKey.D:
Data(bus);
continue;
case ConsoleKey.X:
Expiration(bus);
continue;
}
return;
}
}
// Shut down server before sending this message, after 30 seconds, the message will be moved to Transactional dead-letter messages queue.
static void Expiration(IBus bus)
{
var messageThatExpires = new MessageThatExpires
{
RequestId = new Guid()
};
bus.Send("Samples.Unobtrusive.Server", messageThatExpires);
Console.WriteLine("message with expiration was sent");
}
static void Data(IBus bus)
{
var requestId = Guid.NewGuid();
var largeMessage = new LargeMessage
{
RequestId = requestId,
LargeDataBus = new byte[1024*1024*5]
};
bus.Send("Samples.Unobtrusive.Server", largeMessage);
Console.WriteLine($"Request sent id: {requestId}");
}
static void Express(IBus bus)
{
var requestId = Guid.NewGuid();
var requestExpress = new RequestExpress
{
RequestId = requestId
};
bus.Send("Samples.Unobtrusive.Server", requestExpress);
Console.WriteLine($"Request sent id: {requestId}");
}
static void SendRequest(IBus bus)
{
var requestId = Guid.NewGuid();
var request = new Request
{
RequestId = requestId
};
bus.Send("Samples.Unobtrusive.Server", request);
Console.WriteLine($"Request sent id: {requestId}");
}
static void SendCommand(IBus bus)
{
var commandId = Guid.NewGuid();
var myCommand = new MyCommand
{
CommandId = commandId,
EncryptedString = "Some sensitive information"
};
bus.Send("Samples.Unobtrusive.Server", myCommand);
Console.WriteLine($"Command sent id: {commandId}");
}
} | 27.730435 | 142 | 0.529633 | [
"Apache-2.0"
] | A-Franklin/docs.particular.net | samples/unobtrusive/Core_4/Client/CommandSender.cs | 3,075 | C# |
[assembly: System.Reflection.AssemblyVersion("1.0.0")]
static class Program
{
static void Main() { System.Console.WriteLine("This is a place-holder project just to make file management easier"); }
}
| 34 | 122 | 0.740196 | [
"Apache-2.0"
] | IlincescuMihai/StackExchange.Redis | Docs/Program.cs | 206 | C# |
using System;
using System.Collections.Generic;
namespace SoftUniParking
{
public class StartUp
{
public static void Main(string[] args)
{
var car = new Car("Skoda", "Fabia", 65, "CC1856BG");
var car2 = new Car("Audi", "A3", 110, "EB8787MN");
Console.WriteLine(car.ToString());
//Make: Skoda
//Model: Fabia
//HorsePower: 65
//RegistrationNumber: CC1856BG
var parking = new Parking(5);
Console.WriteLine(parking.AddCar(car));
//Successfully added new car Skoda CC1856BG
Console.WriteLine(parking.AddCar(car));
//Car with that registration number, already exists!
Console.WriteLine(parking.AddCar(car2));
//Successfully added new car Audi EB8787MN
Console.WriteLine(parking.GetCar("EB8787MN").ToString());
//Make: Audi
//Model: A3
//HorsePower: 110
//RegistrationNumber: EB8787MN
Console.WriteLine(parking.RemoveCar("EB8787MN"));
//Successfullyremoved EB8787MN
Console.WriteLine(parking.Count); //1
}
}
}
| 28.209302 | 69 | 0.563067 | [
"MIT"
] | NeSh74/Advanced-CSharp-May-2021 | 06. Defining Classes/06. CSharp-Advanced-Defining-Classes-Exercises_1_2_3_4_5_6_10/10.SoftUniParking/StartUp.cs | 1,215 | C# |
//-----------------------------------------------------------------------
// <copyright file="ExtensionMethods.cs" company="Lost Signal LLC">
// Copyright (c) Lost Signal LLC. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
#if USING_UNITY_ADDRESSABLES
namespace Lost
{
using UnityEngine;
public static class ExtensionMethods
{
public static void ReleaseAddressable(this GameObject gameObject)
{
if (gameObject != null)
{
UnityEngine.AddressableAssets.Addressables.ReleaseInstance(gameObject);
}
}
public static void ReleaseAddressable(this Component component)
{
if (component != null)
{
UnityEngine.AddressableAssets.Addressables.ReleaseInstance(component.gameObject);
}
}
}
}
#endif
| 27.264706 | 97 | 0.514563 | [
"Unlicense",
"MIT"
] | LostSignal/Lost-Library | Lost/Lost.Addressables/Runtime/ExtensionMethods.cs | 929 | C# |
using System;
namespace Deveel.OpenAmat.Client {
static class KnownServiceEndPoints {
public const string TransitLandV1 = "https://transit.land/api/v1/";
}
}
| 20.5 | 69 | 0.75 | [
"Apache-2.0"
] | deveel/openamat.net | src/OpenAmat.Net/Deveel.OpenAmat.Client/KnownServiceEndPoints.cs | 166 | C# |
////////////////////////////////////////////////////////////////////////////////
//NUnit tests for "EF Core Provider for LCPI OLE DB"
// IBProvider and Contributors. 26.11.2020.
using System;
using System.Data;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using NUnit.Framework;
using xdb=lcpi.data.oledb;
namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D3.Query.Operators.SET_001.Add.Complete.Int64.Decimal_15_1{
////////////////////////////////////////////////////////////////////////////////
using T_DATA1=System.Int64;
using T_DATA2=System.Decimal;
////////////////////////////////////////////////////////////////////////////////
//class TestSet_001__fields
public static class TestSet_001__fields
{
private const string c_NameOf__TABLE ="TEST_MODIFY_ROW2";
private const string c_NameOf__COL_DATA1 ="COL_BIGINT";
private const string c_NameOf__COL_DATA2 ="COL2_NUM_15_1";
private sealed class MyContext:TestBaseDbContext
{
[Table(c_NameOf__TABLE)]
public sealed class TEST_RECORD
{
[Key]
[Column("TEST_ID")]
public System.Int64? TEST_ID { get; set; }
[Column(c_NameOf__COL_DATA1)]
public T_DATA1 COL_DATA1 { get; set; }
[Column(c_NameOf__COL_DATA2, TypeName ="NUMERIC(15,1)")]
public T_DATA2 COL_DATA2 { get; set; }
};//class TEST_RECORD
//----------------------------------------------------------------------
public DbSet<TEST_RECORD> testTable { get; set; }
//----------------------------------------------------------------------
public MyContext(xdb.OleDbTransaction tr)
:base(tr)
{
}//MyContext
};//class MyContext
//-----------------------------------------------------------------------
[Test]
public static void Test_001()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
const T_DATA1 c_value1=7;
const T_DATA2 c_value2=4;
System.Int64? testID=Helper__InsertRow(db,c_value1,c_value2);
Assert.AreEqual
(11,
c_value1+c_value2);
var recs=db.testTable.Where(r => (r.COL_DATA1+r.COL_DATA2)==11 && r.TEST_ID==testID);
int nRecs=0;
foreach(var r in recs)
{
Assert.AreEqual
(0,
nRecs);
++nRecs;
Assert.IsTrue
(r.TEST_ID.HasValue);
Assert.AreEqual
(testID,
r.TEST_ID.Value);
Assert.AreEqual
(c_value1,
r.COL_DATA1);
Assert.AreEqual
(c_value2,
r.COL_DATA2);
}//foreach r
//NOTE: At current time (2020-11-26) DataProvider ignores CAST to DECIMAL.
var sqlt
=new TestSqlTemplate()
.T("SELECT ").N("t","TEST_ID").T(", ").N("t",c_NameOf__COL_DATA1).T(", ").N("t",c_NameOf__COL_DATA2).EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("t").EOL()
.T("WHERE ((").N("t",c_NameOf__COL_DATA1).T(" + ").N("t",c_NameOf__COL_DATA2).T(") = 11) AND (").N("t","TEST_ID").T(" = ").P_ID("__testID_0").T(")");
db.CheckTextOfLastExecutedCommand
(sqlt);
Assert.AreEqual
(1,
nRecs);
}//using db
tr.Rollback();
}//using tr
}//using cn
}//Test_001
//-----------------------------------------------------------------------
private static System.Int64 Helper__InsertRow(MyContext db,
T_DATA1 valueForColData1,
T_DATA2 valueForColData2)
{
var newRecord=new MyContext.TEST_RECORD();
newRecord.COL_DATA1 =valueForColData1;
newRecord.COL_DATA2 =valueForColData2;
db.testTable.Add(newRecord);
db.SaveChanges();
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("INSERT INTO ").N(c_NameOf__TABLE).T(" (").N(c_NameOf__COL_DATA1).T(", ").N(c_NameOf__COL_DATA2).T(")").EOL()
.T("VALUES (").P("p0").T(", ").P("p1").T(")").EOL()
.T("RETURNING ").N("TEST_ID").EOL()
.T("INTO ").P("p2").T(";"));
Assert.IsTrue
(newRecord.TEST_ID.HasValue);
Console.WriteLine("TEST_ID: {0}",newRecord.TEST_ID.Value);
return newRecord.TEST_ID.Value;
}//Helper__InsertRow
};//class TestSet_001__fields
////////////////////////////////////////////////////////////////////////////////
}//namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D3.Query.Operators.SET_001.Add.Complete.Int64.Decimal_15_1
| 28.993671 | 156 | 0.558612 | [
"MIT"
] | ibprovider/Lcpi.EFCore.LcpiOleDb | Tests/General/Source/Work/DBMS/Firebird/V03_0_0/D3/Query/Operators/SET_001/Add/Complete/Int64/Decimal_15_1/TestSet_001__fields.cs | 4,583 | C# |
using Blockcore.Web.Bip39;
using Microsoft.AspNetCore.Components.Web;
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("#app");
builder.RootComponents.Add<HeadOutlet>("head::after");
builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });
await builder.Build().RunAsync().ConfigureAwait(false);
| 37.916667 | 112 | 0.804396 | [
"MIT"
] | seniorblockchain/blockcore-tools | src/Blockcore.Web.Bip39/Program.cs | 455 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace EPiServer.Reference.Commerce.Shared.Models
{
public class ApiProductResult
{
public string ResultId { get; set; }
public string ResultDate { get; set; }
public string ResultDay { get; set; }
}
} | 23.357143 | 52 | 0.685015 | [
"Apache-2.0"
] | simerc/QuicksilverPlus | Sources/EPiServer.Reference.Commerce.Shared/Models/ApiProductResult.cs | 329 | C# |
using System.Collections.Generic;
using System.Linq;
using org.ohdsi.cdm.framework.core.Base;
using org.ohdsi.cdm.framework.entities.Omop;
using org.ohdsi.cdm.framework.shared.Extensions;
namespace org.ohdsi.cdm.builders.cprd
{
/// <summary>
/// Implementation of PersonBuilder for CPRD, based on CDM Build spec
/// </summary>
public class CprdPersonBuilder : PersonBuilder
{
public CprdPersonBuilder(ChunkBuilder chunkBuilder)
: base(chunkBuilder)
{
}
/// <summary>
/// Build person entity and all person related entities like: DrugExposures, ConditionOccurrences, ProcedureOccurrences... from raw data sets
/// </summary>
public override void Build()
{
var person = BuildPerson(personRecords.ToList());
if (person == null) return;
var observationPeriods = BuildObservationPeriods(person.ObservationPeriodGap, observationPeriodsRaw.ToArray()).ToArray();
var payerPlanPeriods = BuildPayerPlanPeriods(payerPlanPeriodsRaw.ToArray(), null).ToArray();
var cohort = BuildCohort(cohortRecords.ToArray(), observationPeriods).ToArray();
// Build and clenaup visit occurrences entities
var visitOccurrences =
CleanupVisits(BuildVisitOccurrences(visitOccurrencesRaw.ToArray(), observationPeriods), cohort,
observationPeriods).ToDictionary(visitOccurrence => visitOccurrence.Id);
var drugExposures = BuildDrugExposures(drugExposuresRaw.ToArray(), visitOccurrences, observationPeriods).ToArray();
var conditionOccurrences = Cleanup(BuildConditionOccurrences(conditionOccurrencesRaw.ToArray(), visitOccurrences, observationPeriods), cohort).ToArray();
var procedureOccurrences = Cleanup(BuildProcedureOccurrences(procedureOccurrencesRaw.ToArray(), visitOccurrences, observationPeriods), cohort).ToArray();
var observations = Cleanup(BuildObservations(observationsRaw.ToArray(), visitOccurrences, observationPeriods), cohort).ToArray();
// set corresponding PlanPeriodIds to drug exposure entities and procedure occurrence entities
SetPayerPlanPeriodId(payerPlanPeriods, drugExposures, procedureOccurrences);
// set corresponding ProviderIds
SetProviderIds(drugExposures);
SetProviderIds(conditionOccurrences);
SetProviderIds(procedureOccurrences);
SetProviderIds(observations);
var drugEra = BuildDrugEra(drugExposures).ToArray();
var conditionEra = BuildConditionEra(conditionOccurrences).ToArray();
var death = BuildDeath(deathRecords.ToArray(), visitOccurrences, observationPeriods);
var drugCosts = BuildDrugCosts(drugExposures).ToArray();
var procedureCosts = BuildProcedureCosts(procedureOccurrences).ToArray();
// push built entities to ChunkBuilder for further save to CDM database
AddToChunk(person, death, observationPeriods, payerPlanPeriods, drugExposures, drugEra, drugCosts,
conditionOccurrences, conditionEra, procedureOccurrences, procedureCosts, observations, visitOccurrences.Values.ToArray(), cohort);
}
/// <summary>
/// Projects Enumeration of Observations from the raw set of Observation entities.
/// During build:
/// override the observations start date using the start date of the corresponding obervation period.
/// overide TypeConceptId per CDM Mapping spec.
/// exclude the observations without observation periods and observation that out of current observation period
/// </summary>
/// <param name="observations">raw set of observations entities</param>
/// <param name="visitOccurrences">the visit occurrences entities for current person</param>
/// <param name="observationPeriods">the observation periods entities for current person</param>
/// <returns>Enumeration of Observation from the raw set of Observation entities</returns>
public override IEnumerable<Observation> BuildObservations(Observation[] observations,
Dictionary<long, VisitOccurrence> visitOccurrences,
ObservationPeriod[] observationPeriods)
{
foreach (var observation in observations)
{
// exclude observations for person without observation periods
if (!observationPeriods.Any()) continue;
//Medical History Read code records
if (observation.TypeConceptId >= 1 && observation.TypeConceptId <= 3)
{
// Medical history records are additional observation read code records that occur prior to the observation period start date
if (observation.StartDate < observationPeriods[0].StartDate)
{
// assign Concept Type:
switch (observation.TypeConceptId)
{
case 1:
observation.TypeConceptId = 38000245;
break;
case 2:
observation.TypeConceptId = 38000280;
break;
case 3:
observation.TypeConceptId = 42898140;
break;
}
// set VisitOccurrenceId, ValueAsConceptId, ConceptId, StartDate based on CDM Build spec for Medical History Read code records
observation.VisitOccurrenceId = null;
observation.ValueAsConceptId = observation.ConceptId;
observation.ConceptId = 43054928;
observation.StartDate = observationPeriods[0].StartDate;
yield return observation;
}
}
else if (observation.StartDate.Between(observationPeriods[0].StartDate, observationPeriods[0].EndDate))
{
// set to NULL VisitOccurrenceId for not existing VisitOccurrenceIds
if (observation.VisitOccurrenceId != null &&
!visitOccurrences.ContainsKey(observation.VisitOccurrenceId.Value))
observation.VisitOccurrenceId = null;
yield return observation;
}
}
}
/// <summary>
/// Projects Enumeration of Cohort from the raw set of Cohort entities.
/// During build:
/// override the cohort's start date using the start date of the corresponding obervation period.
/// override the cohort's end date using the end date of the corresponding obervation period.
/// exclude the cohort's without observation periods
/// </summary>
/// <param name="cohort">raw set of Cohort entities</param>
/// <param name="observationPeriods">the observation periods entities for current person</param>
/// <returns>Enumeration of Cohort from the raw set of Cohort entities</returns>
public override IEnumerable<Cohort> BuildCohort(Cohort[] cohort, ObservationPeriod[] observationPeriods)
{
foreach (var c in cohort)
{
//exclude the Cohort without observation periods
if (!observationPeriods.Any()) continue;
if (c.StartDate < observationPeriods[0].StartDate)
c.StartDate = observationPeriods[0].StartDate;
if (c.EndDate > observationPeriods[0].EndDate)
c.EndDate = observationPeriods[0].EndDate;
yield return c;
}
}
/// <summary>
/// Filtering and start/end date adjustment for visit occurrence entities
/// </summary>
/// <param name="visits">the visit occurrence entities for current person</param>
/// <param name="cohorts">the cohort entities for current person</param>
/// <param name="observationPeriods">the observation period entities for current person</param>
/// <returns>Enumeration of filtered out and adjusted visit occurrence entities</returns>
private static IEnumerable<VisitOccurrence> CleanupVisits(IEnumerable<VisitOccurrence> visits, IList<Cohort> cohorts, ObservationPeriod[] observationPeriods)
{
foreach (var visitOccurrence in visits)
{
if (!observationPeriods.Any()) continue;
// Adjust visit start/end date for outpatient Visit
if (visitOccurrence.ConceptId == 9202)
yield return AdjustVisitDates(visitOccurrence, observationPeriods);
else
{
// exclude not outpatient visit for person without cohort records
if (!cohorts.Any()) continue;
// Adjust visit start/end date for not outpatient visit that out of current cohort start & end dates
if (visitOccurrence.StartDate >= cohorts[0].StartDate && visitOccurrence.EndDate <= cohorts[0].EndDate)
{
yield return AdjustVisitDates(visitOccurrence, observationPeriods);
}
}
}
}
/// <summary>
/// override the visit's start/end date for visit entities that out of current obervation period
/// using the start/end date of the corresponding obervation period.
/// </summary>
/// <param name="visitOccurrence">the visit occurrence entities for current person</param>
/// <param name="observationPeriods">the observation period entities for current person</param>
/// <returns>Enumeration of adjusted visit occurrence entities</returns>
private static VisitOccurrence AdjustVisitDates(VisitOccurrence visitOccurrence, ObservationPeriod[] observationPeriods)
{
if (visitOccurrence.StartDate < observationPeriods[0].StartDate)
visitOccurrence.StartDate = observationPeriods[0].StartDate;
if (visitOccurrence.EndDate > observationPeriods[0].EndDate)
visitOccurrence.EndDate = observationPeriods[0].EndDate;
return visitOccurrence;
}
/// <summary>
/// Filtering for HES records
/// </summary>
/// <typeparam name="T">IEntity</typeparam>
/// <param name="items">the set of entities</param>
/// <param name="cohorts">the cohort entities for current person</param>
/// <returns>Enumeration of filtered entities</returns>
private static IEnumerable<T> Cleanup<T>(IEnumerable<T> items, IList<Cohort> cohorts) where T : class, IEntity
{
foreach (var item in items)
{
// hes records
if ((item.TypeConceptId >= 38000183 && item.TypeConceptId <= 38000198) ||
(item.TypeConceptId >= 44818709 && item.TypeConceptId <= 44818713) ||
(item.TypeConceptId >= 900000006 && item.TypeConceptId <= 900000007))
{
// exclude hes records for person without cohort records
if (!cohorts.Any()) continue;
//exclude hes records without VisitOccurrenceId
if (!item.VisitOccurrenceId.HasValue) continue;
// exclude hes records that out of current cohort start & end dates
if (item.StartDate >= cohorts[0].StartDate && item.EndDate <= cohorts[0].EndDate)
{
yield return item;
}
}
else
{
yield return item;
}
}
}
/// <summary>
/// Filtering raw set of entities (DrugExposures, ConditionOccurrences, ProcedureOccurrences...)
/// </summary>
/// <param name="entitiesToBuild">the raw set of entities</param>
/// <param name="visitOccurrences">the visit occurrence entities for current person</param>
/// <param name="observationPeriods">the observation period entities for current person</param>
/// <returns>Enumeration of filtered entities</returns>
public override IEnumerable<T> BuildEntities<T>(IEnumerable<T> entitiesToBuild,
IDictionary<long, VisitOccurrence> visitOccurrences, IEnumerable<ObservationPeriod> observationPeriods)
{
var uniqueEntities = new HashSet<T>();
foreach (var e in Clean(entitiesToBuild, observationPeriods))
{
var entity = e;
if (entity.VisitOccurrenceId != null && !visitOccurrences.ContainsKey(entity.VisitOccurrenceId.Value))
entity.VisitOccurrenceId = null;
if (entity.IsUnique)
{
uniqueEntities.Add(entity);
}
else
{
yield return entity;
}
}
foreach (var ue in uniqueEntities)
{
yield return ue;
}
}
}
}
| 47.317164 | 163 | 0.643719 | [
"Apache-2.0"
] | OHDSI/ETL-CDMBuilder | CDMv4/source/Builders/org.ohdsi.cdm.builders.cprd/CprdPersonBuilder.cs | 12,683 | C# |
namespace devdeer.CoffeeCupApiAccess.Logic.Models.Enumerations
{
using System;
using System.Linq;
/// <summary>
/// Defines valid values for user employments.
/// </summary>
public enum EmploymentType
{
Employee = 0,
Freelancer = 1,
FormerEmployee = 2
}
} | 18.529412 | 63 | 0.609524 | [
"MIT"
] | DEVDEER/CoffeeCupApiAccess | Logic/Logic.Models/Enumerations/EmploymentType.cs | 317 | C# |
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.Extensions.Configuration;
using System;
using System.IO;
namespace Persistence
{
public abstract class DesignTimeDbContextFactoryBase<TContext> :
IDesignTimeDbContextFactory<TContext> where TContext : DbContext
{
private const string ConnectionStringName = "OrderDatabase";
private const string AspNetCoreEnvironment = "ASPNETCORE_ENVIRONMENT";
public TContext CreateDbContext(string[] args)
{
var basePath = Directory.GetCurrentDirectory() + string.Format("{0}..{0}OrderConsumerQueryingService.Api", Path.DirectorySeparatorChar);
return Create(basePath, Environment.GetEnvironmentVariable(AspNetCoreEnvironment));
}
protected abstract TContext CreateNewInstance(DbContextOptions<TContext> options);
private TContext Create(string basePath, string environmentName)
{
var configuration = new ConfigurationBuilder()
.SetBasePath(basePath)
.AddJsonFile("appsettings.json")
.AddJsonFile($"appsettings.Local.json", optional: true)
.AddJsonFile($"appsettings.{environmentName}.json", optional: true)
.AddEnvironmentVariables()
.Build();
var connectionString = configuration.GetConnectionString(ConnectionStringName);
return Create(connectionString);
}
private TContext Create(string connectionString)
{
if (string.IsNullOrEmpty(connectionString))
{
throw new ArgumentException($"Connection string '{ConnectionStringName}' is null or empty.", nameof(connectionString));
}
Console.WriteLine($"DesignTimeDbContextFactoryBase.Create(string): Connection string: '{connectionString}'.");
var optionsBuilder = new DbContextOptionsBuilder<TContext>();
optionsBuilder.UseSqlServer(connectionString);
return CreateNewInstance(optionsBuilder.Options);
}
}
}
| 45.934783 | 148 | 0.681969 | [
"MIT"
] | emrealper/order-event-processing | source/OrderConsumer/Persistance/DesignTimeDbContextFactoryBase.cs | 2,115 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool
// Changes to this file will be lost if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
/*Copyright (C) 2016 History in Paderborn App - Universit�t Paderborn
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.*/
namespace de.upb.hip.domainmodel
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class StringElement : IIdentifiable
{
public string Id{
get;
set;
}
public virtual string Value
{
get;
set;
}
}
}
| 28.093023 | 81 | 0.626656 | [
"Apache-2.0"
] | HiP-App/HiPDomainmodel | HiPDomainModelLib/GeneratedCode/StringElement.cs | 1,212 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Mover : MonoBehaviour {
Camera camera;
GameObject audioAnalyser;
Analyser analyser;
float speed;
// Use this for initialization
void Start () {
speed = Random.Range(400f, 600f);
transform.forward = -Vector3.forward;
camera = GameObject.Find("Main Camera").GetComponent<Camera>();
audioAnalyser = GameObject.Find("AudioAnalyser");
analyser = audioAnalyser.GetComponent<Analyser>();
}
// Update is called once per frame
void Update () {
transform.Translate(0, 0, analyser.bassAmplitude * speed * Time.deltaTime);
if(transform.position.z < camera.transform.position.z - 10)
{
Destroy(this.gameObject);
}
}
}
| 26.129032 | 83 | 0.660494 | [
"MIT"
] | RustedBot/Game-Engines-Assignment | Game Engines Assignment/Assets/Scripts/Mover.cs | 812 | C# |
using Microsoft.AspNetCore.Razor.TagHelpers;
using Util.Ui.Angular.AntDesign.Tests.XUnitHelpers;
using Util.Ui.Configs;
using Util.Ui.Enums;
using Util.Ui.Zorro.Dividers;
using Util.Ui.Zorro.Menus;
using Xunit;
using Xunit.Abstractions;
using String = Util.Helpers.String;
namespace Util.Ui.Angular.AntDesign.Tests.Zorro.Menus {
/// <summary>
/// 菜单测试
/// </summary>
public class MenuTagHelperTest {
/// <summary>
/// 输出工具
/// </summary>
private readonly ITestOutputHelper _output;
/// <summary>
/// 菜单
/// </summary>
private readonly MenuTagHelper _component;
/// <summary>
/// 测试初始化
/// </summary>
public MenuTagHelperTest( ITestOutputHelper output ) {
_output = output;
_component = new MenuTagHelper();
}
/// <summary>
/// 获取结果
/// </summary>
private string GetResult( TagHelperAttributeList contextAttributes = null, TagHelperAttributeList outputAttributes = null, TagHelperContent content = null ) {
return Helper.GetResult( _output, _component, contextAttributes, outputAttributes, content );
}
/// <summary>
/// 测试默认输出
/// </summary>
[Fact]
public void TestDefault() {
var result = new String();
result.Append( "<ul nz-menu=\"\"></ul>" );
Assert.Equal( result.ToString(), GetResult() );
}
/// <summary>
/// 测试添加标识
/// </summary>
[Fact]
public void TestId() {
var attributes = new TagHelperAttributeList { { UiConst.Id, "a" } };
var result = new String();
result.Append( "<ul #a=\"\" nz-menu=\"\"></ul>" );
Assert.Equal( result.ToString(), GetResult( attributes ) );
}
/// <summary>
/// 测试模式
/// </summary>
[Fact]
public void TestMode() {
var attributes = new TagHelperAttributeList { { UiConst.Mode, MenuMode.Inline } };
var result = new String();
result.Append( "<ul nz-menu=\"\" nzMode=\"inline\"></ul>" );
Assert.Equal( result.ToString(), GetResult( attributes ) );
}
/// <summary>
/// 测试允许选中
/// </summary>
[Fact]
public void TestSelectable() {
var attributes = new TagHelperAttributeList { { UiConst.Selectable, false } };
var result = new String();
result.Append( "<ul nz-menu=\"\" [nzSelectable]=\"false\"></ul>" );
Assert.Equal( result.ToString(), GetResult( attributes ) );
}
/// <summary>
/// 测试主题
/// </summary>
[Fact]
public void TestTheme() {
var attributes = new TagHelperAttributeList { { UiConst.Theme, MenuTheme.Light } };
var result = new String();
result.Append( "<ul nz-menu=\"\" nzTheme=\"light\"></ul>" );
Assert.Equal( result.ToString(), GetResult( attributes ) );
}
/// <summary>
/// 测试折叠状态
/// </summary>
[Fact]
public void TestInlineCollapsed() {
var attributes = new TagHelperAttributeList { { UiConst.InlineCollapsed, false } };
var result = new String();
result.Append( "<ul nz-menu=\"\" [nzInlineCollapsed]=\"false\"></ul>" );
Assert.Equal( result.ToString(), GetResult( attributes ) );
}
/// <summary>
/// 测试缩进宽度
/// </summary>
[Fact]
public void TestInlineIndent() {
var attributes = new TagHelperAttributeList { { UiConst.InlineIndent, 2 } };
var result = new String();
result.Append( "<ul nz-menu=\"\" [nzInlineIndent]=\"2\"></ul>" );
Assert.Equal( result.ToString(), GetResult( attributes ) );
}
/// <summary>
/// 测试单击事件
/// </summary>
[Fact]
public void TestOnClick() {
var attributes = new TagHelperAttributeList { { UiConst.OnClick, "a" } };
var result = new String();
result.Append( "<ul (nzClick)=\"a\" nz-menu=\"\"></ul>" );
Assert.Equal( result.ToString(), GetResult( attributes ) );
}
}
} | 33.913386 | 166 | 0.529603 | [
"MIT"
] | 12321/Util | test/Util.Ui.Angular.AntDesign.Tests/Zorro/Menus/MenuTagHelperTest.cs | 4,435 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// Этот код создан программой.
// Исполняемая версия:4.0.30319.42000
//
// Изменения в этом файле могут привести к неправильной работе и будут потеряны в случае
// повторной генерации кода.
// </auto-generated>
//------------------------------------------------------------------------------
namespace NewPlatform.Flexberry.ORM.Tests
{
using System;
using System.Xml;
using ICSSoft.STORMNET;
// *** Start programmer edit section *** (Using statements)
// *** End programmer edit section *** (Using statements)
/// <summary>
/// InformationTestClass3.
/// </summary>
// *** Start programmer edit section *** (InformationTestClass3 CustomAttributes)
// *** End programmer edit section *** (InformationTestClass3 CustomAttributes)
[AutoAltered()]
[AccessType(ICSSoft.STORMNET.AccessType.none)]
public class InformationTestClass3 : ICSSoft.STORMNET.DataObject
{
private string fStringPropertyForInformationTestClass3;
private NewPlatform.Flexberry.ORM.Tests.InformationTestClass2 fInformationTestClass2;
// *** Start programmer edit section *** (InformationTestClass3 CustomMembers)
// *** End programmer edit section *** (InformationTestClass3 CustomMembers)
/// <summary>
/// StringPropertyForInformationTestClass3.
/// </summary>
// *** Start programmer edit section *** (InformationTestClass3.StringPropertyForInformationTestClass3 CustomAttributes)
// *** End programmer edit section *** (InformationTestClass3.StringPropertyForInformationTestClass3 CustomAttributes)
[PropertyStorage("StringPropForInfTestClass3")]
[StrLen(255)]
public virtual string StringPropertyForInformationTestClass3
{
get
{
// *** Start programmer edit section *** (InformationTestClass3.StringPropertyForInformationTestClass3 Get start)
// *** End programmer edit section *** (InformationTestClass3.StringPropertyForInformationTestClass3 Get start)
string result = this.fStringPropertyForInformationTestClass3;
// *** Start programmer edit section *** (InformationTestClass3.StringPropertyForInformationTestClass3 Get end)
// *** End programmer edit section *** (InformationTestClass3.StringPropertyForInformationTestClass3 Get end)
return result;
}
set
{
// *** Start programmer edit section *** (InformationTestClass3.StringPropertyForInformationTestClass3 Set start)
// *** End programmer edit section *** (InformationTestClass3.StringPropertyForInformationTestClass3 Set start)
this.fStringPropertyForInformationTestClass3 = value;
// *** Start programmer edit section *** (InformationTestClass3.StringPropertyForInformationTestClass3 Set end)
// *** End programmer edit section *** (InformationTestClass3.StringPropertyForInformationTestClass3 Set end)
}
}
/// <summary>
/// InformationTestClass3.
/// </summary>
// *** Start programmer edit section *** (InformationTestClass3.InformationTestClass2 CustomAttributes)
// *** End programmer edit section *** (InformationTestClass3.InformationTestClass2 CustomAttributes)
[PropertyStorage(new string[] {
"InformationTestClass2"})]
[NotNull()]
public virtual NewPlatform.Flexberry.ORM.Tests.InformationTestClass2 InformationTestClass2
{
get
{
// *** Start programmer edit section *** (InformationTestClass3.InformationTestClass2 Get start)
// *** End programmer edit section *** (InformationTestClass3.InformationTestClass2 Get start)
NewPlatform.Flexberry.ORM.Tests.InformationTestClass2 result = this.fInformationTestClass2;
// *** Start programmer edit section *** (InformationTestClass3.InformationTestClass2 Get end)
// *** End programmer edit section *** (InformationTestClass3.InformationTestClass2 Get end)
return result;
}
set
{
// *** Start programmer edit section *** (InformationTestClass3.InformationTestClass2 Set start)
// *** End programmer edit section *** (InformationTestClass3.InformationTestClass2 Set start)
this.fInformationTestClass2 = value;
// *** Start programmer edit section *** (InformationTestClass3.InformationTestClass2 Set end)
// *** End programmer edit section *** (InformationTestClass3.InformationTestClass2 Set end)
}
}
}
}
| 44.54955 | 129 | 0.629727 | [
"MIT"
] | AlexBurmatov/NewPlatform.Flexberry.ORM | NewPlatform.Flexberry.ORM.Test.Objects/InformationTestClass3.cs | 5,081 | C# |
using Senparc.Weixin.MP.Helpers;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
namespace Com.ChinaPalmPay.Platform.RentCar.Common
{
public class NotifyHandler
{
/// <summary>
/// 密钥
/// </summary>
private string Key;
/// <summary>
/// appkey
/// </summary>
private string Appkey;
/// <summary>
/// xmlMap
/// </summary>
private Hashtable XmlMap;
/// <summary>
/// 应答的参数
/// </summary>
public Hashtable Parameters;
/// <summary>
/// debug信息
/// </summary>
private string DebugInfo;
/// <summary>
/// 原始内容
/// </summary>
protected string Content;
private string Charset = "gb2312";
/// <summary>
/// 初始化函数
/// </summary>
public virtual void Init()
{
}
/// <summary>
/// 获取页面提交的get和post参数
/// </summary>
/// <param name="httpContext"></param>
public NotifyHandler(Stream stream)
{
Parameters = new Hashtable();
XmlMap = new Hashtable();
if (stream.Length > 0)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(stream);
XmlNode root = xmlDoc.SelectSingleNode("xml");
XmlNodeList xnl = root.ChildNodes;
foreach (XmlNode xnf in xnl)
{
XmlMap.Add(xnf.Name, xnf.InnerText);
this.SetParameter(xnf.Name, xnf.InnerText);
}
}
}
/// <summary>
/// 获取密钥
/// </summary>
/// <returns></returns>
public string GetKey()
{ return Key; }
/// <summary>
/// 设置密钥
/// </summary>
/// <param name="key"></param>
public void SetKey(string key)
{
this.Key = key;
}
/// <summary>
/// 获取参数值
/// </summary>
/// <param name="parameter"></param>
/// <returns></returns>
public string GetParameter(string parameter)
{
string s = (string)Parameters[parameter];
return (null == s) ? "" : s;
}
/// <summary>
/// 设置参数值
/// </summary>
/// <param name="parameter"></param>
/// <param name="parameterValue"></param>
public void SetParameter(string parameter, string parameterValue)
{
if (parameter != null && parameter != "")
{
if (Parameters.Contains(parameter))
{
Parameters.Remove(parameter);
}
Parameters.Add(parameter, parameterValue);
}
}
/// <summary>
/// 是否财付通签名,规则是:按参数名称a-z排序,遇到空值的参数不参加签名。return boolean
/// </summary>
/// <returns></returns>
public virtual Boolean IsTenpaySign()
{
StringBuilder sb = new StringBuilder();
ArrayList akeys = new ArrayList(Parameters.Keys);
akeys.Sort();
foreach (string k in akeys)
{
string v = (string)Parameters[k];
if (null != v && "".CompareTo(v) != 0
&& "sign".CompareTo(k) != 0 && "key".CompareTo(k) != 0)
{
sb.Append(k + "=" + v + "&");
}
}
sb.Append("key=" + this.GetKey());
string sign = MD5UtilHelper.GetMD5(sb.ToString(), GetCharset()).ToLower();
this.SetDebugInfo(sb.ToString() + " &sign=" + sign);
//debug信息
return GetParameter("sign").ToLower().Equals(sign);
}
/// <summary>
/// 获取debug信息
/// </summary>
/// <returns></returns>
public string GetDebugInfo()
{ return DebugInfo; }
/// <summary>
/// 设置debug信息
/// </summary>
/// <param name="debugInfo"></param>
protected void SetDebugInfo(String debugInfo)
{ this.DebugInfo = debugInfo; }
protected virtual string GetCharset()
{
return "UTF-8";
}
}
}
| 25.970588 | 86 | 0.467044 | [
"MIT"
] | gp15237125756/Blog | Com.ChinaPalmPay.Platform.RentCar/Com.ChinaPalmPay.Platform.RentCar.Common/NotifyHandler.cs | 4,589 | C# |
namespace Microsoft.Azure.PowerShell.Cmdlets.DataProtection.Models.Api202101
{
using static Microsoft.Azure.PowerShell.Cmdlets.DataProtection.Runtime.Extensions;
/// <summary>Azure backup recoveryPoint based restore request</summary>
public partial class AzureBackupRecoveryPointBasedRestoreRequest
{
/// <summary>
/// <c>AfterFromJson</c> will be called after the json deserialization has finished, allowing customization of the object
/// before it is returned. Implement this method in a partial class to enable this behavior
/// </summary>
/// <param name="json">The JsonNode that should be deserialized into this object.</param>
partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.DataProtection.Runtime.Json.JsonObject json);
/// <summary>
/// <c>AfterToJson</c> will be called after the json erialization has finished, allowing customization of the <see cref="Microsoft.Azure.PowerShell.Cmdlets.DataProtection.Runtime.Json.JsonObject"
/// /> before it is returned. Implement this method in a partial class to enable this behavior
/// </summary>
/// <param name="container">The JSON container that the serialization result will be placed in.</param>
partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.DataProtection.Runtime.Json.JsonObject container);
/// <summary>
/// <c>BeforeFromJson</c> will be called before the json deserialization has commenced, allowing complete customization of
/// the object before it is deserialized.
/// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter.
/// Implement this method in a partial class to enable this behavior.
/// </summary>
/// <param name="json">The JsonNode that should be deserialized into this object.</param>
/// <param name="returnNow">Determines if the rest of the deserialization should be processed, or if the method should return
/// instantly.</param>
partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.DataProtection.Runtime.Json.JsonObject json, ref bool returnNow);
/// <summary>
/// <c>BeforeToJson</c> will be called before the json serialization has commenced, allowing complete customization of the
/// object before it is serialized.
/// If you wish to disable the default serialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter.
/// Implement this method in a partial class to enable this behavior.
/// </summary>
/// <param name="container">The JSON container that the serialization result will be placed in.</param>
/// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return
/// instantly.</param>
partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.DataProtection.Runtime.Json.JsonObject container, ref bool returnNow);
/// <summary>
/// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.DataProtection.Runtime.Json.JsonObject into a new instance of <see cref="AzureBackupRecoveryPointBasedRestoreRequest" />.
/// </summary>
/// <param name="json">A Microsoft.Azure.PowerShell.Cmdlets.DataProtection.Runtime.Json.JsonObject instance to deserialize from.</param>
internal AzureBackupRecoveryPointBasedRestoreRequest(Microsoft.Azure.PowerShell.Cmdlets.DataProtection.Runtime.Json.JsonObject json)
{
bool returnNow = false;
BeforeFromJson(json, ref returnNow);
if (returnNow)
{
return;
}
__azureBackupRestoreRequest = new Microsoft.Azure.PowerShell.Cmdlets.DataProtection.Models.Api202101.AzureBackupRestoreRequest(json);
{_recoveryPointId = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.DataProtection.Runtime.Json.JsonString>("recoveryPointId"), out var __jsonRecoveryPointId) ? (string)__jsonRecoveryPointId : (string)RecoveryPointId;}
AfterFromJson(json);
}
/// <summary>
/// Deserializes a <see cref="Microsoft.Azure.PowerShell.Cmdlets.DataProtection.Runtime.Json.JsonNode"/> into an instance of Microsoft.Azure.PowerShell.Cmdlets.DataProtection.Models.Api202101.IAzureBackupRecoveryPointBasedRestoreRequest.
/// Note: the Microsoft.Azure.PowerShell.Cmdlets.DataProtection.Models.Api202101.IAzureBackupRecoveryPointBasedRestoreRequest
/// interface is polymorphic, and the precise model class that will get deserialized is determined at runtime based on the
/// payload.
/// </summary>
/// <param name="node">a <see cref="Microsoft.Azure.PowerShell.Cmdlets.DataProtection.Runtime.Json.JsonNode" /> to deserialize from.</param>
/// <returns>
/// an instance of Microsoft.Azure.PowerShell.Cmdlets.DataProtection.Models.Api202101.IAzureBackupRecoveryPointBasedRestoreRequest.
/// </returns>
public static Microsoft.Azure.PowerShell.Cmdlets.DataProtection.Models.Api202101.IAzureBackupRecoveryPointBasedRestoreRequest FromJson(Microsoft.Azure.PowerShell.Cmdlets.DataProtection.Runtime.Json.JsonNode node)
{
if (!(node is Microsoft.Azure.PowerShell.Cmdlets.DataProtection.Runtime.Json.JsonObject json))
{
return null;
}
// Polymorphic type -- select the appropriate constructor using the discriminator
switch ( json.StringProperty("objectType") )
{
case "AzureBackupRestoreWithRehydrationRequest":
{
return new AzureBackupRestoreWithRehydrationRequest(json);
}
}
return new AzureBackupRecoveryPointBasedRestoreRequest(json);
}
/// <summary>
/// Serializes this instance of <see cref="AzureBackupRecoveryPointBasedRestoreRequest" /> into a <see cref="Microsoft.Azure.PowerShell.Cmdlets.DataProtection.Runtime.Json.JsonNode"
/// />.
/// </summary>
/// <param name="container">The <see cref="Microsoft.Azure.PowerShell.Cmdlets.DataProtection.Runtime.Json.JsonObject"/> container to serialize this object into. If the caller
/// passes in <c>null</c>, a new instance will be created and returned to the caller.</param>
/// <param name="serializationMode">Allows the caller to choose the depth of the serialization. See <see cref="Microsoft.Azure.PowerShell.Cmdlets.DataProtection.Runtime.SerializationMode"/>.</param>
/// <returns>
/// a serialized instance of <see cref="AzureBackupRecoveryPointBasedRestoreRequest" /> as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.DataProtection.Runtime.Json.JsonNode"
/// />.
/// </returns>
public Microsoft.Azure.PowerShell.Cmdlets.DataProtection.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.DataProtection.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.DataProtection.Runtime.SerializationMode serializationMode)
{
container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.DataProtection.Runtime.Json.JsonObject();
bool returnNow = false;
BeforeToJson(ref container, ref returnNow);
if (returnNow)
{
return container;
}
__azureBackupRestoreRequest?.ToJson(container, serializationMode);
AddIf( null != (((object)this._recoveryPointId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.DataProtection.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.DataProtection.Runtime.Json.JsonString(this._recoveryPointId.ToString()) : null, "recoveryPointId" ,container.Add );
AfterToJson(ref container);
return container;
}
}
} | 67.173554 | 305 | 0.690576 | [
"MIT"
] | AverageDesigner/azure-powershell | src/DataProtection/generated/api/Models/Api202101/AzureBackupRecoveryPointBasedRestoreRequest.json.cs | 8,008 | C# |
using Extenso.AspNetCore.Mvc.ExtensoUI;
using Extenso.AspNetCore.Mvc.ExtensoUI.Providers;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace Demo.AspNetCore.Mvc.ExtensoUI.Bootstrap4
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddRazorPages();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseStaticFiles();
app.UseExtensoUI<Bootstrap4UIProvider>();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
endpoints.MapRazorPages();
});
}
}
} | 31.568182 | 106 | 0.637149 | [
"MIT"
] | gordon-matt/Extenso | Demos/Demo.AspNetCore.Mvc.ExtensoUI.Bootstrap4/Startup.cs | 1,391 | C# |
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using RafaelaColabora.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace RafaelaColabora.Data
{
public static class ContextSeed
{
public static async Task SeedRolesAsync(RoleManager<IdentityRole> roleManager)
{
//Seed Roles
await roleManager.CreateAsync(new IdentityRole(Enums.Roles.SuperAdmin.ToString()));
await roleManager.CreateAsync(new IdentityRole(Enums.Roles.Admin.ToString()));
await roleManager.CreateAsync(new IdentityRole(Enums.Roles.Moderator.ToString()));
await roleManager.CreateAsync(new IdentityRole(Enums.Roles.Basic.ToString()));
}
public static void SeedCategories(ApplicationDbContext context)
{
// Look for any students.
if (context.Category.Any())
{
return; // DB has been seeded
}
var categories = new Category[]
{
new Category{ Description= Enums.Categories.Comida.ToString() },
new Category{ Description= Enums.Categories.Eventos.ToString() },
new Category{ Description= Enums.Categories.Ropa.ToString() }
};
foreach (Category c in categories)
{
context.Category.Add(c);
}
context.SaveChanges();
}
public static async Task SeedSuperAdminAsync(UserManager<ApplicationUser> userManager, RoleManager<IdentityRole> roleManager)
{
//Seed Default User
var defaultUser = new ApplicationUser
{
UserName = "superadmin",
Email = "admin@hotmail.com",
FirstName = "Super",
LastName = "Admin",
Cuil = "0000000000",
EmailConfirmed = true,
PhoneNumberConfirmed = true
};
if (userManager.Users.All(u => u.Id != defaultUser.Id))
{
var user = await userManager.FindByEmailAsync(defaultUser.Email);
if (user == null)
{
await userManager.CreateAsync(defaultUser, "Super$Admin$123");
await userManager.AddToRoleAsync(defaultUser, Enums.Roles.Basic.ToString());
await userManager.AddToRoleAsync(defaultUser, Enums.Roles.Moderator.ToString());
await userManager.AddToRoleAsync(defaultUser, Enums.Roles.Admin.ToString());
await userManager.AddToRoleAsync(defaultUser, Enums.Roles.SuperAdmin.ToString());
}
}
}
}
}
| 39.112676 | 133 | 0.586604 | [
"MIT"
] | MauroCominotti/TP_Grupo4_IngWeb | Data/ContextSeed.cs | 2,779 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.IO;
using System.Runtime.InteropServices;
using Xunit;
namespace System.IO.Tests
{
public partial class FileStream_ctor_str_fm_fa_fs
{
[Fact]
public void FileShareDeleteNew()
{
string fileName = GetTestFilePath();
using (FileStream fs = CreateFileStream(fileName, FileMode.Create, FileAccess.ReadWrite, FileShare.Delete))
{
Assert.True(File.Exists(fileName));
File.Delete(fileName);
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
// Prior to 1903 Windows would not delete the filename until the last file handle is closed.
Assert.Equal(PlatformDetection.IsWindows10Version1903OrGreater, !File.Exists(fileName));
}
}
Assert.False(File.Exists(fileName));
}
[Fact]
public void FileShareDeleteNewRename()
{
string fileName = GetTestFilePath();
string newFileName = GetTestFilePath();
using (FileStream fs = CreateFileStream(fileName, FileMode.Create, FileAccess.ReadWrite, FileShare.Delete))
{
Assert.True(File.Exists(fileName));
File.Move(fileName, newFileName);
Assert.False(File.Exists(fileName));
Assert.True(File.Exists(newFileName));
}
}
[Fact]
public void FileShareDeleteExisting()
{
// create the file
string fileName = GetTestFilePath();
using (CreateFileStream(fileName, FileMode.Create, FileAccess.ReadWrite, FileShare.None))
{ }
Assert.True(File.Exists(fileName));
// Open with delete sharing
using (FileStream fs = CreateFileStream(fileName, FileMode.Open, FileAccess.ReadWrite, FileShare.Delete))
{
File.Delete(fileName);
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
// Prior to 1903 Windows would not delete the filename until the last file handle is closed.
Assert.Equal(PlatformDetection.IsWindows10Version1903OrGreater, !File.Exists(fileName));
}
}
Assert.False(File.Exists(fileName));
}
[Fact]
public void FileShareDeleteExistingRename()
{
// create the file
string fileName = GetTestFilePath();
using (CreateFileStream(fileName, FileMode.Create, FileAccess.ReadWrite, FileShare.None))
{ }
Assert.True(File.Exists(fileName));
string newFileName = GetTestFilePath();
using (FileStream fs = CreateFileStream(fileName, FileMode.Create, FileAccess.ReadWrite, FileShare.Delete))
{
Assert.True(File.Exists(fileName));
File.Move(fileName, newFileName);
Assert.False(File.Exists(fileName));
Assert.True(File.Exists(newFileName));
}
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // file sharing restriction limitations on Unix
public void FileShareDeleteExistingMultipleClients()
{
// create the file
string fileName = GetTestFilePath();
using (FileStream fs = CreateFileStream(fileName, FileMode.Create, FileAccess.ReadWrite, FileShare.None))
{
fs.WriteByte(0);
}
Assert.True(File.Exists(fileName), $"'{fileName}' should exist after creating and closing filestream.");
using (FileStream fs1 = CreateFileStream(fileName, FileMode.Open, FileAccess.ReadWrite, FileShare.Delete | FileShare.ReadWrite))
{
using (FileStream fs2 = CreateFileStream(fileName, FileMode.Open, FileAccess.ReadWrite, FileShare.Delete | FileShare.ReadWrite))
{
File.Delete(fileName);
Assert.Equal(0, fs2.ReadByte());
// Prior to 1903 Windows would not delete the filename until the last file handle is closed.
Assert.Equal(PlatformDetection.IsWindows10Version1903OrGreater, !File.Exists(fileName));
}
Assert.Equal(0, fs1.ReadByte());
fs1.WriteByte(0xFF);
if (PlatformDetection.IsWindows10Version1903OrGreater)
{
// On 1903 the filename is immediately released after delete is called
Assert.Throws<FileNotFoundException>(() => CreateFileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Delete | FileShare.ReadWrite));
}
else
{
// Any attempt to reopen a file in pending-delete state will return Access-denied
Assert.Throws<UnauthorizedAccessException>(() => CreateFileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Delete | FileShare.ReadWrite));
Assert.True(File.Exists(fileName), $"'{fileName}' should still exist after calling delete with inner filestream closed.");
}
}
Assert.False(File.Exists(fileName));
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // file sharing restriction limitations on Unix
public void FileShareWithoutDeleteThrows()
{
string fileName = GetTestFilePath();
string newFileName = GetTestFilePath();
// Create without delete sharing
using (FileStream fs = CreateFileStream(fileName, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite))
{
FSAssert.ThrowsSharingViolation(() => File.Delete(fileName));
FSAssert.ThrowsSharingViolation(() => File.Move(fileName, newFileName));
}
Assert.True(File.Exists(fileName));
}
}
}
| 41.326667 | 169 | 0.594289 | [
"MIT"
] | 71221-maker/runtime | src/libraries/System.IO.FileSystem/tests/FileStream/ctor_str_fm_fa_fs.delete.cs | 6,199 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using Xunit;
namespace FunK.Tests
{
using static F;
public class ResultTest
{
Func<int, int> doubleTheIn = x => x * 2;
Func<int, Func<int, Result<int>>> checkGreaterThan = x => val => val > x ? Result(val) : Result<int>(new InvalidProgramException($"Should be greater than {x}"));
Func<int, string> randomString = len => len.ToString();
Func<string, Result<string>> toRes = x => Result(x);
Func<string, int> length = x => x.Length;
Func<int, Result<int>> getInt = x => Result(x);
public Result<int> Test()
=> getInt(1)
.Map(doubleTheIn)
.Map(randomString)
.Bind(toRes)
.Map(length);
[Fact]
public void Test2()
{
var checkGreaterThan5 = checkGreaterThan(5);
var checkGreaterThan1 = checkGreaterThan(1);
var res = getInt(6)
.Bind(checkGreaterThan1)
.Map(doubleTheIn)
.Bind(checkGreaterThan5)
.Map(randomString)
.Map(length);
Assert.True(true);
}
}
}
| 27.911111 | 169 | 0.521497 | [
"MIT"
] | juanpablocruz/FunK | Tests/Result/ResultTest.cs | 1,258 | C# |
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using PlasticMetal.MobileSuit;
using PlasticMetal.MobileSuit.Core;
namespace PlasticMetal.MobileSuitDemo
{
[SuitInfo("Demo")]
public class Client
{
/// <summary>
/// Initialize a client
/// </summary>
public Client(IIOHub io)
{
IO = io;
}
public IIOHub IO { get; }
public void Loop([SuitInjected] CancellationToken token)
{
for (;;)
if (token.IsCancellationRequested)
return;
}
[SuitAlias("H")]
[SuitInfo("hello command.")]
public void Hello()
{
IO.WriteLine("Hello! MobileSuit!");
}
[SuitAlias("Sl")]
[SuitInfo("Sleep {-n name (, -t hours, -s)}")]
public void Sleep(SleepArgument argument)
{
var nameChain = "";
foreach (var item in argument.Name) nameChain += item;
if (nameChain == "") nameChain = "No one";
if (argument.IsSleeping)
IO.WriteLine(nameChain + " has been sleeping for " + argument.SleepTime + " hour(s).");
else
IO.WriteLine(nameChain + " is not sleeping.");
}
public static object NumberConvert(string arg)
{
return int.Parse(arg);
}
[SuitAlias("Sn")]
public void ShowNumber(int i)
{
IO.WriteLine(i.ToString());
}
[SuitAlias("Sn2")]
public void ShowNumber2(int i, int[] j
)
{
IO.WriteLine(i.ToString());
IO.WriteLine(j.Length >= 1 ? j[0].ToString() : "");
}
[SuitAlias("GE")]
public void GoodEvening(string[] arg)
{
IO.WriteLine("Good Evening, " + (arg.Length >= 1 ? arg[0] : ""));
}
[SuitAlias("GE2")]
public void GoodEvening2(string arg0, string[] args)
{
IO.WriteLine("Good Evening, " + arg0 + (args.Length >= 1 ? " and " + args[0] : ""));
}
[SuitAlias("GM")]
public void GoodMorning(GoodMorningParameter arg)
{
IO.WriteLine("Good morning," + arg.name);
}
[SuitAlias("GM2")]
public void GoodMorning2(string arg, GoodMorningParameter arg1)
{
IO.WriteLine("Good morning, " + arg + " and " + arg1.name);
}
public string Bye(string name)
{
IO.WriteLine($"Bye! {name}");
return "bye";
}
public string Bye()
{
;
return $"bye, {IO.ReadLine("Name", "foo", true)}";
}
public async Task<string> HelloAsync()
{
await Task.Delay(10);
return "Hello from async Task<string>!";
}
public async Task<string> HelloAsync(string name)
{
await Task.Delay(10);
return $"Hello, {name}, from async Task<string>!";
}
public class SleepArgument : AutoDynamicParameter
{
[Option("n")]
[AsCollection]
[WithDefault]
public List<string> Name { get; set; } = new();
[Option("t")] [WithDefault] public int SleepTime { get; set; } = 0;
[Switch("s")] public bool IsSleeping { get; set; }
}
public class GoodMorningParameter : IDynamicParameter
{
public string name = "foo";
/**
* Parse this Parameter from String[].
*
* @param options String[] to parse from.
* @return Whether the parsing is successful
*/
public bool Parse(IReadOnlyList<string> args, SuitContext context)
{
if (args.Count == 1)
{
name = args[0];
return true;
}
return args.Count == 0;
}
}
}
} | 26.743421 | 103 | 0.483149 | [
"MIT"
] | Plastic-Metal/MobileSu | demo/Client.cs | 4,067 | C# |
using System.Linq;
using System.Threading.Tasks;
using DShop.Common.Handlers;
using DShop.Common.RabbitMq;
using DShop.Messages.Events.Customers;
using DShop.Services.Storage.Framework;
using DShop.Services.Storage.Models.Customers;
using DShop.Services.Storage.Repositories;
using DShop.Services.Storage.Services;
namespace DShop.Services.Storage.Handlers.Customers
{
public class ProductAddedToCartHandler : IEventHandler<ProductAddedToCart>
{
private readonly ICache _cache;
private readonly IProductsRepository _productsRepository;
public ProductAddedToCartHandler(ICache cache,
IProductsRepository productsRepository)
{
_cache = cache;
_productsRepository = productsRepository;
}
public async Task HandleAsync(ProductAddedToCart @event, ICorrelationContext context)
{
var cart = await _cache.GetCartAsync(@event.CustomerId);
var product = await _productsRepository.GetAsync(@event.ProductId);
var item = cart.Items.SingleOrDefault(x => x.ProductId == @event.ProductId);
if (item == null)
{
cart.Items.Add(new CartItem
{
ProductId = product.Id,
ProductName = product.Name,
UnitPrice = product.Price,
Quantity = @event.Quantity
});
}
else
{
item.Quantity += @event.Quantity;
}
await _cache.SetCartAsync(@event.CustomerId, cart);
}
}
} | 34.382979 | 93 | 0.620668 | [
"MIT"
] | devmentors/DNC-DShop.Services.Storage | src/DShop.Services.Storage/Handlers/Customers/ProductAddedToCartHandler.cs | 1,616 | C# |
namespace _04_FixEmails
{
using System;
using System.Collections.Generic;
using System.Linq;
public class StartUp
{
public static void Main()
{
var result = new Dictionary<string, string>();
string name = Console.ReadLine();
while (name!="stop")
{
string email = Console.ReadLine();
if (email.EndsWith("uk")||email.EndsWith("us"))
{
name = Console.ReadLine();
continue;
}
else
{
result[name] = email;
}
name = Console.ReadLine();
}
foreach (var item in result)
{
Console.WriteLine($"{item.Key} -> {item.Value}");
}
}
}
} | 22.487179 | 65 | 0.415051 | [
"MIT"
] | MrPIvanov/SoftUni | 02-Progr Fundamentals/18-Dictionaries, Lambda Expressions and LINQ - Exercises/18-DicLambdEx/04-FixEmails/StartUp.cs | 879 | C# |
using AutoMapper;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Formatters;
using Microsoft.AspNetCore.Mvc.Internal;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace SF.Web.Base.Mappers.ModelBinders
{
public class MappedBodyModelBinder : IModelBinder
{
private readonly IModelMetadataProvider _modelMetadataProvider;
private readonly IMapper _mapper;
private readonly IList<IInputFormatter> _formatters;
private readonly Func<Stream, Encoding, TextReader> _readerFactory;
/// <summary>
/// Creates a new <see cref="BodyModelBinder"/>.
/// </summary>
/// <param name="formatters">The list of <see cref="IInputFormatter"/>.</param>
/// <param name="readerFactory">
/// The <see cref="IHttpRequestStreamReaderFactory"/>, used to create <see cref="System.IO.TextReader"/>
/// instances for reading the request body.
/// </param>
public MappedBodyModelBinder(IModelMetadataProvider modelMetadataProvider, IMapper mapper, IList<IInputFormatter> formatters, IHttpRequestStreamReaderFactory readerFactory)
{
if (modelMetadataProvider == null)
{
throw new ArgumentNullException(nameof(modelMetadataProvider));
}
if (mapper == null)
{
throw new ArgumentNullException(nameof(mapper));
}
if (formatters == null)
{
throw new ArgumentNullException(nameof(formatters));
}
if (readerFactory == null)
{
throw new ArgumentNullException(nameof(readerFactory));
}
_modelMetadataProvider = modelMetadataProvider;
_mapper = mapper;
_formatters = formatters;
_readerFactory = readerFactory.CreateReader;
}
/// <inheritdoc />
public async Task BindModelAsync(ModelBindingContext bindingContext)
{
if (bindingContext == null)
{
throw new ArgumentNullException(nameof(bindingContext));
}
// Special logic for body, treat the model name as string.Empty for the top level
// object, but allow an override via BinderModelName. The purpose of this is to try
// and be similar to the behavior for POCOs bound via traditional model binding.
string modelBindingKey;
if (bindingContext.IsTopLevelObject)
{
modelBindingKey = bindingContext.BinderModelName ?? string.Empty;
}
else
{
modelBindingKey = bindingContext.ModelName;
}
var httpContext = bindingContext.HttpContext;
// Get the mapping source type and its metadata info
var controllerParameters = bindingContext.ActionContext.ActionDescriptor.Parameters.OfType<ControllerParameterDescriptor>();
ControllerParameterDescriptor mapFromBodyParameter = null;
MapFromBodyAttribute mapFromBodyAttribute = null;
foreach (var param in controllerParameters)
{
mapFromBodyAttribute = param.ParameterInfo.GetCustomAttribute<MapFromBodyAttribute>();
if (mapFromBodyAttribute != null)
{
mapFromBodyParameter = param;
break;
}
}
// Set the formatter context for the mapped parameter if found
InputFormatterContext formatterContext = null;
if (mapFromBodyParameter == null || mapFromBodyAttribute == null)
{
formatterContext = new InputFormatterContext(
httpContext,
modelBindingKey,
bindingContext.ModelState,
bindingContext.ModelMetadata,
_readerFactory);
}
else
{
var mappedModelMetadata = _modelMetadataProvider.GetMetadataForType(mapFromBodyAttribute.SourceType);
formatterContext = new InputFormatterContext(
httpContext,
modelBindingKey,
bindingContext.ModelState,
mappedModelMetadata,
_readerFactory);
}
var formatter = (IInputFormatter)null;
for (var i = 0; i < _formatters.Count; i++)
{
if (_formatters[i].CanRead(formatterContext))
{
formatter = _formatters[i];
break;
}
}
if (formatter == null)
{
var message = string.Format("Unsupported content type '{0}'.", httpContext.Request.ContentType);
var exception = new UnsupportedContentTypeException(message);
bindingContext.ModelState.AddModelError(modelBindingKey, exception, bindingContext.ModelMetadata);
return;
}
try
{
var previousCount = bindingContext.ModelState.ErrorCount;
var result = await formatter.ReadAsync(formatterContext);
var model = result.Model;
if (result.HasError)
{
// Formatter encountered an error. Do not use the model it returned.
return;
}
if (mapFromBodyParameter != null && mapFromBodyAttribute != null)
{
// Map the model to the desired model in the action
model = _mapper.Map(model, mapFromBodyAttribute.SourceType, bindingContext.ModelType);
}
bindingContext.Result = ModelBindingResult.Success(model);
return;
}
catch (Exception ex)
{
bindingContext.ModelState.AddModelError(modelBindingKey, ex, bindingContext.ModelMetadata);
return;
}
}
}
}
| 37.838323 | 180 | 0.576832 | [
"Apache-2.0"
] | ZHENGZHENGRONG/SF-Boilerplate | SF.Web/Base/Mappers/ModelBinders/MappedBodyModelBinder.cs | 6,321 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Serilog;
using Serilog.Events;
namespace REAccess.Mobile.Api
{
public class Program
{
public static void Main(string[] args)
{
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.MinimumLevel.Override("Microsoft", LogEventLevel.Information)
.Enrich.FromLogContext()
.WriteTo.Console()
.WriteTo.File(Path.Combine("Logs", "REAccess_Mobile.log"), rollingInterval: RollingInterval.Day)
.CreateLogger();
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
| 30 | 111 | 0.631579 | [
"Apache-2.0"
] | brokensnow/Marven | code/backend/REAccess.Mobile.Api/Program.cs | 1,140 | C# |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using Microsoft.Azure.Commands.Batch.Properties;
using Microsoft.Azure.Management.Batch;
using Microsoft.Azure.Management.Batch.Models;
using Microsoft.WindowsAzure.Storage.Blob;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using Microsoft.Rest.Azure;
namespace Microsoft.Azure.Commands.Batch.Models
{
public partial class BatchClient
{
public virtual void DeleteApplicationPackage(string resourceGroupName, string accountName, string applicationId, string version)
{
if (string.IsNullOrEmpty(resourceGroupName))
{
// use resource mgr to see if account exists and then use resource group name to do the actual lookup
resourceGroupName = GetGroupForAccount(accountName);
}
BatchManagementClient.ApplicationPackage.Delete(resourceGroupName, accountName, applicationId, version);
}
public virtual PSApplicationPackage GetApplicationPackage(string resourceGroupName, string accountName, string applicationId, string version)
{
// single account lookup - find its resource group if not specified
if (string.IsNullOrEmpty(resourceGroupName))
{
resourceGroupName = GetGroupForAccount(accountName);
}
ApplicationPackage response = BatchManagementClient.ApplicationPackage.Get(
resourceGroupName,
accountName,
applicationId,
version);
return this.ConvertGetApplicationPackageResponseToApplicationPackage(response);
}
public virtual PSApplicationPackage UploadAndActivateApplicationPackage(
string resourceGroupName,
string accountName,
string applicationId,
string version,
string filePath,
string format,
bool activateOnly)
{
if (string.IsNullOrEmpty(resourceGroupName))
{
// use resource mgr to see if account exists and then use resource group name to do the actual lookup
resourceGroupName = GetGroupForAccount(accountName);
}
if (activateOnly)
{
// If the package has already been uploaded but wasn't activated.
ActivateApplicationPackage(resourceGroupName, accountName, applicationId, version, format, Resources.FailedToActivate);
}
else
{
if (string.IsNullOrEmpty(filePath))
{
throw new ArgumentNullException("filePath", Resources.NewApplicationPackageNoPathSpecified);
}
if (!File.Exists(filePath))
{
throw new FileNotFoundException(string.Format(Resources.FileNotFound, filePath), filePath);
}
// Else create Application Package and upload.
bool appPackageAlreadyExists;
var storageUrl = GetStorageUrl(resourceGroupName, accountName, applicationId, version, out appPackageAlreadyExists);
if (appPackageAlreadyExists)
{
CheckApplicationAllowsUpdates(resourceGroupName, accountName, applicationId, version);
}
UploadFileToApplicationPackage(resourceGroupName, accountName, applicationId, version, filePath, storageUrl, appPackageAlreadyExists);
ActivateApplicationPackage(resourceGroupName, accountName, applicationId, version, format, Resources.UploadedApplicationButFailedToActivate);
}
return GetApplicationPackage(resourceGroupName, accountName, applicationId, version);
}
private void UploadFileToApplicationPackage(
string resourceGroupName,
string accountName,
string applicationId,
string version,
string filePath,
string storageUrl,
bool appPackageAlreadyExists)
{
try
{
CloudBlockBlob blob = new CloudBlockBlob(new Uri(storageUrl));
blob.UploadFromFile(filePath, FileMode.Open);
}
catch (Exception exception)
{
// If the application package has already been created we don't want to delete the application package mysteriously.
if (appPackageAlreadyExists)
{
// If we are creating a new application package and the upload fails we should delete the application package.
try
{
DeleteApplicationPackage(resourceGroupName, accountName, applicationId, version);
}
catch
{
// Need to throw if we fail to delete the application while attempting to clean it up.
var deleteMessage = string.Format(Resources.FailedToUploadAndDelete, filePath, exception.Message);
throw new NewApplicationPackageException(deleteMessage, exception);
}
}
// Need to throw if we fail to upload the file's content.
var uploadMessage = string.Format(Resources.FailedToUpload, filePath, exception.Message);
throw new NewApplicationPackageException(uploadMessage, exception);
}
}
private void ActivateApplicationPackage(string resourceGroupName, string accountName, string applicationId, string version, string format, string errorMessageFormat)
{
try
{
BatchManagementClient.ApplicationPackage.Activate(
resourceGroupName,
accountName,
applicationId,
version,
format);
}
catch (Exception exception)
{
string message = string.Format(errorMessageFormat, applicationId, version, exception.Message);
throw new NewApplicationPackageException(message, exception);
}
}
private string GetStorageUrl(string resourceGroupName, string accountName, string applicationId, string version, out bool didCreateAppPackage)
{
try
{
// Checks to see if the package exists
ApplicationPackage response = BatchManagementClient.ApplicationPackage.Get(
resourceGroupName,
accountName,
applicationId,
version);
didCreateAppPackage = false;
return response.StorageUrl;
}
catch (CloudException exception)
{
// If the application package is not found we want to create a new application package.
if (exception.Response.StatusCode != HttpStatusCode.NotFound)
{
var message = string.Format(Resources.FailedToGetApplicationPackage, applicationId, version, exception.Message);
throw new CloudException(message, exception);
}
}
try
{
ApplicationPackage addResponse = BatchManagementClient.ApplicationPackage.Create(
resourceGroupName,
accountName,
applicationId,
version);
// If Application was created we need to return a flag.
didCreateAppPackage = true;
return addResponse.StorageUrl;
}
catch (Exception exception)
{
var message = string.Format(Resources.FailedToAddApplicationPackage, applicationId, version, exception.Message);
throw new NewApplicationPackageException(message, exception);
}
}
private PSApplicationPackage ConvertGetApplicationPackageResponseToApplicationPackage(ApplicationPackage response)
{
return new PSApplicationPackage()
{
Format = response.Format,
StorageUrl = response.StorageUrl,
StorageUrlExpiry = response.StorageUrlExpiry.Value,
State = response.State.Value,
Id = response.Id,
Version = response.Version,
LastActivationTime = response.LastActivationTime,
};
}
private static IList<PSApplicationPackage> ConvertApplicationPackagesToPsApplicationPackages(IEnumerable<ApplicationPackage> applicationPackages)
{
return applicationPackages.Select(applicationPackage => new PSApplicationPackage
{
Format = applicationPackage.Format,
LastActivationTime = applicationPackage.LastActivationTime,
State = applicationPackage.State.Value,
Version = applicationPackage.Version,
}).ToList();
}
}
}
| 43.729614 | 174 | 0.585533 | [
"MIT"
] | FosterMichelle/azure-powershell | src/ResourceManager/AzureBatch/Commands.Batch/Models/BatchClient.ApplicationPackages.cs | 9,959 | C# |
namespace DesignPatterns
{
public interface IPagamento
{
Pagamento RealizarPagamento(Pedido pedido, Pagamento pagamento);
}
} | 20.857143 | 72 | 0.712329 | [
"MIT"
] | YuriSiman/fundamentals-software-architecture | DesignPatterns/02 - Structural/2.2 - Facade/Domain/IPagamento.cs | 148 | C# |
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
namespace Glean.App
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
}
}
| 17.944444 | 42 | 0.69969 | [
"MIT"
] | armadilloNik/Glean | src/Glean.App/App.xaml.cs | 325 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNextGen.ContainerService.V20200101.Inputs
{
/// <summary>
/// Access profile for managed cluster API server.
/// </summary>
public sealed class ManagedClusterAPIServerAccessProfileArgs : Pulumi.ResourceArgs
{
[Input("authorizedIPRanges")]
private InputList<string>? _authorizedIPRanges;
/// <summary>
/// Authorized IP Ranges to kubernetes API server.
/// </summary>
public InputList<string> AuthorizedIPRanges
{
get => _authorizedIPRanges ?? (_authorizedIPRanges = new InputList<string>());
set => _authorizedIPRanges = value;
}
/// <summary>
/// Whether to create the cluster as a private cluster or not.
/// </summary>
[Input("enablePrivateCluster")]
public Input<bool>? EnablePrivateCluster { get; set; }
public ManagedClusterAPIServerAccessProfileArgs()
{
}
}
}
| 30.926829 | 90 | 0.65142 | [
"Apache-2.0"
] | pulumi/pulumi-azure-nextgen | sdk/dotnet/ContainerService/V20200101/Inputs/ManagedClusterAPIServerAccessProfileArgs.cs | 1,268 | C# |
namespace BTCTrader.APIClient.Models
{
public class UserTransInput
{
public string Sort { get; set; } // sorting by desc, asc
public int Offset { get; set; } // number of skiping records
public int Limit { get; set; } // number of limit query
}
}
| 28.4 | 68 | 0.623239 | [
"MIT"
] | BTCTrader/broker-api-csharp | APIClient/Models/UserTransInput.cs | 286 | C# |
using System;
namespace _03.Ferrari
{
public class StartUp
{
public static void Main()
{
string ferrariName = typeof(global::Ferrari).Name;
string iCarInterfaceName = typeof(ICar).Name;
bool isCreated = typeof(ICar).IsInterface;
if (!isCreated)
{
throw new Exception("No interface ICar was created");
}
var driver = Console.ReadLine();
ICar ferrari = new global::Ferrari(driver);
Console.WriteLine(ferrari.ToString());
}
}
}
| 23.6 | 69 | 0.542373 | [
"MIT"
] | IvelinMarinov/SoftUni | 06. OOP Advanced - Jul2017/01. Interfaces and Abstraction - Exercise/03. Ferrari/StartUp.cs | 592 | C# |
using System.Text.Json.Serialization;
namespace Essensoft.AspNetCore.Payment.Alipay.Domain
{
/// <summary>
/// KbItemInfo Data Structure.
/// </summary>
public class KbItemInfo : AlipayObject
{
/// <summary>
/// 店铺人气值,共4个等级,1,2,3,4
/// </summary>
[JsonPropertyName("avg_pop_value")]
public string AvgPopValue { get; set; }
/// <summary>
/// 开卖时间
/// </summary>
[JsonPropertyName("begin_time")]
public string BeginTime { get; set; }
/// <summary>
/// 结束时间
/// </summary>
[JsonPropertyName("end_time")]
public string EndTime { get; set; }
/// <summary>
/// 扩展信息,json格式
/// </summary>
[JsonPropertyName("ext_info")]
public string ExtInfo { get; set; }
/// <summary>
/// 商品ID
/// </summary>
[JsonPropertyName("item_id")]
public string ItemId { get; set; }
/// <summary>
/// 商品logo图片
/// </summary>
[JsonPropertyName("logo")]
public string Logo { get; set; }
/// <summary>
/// 商品原价。
/// </summary>
[JsonPropertyName("original_price")]
public string OriginalPrice { get; set; }
/// <summary>
/// 当前库存
/// </summary>
[JsonPropertyName("quota")]
public string Quota { get; set; }
/// <summary>
/// 优惠价
/// </summary>
[JsonPropertyName("sale_price")]
public string SalePrice { get; set; }
/// <summary>
/// 商品所属店铺距离当前用户距离
/// </summary>
[JsonPropertyName("shop_distance")]
public string ShopDistance { get; set; }
/// <summary>
/// 商品所属店铺ID
/// </summary>
[JsonPropertyName("shop_id")]
public string ShopId { get; set; }
/// <summary>
/// 商品所属店铺名称
/// </summary>
[JsonPropertyName("shop_name")]
public string ShopName { get; set; }
/// <summary>
/// 商品状态,SOLD_OUT:售罄,SELL_ING:进行中
/// </summary>
[JsonPropertyName("status")]
public string Status { get; set; }
/// <summary>
/// 商品标题
/// </summary>
[JsonPropertyName("title")]
public string Title { get; set; }
/// <summary>
/// 是否置顶,1:置顶,0:非置顶
/// </summary>
[JsonPropertyName("top")]
public string Top { get; set; }
/// <summary>
/// 总库存
/// </summary>
[JsonPropertyName("total_quota")]
public string TotalQuota { get; set; }
/// <summary>
/// 商品详情页地址
/// </summary>
[JsonPropertyName("url")]
public string Url { get; set; }
}
}
| 24.707965 | 52 | 0.487106 | [
"MIT"
] | LuohuaRain/payment | src/Essensoft.AspNetCore.Payment.Alipay/Domain/KbItemInfo.cs | 3,014 | C# |
using System;
namespace Accretion.Intervals.Tests
{
public readonly struct DoubleComparerByExponent : IBoundaryValueComparer<double>
{
public int Compare(double x, double y)
{
static double Normalize(double exp) => exp switch
{
double.PositiveInfinity => Math.Log10(double.MaxValue) + 1,
double.NegativeInfinity => Math.Log10(double.MinValue) - 1,
_ => exp
};
var xExp = Normalize(Math.Log10(x));
var yExp = Normalize(Math.Log10(y));
return (xExp, yExp) switch
{
(double.NaN, double.NaN) => ComparingValues.IsEqual,
(double.NaN, _) => ComparingValues.IsLess,
(_, double.NaN) => ComparingValues.IsGreater,
_ => (int)xExp - (int)yExp
};
}
public int GetHashCode(double value) => (int)Math.Log10(value);
public bool IsInvalidBoundaryValue(double value) => value <= 0 || double.IsNaN(value);
public string ToString(double value, string format, IFormatProvider formatProvider) => Math.Truncate(Math.Log10(value)).ToString(format, formatProvider).Replace("-0", "0");
}
}
| 34.694444 | 180 | 0.576461 | [
"MIT"
] | SingleAccretion/Accretion.Intervals | Accretion.Intervals.Tests/TestingTypes/TestTypes/DoubleComparerByExponent.cs | 1,251 | C# |
namespace ScottPlot
{
public enum ErrorAction
{
Render,
SkipRender,
DebugLog,
ShowErrorOnPlot,
ThrowException
}
}
| 13.916667 | 27 | 0.550898 | [
"MIT"
] | Jmerk523/ScottPlot | src/ScottPlot/Enums/ErrorAction.cs | 169 | C# |
using System;
using System.Globalization;
namespace RssClient
{
public static class StringParser
{
/// <summary>
/// Method for converting string to DateTime
/// </summary>
public static DateTime? TryParseDateTime(string dateTime, CultureInfo cultureInfo = null)
{
if (string.IsNullOrWhiteSpace(dateTime)) return null;
var dateTimeFormat = cultureInfo?.DateTimeFormat ?? DateTimeFormatInfo.CurrentInfo;
if (!DateTimeOffset.TryParse(dateTime, dateTimeFormat, DateTimeStyles.None, out var dt))
{
if (dateTime.Contains(","))
{
int pos = dateTime.IndexOf(',') + 1;
string newdtstring = dateTime.Substring(pos).Trim();
DateTimeOffset.TryParse(newdtstring, dateTimeFormat, DateTimeStyles.None, out dt);
}
}
if (dt == default(DateTimeOffset))
return null;
return dt.UtcDateTime;
}
/// <summary>
/// Method for converting string to DateTime
/// </summary>
/// <param name="dateTime">string to convert from</param>
/// <param name="language">language to convert according to</param>
public static DateTime? TryParseDateTime(string dateTime, string language)
{
CultureInfo culture;
try
{
culture = new CultureInfo(language);
}
catch
{
culture = null;
}
return TryParseDateTime(dateTime, culture);
}
/// <summary>
/// Method for converting string to int
/// </summary>
/// <param name="strNum">number as string</param>
public static int? TryParseInt(string strNum)
{
if (!int.TryParse(strNum, out int result))
return null;
return result;
}
}
} | 30.769231 | 102 | 0.5375 | [
"MIT"
] | mynameiskate/RSS-client | RssClient/FeedParsers/StringParser.cs | 2,002 | C# |
// Generated by Fuzzlyn v1.2 on 2021-08-16 12:33:10
// Run on .NET 6.0.0-dev on X64 Windows
// Seed: 9553480996520307401
// Reduced from 6.6 KiB to 0.5 KiB in 00:00:12
// Debug: Outputs 0
// Release: Outputs 1
struct S0
{
public bool F0;
}
struct S1
{
public bool F1;
public int F2;
public byte F7;
public S0 F8;
public S1(bool f1): this()
{
F1 = f1;
}
}
struct S2
{
public S1 F0;
public S2(S1 f0): this()
{
F0 = f0;
}
}
public class Program
{
public static void Main()
{
S2 vr0 = new S2(new S1(true));
System.Console.WriteLine(vr0.F0.F1);
System.Console.WriteLine(vr0.F0.F2);
}
}
| 16.285714 | 51 | 0.574561 | [
"MIT"
] | jakobbotsch/Fuzzlyn | examples/reduced/9553480996520307401.cs | 684 | C# |
namespace Toe.Transformations
{
public class TransformationZY : AbstractTransformation
{
public static readonly TransformationZY Instance = new TransformationZY();
public static readonly Quaternion Quaternion = new Quaternion(0.5f, 0.5f, 0.5f, 0.5f);
public static readonly Matrix4 Matrix = new Matrix4(0f, 1f, 0f, 0f, 0f, 0f, 1f, 0f, 1f, 0f, 0f, 1f, 0f, 0f, 0f,
1f);
public override Matrix4 GetMatrix()
{
return Matrix;
}
public override Quaternion GetQuaternion()
{
return Quaternion;
}
public override Vector3 Transform(Vector3 v)
{
return new Vector3(v.Z, v.X, v.Y);
}
public override void Transform(ref Vector3 v, out Vector3 res)
{
res = new Vector3(v.Z, v.X, v.Y);
}
public override Vector4 Transform(Vector4 v)
{
return new Vector4(v.Z, v.X, v.Y, v.W);
}
public override void Transform(ref Vector4 v, out Vector4 res)
{
res = new Vector4(v.Z, v.X, v.Y, v.W);
}
public override string ToString()
{
return "ZY";
}
}
} | 26.76087 | 119 | 0.547522 | [
"MIT"
] | gleblebedev/Toe.Math | src/Toe.Math/Transformations/TransformationZY.cs | 1,231 | C# |
//http://blogs.microsoft.co.il/blogs/alex_golesh/archive/2008/07/15/silverlight-tip-how-to-reflect-scriptobject-content-in-runtime.aspx
#if SILVERLIGHT
namespace Caliburn.PresentationFramework.ApplicationModel
{
using System;
using System.Collections.Generic;
using System.Windows.Browser;
using Caliburn.Core;
using Core.Logging;
/// <summary>
/// An implementation of <see cref="IStateManager"/> that stores state in the browser's URL.
/// Note: This implementation requires the presence of the ASP.NET ScriptManager.
/// </summary>
public class DeepLinkStateManager : PropertyChangedBase, IStateManager
{
static readonly ILog Log = LogManager.GetLog(typeof(DeepLinkStateManager));
readonly Dictionary<string, string> state = new Dictionary<string, string>();
string stateName;
bool isLoadingState, isSavingState, isInitialized;
/// <summary>
/// Occurs after the state was loaded from the backing store.
/// </summary>
public event EventHandler AfterStateLoad = delegate { };
/// <summary>
/// Occurs before the state is committed to the backing store.
/// </summary>
public event EventHandler BeforeStateCommit = delegate { };
/// <summary>
/// Initializes the backing store.
/// </summary>
/// <param name="stateName">Name of the state.</param>
/// <returns></returns>
public virtual bool Initialize(string stateName)
{
if(isInitialized)
return isInitialized;
try
{
Log.Info("Initializing the deep link state manager.");
var hostID = HtmlPage.Plugin.Id;
if(string.IsNullOrEmpty(hostID))
return false;
this.stateName = stateName ?? string.Empty;
HtmlPage.RegisterScriptableObject("DeepLinker", this);
string initScript = @"
ReflectProperties = function(obj)
{
var props = new Array();
for (var s in obj)
{
if (typeof(obj[s]) != 'function')
{
props[props.length] = s;
}
}
return props;
}
ReflectMethods = function(obj)
{
var methods = new Array();
for (var s in obj)
{
if (typeof(obj[s]) == 'function')
{
methods[methods.length] = s;
}
}
return methods;
}
var __navigateHandler = new Function('obj','args','document.getElementById(\'" + hostID + @"\').content.DeepLinker.HandleNavigate(args.get_state())');
Sys.Application.add_navigate(__navigateHandler);
__navigateHandler(this, new Sys.HistoryEventArgs(Sys.Application._state));
";
Log.Info("Injecting javascript.");
HtmlPage.Window.Eval(initScript);
isInitialized = true;
}
catch(Exception ex)
{
Log.Error(ex);
}
return isInitialized;
}
/// <summary>
/// Inserts or updates a value in the state.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
public virtual void InsertOrUpdate(string key, string value)
{
if(isLoadingState) return;
state[key] = value;
}
/// <summary>
/// Gets the value with the specified key.
/// </summary>
/// <param name="key">The key.</param>
/// <returns></returns>
public virtual string Get(string key)
{
string value;
state.TryGetValue(key, out value);
return value;
}
/// <summary>
/// Removes the value with the specified key.
/// </summary>
/// <param name="key">The key.</param>
/// <returns></returns>
public virtual bool Remove(string key)
{
if(isLoadingState) return false;
return state.Remove(key);
}
/// <summary>
/// Commits the changes to the backing store.
/// </summary>
/// <param name="stateName">Name of the state.</param>
/// <returns></returns>
public virtual bool CommitChanges(string stateName)
{
if(isLoadingState || isSavingState) return false;
isSavingState = true;
BeforeStateCommit(this, EventArgs.Empty);
try
{
string script = "Sys.Application.addHistoryPoint({";
foreach(var pair in state)
{
if(pair.Value == null)
{
script = script + string.Format("{0}:null, ", pair.Key);
}
else
{
script = script + string.Format("{0}:'{1}', ", pair.Key, pair.Value);
}
}
script = script.Remove(script.Length - 2);
script += string.Format("}}, '{0}');", stateName ?? this.stateName);
HtmlPage.Window.Eval(script);
return true;
}
catch(Exception ex)
{
Log.Error(ex);
return false;
}
finally
{
isSavingState = false;
}
}
/// <summary>
/// Handles a navigation event signaled by the browser.
/// </summary>
/// <param name="newState">The new state.</param>
[ScriptableMember]
public virtual void HandleNavigate(ScriptObject newState)
{
Log.Info("Browser navigate occurred.");
if(isLoadingState || isSavingState)
return;
isLoadingState = true;
state.Clear();
var props = ReflectProperties<string[]>(newState);
if (null != props)
{
foreach (string prop in props)
{
state.Add(prop, newState.GetProperty(prop).ToString());
}
}
AfterStateLoad(this, EventArgs.Empty);
isLoadingState = false;
}
/// <summary>
/// Reflects the properties of a scriptable object.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="obj">The obj.</param>
/// <returns></returns>
public static T ReflectProperties<T>(ScriptObject obj)
{
T retVal = default(T);
var properties = HtmlPage.Window.Invoke("ReflectProperties", obj) as ScriptObject;
if (null != properties)
if (int.Parse(properties.GetProperty("length").ToString()) > 0)
retVal = properties.ConvertTo<T>();
return retVal;
}
/// <summary>
/// Reflects the methods of a scriptable object.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="obj">The obj.</param>
/// <returns></returns>
public static T ReflectMethods<T>(ScriptObject obj)
{
T retVal = default(T);
var methods = HtmlPage.Window.Invoke("ReflectMethods", obj) as ScriptObject;
if (null != methods)
if (int.Parse(methods.GetProperty("length").ToString()) > 0)
retVal = methods.ConvertTo<T>();
return retVal;
}
}
}
#endif | 31.957364 | 167 | 0.480291 | [
"MIT"
] | chrismcv/caliburn | src/Caliburn.PresentationFramework/ApplicationModel/DeepLinkStateManager.silverlight.cs | 8,245 | C# |
using HttpPaymentRequiredException = Saklient.Errors.HttpPaymentRequiredException;
namespace Saklient.Cloud.Errors
{
/// <summary>お客様のご都合により操作を受け付けることができません。
/// </summary>
public class PaymentPaymentException : HttpPaymentRequiredException
{
/// <summary>
/// <param name="status" />
/// <param name="code" />
/// <param name="message" />
/// </summary>
public PaymentPaymentException(long status, string code=null, string message="") : base(status, code, message == null || message == "" ? "お客様のご都合により操作を受け付けることができません。" : message)
{
/*!base!*/;
}
}
}
| 24.458333 | 179 | 0.678024 | [
"MIT"
] | 223n/saklient.cs | src/Saklient/Cloud/Errors/PaymentPaymentException.cs | 695 | C# |
namespace IcIWare.NamedIndexers
{
/// <summary>
/// A named indexer which only has a getter. (read-only)
/// </summary>
/// <typeparam name="Tkey">The type of the indexer's key.</typeparam>
/// <typeparam name="Tvalue">The type of the getter's output.</typeparam>
public class NamedGetter<Tkey, Tvalue> : NamedIndexerBase<Tkey, Tvalue>
{
/// <summary>
/// Gets the value using the logic passed in to the constructor.
/// </summary>
/// <param name="key">The key which is used to pick which data to read.</param>
/// <returns>The value indicated by the key using the user-prepared getter logic.</returns>
public Tvalue this[Tkey key]
{
get => _getter(key);
}
/// <summary>
/// Creates a named indexer which has only a getter.
/// </summary>
/// <param name="host">The object which contains the indexer instance. (ie. "this")</param>
/// <param name="getter">The method that will be used as the indexer's getter.</param>
/// <param name="setter">The method that will be used as the indexer's setter.</param>
public NamedGetter(GetterFunction getter) : base(getter) { }
}
}
| 42.655172 | 99 | 0.610348 | [
"MIT"
] | DAud-IcI/NamedIndexers | NamedIndexer/NamedGetter.cs | 1,239 | C# |
using System;
using Metrics.MetricData;
namespace Metrics
{
/// <summary>
/// Represents a logical grouping of metrics
/// </summary>
public interface MetricsContext : IDisposable, Utils.IHideObjectMembers
{
/// <summary>
/// Exposes advanced operations that are possible on this metrics context.
/// </summary>
AdvancedMetricsContext Advanced { get; }
/// <summary>
/// Returns a metrics data provider capable of returning the metrics in this context and any existing child contexts.
/// </summary>
MetricsDataProvider DataProvider { get; }
/// <summary>
/// Create a new child metrics context. Metrics added to the child context are kept separate from the metrics in the
/// parent context.
/// </summary>
/// <param name="contextName">Name of the child context.</param>
/// <returns>Newly created child context.</returns>
MetricsContext Context(string contextName);
/// <summary>
/// Create a new child metrics context. Metrics added to the child context are kept separate from the metrics in the
/// parent context.
/// </summary>
/// <param name="contextName">Name of the child context.</param>
/// <param name="contextCreator">Function used to create the instance of the child context. (Use for creating custom contexts)</param>
/// <returns>Newly created child context.</returns>
MetricsContext Context(string contextName, Func<string, MetricsContext> contextCreator);
/// <summary>
/// Remove a child context. The metrics for the child context are removed from the MetricsData of the parent context.
/// </summary>
/// <param name="contextName">Name of the child context to shutdown.</param>
void ShutdownContext(string contextName);
/// <summary>
/// A gauge is the simplest metric type. It just returns a value. This metric is suitable for instantaneous values.
/// </summary>
/// <param name="name">Name of this gauge metric. Must be unique across all gauges in this context.</param>
/// <param name="valueProvider">Function that returns the value for the gauge.</param>
/// <param name="unit">Description of want the value represents ( Unit.Requests , Unit.Items etc ) .</param>
/// <param name="tags">Optional set of tags that can be associated with the metric.</param>
void Gauge(string name, Func<double> valueProvider, Unit unit, MetricTags tags = default(MetricTags));
/// <summary>
/// Register a performance counter as a Gauge metric.
/// </summary>
/// <param name="name">Name of this gauge metric. Must be unique across all gauges in this context.</param>
/// <param name="counterCategory">Category of the performance counter</param>
/// <param name="counterName">Name of the performance counter</param>
/// <param name="counterInstance">Instance of the performance counter</param>
/// <param name="unit">Description of want the value represents ( Unit.Requests , Unit.Items etc ) .</param>
/// <param name="tags">Optional set of tags that can be associated with the metric.</param>
void PerformanceCounter(string name, string counterCategory, string counterName, string counterInstance, Unit unit, MetricTags tags = default(MetricTags));
/// <summary>
/// A counter is a simple incrementing and decrementing 64-bit integer. Ex number of active requests.
/// </summary>
/// <param name="name">Name of the metric. Must be unique across all counters in this context.</param>
/// <param name="unit">Description of what the is being measured ( Unit.Requests , Unit.Items etc ) .</param>
/// <param name="tags">Optional set of tags that can be associated with the metric.</param>
/// <returns>Reference to the metric</returns>
Counter Counter(string name, Unit unit, MetricTags tags = default(MetricTags));
/// <summary>
/// A meter measures the rate at which a set of events occur, in a few different ways.
/// This metric is suitable for keeping a record of now often something happens ( error, request etc ).
/// </summary>
/// <remarks>
/// The mean rate is the average rate of events. It’s generally useful for trivia,
/// but as it represents the total rate for your application’s entire lifetime (e.g., the total number of requests handled,
/// divided by the number of seconds the process has been running), it doesn’t offer a sense of recency.
/// Luckily, meters also record three different exponentially-weighted moving average rates: the 1-, 5-, and 15-minute moving averages.
/// </remarks>
/// <param name="name">Name of the metric. Must be unique across all meters in this context.</param>
/// <param name="unit">Description of what the is being measured ( Unit.Requests , Unit.Items etc ) .</param>
/// <param name="rateUnit">Time unit for rates reporting. Defaults to Second ( occurrences / second ).</param>
/// <param name="tags">Optional set of tags that can be associated with the metric.</param>
/// <returns>Reference to the metric</returns>
Meter Meter(string name, Unit unit, TimeUnit rateUnit = TimeUnit.Seconds, MetricTags tags = default(MetricTags));
/// <summary>
/// A Histogram measures the distribution of values in a stream of data: e.g., the number of results returned by a search.
/// </summary>
/// <param name="name">Name of the metric. Must be unique across all histograms in this context.</param>
/// <param name="unit">Description of what the is being measured ( Unit.Requests , Unit.Items etc ) .</param>
/// <param name="samplingType">Type of the sampling to use (see SamplingType for details ).</param>
/// <param name="tags">Optional set of tags that can be associated with the metric.</param>
/// <returns>Reference to the metric</returns>
Histogram Histogram(string name,
Unit unit,
SamplingType samplingType = SamplingType.Default,
MetricTags tags = default(MetricTags));
/// <summary>
/// A timer is basically a histogram of the duration of a type of event and a meter of the rate of its occurrence.
/// <seealso cref="Histogram"/> and <seealso cref="Meter"/>
/// </summary>
/// <param name="name">Name of the metric. Must be unique across all timers in this context.</param>
/// <param name="unit">Description of what the is being measured ( Unit.Requests , Unit.Items etc ) .</param>
/// <param name="samplingType">Type of the sampling to use (see SamplingType for details ).</param>
/// <param name="rateUnit">Time unit for rates reporting. Defaults to Second ( occurrences / second ).</param>
/// <param name="durationUnit">Time unit for reporting durations. Defaults to Milliseconds. </param>
/// <param name="tags">Optional set of tags that can be associated with the metric.</param>
/// <returns>Reference to the metric</returns>
Timer Timer(string name,
Unit unit,
SamplingType samplingType = SamplingType.Default,
TimeUnit rateUnit = TimeUnit.Seconds,
TimeUnit durationUnit = TimeUnit.Milliseconds,
MetricTags tags = default(MetricTags));
}
}
| 63.644628 | 164 | 0.645241 | [
"Apache-2.0"
] | AzVedi/microdot | Metrics/MetricsContext.cs | 7,709 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace Encoder
{
public class EncoderProcessor
{
public StringBuilder sb = new StringBuilder();
public string Encode(string message)
{
//Implement your code here!
string lowerMessage = message.ToLower();
Stack<char> numbers = new Stack<char>();
Queue<char> characters = new Queue<char>();
bool isNum = false, isAlphabet = false, isSpecial = false, isVowel = false, isConsonant = false;
foreach (char c in lowerMessage)
{
int charAsciiVal = c;
string charTypeText = charType(c);
switch (charTypeText)
{
case "number": isNum = true; isAlphabet = false; isSpecial = false; break;
case "alphabet": isNum = false; isAlphabet = true; isSpecial = false; break;
case "special character": isNum = false; isAlphabet = false; isSpecial = true; break;
}
if (isAlphabet)
{
isVowel = "aeiou".IndexOf(c) >= 0;
isConsonant = !isVowel;
}
if (charAsciiVal == 32) // Space
{
GetElements(numbers);
sb.Append('y');
numbers.Clear();
}
else if (charAsciiVal == 121) // y
{
GetElements(numbers);
sb.Append(' ');
numbers.Clear();
}
else if (isSpecial) // special character
{
GetElements(numbers);
sb.Append(c);
numbers.Clear();
}
else if (isAlphabet)
{
GetElements(numbers);
if (isVowel) // Vowel
{
sb.Append(VowelValue(c));
}
else if (isConsonant) // Consonant
{
sb.Append(ConsonentValue(c));
}
numbers.Clear();
}
else if (isNum)
{
numbers.Push(c);
}
}
GetElements(numbers); // ending with number
return sb.ToString();
}
private char ConsonentValue(char val)
{
int ascii = val;
int previousAscii = ascii - 1;
char result = (char)previousAscii;
return result;
}
private char VowelValue(char val)
{
switch (val)
{
case 'a': return '1';
case 'e': return '2';
case 'i': return '3';
case 'o': return '4';
case 'u': return '5';
default: return '0';
}
}
private string charType(int val)
{
if (val >= 48 && val <= 57)
{
return "number";
}
else if (val >= 97 && val <= 122)
{
return "alphabet";
}
else
{
return "special character";
}
}
private void GetElements(Stack<char> num)
{
foreach (var n in num)
{
sb.Append(n);
}
}
}
}
| 29.822581 | 108 | 0.386966 | [
"Apache-2.0"
] | mani779/as-dotnet-string-encoder | Encoder/Encoder.cs | 3,698 | C# |
namespace LottoDataManager.Forms.Reports
{
partial class ProfitAndLossFrm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ProfitAndLossFrm));
this.panel1 = new System.Windows.Forms.Panel();
this.gbGameModes = new System.Windows.Forms.GroupBox();
this.cblGameModes = new System.Windows.Forms.CheckedListBox();
this.panel2 = new System.Windows.Forms.Panel();
this.linkLblCheckAll = new System.Windows.Forms.LinkLabel();
this.linkLblReset = new System.Windows.Forms.LinkLabel();
this.btnRunReport = new System.Windows.Forms.Button();
this.btnExit = new System.Windows.Forms.Button();
this.panel1.SuspendLayout();
this.gbGameModes.SuspendLayout();
this.panel2.SuspendLayout();
this.SuspendLayout();
//
// panel1
//
this.panel1.Controls.Add(this.gbGameModes);
this.panel1.Dock = System.Windows.Forms.DockStyle.Fill;
this.panel1.Location = new System.Drawing.Point(0, 0);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(547, 236);
this.panel1.TabIndex = 0;
//
// gbGameModes
//
this.gbGameModes.Controls.Add(this.cblGameModes);
this.gbGameModes.Dock = System.Windows.Forms.DockStyle.Fill;
this.gbGameModes.Location = new System.Drawing.Point(0, 0);
this.gbGameModes.Name = "gbGameModes";
this.gbGameModes.Size = new System.Drawing.Size(547, 236);
this.gbGameModes.TabIndex = 0;
this.gbGameModes.TabStop = false;
this.gbGameModes.Text = "Select your Game Mode to include on the report";
//
// cblGameModes
//
this.cblGameModes.ColumnWidth = 2;
this.cblGameModes.Dock = System.Windows.Forms.DockStyle.Fill;
this.cblGameModes.Font = new System.Drawing.Font("Microsoft Sans Serif", 10.8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.cblGameModes.FormattingEnabled = true;
this.cblGameModes.HorizontalScrollbar = true;
this.cblGameModes.Location = new System.Drawing.Point(3, 18);
this.cblGameModes.Name = "cblGameModes";
this.cblGameModes.Size = new System.Drawing.Size(541, 215);
this.cblGameModes.TabIndex = 0;
//
// panel2
//
this.panel2.Controls.Add(this.linkLblCheckAll);
this.panel2.Controls.Add(this.linkLblReset);
this.panel2.Controls.Add(this.btnRunReport);
this.panel2.Controls.Add(this.btnExit);
this.panel2.Dock = System.Windows.Forms.DockStyle.Bottom;
this.panel2.Location = new System.Drawing.Point(0, 236);
this.panel2.Name = "panel2";
this.panel2.Size = new System.Drawing.Size(547, 69);
this.panel2.TabIndex = 1;
//
// linkLblCheckAll
//
this.linkLblCheckAll.AutoSize = true;
this.linkLblCheckAll.Location = new System.Drawing.Point(12, 13);
this.linkLblCheckAll.Name = "linkLblCheckAll";
this.linkLblCheckAll.Size = new System.Drawing.Size(66, 17);
this.linkLblCheckAll.TabIndex = 1;
this.linkLblCheckAll.TabStop = true;
this.linkLblCheckAll.Text = "Check All";
this.linkLblCheckAll.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLblCheckAll_LinkClicked);
//
// linkLblReset
//
this.linkLblReset.AutoSize = true;
this.linkLblReset.Location = new System.Drawing.Point(12, 39);
this.linkLblReset.Name = "linkLblReset";
this.linkLblReset.Size = new System.Drawing.Size(45, 17);
this.linkLblReset.TabIndex = 2;
this.linkLblReset.TabStop = true;
this.linkLblReset.Text = "Reset";
this.linkLblReset.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLblUnCheckAll_LinkClicked);
//
// btnRunReport
//
this.btnRunReport.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.btnRunReport.Image = global::LottoDataManager.Properties.Resources.statistic_32;
this.btnRunReport.Location = new System.Drawing.Point(187, 2);
this.btnRunReport.Name = "btnRunReport";
this.btnRunReport.Size = new System.Drawing.Size(177, 63);
this.btnRunReport.TabIndex = 1;
this.btnRunReport.Text = "Run Report";
this.btnRunReport.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
this.btnRunReport.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageBeforeText;
this.btnRunReport.UseVisualStyleBackColor = true;
this.btnRunReport.Click += new System.EventHandler(this.btnRunReport_Click);
//
// btnExit
//
this.btnExit.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.btnExit.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.btnExit.Image = global::LottoDataManager.Properties.Resources.Exit_32;
this.btnExit.Location = new System.Drawing.Point(367, 3);
this.btnExit.Name = "btnExit";
this.btnExit.Size = new System.Drawing.Size(177, 63);
this.btnExit.TabIndex = 0;
this.btnExit.Text = "Exit";
this.btnExit.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
this.btnExit.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageBeforeText;
this.btnExit.UseVisualStyleBackColor = true;
this.btnExit.Click += new System.EventHandler(this.btnExit_Click);
//
// ProfitAndLossFrm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.CancelButton = this.btnExit;
this.ClientSize = new System.Drawing.Size(547, 305);
this.Controls.Add(this.panel1);
this.Controls.Add(this.panel2);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MinimizeBox = false;
this.Name = "ProfitAndLossFrm";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Profit And Loss Reports";
this.Load += new System.EventHandler(this.ProfitAndLossFrm_Load);
this.panel1.ResumeLayout(false);
this.gbGameModes.ResumeLayout(false);
this.panel2.ResumeLayout(false);
this.panel2.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Panel panel1;
private System.Windows.Forms.Panel panel2;
private System.Windows.Forms.Button btnExit;
private System.Windows.Forms.Button btnRunReport;
private System.Windows.Forms.GroupBox gbGameModes;
private System.Windows.Forms.CheckedListBox cblGameModes;
private System.Windows.Forms.LinkLabel linkLblCheckAll;
private System.Windows.Forms.LinkLabel linkLblReset;
}
} | 49.729885 | 174 | 0.619785 | [
"CC0-1.0"
] | AngelsSoftwareOrg/LottoDataManager | Forms/Reports/ProfitAndLossFrm.Designer.cs | 8,655 | C# |
/***
* Lockstep Platform SDK for C#
*
* (c) 2021-2022 Lockstep, Inc.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Lockstep Network <support@lockstep.io>
* @copyright 2021-2022 Lockstep, Inc.
* @link https://github.com/Lockstep-Network/lockstep-sdk-csharp
*/
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
namespace LockstepSDK
{
/// <summary>
/// API methods related to InvoiceHistory
/// </summary>
public class InvoiceHistoryClient
{
private readonly LockstepApi _client;
/// <summary>
/// Constructor
/// </summary>
public InvoiceHistoryClient(LockstepApi client) {
_client = client;
}
/// <summary>
/// Retrieves the history of the Invoice specified by this unique identifier.
///
/// An Invoice represents a bill sent from one company to another. The Lockstep Platform tracks changes to each Invoice so that you can observe the changes over time. You can view the InvoiceHistory list to monitor and observe the changes of this Invoice and track the dates when changes occurred.
///
/// </summary>
/// <param name="id">The unique Lockstep Platform ID number of this invoice; NOT the customer's ERP key</param>
public async Task<LockstepResponse<FetchResult<InvoiceHistoryModel>>> RetrieveInvoiceHistory(Guid id)
{
var url = $"/api/v1/InvoiceHistory/{id}";
return await _client.Request<FetchResult<InvoiceHistoryModel>>(HttpMethod.Get, url, null, null, null);
}
/// <summary>
/// Queries Invoice History for this account using the specified filtering, sorting, and pagination rules requested.
///
/// An Invoice represents a bill sent from one company to another. The Lockstep Platform tracks changes to each Invoice so that you can observe the changes over time. You can view the InvoiceHistory list to monitor and observe the changes of this Invoice and track the dates when changes occurred.
///
/// </summary>
/// <param name="filter">The filter for this query. See [Searchlight Query Language](https://developer.lockstep.io/docs/querying-with-searchlight)</param>
/// <param name="include">To fetch additional data on this object, specify the list of elements to retrieve. No collections are currently available for querying but may be available in the future.</param>
/// <param name="order">The sort order for this query. See See [Searchlight Query Language](https://developer.lockstep.io/docs/querying-with-searchlight)</param>
/// <param name="pageSize">The page size for results (default 200). See [Searchlight Query Language](https://developer.lockstep.io/docs/querying-with-searchlight)</param>
/// <param name="pageNumber">The page number for results (default 0). See [Searchlight Query Language](https://developer.lockstep.io/docs/querying-with-searchlight)</param>
public async Task<LockstepResponse<FetchResult<InvoiceHistoryModel>>> QueryInvoiceHistory(string filter = null, string include = null, string order = null, int? pageSize = null, int? pageNumber = null)
{
var url = $"/api/v1/InvoiceHistory/query";
var options = new Dictionary<string, object>();
if (filter != null) { options["filter"] = filter; }
if (include != null) { options["include"] = include; }
if (order != null) { options["order"] = order; }
if (pageSize != null) { options["pageSize"] = pageSize; }
if (pageNumber != null) { options["pageNumber"] = pageNumber; }
return await _client.Request<FetchResult<InvoiceHistoryModel>>(HttpMethod.Get, url, options, null, null);
}
}
}
| 52.613333 | 307 | 0.672833 | [
"MIT"
] | Lockstep-Network/lockstep-sdk-csharp | src/clients/InvoiceHistoryClient.cs | 3,946 | C# |
namespace ChangeFeedProcessor
{
using System;
using System.Configuration;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.Documents;
using Microsoft.Azure.Documents.ChangeFeedProcessor;
using Microsoft.Azure.Documents.ChangeFeedProcessor.Logging;
using Microsoft.Azure.Documents.Client;
/// ------------------------------------------------------------------------------------------------
public class Program
{
// Modify EndPointUrl and PrimaryKey to connect to your own subscription
private string monitoredUri = ConfigurationManager.AppSettings["monitoredUri"];
private string monitoredSecretKey = ConfigurationManager.AppSettings["monitoredSecretKey"];
private string monitoredDbName = ConfigurationManager.AppSettings["monitoredDbName"];
private string monitoredCollectionName = ConfigurationManager.AppSettings["monitoredCollectionName"];
private int monitoredThroughput = int.Parse(ConfigurationManager.AppSettings["monitoredThroughput"]);
// optional setting to store lease collection on different account
// set lease Uri, secretKey and DbName to same as monitored if both collections
// are on the same account
private string leaseUri = ConfigurationManager.AppSettings["leaseUri"];
private string leaseSecretKey = ConfigurationManager.AppSettings["leaseSecretKey"];
private string leaseDbName = ConfigurationManager.AppSettings["leaseDbName"];
private string leaseCollectionName = ConfigurationManager.AppSettings["leaseCollectionName"];
private int leaseThroughput = int.Parse(ConfigurationManager.AppSettings["leaseThroughput"]);
private readonly CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
private readonly ChangeFeedProcessorBuilder builder = new ChangeFeedProcessorBuilder();
/// <summary>
/// Main program function; called when program runs
/// </summary>
/// <param name="args">Command line parameters (not used)</param>
///
public static void Main(string[] args)
{
string hostName = "HostName " + DateTime.Now.Ticks.ToString();
if (args.Length == 1)
{
hostName = args[0];
}
Console.WriteLine("Change Feed Processor client Started at:{0} for HostName: {1} ", DateTime.Now.ToShortTimeString(), hostName);
//Setting up Logging
var tracelogProvider = new TraceLogProvider();
using (tracelogProvider.OpenNestedContext(hostName))
{
LogProvider.SetCurrentLogProvider(tracelogProvider);
// After this, create IChangeFeedProcessor instance and start/stop it.
}
Program newApp = new Program();
newApp.MainAsync().Wait();
}
/// <summary>
/// Main Async function; checks for or creates monitored/lease collections and runs
/// Change Feed Host (RunChangeFeedHostAsync)
/// </summary>
/// <returns>A Task to allow asynchronous execution</returns>
private async Task MainAsync()
{
await this.CreateCollectionIfNotExistsAsync(
this.monitoredUri,
this.monitoredSecretKey,
this.monitoredDbName,
this.monitoredCollectionName,
this.monitoredThroughput);
await this.CreateCollectionIfNotExistsAsync(
this.leaseUri,
this.leaseSecretKey,
this.leaseDbName,
this.leaseCollectionName,
this.leaseThroughput);
await this.RunChangeFeedHostAsync();
}
/// <summary>
/// Registers change feed observer to update changes read on change feed to destination
/// collection. Deregisters change feed observer and closes process when enter key is pressed
/// </summary>
/// <returns>A Task to allow asynchronous execution</returns>
public async Task RunChangeFeedHostAsync()
{
string hostName = Guid.NewGuid().ToString();
// monitored collection info
DocumentCollectionInfo documentCollectionInfo = new DocumentCollectionInfo
{
Uri = new Uri(this.monitoredUri),
MasterKey = this.monitoredSecretKey,
DatabaseName = this.monitoredDbName,
CollectionName = this.monitoredCollectionName
};
DocumentCollectionInfo leaseCollectionInfo = new DocumentCollectionInfo
{
Uri = new Uri(this.leaseUri),
MasterKey = this.leaseSecretKey,
DatabaseName = this.leaseDbName,
CollectionName = this.leaseCollectionName
};
DocumentFeedObserverFactory docObserverFactory = new DocumentFeedObserverFactory();
ChangeFeedOptions feedOptions = new ChangeFeedOptions();
/* ie customize StartFromBeginning so change feed reads from beginning
can customize MaxItemCount, PartitonKeyRangeId, RequestContinuation, SessionToken and StartFromBeginning
*/
feedOptions.StartFromBeginning = true;
ChangeFeedProcessorOptions feedProcessorOptions = new ChangeFeedProcessorOptions();
// ie. customizing lease renewal interval to 15 seconds
// can customize LeaseRenewInterval, LeaseAcquireInterval, LeaseExpirationInterval, FeedPollDelay
feedProcessorOptions.LeaseRenewInterval = TimeSpan.FromSeconds(15);
this.builder
.WithHostName(hostName)
.WithFeedCollection(documentCollectionInfo)
.WithLeaseCollection(leaseCollectionInfo)
.WithProcessorOptions(feedProcessorOptions)
.WithObserverFactory(new DocumentFeedObserverFactory());
// .WithObserver<DocumentFeedObserver>(); or just pass a observer
var result = await this.builder.BuildAsync();
await result.StartAsync();
Console.Read();
await result.StopAsync();
}
/// <summary>
/// Checks whether collections exists. Creates new collection if collection does not exist
/// WARNING: CreateCollectionIfNotExistsAsync will create a new
/// with reserved throughput which has pricing implications. For details
/// visit: https://azure.microsoft.com/en-us/pricing/details/cosmos-db/
/// </summary>
/// <param name="endPointUri">End point URI for account </param>
/// <param name="secretKey">Primary key to access the account </param>
/// <param name="databaseName">Name of database </param>
/// <param name="collectionName">Name of collection</param>
/// <param name="throughput">Amount of throughput to provision</param>
/// <returns>A Task to allow asynchronous execution</returns>
public async Task CreateCollectionIfNotExistsAsync(string endPointUri, string secretKey, string databaseName, string collectionName, int throughput)
{
// connecting client
using (DocumentClient client = new DocumentClient(new Uri(endPointUri), secretKey))
{
await client.CreateDatabaseIfNotExistsAsync(new Database { Id = databaseName });
// create collection if it does not exist
// WARNING: CreateDocumentCollectionIfNotExistsAsync will create a new
// with reserved throughput which has pricing implications. For details
// visit: https://azure.microsoft.com/en-us/pricing/details/cosmos-db/
await client.CreateDocumentCollectionIfNotExistsAsync(
UriFactory.CreateDatabaseUri(databaseName),
new DocumentCollection { Id = collectionName },
new RequestOptions { OfferThroughput = throughput });
}
}
}
}
| 44.868132 | 156 | 0.639848 | [
"MIT"
] | chrispike01/azure-documentdb-dotnet | samples/code-samples/ChangeFeedProcessorV2/Program.cs | 8,168 | C# |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TelegramBotBase.Args;
using TelegramBotBase.Controls;
using TelegramBotBase.Controls.Hybrid;
using TelegramBotBase.Form;
namespace TelegramBotBaseTest.Tests.Controls
{
public class ButtonGridPagingForm : AutoCleanForm
{
ButtonGrid m_Buttons = null;
public ButtonGridPagingForm()
{
this.DeleteMode = TelegramBotBase.Enums.eDeleteMode.OnLeavingForm;
this.Init += ButtonGridForm_Init;
}
private async Task ButtonGridForm_Init(object sender, InitEventArgs e)
{
m_Buttons = new ButtonGrid();
m_Buttons.KeyboardType = TelegramBotBase.Enums.eKeyboardType.ReplyKeyboard;
m_Buttons.EnablePaging = true;
m_Buttons.EnableSearch = true;
m_Buttons.HeadLayoutButtonRow = new List<ButtonBase>() { new ButtonBase("Back", "back") };
var countries = CultureInfo.GetCultures(CultureTypes.SpecificCultures);
ButtonForm bf = new ButtonForm();
foreach (var c in countries)
{
bf.AddButtonRow(new ButtonBase(c.EnglishName, c.EnglishName));
}
m_Buttons.ButtonsForm = bf;
m_Buttons.ButtonClicked += Bg_ButtonClicked;
this.AddControl(m_Buttons);
}
private async Task Bg_ButtonClicked(object sender, ButtonClickedEventArgs e)
{
if (e.Button == null)
return;
if (e.Button.Value == "back")
{
var start = new Menu();
await this.NavigateTo(start);
}
else
{
await this.Device.Send($"Button clicked with Text: {e.Button.Text} and Value {e.Button.Value}");
}
}
}
}
| 25.84 | 112 | 0.606295 | [
"MIT"
] | MajMcCloud/TelegramBotFramework | TelegramBotBaseTest/Tests/Controls/ButtonGridPagingForm.cs | 1,940 | C# |
namespace FluentNHibernate.Specs.PersistenceModel.Fixtures
{
class UnionEntity
{
public int Id { get; set; }
}
} | 19.857143 | 60 | 0.625899 | [
"BSD-3-Clause"
] | BrunoJuchli/fluent-nhibernate | src/FluentNHibernate.Specs/PersistenceModel/Fixtures/UnionEntity.cs | 141 | C# |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Linq;
namespace Microsoft.WindowsAzure.Management.StorSimple.Models
{
public enum AppType
{
Invalid = 0,
PrimaryVolume = 13,
ArchiveVolume = 14,
}
}
| 28.305556 | 76 | 0.701668 | [
"Apache-2.0"
] | CerebralMischief/azure-sdk-for-net | src/ServiceManagement/StorSimple/StorSimple/Generated/Models/AppType.cs | 1,019 | C# |
using DotNetRevolution.Core.Base;
using System;
using System.Diagnostics.Contracts;
namespace DotNetRevolution.EventSourcing
{
public class AggregateRootType : ValueObject<AggregateRootType>
{
private readonly Type _type;
public Type Type
{
get
{
Contract.Ensures(Contract.Result<Type>() != null);
return _type;
}
}
public AggregateRootType(Type aggregateRootType)
{
Contract.Requires(aggregateRootType != null);
_type = aggregateRootType;
}
public static implicit operator Type(AggregateRootType aggregateRootType)
{
Contract.Requires(aggregateRootType != null);
Contract.Ensures(Contract.Result<Type>() != null);
return aggregateRootType.Type;
}
public static implicit operator AggregateRootType(Type type)
{
Contract.Requires(type != null);
Contract.Ensures(Contract.Result<AggregateRootType>() != null);
return new AggregateRootType(type);
}
[ContractInvariantMethod]
private void ObjectInvariants()
{
Contract.Invariant(_type != null);
}
}
}
| 25.764706 | 81 | 0.576104 | [
"MIT"
] | DotNetRevolution/DotNetRevolution-Framework | src/DotNetRevolution.EventSourcing/AggregateRootType.cs | 1,316 | C# |
// Copyright (c) Christophe Gondouin (CGO Conseils). All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System;
namespace XrmFramework
{
public delegate void LogServiceMethod(string methodName, string message, params object[] args);
public delegate void LogMethod(string message, params object[] args);
public enum Stages
{
PreValidation = 10,
PreOperation = 20,
PostOperation = 40
}
public enum Modes
{
Synchronous = 0,
Asynchronous = 1
}
public enum WorkflowModes
{
Asynchronous = 0,
RealTime = 1
}
public partial class InputParameters
{
protected string ParameterName { get; }
protected InputParameters(string inputParameterName)
{
ParameterName = inputParameterName;
}
public override string ToString() => ParameterName;
public override int GetHashCode() => ParameterName.GetHashCode();
public override bool Equals(object obj) => obj is InputParameters message && message.ParameterName == ParameterName;
public static InputParameters Assignee = new InputParameters("Assignee");
public static InputParameters EntityMoniker = new InputParameters("EntityMoniker");
public static InputParameters OpportunityClose = new InputParameters("OpportunityClose");
public static InputParameters Query = new InputParameters("Query");
public static InputParameters Record = new InputParameters("Record");
public static InputParameters RelatedEntities = new InputParameters("RelatedEntities");
public static InputParameters Relationship = new InputParameters("Relationship");
public static InputParameters State = new InputParameters("State");
public static InputParameters Status = new InputParameters("Status");
public static InputParameters SystemUserId = new InputParameters("SystemUserId");
public static InputParameters Target = new InputParameters("Target");
public static InputParameters TeamTemplateId = new InputParameters("TeamTemplateId");
public static InputParameters AppointmentId = new InputParameters("AppointmentId");
public static InputParameters FetchXml = new InputParameters("FetchXml");
public static InputParameters SubordinateId = new InputParameters("SubordinateId");
public static InputParameters UpdateContent = new InputParameters("UpdateContent");
}
public partial class OutputParameters
{
protected string ParameterName { get; }
protected OutputParameters(string outputParameterName)
{
ParameterName = outputParameterName;
}
public override string ToString() => ParameterName;
public override int GetHashCode() => ParameterName.GetHashCode();
public override bool Equals(object obj) => obj is OutputParameters message && message.ParameterName == ParameterName;
public static OutputParameters BusinessEntityCollection = new OutputParameters("BusinessEntityCollection");
public static OutputParameters ValidationResult = new OutputParameters("ValidationResult");
}
public partial class Messages
{
public static Messages AddItem = new Messages("AddItem");
public static Messages AddListMembers = new Messages("AddListMembers");
public static Messages AddMember = new Messages("AddMember");
public static Messages AddMembers = new Messages("AddMembers");
public static Messages AddPrivileges = new Messages("AddPrivileges");
public static Messages AddProductToKit = new Messages("AddProductToKit");
public static Messages AddRecurrence = new Messages("AddRecurrence");
public static Messages AddToQueue = new Messages("AddToQueue");
public static Messages AddUserToRecordTeam = new Messages("AddUserToRecordTeam");
public static Messages Assign = new Messages("Assign");
public static Messages AssignUserRoles = new Messages("AssignUserRoles");
public static Messages Associate = new Messages("Associate");
public static Messages BackgroundSend = new Messages("BackgroundSend");
public static Messages Book = new Messages("Book");
public static Messages Cancel = new Messages("Cancel");
public static Messages CheckIncoming = new Messages("CheckIncoming");
public static Messages CheckPromote = new Messages("CheckPromote");
public static Messages Clone = new Messages("Clone");
public static Messages Close = new Messages("Close");
public static Messages CopyDynamicListToStatic = new Messages("CopyDynamicListToStatic");
public static Messages CopySystemForm = new Messages("CopySystemForm");
public static Messages Create = new Messages("Create");
public static Messages CreateException = new Messages("CreateException");
public static Messages CreateInstance = new Messages("CreateInstance");
public static Messages Delete = new Messages("Delete");
public static Messages DeleteOpenInstances = new Messages("DeleteOpenInstances");
public static Messages DeliverIncoming = new Messages("DeliverIncoming");
public static Messages DeliverPromote = new Messages("DeliverPromote");
public static Messages DetachFromQueue = new Messages("DetachFromQueue");
public static Messages Disassociate = new Messages("Disassociate");
public static Messages Execute = new Messages("Execute");
public static Messages ExecuteById = new Messages("ExecuteById");
public static Messages Export = new Messages("Export");
public static Messages ExportAll = new Messages("ExportAll");
public static Messages ExportCompressed = new Messages("ExportCompressed");
public static Messages ExportCompressedAll = new Messages("ExportCompressedAll");
public static Messages GrantAccess = new Messages("GrantAccess");
public static Messages Handle = new Messages("Handle");
public static Messages Import = new Messages("Import");
public static Messages ImportAll = new Messages("ImportAll");
public static Messages ImportCompressedAll = new Messages("ImportCompressedAll");
public static Messages ImportCompressedWithProgress = new Messages("ImportCompressedWithProgress");
public static Messages ImportWithProgress = new Messages("ImportWithProgress");
public static Messages LockInvoicePricing = new Messages("LockInvoicePricing");
public static Messages LockSalesOrderPricing = new Messages("LockSalesOrderPricing");
public static Messages Lose = new Messages("Lose");
public static Messages Merge = new Messages("Merge");
public static Messages ModifyAccess = new Messages("ModifyAccess");
public static Messages Publish = new Messages("Publish");
public static Messages PublishAll = new Messages("PublishAll");
public static Messages QualifyLead = new Messages("QualifyLead");
public static Messages Recalculate = new Messages("Recalculate");
public static Messages RemoveItem = new Messages("RemoveItem");
public static Messages RemoveMember = new Messages("RemoveMember");
public static Messages RemoveMembers = new Messages("RemoveMembers");
public static Messages RemovePrivilege = new Messages("RemovePrivilege");
public static Messages RemoveProductFromKit = new Messages("RemoveProductFromKit");
public static Messages RemoveRelated = new Messages("RemoveRelated");
public static Messages RemoveUserFromRecordTeam = new Messages("RemoveUserFromRecordTeam");
public static Messages RemoveUserRoles = new Messages("RemoveUserRoles");
public static Messages ReplacePrivileges = new Messages("ReplacePrivileges");
public static Messages Reschedule = new Messages("Reschedule");
public static Messages Retrieve = new Messages("Retrieve");
public static Messages RetrieveExchangeRate = new Messages("RetrieveExchangeRate");
public static Messages RetrieveFilteredForms = new Messages("RetrieveFilteredForms");
public static Messages RetrieveMultiple = new Messages("RetrieveMultiple");
public static Messages RetrievePersonalWall = new Messages("RetrievePersonalWall");
public static Messages RetrievePrincipalAccess = new Messages("RetrievePrincipalAccess");
public static Messages RetrieveRecordWall = new Messages("RetrieveRecordWall");
public static Messages RetrieveSharedPrincipalsAndAccess = new Messages("RetrieveSharedPrincipalsAndAccess");
public static Messages RetrieveUnpublished = new Messages("RetrieveUnpublished");
public static Messages RetrieveUnpublishedMultiple = new Messages("RetrieveUnpublishedMultiple");
public static Messages RevokeAccess = new Messages("RevokeAccess");
public static Messages Route = new Messages("Route");
public static Messages Send = new Messages("Send");
public static Messages SendFromTemplate = new Messages("SendFromTemplate");
public static Messages SetRelated = new Messages("SetRelated");
[Obsolete("Use Update message with state filtering attribute instead")]
public static Messages SetState = new Messages("SetState");
[Obsolete("Use Update message with state filtering attribute instead")]
public static Messages SetStateDynamicEntity = new Messages("SetStateDynamicEntity");
public static Messages TriggerServiceEndpointCheck = new Messages("TriggerServiceEndpointCheck");
public static Messages UnlockInvoicePricing = new Messages("UnlockInvoicePricing");
public static Messages UnlockSalesOrderPricing = new Messages("UnlockSalesOrderPricing");
public static Messages Update = new Messages("Update");
public static Messages ValidateRecurrenceRule = new Messages("ValidateRecurrenceRule");
public static Messages Win = new Messages("Win");
public static Messages ExecuteWorkflow = new Messages("ExecuteWorkflow");
public static Messages Default = new Messages("Default");
protected string MessageName { get; }
protected Messages(string messageName)
{
MessageName = messageName;
}
public static bool operator ==(Messages x, Messages y) => x?.MessageName == y?.MessageName;
public static bool operator !=(Messages x, Messages y) => !(x == y);
public override string ToString() => MessageName;
public override int GetHashCode() => MessageName.GetHashCode();
public override bool Equals(object obj) => obj is Messages message && message.MessageName == MessageName;
public static Messages GetMessage(string messageName)
{
if (string.IsNullOrEmpty(messageName))
{
return Default;
}
return new Messages(messageName);
}
}
} | 55.287129 | 125 | 0.715795 | [
"MIT"
] | cgoconseils/XrmFramework | src/XrmFramework/Utils/Statics.cs | 11,170 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Elu_application.Service;
using ZXing.Mobile;
using Xamarin.Forms;
[assembly: Dependency(typeof(WorldEnd_Clock.Droid.Service.QrScanningService))]
namespace WorldEnd_Clock.Droid.Service
{
public class QrScanningService : IQrScanningService
{
public async Task<string> ScanAsync()
{
var optionsDefault = new MobileBarcodeScanningOptions();
var optionsCustom = new MobileBarcodeScanningOptions();
var scanner = new MobileBarcodeScanner()
{
TopText = "Scan the QR Code",
BottomText = "Please Wait",
};
var scanResult = await scanner.Scan(optionsCustom);
if (scanResult == null)
{
return "";
}
else
{
return scanResult.Text;
}
}
}
} | 25.522727 | 78 | 0.615316 | [
"MIT"
] | DTI-tudengite-tarkvaraprojektid/summer_project | Elu_application.Android/Services/QrScanningService.cs | 1,125 | C# |
#pragma checksum "D:\MyLearnMate\iCLASS\comptest.xaml" "{406ea660-64cf-4c82-b6f0-42d48172a799}" "DB030F7CB052EDD5F95BA98C14238FCF"
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.1
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Windows;
using System.Windows.Automation;
using System.Windows.Automation.Peers;
using System.Windows.Automation.Provider;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Resources;
using System.Windows.Shapes;
using System.Windows.Threading;
namespace iCLASS {
public partial class comptest : System.Windows.Controls.UserControl {
internal System.Windows.Controls.Canvas LayoutRoot;
internal System.Windows.Shapes.Rectangle rectangle1;
internal System.Windows.Controls.Label label21;
internal System.Windows.Controls.Image image8;
internal System.Windows.Controls.Border border1;
internal System.Windows.Controls.Button button6;
internal System.Windows.Controls.Button button15;
internal System.Windows.Controls.TextBlock txtCommandDsiplay;
internal System.Windows.Controls.TextBlock txtNumDisplay;
internal System.Windows.Controls.Button btnClear;
internal System.Windows.Controls.Primitives.Popup myPopup;
internal System.Windows.Controls.TextBlock PopUpText;
internal System.Windows.Controls.Button PopUpButton;
internal System.Windows.Controls.Label label2;
internal System.Windows.Controls.Label label221;
internal System.Windows.Controls.Label label3;
internal System.Windows.Controls.Label label1;
internal System.Windows.Controls.Image image33;
internal System.Windows.Controls.Button button1;
internal System.Windows.Controls.Image image1;
internal System.Windows.Controls.Button button3;
internal System.Windows.Controls.Button button4;
private bool _contentLoaded;
/// <summary>
/// InitializeComponent
/// </summary>
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
public void InitializeComponent() {
if (_contentLoaded) {
return;
}
_contentLoaded = true;
System.Windows.Application.LoadComponent(this, new System.Uri("/iCLASS;component/comptest.xaml", System.UriKind.Relative));
this.LayoutRoot = ((System.Windows.Controls.Canvas)(this.FindName("LayoutRoot")));
this.rectangle1 = ((System.Windows.Shapes.Rectangle)(this.FindName("rectangle1")));
this.label21 = ((System.Windows.Controls.Label)(this.FindName("label21")));
this.image8 = ((System.Windows.Controls.Image)(this.FindName("image8")));
this.border1 = ((System.Windows.Controls.Border)(this.FindName("border1")));
this.button6 = ((System.Windows.Controls.Button)(this.FindName("button6")));
this.button15 = ((System.Windows.Controls.Button)(this.FindName("button15")));
this.txtCommandDsiplay = ((System.Windows.Controls.TextBlock)(this.FindName("txtCommandDsiplay")));
this.txtNumDisplay = ((System.Windows.Controls.TextBlock)(this.FindName("txtNumDisplay")));
this.btnClear = ((System.Windows.Controls.Button)(this.FindName("btnClear")));
this.myPopup = ((System.Windows.Controls.Primitives.Popup)(this.FindName("myPopup")));
this.PopUpText = ((System.Windows.Controls.TextBlock)(this.FindName("PopUpText")));
this.PopUpButton = ((System.Windows.Controls.Button)(this.FindName("PopUpButton")));
this.label2 = ((System.Windows.Controls.Label)(this.FindName("label2")));
this.label221 = ((System.Windows.Controls.Label)(this.FindName("label221")));
this.label3 = ((System.Windows.Controls.Label)(this.FindName("label3")));
this.label1 = ((System.Windows.Controls.Label)(this.FindName("label1")));
this.image33 = ((System.Windows.Controls.Image)(this.FindName("image33")));
this.button1 = ((System.Windows.Controls.Button)(this.FindName("button1")));
this.image1 = ((System.Windows.Controls.Image)(this.FindName("image1")));
this.button3 = ((System.Windows.Controls.Button)(this.FindName("button3")));
this.button4 = ((System.Windows.Controls.Button)(this.FindName("button4")));
}
}
}
| 44.932773 | 136 | 0.631569 | [
"MIT"
] | VikramadityaJakkula/MyLearnMateCode | iCLASS/obj/Release/comptest.g.cs | 5,349 | C# |
using System;
using System.Collections.Specialized;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Bot.Builder;
using Microsoft.Bot.Builder.Dialogs;
using Microsoft.Bot.Solutions.Dialogs;
using Microsoft.Bot.Solutions.Extensions;
using Microsoft.Bot.Solutions.Skills;
using Microsoft.Bot.Solutions.Util;
using ToDoSkill.Dialogs.AddToDo.Resources;
using ToDoSkill.Dialogs.Shared;
using ToDoSkill.Dialogs.Shared.Resources;
using ToDoSkill.ServiceClients;
using Action = ToDoSkill.Dialogs.Shared.Action;
namespace ToDoSkill.Dialogs.AddToDo
{
public class AddToDoItemDialog : ToDoSkillDialog
{
public AddToDoItemDialog(
SkillConfigurationBase services,
IStatePropertyAccessor<ToDoSkillState> toDoStateAccessor,
IStatePropertyAccessor<ToDoSkillUserState> userStateAccessor,
IServiceManager serviceManager,
IBotTelemetryClient telemetryClient)
: base(nameof(AddToDoItemDialog), services, toDoStateAccessor, userStateAccessor, serviceManager, telemetryClient)
{
TelemetryClient = telemetryClient;
var addTask = new WaterfallStep[]
{
GetAuthToken,
AfterGetAuthToken,
ClearContext,
DoAddTask,
};
var doAddTask = new WaterfallStep[]
{
CollectTaskContent,
CollectSwitchListTypeConfirmation,
CollectAddDupTaskConfirmation,
AddTask,
ContinueAddTask,
};
var collectTaskContent = new WaterfallStep[]
{
AskTaskContent,
AfterAskTaskContent,
};
var collectSwitchListTypeConfirmation = new WaterfallStep[]
{
AskSwitchListTypeConfirmation,
AfterAskSwitchListTypeConfirmation,
};
var collectAddDupTaskConfirmation = new WaterfallStep[]
{
AskAddDupTaskConfirmation,
AfterAskAddDupTaskConfirmation,
};
var continueAddTask = new WaterfallStep[]
{
AskContinueAddTask,
AfterAskContinueAddTask,
};
// Define the conversation flow using a waterfall model.
AddDialog(new WaterfallDialog(Action.DoAddTask, doAddTask) { TelemetryClient = telemetryClient });
AddDialog(new WaterfallDialog(Action.AddTask, addTask) { TelemetryClient = telemetryClient });
AddDialog(new WaterfallDialog(Action.CollectTaskContent, collectTaskContent) { TelemetryClient = telemetryClient });
AddDialog(new WaterfallDialog(Action.CollectSwitchListTypeConfirmation, collectSwitchListTypeConfirmation) { TelemetryClient = telemetryClient });
AddDialog(new WaterfallDialog(Action.CollectAddDupTaskConfirmation, collectAddDupTaskConfirmation) { TelemetryClient = telemetryClient });
AddDialog(new WaterfallDialog(Action.ContinueAddTask, continueAddTask) { TelemetryClient = telemetryClient });
// Set starting dialog for component
InitialDialogId = Action.AddTask;
}
protected async Task<DialogTurnResult> DoAddTask(WaterfallStepContext sc, CancellationToken cancellationToken = default(CancellationToken))
{
try
{
return await sc.BeginDialogAsync(Action.DoAddTask);
}
catch (Exception ex)
{
await HandleDialogExceptions(sc, ex);
return new DialogTurnResult(DialogTurnStatus.Cancelled, CommonUtil.DialogTurnResultCancelAllDialogs);
}
}
protected async Task<DialogTurnResult> AddTask(WaterfallStepContext sc, CancellationToken cancellationToken = default(CancellationToken))
{
try
{
var state = await ToDoStateAccessor.GetAsync(sc.Context);
if (state.AddDupTask)
{
state.ListType = state.ListType ?? ToDoStrings.ToDo;
state.LastListType = state.ListType;
var service = await InitListTypeIds(sc);
var currentAllTasks = await service.GetTasksAsync(state.ListType);
var duplicatedTaskIndex = currentAllTasks.FindIndex(t => t.Topic.Equals(state.TaskContent, StringComparison.InvariantCultureIgnoreCase));
await service.AddTaskAsync(state.ListType, state.TaskContent);
state.AllTasks = await service.GetTasksAsync(state.ListType);
state.ShowTaskPageIndex = 0;
var rangeCount = Math.Min(state.PageSize, state.AllTasks.Count);
state.Tasks = state.AllTasks.GetRange(0, rangeCount);
var toDoListAttachment = ToAdaptiveCardForTaskAddedFlow(
state.Tasks,
state.TaskContent,
state.AllTasks.Count,
state.ListType);
var cardReply = sc.Context.Activity.CreateReply();
cardReply.Attachments.Add(toDoListAttachment);
await sc.Context.SendActivityAsync(cardReply);
return await sc.NextAsync();
}
else
{
await sc.Context.SendActivityAsync(sc.Context.Activity.CreateReply(ToDoSharedResponses.ActionEnded));
return await sc.EndDialogAsync(true);
}
}
catch (SkillException ex)
{
await HandleDialogExceptions(sc, ex);
return new DialogTurnResult(DialogTurnStatus.Cancelled, CommonUtil.DialogTurnResultCancelAllDialogs);
}
catch (Exception ex)
{
await HandleDialogExceptions(sc, ex);
return new DialogTurnResult(DialogTurnStatus.Cancelled, CommonUtil.DialogTurnResultCancelAllDialogs);
}
}
protected async Task<DialogTurnResult> CollectTaskContent(WaterfallStepContext sc, CancellationToken cancellationToken = default(CancellationToken))
{
try
{
return await sc.BeginDialogAsync(Action.CollectTaskContent);
}
catch (Exception ex)
{
await HandleDialogExceptions(sc, ex);
return new DialogTurnResult(DialogTurnStatus.Cancelled, CommonUtil.DialogTurnResultCancelAllDialogs);
}
}
protected async Task<DialogTurnResult> AskTaskContent(WaterfallStepContext sc, CancellationToken cancellationToken = default(CancellationToken))
{
try
{
var state = await this.ToDoStateAccessor.GetAsync(sc.Context);
if (!string.IsNullOrEmpty(state.TaskContentPattern)
|| !string.IsNullOrEmpty(state.TaskContentML)
|| !string.IsNullOrEmpty(state.ShopContent))
{
return await sc.NextAsync();
}
else
{
var prompt = sc.Context.Activity.CreateReply(AddToDoResponses.AskTaskContentText);
return await sc.PromptAsync(Action.Prompt, new PromptOptions() { Prompt = prompt });
}
}
catch (Exception ex)
{
await HandleDialogExceptions(sc, ex);
return new DialogTurnResult(DialogTurnStatus.Cancelled, CommonUtil.DialogTurnResultCancelAllDialogs);
}
}
protected async Task<DialogTurnResult> AfterAskTaskContent(WaterfallStepContext sc, CancellationToken cancellationToken = default(CancellationToken))
{
try
{
var state = await ToDoStateAccessor.GetAsync(sc.Context);
if (string.IsNullOrEmpty(state.TaskContentPattern)
&& string.IsNullOrEmpty(state.TaskContentML)
&& string.IsNullOrEmpty(state.ShopContent))
{
if (sc.Result != null)
{
sc.Context.Activity.Properties.TryGetValue("OriginText", out var toDoContent);
state.TaskContent = toDoContent != null ? toDoContent.ToString() : sc.Context.Activity.Text;
return await sc.EndDialogAsync(true);
}
else
{
return await sc.ReplaceDialogAsync(Action.CollectTaskContent);
}
}
else
{
this.ExtractListTypeAndTaskContent(state);
return await sc.EndDialogAsync(true);
}
}
catch (Exception ex)
{
await HandleDialogExceptions(sc, ex);
return new DialogTurnResult(DialogTurnStatus.Cancelled, CommonUtil.DialogTurnResultCancelAllDialogs);
}
}
protected async Task<DialogTurnResult> CollectSwitchListTypeConfirmation(WaterfallStepContext sc, CancellationToken cancellationToken = default(CancellationToken))
{
try
{
var state = await ToDoStateAccessor.GetAsync(sc.Context);
if (state.SwitchListType)
{
state.SwitchListType = false;
return await sc.BeginDialogAsync(Action.CollectSwitchListTypeConfirmation);
}
else
{
return await sc.NextAsync();
}
}
catch (Exception ex)
{
await HandleDialogExceptions(sc, ex);
return new DialogTurnResult(DialogTurnStatus.Cancelled, CommonUtil.DialogTurnResultCancelAllDialogs);
}
}
protected async Task<DialogTurnResult> AskSwitchListTypeConfirmation(WaterfallStepContext sc, CancellationToken cancellationToken = default(CancellationToken))
{
try
{
var state = await ToDoStateAccessor.GetAsync(sc.Context);
var token = new StringDictionary() { { "listType", state.ListType } };
var response = GenerateResponseWithTokens(AddToDoResponses.SwitchListType, token);
var prompt = sc.Context.Activity.CreateReply(response);
prompt.Speak = response;
return await sc.PromptAsync(Action.Prompt, new PromptOptions() { Prompt = prompt });
}
catch (Exception ex)
{
await HandleDialogExceptions(sc, ex);
return new DialogTurnResult(DialogTurnStatus.Cancelled, CommonUtil.DialogTurnResultCancelAllDialogs);
}
}
protected async Task<DialogTurnResult> AfterAskSwitchListTypeConfirmation(WaterfallStepContext sc, CancellationToken cancellationToken = default(CancellationToken))
{
try
{
var state = await ToDoStateAccessor.GetAsync(sc.Context);
sc.Context.Activity.Properties.TryGetValue("OriginText", out var content);
var userInput = content != null ? content.ToString() : sc.Context.Activity.Text;
var promptRecognizerResult = ConfirmRecognizerHelper.ConfirmYesOrNo(userInput, sc.Context.Activity.Locale);
if (promptRecognizerResult.Succeeded && promptRecognizerResult.Value == true)
{
return await sc.EndDialogAsync(true);
}
else
{
state.ListType = state.LastListType;
state.LastListType = null;
return await sc.EndDialogAsync(true);
}
}
catch (Exception ex)
{
await HandleDialogExceptions(sc, ex);
return new DialogTurnResult(DialogTurnStatus.Cancelled, CommonUtil.DialogTurnResultCancelAllDialogs);
}
}
protected async Task<DialogTurnResult> CollectAddDupTaskConfirmation(WaterfallStepContext sc, CancellationToken cancellationToken = default(CancellationToken))
{
try
{
return await sc.BeginDialogAsync(Action.CollectAddDupTaskConfirmation);
}
catch (Exception ex)
{
await HandleDialogExceptions(sc, ex);
return new DialogTurnResult(DialogTurnStatus.Cancelled, CommonUtil.DialogTurnResultCancelAllDialogs);
}
}
protected async Task<DialogTurnResult> AskAddDupTaskConfirmation(WaterfallStepContext sc, CancellationToken cancellationToken = default(CancellationToken))
{
try
{
var state = await ToDoStateAccessor.GetAsync(sc.Context);
state.ListType = state.ListType ?? ToDoStrings.ToDo;
state.LastListType = state.ListType;
var service = await InitListTypeIds(sc);
var currentAllTasks = await service.GetTasksAsync(state.ListType);
state.AddDupTask = false;
var duplicatedTaskIndex = currentAllTasks.FindIndex(t => t.Topic.Equals(state.TaskContent, StringComparison.InvariantCultureIgnoreCase));
if (duplicatedTaskIndex < 0)
{
state.AddDupTask = true;
return await sc.NextAsync();
}
else
{
var token = new StringDictionary() { { "taskContent", state.TaskContent } };
var prompt = sc.Context.Activity.CreateReply(AddToDoResponses.AskAddDupTaskPrompt, tokens: token);
return await sc.PromptAsync(Action.Prompt, new PromptOptions() { Prompt = prompt });
}
}
catch (Exception ex)
{
await HandleDialogExceptions(sc, ex);
return new DialogTurnResult(DialogTurnStatus.Cancelled, CommonUtil.DialogTurnResultCancelAllDialogs);
}
}
protected async Task<DialogTurnResult> AfterAskAddDupTaskConfirmation(WaterfallStepContext sc, CancellationToken cancellationToken = default(CancellationToken))
{
try
{
var state = await ToDoStateAccessor.GetAsync(sc.Context);
if (!state.AddDupTask)
{
sc.Context.Activity.Properties.TryGetValue("OriginText", out var content);
var userInput = content != null ? content.ToString() : sc.Context.Activity.Text;
var promptRecognizerResult = ConfirmRecognizerHelper.ConfirmYesOrNo(userInput, sc.Context.Activity.Locale);
if (promptRecognizerResult.Succeeded && promptRecognizerResult.Value == true)
{
state.AddDupTask = true;
}
}
return await sc.EndDialogAsync(true);
}
catch (Exception ex)
{
await HandleDialogExceptions(sc, ex);
return new DialogTurnResult(DialogTurnStatus.Cancelled, CommonUtil.DialogTurnResultCancelAllDialogs);
}
}
protected async Task<DialogTurnResult> ContinueAddTask(WaterfallStepContext sc, CancellationToken cancellationToken = default(CancellationToken))
{
try
{
return await sc.BeginDialogAsync(Action.ContinueAddTask);
}
catch (Exception ex)
{
await HandleDialogExceptions(sc, ex);
return new DialogTurnResult(DialogTurnStatus.Cancelled, CommonUtil.DialogTurnResultCancelAllDialogs);
}
}
protected async Task<DialogTurnResult> AskContinueAddTask(WaterfallStepContext sc, CancellationToken cancellationToken = default(CancellationToken))
{
try
{
var state = await ToDoStateAccessor.GetAsync(sc.Context);
var prompt = sc.Context.Activity.CreateReply(AddToDoResponses.AddMoreTask, tokens: new StringDictionary() { { "listType", state.ListType } });
return await sc.PromptAsync(Action.Prompt, new PromptOptions() { Prompt = prompt });
}
catch (Exception ex)
{
await HandleDialogExceptions(sc, ex);
return new DialogTurnResult(DialogTurnStatus.Cancelled, CommonUtil.DialogTurnResultCancelAllDialogs);
}
}
protected async Task<DialogTurnResult> AfterAskContinueAddTask(WaterfallStepContext sc, CancellationToken cancellationToken = default(CancellationToken))
{
try
{
var state = await ToDoStateAccessor.GetAsync(sc.Context);
sc.Context.Activity.Properties.TryGetValue("OriginText", out var content);
var userInput = content != null ? content.ToString() : sc.Context.Activity.Text;
var promptRecognizerResult = ConfirmRecognizerHelper.ConfirmYesOrNo(userInput, sc.Context.Activity.Locale);
if (promptRecognizerResult.Succeeded && promptRecognizerResult.Value == true)
{
// reset some fields here
state.TaskContentPattern = null;
state.TaskContentML = null;
state.ShopContent = null;
state.TaskContent = null;
state.FoodOfGrocery = null;
state.HasShopVerb = false;
// replace current dialog to continue add more tasks
return await sc.ReplaceDialogAsync(Action.DoAddTask);
}
else
{
await sc.Context.SendActivityAsync(sc.Context.Activity.CreateReply(ToDoSharedResponses.ActionEnded));
return await sc.EndDialogAsync(true);
}
}
catch (Exception ex)
{
await HandleDialogExceptions(sc, ex);
return new DialogTurnResult(DialogTurnStatus.Cancelled, CommonUtil.DialogTurnResultCancelAllDialogs);
}
}
private void ExtractListTypeAndTaskContent(ToDoSkillState state)
{
if (state.HasShopVerb && !string.IsNullOrEmpty(state.FoodOfGrocery))
{
if (state.ListType != ToDoStrings.Grocery)
{
state.LastListType = state.ListType;
state.ListType = ToDoStrings.Grocery;
state.SwitchListType = true;
}
}
else if (state.HasShopVerb && !string.IsNullOrEmpty(state.ShopContent))
{
if (state.ListType != ToDoStrings.Shopping)
{
state.LastListType = state.ListType;
state.ListType = ToDoStrings.Shopping;
state.SwitchListType = true;
}
}
if (state.ListType == ToDoStrings.Grocery || state.ListType == ToDoStrings.Shopping)
{
state.TaskContent = string.IsNullOrEmpty(state.ShopContent) ? state.TaskContentML ?? state.TaskContentPattern : state.ShopContent;
}
else
{
state.ListType = ToDoStrings.ToDo;
state.TaskContent = state.TaskContentML ?? state.TaskContentPattern;
}
}
}
} | 44.607623 | 172 | 0.584418 | [
"MIT"
] | AllcryptoquickDevelopment/AI | solutions/Virtual-Assistant/src/csharp/skills/todoskill/todoskill/Dialogs/AddToDo/AddToDoItemDialog.cs | 19,897 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _004WeddingDecoration
{
class Program
{
static void Main(string[] args)
{
double budget = double.Parse(Console.ReadLine());
double flowersSum = 0;
double balloonsSum = 0;
double candlesSum = 0;
double ribbonSum = 0;
double totalSum = 0;
int flowersCount = 0;
int balloonsCount = 0;
int candlesCount = 0;
int ribbonCount = 0;
string stock = Console.ReadLine();
while (stock != "stop")
{
int numberStocks = int.Parse(Console.ReadLine());
if(stock == "flowers")
{
flowersSum = flowersSum + (numberStocks * 1.5);
flowersCount = flowersCount + numberStocks;
}
if(stock == "balloons")
{
balloonsSum = balloonsSum + (numberStocks * 0.1);
balloonsCount = balloonsCount + numberStocks;
}
if (stock == "candles")
{
candlesSum = candlesSum + (numberStocks * 0.5);
candlesCount = candlesCount + numberStocks;
}
if (stock == "ribbon")
{
ribbonSum = ribbonSum + (numberStocks * 2);
ribbonCount = ribbonCount + numberStocks;
}
totalSum = flowersSum + balloonsSum + candlesSum + ribbonSum;
if (budget <= totalSum)
{
Console.WriteLine("All money is spent!");
break;
}
stock = Console.ReadLine();
}
if (stock == "stop")
{
Console.WriteLine($"Spend money: {totalSum:F2}");
Console.WriteLine($"Money left: {budget-totalSum:F2}");
}
Console.WriteLine($"Purchased decoration is {balloonsCount} balloons, {ribbonCount} m ribbon, {flowersCount} flowers and {candlesCount} candles.");
}
}
}
| 32.239437 | 159 | 0.473569 | [
"MIT"
] | kalintsenkov/SoftUni-Software-Engineering | CSharp-Programming-Basics/Exams/ExamNovember2018/004WeddingDecoration/Program.cs | 2,291 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LockZ : MonoBehaviour
{
private Transform trans;
// Start is called before the first frame update
void Awake()
{
trans = GetComponent<Transform>();
}
// Update is called once per frame
void LateUpdate()
{
trans.rotation = Quaternion.Euler(90f, 0f, 0f);
}
}
| 20.2 | 55 | 0.655941 | [
"MIT"
] | cortstar/AlbertaGameJam2019 | AlbertaGameJam2019/Assets/LockZ.cs | 406 | C# |
using Amazon.JSII.Runtime.Deputy;
#pragma warning disable CS0672,CS0809,CS1591
namespace aws
{
[JsiiByValue(fqn: "aws.Wafv2WebAclRuleStatementOrStatementStatementOrStatementStatementOrStatementStatement")]
public class Wafv2WebAclRuleStatementOrStatementStatementOrStatementStatementOrStatementStatement : aws.IWafv2WebAclRuleStatementOrStatementStatementOrStatementStatementOrStatementStatement
{
/// <summary>byte_match_statement block.</summary>
[JsiiOptional]
[JsiiProperty(name: "byteMatchStatement", typeJson: "{\"collection\":{\"elementtype\":{\"fqn\":\"aws.Wafv2WebAclRuleStatementOrStatementStatementOrStatementStatementOrStatementStatementByteMatchStatement\"},\"kind\":\"array\"}}", isOptional: true, isOverride: true)]
public aws.IWafv2WebAclRuleStatementOrStatementStatementOrStatementStatementOrStatementStatementByteMatchStatement[]? ByteMatchStatement
{
get;
set;
}
/// <summary>geo_match_statement block.</summary>
[JsiiOptional]
[JsiiProperty(name: "geoMatchStatement", typeJson: "{\"collection\":{\"elementtype\":{\"fqn\":\"aws.Wafv2WebAclRuleStatementOrStatementStatementOrStatementStatementOrStatementStatementGeoMatchStatement\"},\"kind\":\"array\"}}", isOptional: true, isOverride: true)]
public aws.IWafv2WebAclRuleStatementOrStatementStatementOrStatementStatementOrStatementStatementGeoMatchStatement[]? GeoMatchStatement
{
get;
set;
}
/// <summary>ip_set_reference_statement block.</summary>
[JsiiOptional]
[JsiiProperty(name: "ipSetReferenceStatement", typeJson: "{\"collection\":{\"elementtype\":{\"fqn\":\"aws.Wafv2WebAclRuleStatementOrStatementStatementOrStatementStatementOrStatementStatementIpSetReferenceStatement\"},\"kind\":\"array\"}}", isOptional: true, isOverride: true)]
public aws.IWafv2WebAclRuleStatementOrStatementStatementOrStatementStatementOrStatementStatementIpSetReferenceStatement[]? IpSetReferenceStatement
{
get;
set;
}
/// <summary>regex_pattern_set_reference_statement block.</summary>
[JsiiOptional]
[JsiiProperty(name: "regexPatternSetReferenceStatement", typeJson: "{\"collection\":{\"elementtype\":{\"fqn\":\"aws.Wafv2WebAclRuleStatementOrStatementStatementOrStatementStatementOrStatementStatementRegexPatternSetReferenceStatement\"},\"kind\":\"array\"}}", isOptional: true, isOverride: true)]
public aws.IWafv2WebAclRuleStatementOrStatementStatementOrStatementStatementOrStatementStatementRegexPatternSetReferenceStatement[]? RegexPatternSetReferenceStatement
{
get;
set;
}
/// <summary>size_constraint_statement block.</summary>
[JsiiOptional]
[JsiiProperty(name: "sizeConstraintStatement", typeJson: "{\"collection\":{\"elementtype\":{\"fqn\":\"aws.Wafv2WebAclRuleStatementOrStatementStatementOrStatementStatementOrStatementStatementSizeConstraintStatement\"},\"kind\":\"array\"}}", isOptional: true, isOverride: true)]
public aws.IWafv2WebAclRuleStatementOrStatementStatementOrStatementStatementOrStatementStatementSizeConstraintStatement[]? SizeConstraintStatement
{
get;
set;
}
/// <summary>sqli_match_statement block.</summary>
[JsiiOptional]
[JsiiProperty(name: "sqliMatchStatement", typeJson: "{\"collection\":{\"elementtype\":{\"fqn\":\"aws.Wafv2WebAclRuleStatementOrStatementStatementOrStatementStatementOrStatementStatementSqliMatchStatement\"},\"kind\":\"array\"}}", isOptional: true, isOverride: true)]
public aws.IWafv2WebAclRuleStatementOrStatementStatementOrStatementStatementOrStatementStatementSqliMatchStatement[]? SqliMatchStatement
{
get;
set;
}
/// <summary>xss_match_statement block.</summary>
[JsiiOptional]
[JsiiProperty(name: "xssMatchStatement", typeJson: "{\"collection\":{\"elementtype\":{\"fqn\":\"aws.Wafv2WebAclRuleStatementOrStatementStatementOrStatementStatementOrStatementStatementXssMatchStatement\"},\"kind\":\"array\"}}", isOptional: true, isOverride: true)]
public aws.IWafv2WebAclRuleStatementOrStatementStatementOrStatementStatementOrStatementStatementXssMatchStatement[]? XssMatchStatement
{
get;
set;
}
}
}
| 59.945946 | 304 | 0.731515 | [
"MIT"
] | scottenriquez/cdktf-alpha-csharp-testing | resources/.gen/aws/aws/Wafv2WebAclRuleStatementOrStatementStatementOrStatementStatementOrStatementStatement.cs | 4,436 | 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("LuceneManager")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("LuceneManager")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[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("382ea2d9-80e2-4fc2-8aea-4abc9d730249")]
// 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 Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.75 | 84 | 0.74908 | [
"Apache-2.0"
] | NielsKuhnel/NrtManager | source/LuceneManager/Properties/AssemblyInfo.cs | 1,362 | C# |
using System;
namespace Musoq.Parser.Nodes
{
public class IsNullNode : Node
{
public IsNullNode(Node expression, bool isNegated)
{
IsNegated = isNegated;
Id = $"{nameof(IsNullNode)}{isNegated}";
Expression = expression;
}
public Node Expression { get; }
public bool IsNegated { get; }
public override Type ReturnType => typeof(bool);
public override string Id { get; }
public override void Accept(IExpressionVisitor visitor)
{
visitor.Visit(this);
}
public override string ToString()
{
return IsNegated ? $"{Expression.ToString()} is not null" : $"{Expression.ToString()} is null";
}
}
} | 24.09375 | 107 | 0.565499 | [
"MIT"
] | JTOne123/Musoq | Musoq.Parser/Nodes/IsNullNode.cs | 773 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the customer-profiles-2020-08-15.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.CustomerProfiles.Model
{
/// <summary>
/// Container for the parameters to the PutProfileObject operation.
/// Adds additional objects to customer profiles of a given ObjectType.
///
///
/// <para>
/// When adding a specific profile object, like a Contact Trace Record (CTR), an inferred
/// profile can get created if it is not mapped to an existing profile. The resulting
/// profile will only have a phone number populated in the standard ProfileObject. Any
/// additional CTRs with the same phone number will be mapped to the same inferred profile.
/// </para>
///
/// <para>
/// When a ProfileObject is created and if a ProfileObjectType already exists for the
/// ProfileObject, it will provide data to a standard profile depending on the ProfileObjectType
/// definition.
/// </para>
///
/// <para>
/// PutProfileObject needs an ObjectType, which can be created using PutProfileObjectType.
/// </para>
/// </summary>
public partial class PutProfileObjectRequest : AmazonCustomerProfilesRequest
{
private string _domainName;
private string _object;
private string _objectTypeName;
/// <summary>
/// Gets and sets the property DomainName.
/// <para>
/// The unique name of the domain.
/// </para>
/// </summary>
[AWSProperty(Required=true, Min=1, Max=64)]
public string DomainName
{
get { return this._domainName; }
set { this._domainName = value; }
}
// Check to see if DomainName property is set
internal bool IsSetDomainName()
{
return this._domainName != null;
}
/// <summary>
/// Gets and sets the property Object.
/// <para>
/// A string that is serialized from a JSON object.
/// </para>
/// </summary>
[AWSProperty(Required=true, Min=1, Max=256000)]
public string Object
{
get { return this._object; }
set { this._object = value; }
}
// Check to see if Object property is set
internal bool IsSetObject()
{
return this._object != null;
}
/// <summary>
/// Gets and sets the property ObjectTypeName.
/// <para>
/// The name of the profile object type.
/// </para>
/// </summary>
[AWSProperty(Required=true, Min=1, Max=255)]
public string ObjectTypeName
{
get { return this._objectTypeName; }
set { this._objectTypeName = value; }
}
// Check to see if ObjectTypeName property is set
internal bool IsSetObjectTypeName()
{
return this._objectTypeName != null;
}
}
} | 32.188034 | 115 | 0.616835 | [
"Apache-2.0"
] | ChristopherButtars/aws-sdk-net | sdk/src/Services/CustomerProfiles/Generated/Model/PutProfileObjectRequest.cs | 3,766 | 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: IEntityCollectionRequestBuilder.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
/// <summary>
/// The interface IGraphServiceGroupSettingsCollectionRequestBuilder.
/// </summary>
public partial interface IGraphServiceGroupSettingsCollectionRequestBuilder : IBaseRequestBuilder
{
/// <summary>
/// Builds the request.
/// </summary>
/// <returns>The built request.</returns>
IGraphServiceGroupSettingsCollectionRequest Request();
/// <summary>
/// Builds the request.
/// </summary>
/// <param name="options">The query and header options for the request.</param>
/// <returns>The built request.</returns>
IGraphServiceGroupSettingsCollectionRequest Request(IEnumerable<Option> options);
/// <summary>
/// Gets an <see cref="IGroupSettingRequestBuilder"/> for the specified GroupSetting.
/// </summary>
/// <param name="id">The ID for the GroupSetting.</param>
/// <returns>The <see cref="IGroupSettingRequestBuilder"/>.</returns>
IGroupSettingRequestBuilder this[string id] { get; }
}
}
| 39.166667 | 153 | 0.599392 | [
"MIT"
] | Aliases/msgraph-sdk-dotnet | src/Microsoft.Graph/Generated/requests/IGraphServiceGroupSettingsCollectionRequestBuilder.cs | 1,645 | C# |
using FileExplorerGallery.Common;
using FileExplorerGallery.Helpers;
using FileExplorerGallery.Settings;
using FileExplorerGallery.ViewModelContracts;
using System.ComponentModel.Composition;
using System.Reflection;
using System.Windows.Input;
namespace FileExplorerGallery.ViewModels
{
[Export(typeof(ISettingsViewModel))]
public class SettingsViewModel : ViewModelBase, ISettingsViewModel
{
private readonly IUserSettings _userSettings;
private bool _showingKeyboardCaptureOverlay = false;
private string _shortcutPreview;
private bool _checkingForUpdateInProgress;
[ImportingConstructor]
public SettingsViewModel(IUserSettings userSettings, AppUpdateManager appUpdateManager)
{
ChangeShortcutCommand = new RelayCommand(() =>
{
ShortCutPreview = ShortCut;
ShowingKeyboardCaptureOverlay = true;
});
ConfirmShortcutCommand = new RelayCommand(() =>
{
ShortCut = ShortCutPreview;
ShowingKeyboardCaptureOverlay = false;
});
CancelShortcutCommand = new RelayCommand(() =>
{
ShowingKeyboardCaptureOverlay = false;
});
CheckForUpdatesCommand = new RelayCommand(async () =>
{
CheckingForUpdateInProgress = true;
if (await appUpdateManager.IsNewUpdateAvailable())
{
await appUpdateManager.Update();
}
CheckingForUpdateInProgress = false;
});
_userSettings = userSettings;
_userSettings.ActivationShortcut.PropertyChanged += (s, e) => { OnPropertyChanged(nameof(ShortCut)); };
}
public bool RunOnStartup
{
get
{
return _userSettings.RunOnStartup.Value;
}
set
{
// only set value if registry save successful
if (RegistryHelper.SetRunOnStartup(value))
{
_userSettings.RunOnStartup.Value = value;
OnPropertyChanged();
}
}
}
public string ShortCut
{
get
{
return _userSettings.ActivationShortcut.Value;
}
private set
{
_userSettings.ActivationShortcut.Value = value;
OnPropertyChanged();
}
}
public string ShortCutPreview
{
get
{
return _shortcutPreview;
}
set
{
_shortcutPreview = value;
OnPropertyChanged();
}
}
public bool AutomaticUpdates
{
get
{
return _userSettings.AutomaticUpdates.Value;
}
set
{
_userSettings.AutomaticUpdates.Value = value;
OnPropertyChanged();
}
}
public int SlideshowDuration
{
get
{
return _userSettings.SlideshowDuration.Value;
}
set
{
_userSettings.SlideshowDuration.Value = value;
OnPropertyChanged();
}
}
public bool ShowingKeyboardCaptureOverlay
{
get
{
return _showingKeyboardCaptureOverlay;
}
set
{
_showingKeyboardCaptureOverlay = value;
OnPropertyChanged();
}
}
public bool CheckingForUpdateInProgress
{
get
{
return _checkingForUpdateInProgress;
}
set
{
_checkingForUpdateInProgress = value;
OnPropertyChanged();
}
}
public bool ShowDeleteConfirmation
{
get
{
return _userSettings.ShowDeleteConfirmation.Value;
}
set
{
_userSettings.ShowDeleteConfirmation.Value = value;
OnPropertyChanged();
}
}
public bool BackupDeletedImages
{
get
{
return _userSettings.BackupDeletedImages.Value;
}
set
{
_userSettings.BackupDeletedImages.Value = value;
OnPropertyChanged();
}
}
public string ApplicationVersion { get { return Assembly.GetExecutingAssembly().GetName().Version.ToString(); } }
public ICommand ChangeShortcutCommand { get; }
public ICommand CheckForUpdatesCommand { get; }
public ICommand ConfirmShortcutCommand { get; }
public ICommand CancelShortcutCommand { get; }
}
}
| 27.48913 | 121 | 0.51206 | [
"MIT"
] | ScriptBox99/FileExplorerGallery | FileExplorerGallery/ViewModels/SettingsViewModel.cs | 5,060 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace Amido.Stacks.DependencyInjection
{
public static class AssemblyExtensions
{
/// <summary>
/// Returns a dictionary with the Implemented Interface as key and the type that implements it
/// </summary>
/// <param name="assembly">Assembly containing the implementations of the interface</param>
/// <param name="openGenericType">The interface being implemented</param>
public static List<(Type interfaceVariation, Type implementation)> GetImplementationsOf(this Assembly assembly, params Type[] openGenericTypes)
{
List<(Type, Type)> implementations = new List<(Type, Type)>();
foreach (var openGenericType in openGenericTypes)
{
foreach (var type in assembly.GetTypes().Where(t => !t.IsAbstract && !t.IsInterface))
{
foreach (var implementedInterface in type.GetInterfaces()
.Where(x => x == openGenericType ||
(
x.IsGenericType &&
x.GetGenericTypeDefinition() == openGenericType
)))
{
implementations.Add((implementedInterface, type));
}
}
}
return implementations;
}
}
}
| 44.947368 | 151 | 0.483021 | [
"MIT"
] | amido/stacks-dotnet-packages-dependencyinjection | src/Amido.Stacks.DependencyInjection/AssemblyExtensions.cs | 1,708 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Nextt_Gestao_Compra.Aplicacao.ViewModel
{
public class EntradaNFPackPedidoSalvarVM
{
public string IDNFFornecedorPack { get; set; }
public string Agrupamento { get; set; }
public string TipoPack { get; set; }
public int QtdeEntregue { get; set; }
public int QtdeNota { get; set; }
public int Pack { get; set; }
public int IDPedido { get; set; }
public List<EntradaNFPackItensSalvarVM> NFFornecedorPackProdutoItems { get; set; }
}
}
| 27.73913 | 90 | 0.677116 | [
"MIT"
] | Philipe1985/NexttWeb | Nextt_Gestao_Compra/Nextt_Gestao_Compra.Aplicacao/ViewModel/EntradaNFPackPedidoSalvarVM.cs | 640 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.18033
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace MixERP.Net.FrontEnd.Purchase {
public partial class Invoice {
protected System.Web.UI.WebControls.Content Content1;
}
}
| 28.315789 | 80 | 0.48513 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | gj86/mixerp2 | MixERP.Net.FrontEnd/Purchase/Invoice.aspx.designer.cs | 538 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using Foundation;
using UIKit;
namespace HyperlinkText.iOS
{
// The UIApplicationDelegate for the application. This class is responsible for launching the
// User Interface of the application, as well as listening (and optionally responding) to
// application events from iOS.
[Register("AppDelegate")]
public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate
{
//
// This method is invoked when the application has loaded and is ready to run. In this
// method you should instantiate the window, load the UI into it and then make the window
// visible.
//
// You have 17 seconds to return from this method, or iOS will terminate your application.
//
public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
global::Xamarin.Forms.Forms.Init();
LoadApplication(new App());
return base.FinishedLaunching(app, options);
}
}
}
| 34.5 | 98 | 0.678442 | [
"MIT"
] | JaridKG/xamarin-forms | HyperlinkText/HyperlinkText.iOS/AppDelegate.cs | 1,106 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace lab_47_API_framework.Models
{
using System;
using System.Collections.Generic;
public partial class Alphabetical_list_of_product
{
public int ProductID { get; set; }
public string ProductName { get; set; }
public Nullable<int> SupplierID { get; set; }
public Nullable<int> CategoryID { get; set; }
public string QuantityPerUnit { get; set; }
public Nullable<decimal> UnitPrice { get; set; }
public Nullable<short> UnitsInStock { get; set; }
public Nullable<short> UnitsOnOrder { get; set; }
public Nullable<short> ReorderLevel { get; set; }
public bool Discontinued { get; set; }
public string CategoryName { get; set; }
}
}
| 39.033333 | 85 | 0.567891 | [
"MIT"
] | SamRibes/2019-09-c-sharp-labs | labs/lab_47_API_framework/Models/Alphabetical_list_of_product.cs | 1,171 | C# |
#if !NET40PLUS
namespace System.Runtime.CompilerServices
{
using System.Threading.Tasks;
/// <summary>Provides a base class used to cache tasks of a specific return type.</summary>
/// <typeparam name="TResult">Specifies the type of results the cached tasks return.</typeparam>
internal class AsyncMethodTaskCache<TResult>
{
/// <summary>
/// A singleton cache for this result type. This may be <see langword="null"/> if there are no cached tasks for
/// this <typeparamref name="TResult"/>.
/// </summary>
internal static readonly AsyncMethodTaskCache<TResult> Singleton = CreateCache();
/// <summary>Creates a non-disposable task.</summary>
/// <param name="result">The result for the task.</param>
/// <returns>The cacheable task.</returns>
internal static TaskCompletionSource<TResult> CreateCompleted(TResult result)
{
TaskCompletionSource<TResult> taskCompletionSource = new TaskCompletionSource<TResult>();
taskCompletionSource.TrySetResult(result);
return taskCompletionSource;
}
/// <summary>Creates a cache.</summary>
/// <returns>A task cache for this result type.</returns>
private static AsyncMethodTaskCache<TResult> CreateCache()
{
Type typeFromHandle = typeof(TResult);
if (typeFromHandle == typeof(bool))
{
return (AsyncMethodTaskCache<TResult>)(object)new AsyncMethodBooleanTaskCache();
}
if (typeFromHandle == typeof(int))
{
return (AsyncMethodTaskCache<TResult>)(object)new AsyncMethodInt32TaskCache();
}
return null;
}
/// <summary>Gets a cached task if one exists.</summary>
/// <param name="result">The result for which we want a cached task.</param>
/// <returns>A cached task if one exists; otherwise, <see langword="null"/>.</returns>
internal virtual TaskCompletionSource<TResult> FromResult(TResult result)
{
return CreateCompleted(result);
}
/// <summary>Provides a cache for <see cref="bool"/> tasks.</summary>
private sealed class AsyncMethodBooleanTaskCache : AsyncMethodTaskCache<bool>
{
/// <summary>A <see langword="true"/> task.</summary>
private readonly TaskCompletionSource<bool> _true = CreateCompleted(true);
/// <summary>A <see langword="false"/> task.</summary>
private readonly TaskCompletionSource<bool> _false = CreateCompleted(false);
/// <summary>Gets a cached task for the <see cref="bool"/> result.</summary>
/// <param name="result"><see langword="true"/> or <see langword="false"/></param>
/// <returns>A cached task for the <see cref="bool"/> result.</returns>
internal sealed override TaskCompletionSource<bool> FromResult(bool result)
{
if (!result)
{
return _false;
}
return _true;
}
}
/// <summary>Provides a cache for <see cref="int"/> tasks.</summary>
private sealed class AsyncMethodInt32TaskCache : AsyncMethodTaskCache<int>
{
/// <summary>The minimum value, inclusive, for which we want a cached task.</summary>
internal const int INCLUSIVE_INT32_MIN = -1;
/// <summary>The maximum value, exclusive, for which we want a cached task.</summary>
internal const int EXCLUSIVE_INT32_MAX = 9;
/// <summary>The cache of <see cref="int"/>-returning <see cref="Task{TResult}"/> instances.</summary>
internal static readonly TaskCompletionSource<int>[] Int32Tasks = CreateInt32Tasks();
/// <summary>
/// Creates an array of cached tasks for the values in the range [<see cref="INCLUSIVE_INT32_MIN"/>,
/// <see cref="EXCLUSIVE_INT32_MAX"/>).
/// </summary>
private static TaskCompletionSource<int>[] CreateInt32Tasks()
{
TaskCompletionSource<int>[] array = new TaskCompletionSource<int>[EXCLUSIVE_INT32_MAX - INCLUSIVE_INT32_MIN];
for (int i = 0; i < array.Length; i++)
{
array[i] = CreateCompleted(i + INCLUSIVE_INT32_MIN);
}
return array;
}
/// <summary>Gets a cached task for the <see cref="int"/> result.</summary>
/// <param name="result">The integer value.</param>
/// <returns>
/// A cached task for the <see cref="int"/> result; otherwise, <see langword="null"/> if no task is cached
/// for the value <paramref name="result"/>.
/// </returns>
internal sealed override TaskCompletionSource<int> FromResult(int result)
{
if (result < INCLUSIVE_INT32_MIN || result >= EXCLUSIVE_INT32_MAX)
{
return CreateCompleted(result);
}
return Int32Tasks[result - INCLUSIVE_INT32_MIN];
}
}
}
}
#endif
| 43.739837 | 126 | 0.575651 | [
"MIT"
] | JTOne123/MinimumAsyncBridge | src/MinimumAsync/MinimumAsyncBridge/Runtime/CompilerServices/AsyncMethodTaskCache.cs | 5,382 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the discovery-2015-11-01.normal.json service model.
*/
using System;
using Amazon.Runtime;
using Amazon.Util.Internal;
namespace Amazon.ApplicationDiscoveryService
{
/// <summary>
/// Configuration for accessing Amazon ApplicationDiscoveryService service
/// </summary>
public partial class AmazonApplicationDiscoveryServiceConfig : ClientConfig
{
private static readonly string UserAgentString =
InternalSDKUtils.BuildUserAgentString("3.3.102.85");
private string _userAgent = UserAgentString;
/// <summary>
/// Default constructor
/// </summary>
public AmazonApplicationDiscoveryServiceConfig()
{
this.AuthenticationServiceName = "discovery";
}
/// <summary>
/// The constant used to lookup in the region hash the endpoint.
/// </summary>
public override string RegionEndpointServiceName
{
get
{
return "discovery";
}
}
/// <summary>
/// Gets the ServiceVersion property.
/// </summary>
public override string ServiceVersion
{
get
{
return "2015-11-01";
}
}
/// <summary>
/// Gets the value of UserAgent property.
/// </summary>
public override string UserAgent
{
get
{
return _userAgent;
}
}
}
} | 27.1125 | 107 | 0.602121 | [
"Apache-2.0"
] | Melvinerall/aws-sdk-net | sdk/src/Services/ApplicationDiscoveryService/Generated/AmazonApplicationDiscoveryServiceConfig.cs | 2,169 | C# |
using Interpidians.Catalyst.Core.ApplicationService;
using Interpidians.Catalyst.Core.Entity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Interpidians.Catalyst.Client.Web.Controllers
{
public partial class EmployeeController : BaseController
{
private IEmployeeService Service { get; set; }
public EmployeeController(IEmployeeService service)
{
this.Service = service;
}
public virtual ActionResult Index()
{
return this.RedirectToAction(MVC.Employee.List());
}
public virtual ActionResult List()
{
List<Employee> lstEmployee = this.Service.GetAll();
return View(lstEmployee);
}
}
}
| 23.617647 | 63 | 0.65878 | [
"MIT"
] | prashantkakde31/Catalyst | app/SRC/Interpidians.Catalyst/Interpidians.Catalyst.Client.Web/Controllers/EmployeeController.cs | 805 | C# |
using System.Collections.Generic;
using SchoolSystem.CLI.Core.Contracts;
using SchoolSystem.CLI.Models;
using SchoolSystem.CLI.Models.Enums;
namespace SchoolSystem.CLI.Core.Commands
{
public class CreateStudentCommand : ICommand
{
private static int id = 0;
public string Execute(IList<string> parameters)
{
var firstName = parameters[0];
var lastName = parameters[1];
var grade = (Grade)int.Parse(parameters[2]);
var student = new Student(firstName, lastName, grade);
Engine.Students.Add(id, student);
var result = $"A new student with name {firstName} {lastName}," +
$" grade {grade} and ID {id++} was created.";
return result;
}
}
}
| 29.407407 | 77 | 0.607053 | [
"MIT"
] | BogdanDimov/HQC-2-HW | Topics/Exam/Task/Exam/SchoolSystem.CLI/Core/Commands/CreateStudentCommand.cs | 796 | 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("SetPrintSettingsInXls")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("SetPrintSettingsInXls")]
[assembly: AssemblyCopyright("Copyright © 2009")]
[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("23cce8ae-c526-4371-a2f5-b9a070e486e8")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.243243 | 84 | 0.74841 | [
"Apache-2.0"
] | 0xAAE/npoi | examples/hssf/SetPrintSettingsInXls/Properties/AssemblyInfo.cs | 1,418 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the appflow-2020-08-23.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Serialization;
using Amazon.Appflow.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.Appflow.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for DescribeConnectorEntity operation
/// </summary>
public class DescribeConnectorEntityResponseUnmarshaller : JsonResponseUnmarshaller
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context)
{
DescribeConnectorEntityResponse response = new DescribeConnectorEntityResponse();
context.Read();
int targetDepth = context.CurrentDepth;
while (context.ReadAtDepth(targetDepth))
{
if (context.TestExpression("connectorEntityFields", targetDepth))
{
var unmarshaller = new ListUnmarshaller<ConnectorEntityField, ConnectorEntityFieldUnmarshaller>(ConnectorEntityFieldUnmarshaller.Instance);
response.ConnectorEntityFields = unmarshaller.Unmarshall(context);
continue;
}
}
return response;
}
/// <summary>
/// Unmarshaller error response to exception.
/// </summary>
/// <param name="context"></param>
/// <param name="innerException"></param>
/// <param name="statusCode"></param>
/// <returns></returns>
public override AmazonServiceException UnmarshallException(JsonUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode)
{
var errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context);
errorResponse.InnerException = innerException;
errorResponse.StatusCode = statusCode;
var responseBodyBytes = context.GetResponseBodyBytes();
using (var streamCopy = new MemoryStream(responseBodyBytes))
using (var contextCopy = new JsonUnmarshallerContext(streamCopy, false, null))
{
if (errorResponse.Code != null && errorResponse.Code.Equals("ConnectorAuthenticationException"))
{
return ConnectorAuthenticationExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("ConnectorServerException"))
{
return ConnectorServerExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("InternalServerException"))
{
return InternalServerExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("ResourceNotFoundException"))
{
return ResourceNotFoundExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("ValidationException"))
{
return ValidationExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
}
return new AmazonAppflowException(errorResponse.Message, errorResponse.InnerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode);
}
private static DescribeConnectorEntityResponseUnmarshaller _instance = new DescribeConnectorEntityResponseUnmarshaller();
internal static DescribeConnectorEntityResponseUnmarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static DescribeConnectorEntityResponseUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 41.436508 | 190 | 0.652749 | [
"Apache-2.0"
] | ChristopherButtars/aws-sdk-net | sdk/src/Services/Appflow/Generated/Model/Internal/MarshallTransformations/DescribeConnectorEntityResponseUnmarshaller.cs | 5,221 | C# |
// ==========================================================================
// Squidex Headless CMS
// ==========================================================================
// Copyright (c) Squidex UG (haftungsbeschraenkt)
// All rights reserved. Licensed under the MIT license.
// ==========================================================================
using System;
using System.Collections.Concurrent;
using System.Threading;
#pragma warning disable CS8601 // Possible null reference assignment.
namespace Squidex.Caching
{
public sealed class AsyncLocalCache : ILocalCache
{
private static readonly AsyncLocal<ConcurrentDictionary<object, object>> LocalCache = new AsyncLocal<ConcurrentDictionary<object, object>>();
private static readonly AsyncLocalCleaner<ConcurrentDictionary<object, object>> Cleaner;
static AsyncLocalCache()
{
Cleaner = new AsyncLocalCleaner<ConcurrentDictionary<object, object>>(LocalCache);
}
public IDisposable StartContext()
{
LocalCache.Value = new ConcurrentDictionary<object, object>();
return Cleaner;
}
public void Add(object key, object? value)
{
var cacheKey = GetCacheKey(key);
var cache = LocalCache.Value;
if (cache != null)
{
cache[cacheKey] = value;
}
}
public void Remove(object key)
{
var cacheKey = GetCacheKey(key);
var cache = LocalCache.Value;
if (cache != null)
{
cache.TryRemove(cacheKey, out _);
}
}
public bool TryGetValue(object key, out object? value)
{
var cacheKey = GetCacheKey(key);
var cache = LocalCache.Value;
if (cache != null)
{
return cache.TryGetValue(cacheKey, out value);
}
value = null;
return false;
}
private static string GetCacheKey(object key)
{
return $"CACHE_{key}";
}
}
}
| 27.253165 | 149 | 0.509522 | [
"MIT"
] | Squidex/caching | Squidex.Caching/AsyncLocalCache.cs | 2,155 | C# |
// 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.
//
// Copyright (c) 2008 Novell, Inc.
//
// Authors:
// Carlos Alberto Cortez <calberto.cortez@gmail.com>
//
using System;
using System.ComponentModel;
using System.Windows.Forms;
using NUnit.Framework;
namespace MonoTests.System.Windows.Forms.DataBinding {
[TestFixture]
public class BindingsCollectionTest : TestHelper
{
#if NET_2_0
//
// CollectionChanging event test section
//
bool collection_changing_called;
int collection_expected_count;
string collection_expected_assert;
CollectionChangeAction collection_action_expected;
object collection_element_expected;
void CollectionChangingHandler (object o, CollectionChangeEventArgs args)
{
BindingsCollection coll = (BindingsCollection)o;
collection_changing_called = true;
Assert.AreEqual (collection_expected_count, coll.Count, collection_expected_assert + "-0");
Assert.AreEqual (collection_action_expected, args.Action, collection_expected_assert + "-1");
Assert.AreEqual (collection_element_expected, args.Element, collection_expected_assert + "-2");
}
[Test]
public void CollectionChangingTest ()
{
Control c = new Control ();
c.BindingContext = new BindingContext ();
c.CreateControl ();
ControlBindingsCollection binding_coll = c.DataBindings;
Binding binding = new Binding ("Text", new MockItem ("A", 0), "Text");
Binding binding2 = new Binding ("Name", new MockItem ("B", 0), "Text");
binding_coll.Add (binding);
binding_coll.CollectionChanging += CollectionChangingHandler;
collection_expected_count = 1;
collection_action_expected = CollectionChangeAction.Add;
collection_element_expected = binding2;
collection_expected_assert = "#A0";
binding_coll.Add (binding2);
Assert.IsTrue (collection_changing_called, "#A1");
collection_changing_called = false;
collection_expected_count = 2;
collection_action_expected = CollectionChangeAction.Remove;
collection_element_expected = binding;
collection_expected_assert = "#B0";
binding_coll.Remove (binding);
Assert.IsTrue (collection_changing_called, "#B1");
collection_changing_called = false;
collection_expected_count = 1;
collection_element_expected = null;
collection_action_expected = CollectionChangeAction.Refresh;
collection_expected_assert = "#C0";
binding_coll.Clear ();
Assert.IsTrue (collection_changing_called, "#C1");
}
#endif
}
}
| 34.82 | 98 | 0.76077 | [
"Apache-2.0"
] | 121468615/mono | mcs/class/Managed.Windows.Forms/Test/System.Windows.Forms/BindingsCollectionTest.cs | 3,482 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.