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 |
|---|---|---|---|---|---|---|---|---|
// MIT License
// Copyright (c) 2019 Daniel Kubis
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
using System.Net;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace IPAddressExtension.UnitTest
{
[TestClass()]
public class ReservedAddressTest
{
/// <summary>
///Die erste und letzte IPv4-Adresse eines Subnetzes sind reserviert
/// x.x.x.0: Netz- oder Subnetz-Adresse
///</summary>
[TestMethod()]
[TestCategory("Gated")]
public void Ipv4NetOrSubNetTests()
{
var ip = IPAddress.Parse("195.1.1.0");
Assert.IsTrue(ip.IsReservedAddress());
ip = IPAddress.Parse("19.1.1.0");
Assert.IsTrue(ip.IsReservedAddress());
}
/// <summary>
///Die erste und letzte IPv4-Adresse eines Subnetzes sind reserviert
/// x.x.x.255: Broadcast-Adresse
///</summary>
[TestMethod()]
[TestCategory("Gated")]
public void Ipv4BroadcastTests()
{
var ip = IPAddress.Parse("195.1.1.255");
Assert.IsTrue(ip.IsReservedAddress());
ip = IPAddress.Parse("19.1.1.255");
Assert.IsTrue(ip.IsReservedAddress());
}
/// <summary>
/// Nicht routbare IPv4-Adressen
/// 0.0.0.0/8 (0.0.0.0 bis 0.255.255.255): Standard- bzw.Default-Route im Subnetz(Current Network).
/// 127.0.0.0/8 (127.0.0.0 bis 127.255.255.255): Reserviert f�r den Local Loop bzw.Loopback.
/// </summary>
[TestMethod()]
[TestCategory("Gated")]
public void Ipv4NotRoutableTests()
{
var ip = IPAddress.Parse("0.0.0.0");
Assert.IsTrue(ip.IsReservedAddress(), "Standard- bzw. Default-Route im Subnetz (Current Network)");
ip = IPAddress.Parse("0.255.255.5");
Assert.IsTrue(ip.IsReservedAddress(), "Standard- bzw. Default-Route im Subnetz (Current Network)");
ip = IPAddress.Parse("0.255.255.255");
Assert.IsTrue(ip.IsReservedAddress(), "Standard- bzw. Default-Route im Subnetz (Current Network)");
ip = IPAddress.Parse("127.255.255.255");
Assert.IsTrue(ip.IsReservedAddress(), "Reserviert f�r den Local Loop bzw. Loopback.");
ip = IPAddress.Parse("127.0.0.2");
Assert.IsTrue(ip.IsReservedAddress(), "Reserviert f�r den Local Loop bzw. Loopback.");
}
/// <summary>
/// Private IPv4-Adressen
/// 10.0.0.0/8 (10.0.0.0 bis 10.255.255.255): Reserviert f�r die Nutzung in privaten Netzwerken.Nicht im Internet routbar.
/// 172.16.0.0/12 (172.16.0.0 bis 172.31.255.255): Reserviert f�r die Nutzung in privaten Netzwerken.Nicht im Internet routbar.
/// 192.168.0.0/16 (192.168.0.0 bis 192.168.255.255): Reserviert f�r die Nutzung in privaten Netzwerken.Nicht im Internet routbar.
/// 169.254.0.0/16 (169.254.0.0 bis 169.254.255.255): Link-local Adresses f�r IPv4LL.
/// </summary>
[TestMethod()]
[TestCategory("Gated")]
public void Ipv4PrivateTests()
{
var ip = IPAddress.Parse("10.0.0.0");
Assert.IsTrue(ip.IsReservedAddress(), "Reserviert f�r die Nutzung in privaten Netzwerken. Nicht im Internet routbar.");
ip = IPAddress.Parse("10.255.255.5");
Assert.IsTrue(ip.IsReservedAddress(), "Reserviert f�r die Nutzung in privaten Netzwerken. Nicht im Internet routbar.");
ip = IPAddress.Parse("10.255.255.254");
Assert.IsTrue(ip.IsReservedAddress(), "Reserviert f�r die Nutzung in privaten Netzwerken. Nicht im Internet routbar.");
ip = IPAddress.Parse("172.16.0.0");
Assert.IsTrue(ip.IsReservedAddress(), "Reserviert f�r die Nutzung in privaten Netzwerken. Nicht im Internet routbar.");
ip = IPAddress.Parse("172.16.0.1");
Assert.IsTrue(ip.IsReservedAddress(), "Reserviert f�r die Nutzung in privaten Netzwerken. Nicht im Internet routbar.");
ip = IPAddress.Parse("172.31.4.5");
Assert.IsTrue(ip.IsReservedAddress(), "Reserviert f�r die Nutzung in privaten Netzwerken. Nicht im Internet routbar.");
ip = IPAddress.Parse("172.31.255.200");
Assert.IsTrue(ip.IsReservedAddress(), "Reserviert f�r die Nutzung in privaten Netzwerken. Nicht im Internet routbar.");
ip = IPAddress.Parse("192.168.1.1");
Assert.IsTrue(ip.IsReservedAddress(), "Reserviert f�r die Nutzung in privaten Netzwerken. Nicht im Internet routbar.");
ip = IPAddress.Parse("192.168.0.1");
Assert.IsTrue(ip.IsReservedAddress(), "Reserviert f�r die Nutzung in privaten Netzwerken. Nicht im Internet routbar.");
ip = IPAddress.Parse("192.168.4.5");
Assert.IsTrue(ip.IsReservedAddress(), "Reserviert f�r die Nutzung in privaten Netzwerken. Nicht im Internet routbar.");
ip = IPAddress.Parse("192.168.255.200");
Assert.IsTrue(ip.IsReservedAddress(), "Reserviert f�r die Nutzung in privaten Netzwerken. Nicht im Internet routbar.");
ip = IPAddress.Parse("169.254.0.0");
Assert.IsTrue(ip.IsReservedAddress(), "Link-local Adresses f�r IPv4LL.");
ip = IPAddress.Parse("169.254.10.10");
Assert.IsTrue(ip.IsReservedAddress(), "Link-local Adresses f�r IPv4LL.");
ip = IPAddress.Parse("169.254.255.254");
Assert.IsTrue(ip.IsReservedAddress(), "Link-local Adresses f�r IPv4LL.");
}
/// <summary>
/// Class D (Multicast)
/// 224.0.0.0 bis 239.255.255.255: Nicht im Internet, sondern nur lokal in den eigenen Netzen routbar.
/// </summary>
[TestMethod()]
[TestCategory("Gated")]
public void Ipv4MulticastTests()
{
var ip = IPAddress.Parse("224.0.0.0");
Assert.IsTrue(ip.IsReservedAddress(), "Nicht im Internet, sondern nur lokal in den eigenen Netzen routbar.");
ip = IPAddress.Parse("239.255.255.255");
Assert.IsTrue(ip.IsReservedAddress(), "Nicht im Internet, sondern nur lokal in den eigenen Netzen routbar.");
ip = IPAddress.Parse("239.255.255.254");
Assert.IsTrue(ip.IsReservedAddress(), "Nicht im Internet, sondern nur lokal in den eigenen Netzen routbar.");
ip = IPAddress.Parse("239.255.255.2");
Assert.IsTrue(ip.IsReservedAddress(), "Nicht im Internet, sondern nur lokal in den eigenen Netzen routbar.");
ip = IPAddress.Parse("224.1.1.1");
Assert.IsTrue(ip.IsReservedAddress(), "Nicht im Internet, sondern nur lokal in den eigenen Netzen routbar.");
}
/// <summary>
/// Class E (reservierte Adressen)
/// 240.0.0.0 bis 255.255.255.255: Alte IPv4-Stacks, die nur mit Netzklassen arbeiten, kommen damit nicht klar.
/// </summary>
[TestMethod()]
[TestCategory("Gated")]
public void Ipv4ReservedAddressesTests()
{
var ip = IPAddress.Parse("240.0.0.0");
Assert.IsTrue(ip.IsReservedAddress(), "Alte IPv4-Stacks, die nur mit Netzklassen arbeiten, kommen damit nicht klar.");
ip = IPAddress.Parse("255.255.255.255");
Assert.IsTrue(ip.IsReservedAddress(), "Alte IPv4-Stacks, die nur mit Netzklassen arbeiten, kommen damit nicht klar.");
ip = IPAddress.Parse("240.255.255.254");
Assert.IsTrue(ip.IsReservedAddress(), "Alte IPv4-Stacks, die nur mit Netzklassen arbeiten, kommen damit nicht klar.");
ip = IPAddress.Parse("240.255.255.2");
Assert.IsTrue(ip.IsReservedAddress(), "Alte IPv4-Stacks, die nur mit Netzklassen arbeiten, kommen damit nicht klar.");
ip = IPAddress.Parse("255.1.1.1");
Assert.IsTrue(ip.IsReservedAddress(), "Alte IPv4-Stacks, die nur mit Netzklassen arbeiten, kommen damit nicht klar.");
}
/// <summary>
/// Adresse: ::1/128
/// </summary>
[TestMethod()]
[TestCategory("Gated")]
public void Ipv6LoopbackTests()
{
var ip = IPAddress.Parse("::1");
Assert.IsTrue(ip.IsReservedAddress(), "Loopback");
}
/// <summary>
/// Link Local Unicast
/// Adressraum: fe80::/10 -- fe80:: - febf::
/// </summary>
[TestMethod()]
[TestCategory("Gated")]
public void Ipv6LinkLocalUnicastTests()
{
var ip = IPAddress.Parse("fe80::");
Assert.IsTrue(ip.IsReservedAddress(), "Link Local Unicast");
ip = IPAddress.Parse("febf::");
Assert.IsTrue(ip.IsReservedAddress(), "Link Local Unicast");
}
/// <summary>
/// Unique Local Unicast
/// Adressraum: fe80::/10 -- fe80:: - febf::
/// </summary>
[TestMethod()]
[TestCategory("Gated")]
public void Ipv6UniqueLocalUnicastTests()
{
var ip = IPAddress.Parse("fc00::");
Assert.IsTrue(ip.IsReservedAddress(), "Unique Local Unicast");
ip = IPAddress.Parse("fdff::");
Assert.IsTrue(ip.IsReservedAddress(), "Unique Local Unicast");
}
/// <summary>
/// Multicast
/// Adressraum: ff00::/8 -- ff00:: - ffff::
/// </summary>
[TestMethod()]
[TestCategory("Gated")]
public void Ipv6MulticastTests()
{
var ip = IPAddress.Parse("ff01::1");
Assert.IsTrue(ip.IsReservedAddress(), "Multicast");
ip = IPAddress.Parse("ff02::1");
Assert.IsTrue(ip.IsReservedAddress(), "Multicast");
ip = IPAddress.Parse("ff02::1");
Assert.IsTrue(ip.IsReservedAddress(), "Multicast");
ip = IPAddress.Parse("ff00::");
Assert.IsTrue(ip.IsReservedAddress(), "Multicast");
ip = IPAddress.Parse("ffff::");
Assert.IsTrue(ip.IsReservedAddress(), "Multicast");
ip = IPAddress.Parse("ff01::2");
Assert.IsTrue(ip.IsReservedAddress(), "Multicast");
ip = IPAddress.Parse("ff02::2");
Assert.IsTrue(ip.IsReservedAddress(), "Multicast");
ip = IPAddress.Parse("ff05::2");
Assert.IsTrue(ip.IsReservedAddress(), "Multicast");
}
/// <summary>
/// Global Unicast
/// 0:0:0:0:0:ffff::/96 -- IPv4 mapped (abgebildet)
/// 2000::/3 -- von der IANA an die RIRs vergebene Netze
/// 2002::/4 -- f�r den Tunnelmechanismus 6to4
/// 2001:db8::/32 -- f�r Dokumentationszwecke
/// </summary>
[TestMethod()]
[TestCategory("Gated")]
public void Ipv6GlobalUnicastTests()
{
//var ip = IPAddress.Parse("0:0:0:0:0:ffff::");
//Assert.IsTrue(ip.IsReservedAddress(), " IPv4 mapped (abgebildet)");
//var ip = IPAddress.Parse("2002::");
//Assert.IsTrue(ip.IsReservedAddress(), "f�r den Tunnelmechanismus 6to4");
var ip = IPAddress.Parse("2001:db8::");
Assert.IsTrue(ip.IsReservedAddress(), "f�r Dokumentationszwecke");
}
[TestMethod()]
[TestCategory("Gated")]
public void Ipv6NotReserved()
{
var ip = IPAddress.Parse("2003:D4:BC0:0:0:0:0:0");
Assert.IsFalse(ip.IsReservedAddress(), "Ip 2003:D4:BC0:0:0:0:0:0 should be valid");
}
}
}
| 49.434783 | 138 | 0.604142 | [
"MIT"
] | dkubi/IPAddressExtension | test/IPAddressExtension.UnitTest/ReservedAddressTest.cs | 12,557 | C# |
// Decompiled with JetBrains decompiler
// Type: BstkTypeLib.NATProtocol
// Assembly: BstkTypeLib, Version=1.3.0.0, Culture=neutral, PublicKeyToken=null
// MVID: 38E91E34-8BF8-4856-A23F-FE231831C5D8
// Assembly location: C:\Program Files\BlueStacks\BstkTypeLib.dll
using System.Runtime.InteropServices;
namespace BstkTypeLib
{
[Guid("E90164BE-EB03-11DE-94AF-FFF9B1C1B19F")]
public enum NATProtocol
{
NATProtocol_UDP,
NATProtocol_TCP,
}
}
| 25.388889 | 79 | 0.765864 | [
"MIT"
] | YehudaEi/Bluestacks-source-code | src/BstkTypeLib/NATProtocol.cs | 459 | C# |
using System;
namespace SPAwesome.WebAPI.Areas.HelpPage
{
/// <summary>
/// This represents an image sample on the help page. There's a display template named ImageSample associated with this class.
/// </summary>
public class ImageSample
{
/// <summary>
/// Initializes a new instance of the <see cref="ImageSample"/> class.
/// </summary>
/// <param name="src">The URL of an image.</param>
public ImageSample(string src)
{
if (src == null)
{
throw new ArgumentNullException("src");
}
Src = src;
}
public string Src { get; private set; }
public override bool Equals(object obj)
{
ImageSample other = obj as ImageSample;
return other != null && Src == other.Src;
}
public override int GetHashCode()
{
return Src.GetHashCode();
}
public override string ToString()
{
return Src;
}
}
} | 25.829268 | 130 | 0.527856 | [
"MIT"
] | lazarofl/SPAwesome | WebAPI/SPAwesome.WebAPI/SPAwesome.WebAPI/Areas/HelpPage/SampleGeneration/ImageSample.cs | 1,059 | C# |
namespace SoarBeyond.Data.Entities;
public class JournalEntity : IHealthItem
{
public JournalEntity()
{
JournalEntries = new List<JournalEntryEntity>();
}
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public DateTime CreationDate { get; set; }
// Relationships
public int UserId { get; set; }
public virtual SoarBeyondUserEntity User { get; set; }
public virtual List<JournalEntryEntity> JournalEntries { get; set; }
} | 26.5 | 72 | 0.671698 | [
"MIT"
] | CalebABG/SoarBeyond | src/SoarBeyond.Data/Entities/JournalEntity.cs | 532 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace VSTranslator.Translation.Bing
{
public class BingConnector
{
private const string BaseUrl = "http://api.microsofttranslator.com/v2/ajax.svc/";
//access token
private const string TokenUrl = "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13";
private const string TokenClientID = "VsTranslator";
private const string TokenClientSecret = "SVJTxigXb3ezDDm6ZG5hn/FC20YUbV37clW3zw8hLLE=";
private DateTime TokenExpires;
private string CurrentToken;
public BingConnector()
{
}
public string GetCurrentToken()
{
if ((TokenExpires - DateTime.Now).TotalMinutes < 1) {
RenewToken();
}
return CurrentToken;
}
private void RenewToken()
{
var data = new Dictionary<string, string> {
{ "grant_type", "client_credentials" },
{ "client_id", TokenClientID },
{ "client_secret", TokenClientSecret },
{ "scope", "http://api.microsofttranslator.com" }
};
string response = Utils.GetHttpResponse(TokenUrl, Utils.CreateQuerystring(data));
JObject jToken = JObject.Parse(response);
CurrentToken = jToken["access_token"].Value<string>();
TokenExpires = DateTime.Now.AddSeconds(int.Parse(jToken["expires_in"].Value<string>()));
}
private string GetData(string method, Dictionary<string, string> data = null)
{
data = data ?? new Dictionary<string, string>();
WebClient client = new WebClient();
client.Headers["Authorization"] = "Bearer " + GetCurrentToken();
return client.DownloadString(BaseUrl + method + "?" + Utils.CreateQuerystring(data));
}
public virtual string GetLanguageNames(string locale, IEnumerable<string> codes)
{
return GetData("GetLanguageNames", new Dictionary<string, string>{
{ "locale", "en" },
{ "languageCodes", JsonConvert.SerializeObject(codes) }
});
}
public virtual string GetLanguagesForTranslate()
{
return GetData("GetLanguagesForTranslate");
}
public virtual string GetTranslations(string text, string sourceLang, string destLang)
{
return GetData("GetTranslations", new Dictionary<string, string> {
{"text", text},
{"from", sourceLang},
{"to", destLang},
{"maxTranslations", "20"}
});
}
}
}
| 36.17284 | 121 | 0.566553 | [
"MIT"
] | umiyuki/VisualStudioExtensionTranslatorENtoJP | TranslatorVSIX/Translation/Bing/BingConnector.cs | 2,932 | C# |
namespace Basics.Caching
{
internal sealed class NullCache : IDistributedCache, ICache
{
}
} | 17.5 | 63 | 0.695238 | [
"Apache-2.0"
] | JeevanJames/Basics | Basics/Caching/NullCache.cs | 107 | C# |
namespace NBitcoin.BouncyCastle.Crypto
{
/**
* interface that a message digest conforms to.
*/
internal interface IDigest
{
/**
* return the algorithm name
*
* @return the algorithm name
*/
string AlgorithmName
{
get;
}
/**
* return the size, in bytes, of the digest produced by this message digest.
*
* @return the size, in bytes, of the digest produced by this message digest.
*/
int GetDigestSize();
/**
* return the size, in bytes, of the internal buffer used by this digest.
*
* @return the size, in bytes, of the internal buffer used by this digest.
*/
int GetByteLength();
/**
* update the message digest with a single byte.
*
* @param inByte the input byte to be entered.
*/
void Update(byte input);
/**
* update the message digest with a block of bytes.
*
* @param input the byte array containing the data.
* @param inOff the offset into the byte array where the data starts.
* @param len the length of the data.
*/
void BlockUpdate(byte[] input, int inOff, int length);
/**
* Close the digest, producing the final digest value. The doFinal
* call leaves the digest reset.
*
* @param output the array the digest is to be copied into.
* @param outOff the offset into the out array the digest is to start at.
*/
int DoFinal(byte[] output, int outOff);
/**
* reset the digest back to it's initial state.
*/
void Reset();
}
}
| 28.142857 | 85 | 0.539199 | [
"MIT"
] | 0tim0/StratisFullNode | src/NBitcoin/BouncyCastle/crypto/IDigest.cs | 1,773 | C# |
using System;
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization;
namespace PixelComrades {
[System.Serializable]
public class ImpactRadius : IComponent, ISerializable {
public ImpactRadiusTypes Radius { get; }
public bool LimitToEnemy { get; }
public ImpactRadius(ImpactRadiusTypes radius, bool limitToEnemy) {
Radius = radius;
LimitToEnemy = limitToEnemy;
}
public ImpactRadius(SerializationInfo info, StreamingContext context) {
Radius = info.GetValue(nameof(Radius), Radius);
}
public void GetObjectData(SerializationInfo info, StreamingContext context) {
info.AddValue(nameof(Radius), Radius);
}
}
}
| 29.518519 | 85 | 0.677541 | [
"MIT"
] | FuzzySlipper/Framework | Assets/Framework/Components/Impacts/Radius/ImpactRadius.cs | 799 | C# |
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Losol.Communication.Sms;
using Losol.Identity.Data;
using Losol.Identity.Model;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.AspNetCore.TestHost;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Moq;
namespace Losol.Identity.Tests
{
public class CustomWebApplicationFactory<TStartup>
: WebApplicationFactory<TStartup> where TStartup : class
{
public readonly Mock<ISmsSender> SmsSenderMock = new Mock<ISmsSender>();
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
builder
.UseSolutionRelativeContentRoot("src/Losol.Identity")
.UseEnvironment("Development")
.ConfigureAppConfiguration(app => app
.AddInMemoryCollection(new Dictionary<string, string>
{
{ "IdentityServer:ConfigurationType", "InMemory" },
{ "SkipDbInitialization", bool.TrueString }, // don't run migrations on in-memory DB
{ "InMemoryConfiguration:Ids:0", "OpenId" },
{ "InMemoryConfiguration:Ids:1", "Profile" },
{ "InMemoryConfiguration:Ids:2", "Phone" },
{ "InMemoryConfiguration:Apis:0:Id", "demo.api" },
{ "InMemoryConfiguration:Apis:0:Name", "Demo API" },
{ "InMemoryConfiguration:Apis:0:UserClaims:0", "role" },
{ "InMemoryConfiguration:Apis:0:UserClaims:1", "phone_number" },
{ "InMemoryConfiguration:Clients:0:Id", "test" },
{ "InMemoryConfiguration:Clients:0:Name", "Integration Tests Client" },
{ "InMemoryConfiguration:Clients:0:Url", "http://integration-tests.local" },
{ "InMemoryConfiguration:Clients:0:UserClaims:0", "role" },
{ "InMemoryConfiguration:Clients:0:UserClaims:1", "phone_number" },
{ "InMemoryConfiguration:Clients:0:RedirectPaths:0", "/callback.html" },
{ "InMemoryConfiguration:Clients:0:PostLogoutRedirectPaths:0", "/index.html" },
{ "InMemoryConfiguration:Clients:0:AllowedScopes:0", "openid" },
{ "InMemoryConfiguration:Clients:0:AllowedScopes:1", "profile" },
{ "InMemoryConfiguration:Clients:0:AllowedScopes:2", "demo.api" },
{ "InMemoryConfiguration:Clients:0:AllowedGrantTypes:0", "authorization_code" },
{ "InMemoryConfiguration:Clients:0:AllowedCorsOrigins:0", "http://integration-tests.local" },
{ "InMemoryConfiguration:Clients:0:RequirePkce", bool.TrueString },
{ "InMemoryConfiguration:Clients:0:RequireConsent", bool.FalseString },
{ "InMemoryConfiguration:Clients:0:RequireClientSecret", bool.FalseString },
{ "InMemoryConfiguration:Clients:0:AllowAccessTokensViaBrowser", bool.TrueString },
{ "InMemoryConfiguration:Clients:0:Properties:EnablePasswordLogin", bool.TrueString },
{ "InMemoryConfiguration:Clients:0:Properties:EnablePhoneLogin", bool.TrueString }
}))
.ConfigureServices(services =>
{
// Override already added email sender with the true mock
services.AddSingleton(SmsSenderMock.Object);
// Remove the app's ApplicationDbContext registration.
var descriptor = services.SingleOrDefault(
d => d.ServiceType ==
typeof(DbContextOptions<ApplicationDbContext>));
if (descriptor != null)
{
services.Remove(descriptor);
}
// Add ApplicationDbContext using an in-memory database for testing.
services.AddDbContext<ApplicationDbContext>(options =>
{
options.UseInMemoryDatabase("idem-itests");
});
});
}
public async Task CleanupAsync()
{
SmsSenderMock.Reset();
using var scope = Services.CreateScope();
var userManager = scope.ServiceProvider.GetRequiredService<UserManager<ApplicationUser>>();
var users = userManager.Users.ToArray();
await Task.WhenAll(users.Select(u => (Task)userManager.DeleteAsync(u)).ToArray());
}
}
}
| 52.580645 | 117 | 0.5818 | [
"MIT"
] | losol/idem | tests/Losol.Identity.Tests/CustomWebApplicationFactory.cs | 4,890 | 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 cognito-idp-2016-04-18.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.CognitoIdentityProvider.Model
{
/// <summary>
/// The compromised credentials actions type
/// </summary>
public partial class CompromisedCredentialsActionsType
{
private CompromisedCredentialsEventActionType _eventAction;
/// <summary>
/// Gets and sets the property EventAction.
/// <para>
/// The event action.
/// </para>
/// </summary>
[AWSProperty(Required=true)]
public CompromisedCredentialsEventActionType EventAction
{
get { return this._eventAction; }
set { this._eventAction = value; }
}
// Check to see if EventAction property is set
internal bool IsSetEventAction()
{
return this._eventAction != null;
}
}
} | 29.431034 | 109 | 0.670182 | [
"Apache-2.0"
] | ChristopherButtars/aws-sdk-net | sdk/src/Services/CognitoIdentityProvider/Generated/Model/CompromisedCredentialsActionsType.cs | 1,707 | C# |
using System;
using System.Linq;
using Xamarin.Forms;
using SignaturePad.Forms;
namespace Samples.Views
{
public partial class SignatureXamlView : ContentPage
{
public SignatureXamlView ()
{
InitializeComponent ();
}
private async void OnChangeTheme (object sender, EventArgs e)
{
var action = await DisplayActionSheet ("Change Theme", "Cancel", null, "White", "Black", "Aqua");
switch (action)
{
case "White":
padView.BackgroundColor = Color.White;
padView.StrokeColor = Color.Black;
padView.ClearTextColor = Color.Black;
padView.ClearText = "Clear Markers";
break;
case "Black":
padView.BackgroundColor = Color.Black;
padView.StrokeColor = Color.White;
padView.ClearTextColor = Color.White;
padView.ClearText = "Clear Chalk";
break;
case "Aqua":
padView.BackgroundColor = Color.Aqua;
padView.StrokeColor = Color.Red;
padView.ClearTextColor = Color.Black;
padView.ClearText = "Clear The Aqua";
break;
}
}
private async void OnGetStats (object sender, EventArgs e)
{
using (var image = await padView.GetImageStreamAsync (SignatureImageFormat.Png))
{
var imageSize = (image?.Length ?? 0) / 1000;
var points = padView.Points.ToArray ();
var pointCount = points.Count ();
var linesCount = points.Count (p => p == Point.Zero) + (points.Length > 0 ? 1 : 0);
image?.Dispose ();
await DisplayAlert ("Stats", $"The signature has {linesCount} lines or {pointCount} points, and is {imageSize:#,###.0}KB (in memory) when saved as a PNG.", "Cool");
}
}
private async void OnGetImage (object sender, EventArgs e)
{
var settings = new ImageConstructionSettings
{
Padding = 12,
StrokeColor = Color.FromRgb (25, 25, 25),
BackgroundColor = Color.FromRgb (225, 225, 225),
DesiredSizeOrScale = 2f
};
var image = await padView.GetImageStreamAsync (SignatureImageFormat.Png, settings);
if (image == null)
return;
var page = new ContentPage
{
Title = "Signature",
Content = new Image
{
Aspect = Aspect.AspectFit,
Source = ImageSource.FromStream (() => image)
}
};
await Navigation.PushAsync (page);
}
}
}
| 25.363636 | 168 | 0.657706 | [
"MIT"
] | Acidburn0zzz/SignaturePad | samples/Sample.Forms/Samples/Views/SignatureXamlView.xaml.cs | 2,234 | C# |
using System;
using Xunit;
using Newtonsoft.Json;
using System.Runtime.Serialization.Json;
using System.IO;
using System.Text;
using Papabytes.Cronofy.NetCore.Requests;
namespace Papabytes.Cronofy.NetCore.Test.PushNotificationTests
{
public sealed class JsonParsing
{
private const string VerificationRequestBody = @"{
""notification"": {
""type"": ""verification""
},
""channel"": {
""channel_id"": ""chn_54cf7c7cb4ad4c1027000001"",
""callback_url"": ""https://example.com/callback"",
""filters"": {
""calendar_ids"": [""cal_U9uuErStTG@EAAAB_IsAsykA2DBTWqQTf-f0kJw""]
}
}
}";
private static readonly PushNotificationRequest ExpectedVerification
= new PushNotificationRequest
{
Notification = new PushNotificationRequest.NotificationDetail
{
Type = "verification",
},
Channel = new PushNotificationRequest.ChannelDetail
{
Id = "chn_54cf7c7cb4ad4c1027000001",
CallbackUrl = "https://example.com/callback",
Filters = new PushNotificationRequest.ChannelDetail.ChannelFilters
{
CalendarIds = new[] { "cal_U9uuErStTG@EAAAB_IsAsykA2DBTWqQTf-f0kJw" },
},
}
};
private const string ChangeRequestBody = @"{
""notification"": {
""type"": ""change"",
""changes_since"": ""2015-11-13T10:39:12Z""
},
""channel"": {
""channel_id"": ""chn_54cf7c7cb4ad4c1027000001"",
""callback_url"": ""https://example.com/callback"",
""filters"": {
""calendar_ids"": [""cal_U9uuErStTG@EAAAB_IsAsykA2DBTWqQTf-f0kJw""]
}
}
}";
private static readonly PushNotificationRequest ExpectedChange
= new PushNotificationRequest
{
Notification = new PushNotificationRequest.NotificationDetail
{
Type = "change",
ChangesSince = new DateTime(2015, 11, 13, 10, 39, 12, DateTimeKind.Utc),
},
Channel = new PushNotificationRequest.ChannelDetail
{
Id = "chn_54cf7c7cb4ad4c1027000001",
CallbackUrl = "https://example.com/callback",
Filters = new PushNotificationRequest.ChannelDetail.ChannelFilters
{
CalendarIds = new[] { "cal_U9uuErStTG@EAAAB_IsAsykA2DBTWqQTf-f0kJw" },
},
}
};
[Fact]
public void CanParseVerificationWithJsonNet()
{
var actualVerification = JsonConvert.DeserializeObject<PushNotificationRequest>(VerificationRequestBody);
Assert.Equal(ExpectedVerification, actualVerification);
}
[Fact]
public void CanParseChangeWithJsonNet()
{
var actualChange = JsonConvert.DeserializeObject<PushNotificationRequest>(ChangeRequestBody);
Assert.Equal(ExpectedChange, actualChange);
}
[Fact]
public void CanParseVerificationWithCoreSerialization()
{
var serializer = new DataContractJsonSerializer(typeof(PushNotificationRequest));
var verificationBytes = Encoding.UTF8.GetBytes(VerificationRequestBody);
var verificationStream = new MemoryStream(verificationBytes);
var actualVerification = (PushNotificationRequest)serializer.ReadObject(verificationStream);
Assert.Equal(ExpectedVerification, actualVerification);
}
[Fact]
public void CanParseChangeWithCoreSerialization()
{
var serializer = new DataContractJsonSerializer(typeof(PushNotificationRequest));
var changeBytes = Encoding.UTF8.GetBytes(ChangeRequestBody);
var changeStream = new MemoryStream(changeBytes);
var actualChange = (PushNotificationRequest)serializer.ReadObject(changeStream);
Assert.Equal(ExpectedChange, actualChange);
}
}
}
| 36.448276 | 117 | 0.594371 | [
"MIT"
] | Toky0/cronofy-csharp | test/Papabytes.Cronofy.NetCore.Test/PushNotificationTests/JsonParsing.cs | 4,228 | C# |
using UnityEngine;
using UnityEngine.UI;
public class DebugOverlay : MonoBehaviour {
[RuntimeInitializeOnLoadMethod]
static void Init() {
var asset = Resources.Load<GameObject>("UI/Debug");
if(asset == null) return;
var go = GameObject.Instantiate(asset.gameObject);
DontDestroyOnLoad(go);
}
static string LOG_MESSAGE = "> <color=\"#{0}\">{1}</color>\n";
[SerializeField]
private Text log;
private void Awake() {
Application.logMessageReceived += Application_logMessageReceived;
}
private void OnDestroy() {
Application.logMessageReceived -= Application_logMessageReceived;
}
private void Application_logMessageReceived(string condition, string stackTrace, LogType type) {
if(this.log.text.Split('\n').Length >= 25) {
this.log.text = string.Empty;
}
var color = Color.green;
switch(type) {
case LogType.Error:
color = Color.red;
break;
case LogType.Warning:
color = Color.yellow;
break;
case LogType.Assert:
color = Color.blue;
break;
}
this.log.text += string.Format(LOG_MESSAGE, ColorUtility.ToHtmlStringRGBA(color), condition);
}
} | 22.38 | 97 | 0.706881 | [
"MIT"
] | Software-Developers-Association/maze | Assets/App/Scripts/UI/Overlays/Debug/DebugOverlay.cs | 1,121 | C# |
namespace ClearHl7.Codes.V280
{
/// <summary>
/// HL7 Version 2 Table 0236 - Event Reported To.
/// </summary>
/// <remarks>https://www.hl7.org/fhir/v2/0236</remarks>
public enum CodeEventReportedTo
{
/// <summary>
/// D - Distributor.
/// </summary>
Distributor,
/// <summary>
/// L - Local facility/user facility.
/// </summary>
LocalFacilityUserFacility,
/// <summary>
/// M - Manufacturer.
/// </summary>
Manufacturer,
/// <summary>
/// R - Regulatory agency.
/// </summary>
RegulatoryAgency
}
}
| 22 | 59 | 0.5 | [
"MIT"
] | kamlesh-microsoft/clear-hl7-net | src/ClearHl7.Codes/V280/CodeEventReportedTo.cs | 662 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
namespace ChromeRemoteSharp.EmulationDomain
{
public partial class EmulationDomain
{
/// <summary>
/// Overrides value returned by the javascript navigator object.
/// <see cref="https://chromedevtools.github.io/devtools-protocol/tot/Emulation#method-setNavigatorOverrides"/>
/// </summary>
/// <param name="platform">The platform navigator.platform should return.</param>
/// <returns></returns>
public async Task<JObject> SetNavigatorOverridesAsync(string platform)
{
return await CommandAsync("setNavigatorOverrides",
new KeyValuePair<string, object>("platform", platform)
);
}
}
}
| 33.68 | 119 | 0.66152 | [
"MIT"
] | jefersonsv/ChromeRemoteSharp | src/ChromeRemoteSharp/EmulationDomain/SetNavigatorOverridesAsync.cs | 842 | C# |
using System;
using GenericServices;
using NewAlbums.Entities;
using NewAlbums.Spotify.Dto;
namespace NewAlbums.Albums.Dto
{
public class AlbumDto : CreationAuditedEntityDto<long>, ILinkToEntity<Album>
{
public string SpotifyId { get; set; }
public string Name { get; set; }
public string ReleaseDate { get; set; }
/// <summary>
/// Returns the ReleaseDate as a DateTime if it represents a specific day in format "yyyy-MM-dd", and not just a year or year and month.
/// Otherwise returns a DateTime initialised to DateTime.MinValue
/// </summary>
public DateTime ReleaseDateNormalised
{
get
{
if (String.IsNullOrWhiteSpace(ReleaseDate) || ReleaseDate.Length != 10)
return DateTime.MinValue;
DateTime releaseDate;
if (DateTime.TryParse(ReleaseDate, out releaseDate))
{
return releaseDate;
}
return DateTime.MinValue;
}
}
public SpotifyImageDto Image { get; set; }
public AlbumDto()
{
//Default
Image = new SpotifyImageDto();
}
}
}
| 27.369565 | 144 | 0.564734 | [
"MIT"
] | Ellfish/newalbumsviaemail | src/NewAlbums.Application/Albums/Dto/AlbumDto.cs | 1,261 | C# |
// Copyright 2007-2015 Chris Patterson, Dru Sellers, Travis Smith, et. al.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
namespace MassTransit.Tests.Pipeline
{
using System;
using Context;
using Context.Converters;
using GreenPipes;
using MassTransit.Pipeline;
using NUnit.Framework;
using Policies;
using Shouldly;
using TestFramework;
[TestFixture]
public class Using_the_retry_filter
{
class A
{
}
[Test]
public void Should_retry_the_specified_times_and_fail()
{
int count = 0;
IPipe<ConsumeContext<A>> pipe = Pipe.New<ConsumeContext<A>>(x =>
{
x.UseRetry(r => r.Interval(4, TimeSpan.FromMilliseconds(2)));
x.UseExecute(payload =>
{
count++;
throw new IntentionalTestException("Kaboom!");
});
});
var context = new TestConsumeContext<A>(new A());
Assert.That(async () => await pipe.Send(context), Throws.TypeOf<IntentionalTestException>());
count.ShouldBe(5);
}
[Test]
public void Should_support_overloading_downstream()
{
int count = 0;
IPipe<ConsumeContext<A>> pipe = Pipe.New<ConsumeContext<A>>(x =>
{
x.UseRetry(r => r.Interval(4, TimeSpan.FromMilliseconds(2)));
x.UseRetry(r => r.None());
x.UseExecute(payload =>
{
count++;
throw new IntentionalTestException("Kaboom!");
});
});
var context = new TestConsumeContext<A>(new A());
Assert.That(async () => await pipe.Send(context), Throws.TypeOf<IntentionalTestException>());
count.ShouldBe(1);
}
[Test]
public void Should_support_overloading_downstream_on_cc()
{
int count = 0;
IPipe<ConsumeContext> pipe = Pipe.New<ConsumeContext>(x =>
{
x.UseRetry(r =>
{
r.Handle<IntentionalTestException>();
r.Interval(4, TimeSpan.FromMilliseconds(2));
});
x.UseRetry(r =>
{
r.Handle<IntentionalTestException>();
r.None();
});
x.UseDispatch(new ConsumeContextConverterFactory(), d =>
{
d.Pipe<ConsumeContext<A>>(a =>
{
a.UseExecute(payload =>
{
count++;
throw new IntentionalTestException("Kaboom!");
});
});
});
});
var context = new TestConsumeContext<A>(new A());
Assert.That(async () => await pipe.Send(context), Throws.TypeOf<IntentionalTestException>());
count.ShouldBe(1);
}
[Test]
public void Should_support_overloading_downstream_either_way()
{
int count = 0;
IPipe<ConsumeContext<A>> pipe = Pipe.New<ConsumeContext<A>>(x =>
{
x.UseRetry(r => r.None());
x.UseRetry(r => r.Interval(4, TimeSpan.FromMilliseconds(2)));
x.UseExecute(payload =>
{
count++;
throw new IntentionalTestException("Kaboom!");
});
});
var context = new TestConsumeContext<A>(new A());
Assert.That(async () => await pipe.Send(context), Throws.TypeOf<IntentionalTestException>());
count.ShouldBe(5);
}
}
} | 33.058824 | 106 | 0.496219 | [
"ECL-2.0",
"Apache-2.0"
] | AOrlov/MassTransit | src/MassTransit.Tests/Pipeline/Retry_Specs.cs | 4,498 | C# |
using Microsoft.EntityFrameworkCore.Migrations;
namespace TrashMob.Migrations
{
public partial class AddPrivateEvents : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<bool>(
name: "IsEventPublic",
table: "Events",
type: "bit",
nullable: false,
defaultValue: false);
migrationBuilder.AddColumn<bool>(
name: "IsEventPublic",
table: "EventHistory",
type: "bit",
nullable: false,
defaultValue: false);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "IsEventPublic",
table: "Events");
migrationBuilder.DropColumn(
name: "IsEventPublic",
table: "EventHistory");
}
}
}
| 28.083333 | 71 | 0.527201 | [
"Apache-2.0"
] | ArijitCloud/TrashMob | TrashMob.Shared/Migrations/20210821003448_AddPrivateEvents.cs | 1,013 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("01.02.03.GenericBox")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("01.02.03.GenericBox")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[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("fe7b4dc9-af7f-4e7a-9881-eaef85e77810")]
// 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 | 84 | 0.746088 | [
"MIT"
] | mdamyanova/C-Sharp-Web-Development | 08.C# Fundamentals/08.03.C# OOP Advanced/04.Generic - Exercise/01.02.03.GenericBox/Properties/AssemblyInfo.cs | 1,409 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using XCommerce.AccesoDatos;
namespace XCommerce.Servicio.Core._04_Localidad
{
class VarGlobalLocalidad
{
public void Iniciar()
{
using (var contex = new ModeloXCommerceContainer())
{
if (!contex.Localidades.Any())
{
contex.Localidades.Add(new AccesoDatos.Localidad { Descripcion = "San miguel", EstaEliminado = false, });
}
if (!contex.Localidades.Any())
{
contex.Localidades.Add(new AccesoDatos.Localidad { Descripcion = "Cafayate", EstaEliminado = false, });
}
if (!contex.Localidades.Any())
{
contex.Localidades.Add(new AccesoDatos.Localidad { Descripcion = "Perico", EstaEliminado = false, });
}
if (!contex.Localidades.Any())
{
contex.Localidades.Add(new AccesoDatos.Localidad { Descripcion = "Rosario", EstaEliminado = false, });
}
if (!contex.Localidades.Any())
{
contex.Localidades.Add(new AccesoDatos.Localidad { Descripcion = "Lomas ", EstaEliminado = false, });
}
contex.SaveChanges();
}
}
}
}
| 29.22 | 125 | 0.524298 | [
"MIT"
] | RamonChauqui/SubeCodigo | XCommerce.Servicio.Core/04-Localidad/VarGlobalLocalidad.cs | 1,463 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RaisingTimer : TimerScript
{
public GameObject toRaise;
public Transform raiseTo;
public Transform raiseFrom;
public override void Stopped()
{
StartCoroutine(SimpleDrop());
}
public IEnumerator SimpleDrop()
{
float st = Time.time + 1f;
Vector3 pp = toRaise.transform.position;
while (st - Time.time >= 0)
{
toRaise.transform.position = Vector3.Lerp(raiseFrom.position, pp, st - Time.time);
yield return null;
}
}
[HideInInspector] public float startTime = -1;
[HideInInspector] public float origSpeed = -1;
public override void Ticked(float timeRem)
{
if(Mathf.Approximately(startTime, -1f))
{
startTime = timeRem;
origSpeed = RoomManager.instance.Player.moveSpeed;
}
toRaise.transform.position = Vector3.Lerp(raiseTo.position, raiseFrom.position, timeRem / startTime);
RoomManager.instance.Player.moveSpeed = Mathf.Lerp(origSpeed / 5f, origSpeed, timeRem / startTime);
}
}
| 29.365854 | 110 | 0.623754 | [
"MIT"
] | Arutsuyo/The-Final-Lock | Assets/Scripts/RaisingTimer.cs | 1,206 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PairsByDifference
{
class PairsByDifference
{
static void Main(string[] args)
{
int[] inputArray = Console.ReadLine()
.Split()
.Select(int.Parse)
.ToArray();
int difference = int.Parse(Console.ReadLine());
int pairsCount = 0;
for (int i = 0; i < inputArray.Length - 1; i++)
{
for (int j = i + 1; j < inputArray.Length; j++)
{
if (inputArray[i] - inputArray[j] == difference || inputArray[j] - inputArray[i] == difference) //1 5 3 4 2
{
pairsCount++;
}
}
}
Console.WriteLine(pairsCount);
}
}
}
| 25.694444 | 128 | 0.467027 | [
"MIT"
] | Melkiah/GitubExerciseHomework | ArraysExercises/PairsByDifference/PairsByDifference.cs | 927 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Threading;
using System.Threading.Tasks;
using Azure.Analytics.Synapse.Spark.Models;
using Azure.Core;
using Azure.Core.Pipeline;
namespace Azure.Analytics.Synapse.Spark
{
[CodeGenSuppress("CreateSparkSessionAsync", typeof(SparkSessionOptions), typeof(bool?), typeof(CancellationToken))]
[CodeGenSuppress("CreateSparkSession", typeof(SparkSessionOptions), typeof(bool?), typeof(CancellationToken))]
[CodeGenSuppress("CreateSparkStatementAsync", typeof(int), typeof(SparkStatementOptions), typeof(CancellationToken))]
[CodeGenSuppress("CreateSparkStatement", typeof(int), typeof(SparkStatementOptions), typeof(CancellationToken))]
public partial class SparkSessionClient
{
/// <summary>
/// Initializes a new instance of the <see cref="SparkSessionClient"/>.
/// </summary>
public SparkSessionClient(Uri endpoint, string sparkPoolName, TokenCredential credential)
: this(endpoint, sparkPoolName, credential, SparkClientOptions.Default)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="SparkSessionClient"/>.
/// </summary>
public SparkSessionClient(Uri endpoint, string sparkPoolName, TokenCredential credential, SparkClientOptions options)
: this(new ClientDiagnostics(options),
SynapseClientPipeline.Build(options, credential),
endpoint.ToString(),
sparkPoolName,
options.VersionString)
{
}
public virtual async Task<SparkSessionOperation> StartCreateSparkSessionAsync(SparkSessionOptions sparkSessionOptions, bool? detailed = null, CancellationToken cancellationToken = default)
=> await StartCreateSparkSessionInternal(true, sparkSessionOptions, detailed, cancellationToken).ConfigureAwait(false);
public virtual SparkSessionOperation StartCreateSparkSession(SparkSessionOptions sparkSessionOptions, bool? detailed = null, CancellationToken cancellationToken = default)
=> StartCreateSparkSessionInternal(false, sparkSessionOptions, detailed, cancellationToken).EnsureCompleted();
private async Task<SparkSessionOperation> StartCreateSparkSessionInternal (bool async, SparkSessionOptions sparkSessionOptions, bool? detailed = null, CancellationToken cancellationToken = default)
{
using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(SparkSessionClient)}.{nameof(StartCreateSparkSession)}");
scope.Start();
try
{
Response<SparkSession> session;
if (async)
{
session = await RestClient.CreateSparkSessionAsync(sparkSessionOptions, detailed, cancellationToken).ConfigureAwait(false);
}
else
{
session = RestClient.CreateSparkSession(sparkSessionOptions, detailed, cancellationToken);
}
return new SparkSessionOperation(this, _clientDiagnostics, session);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
public virtual async Task<SparkStatementOperation> StartCreateSparkStatementAsync(int sessionId, SparkStatementOptions sparkStatementOptions, CancellationToken cancellationToken = default)
=> await StartCreateSparkStatementInternal (true, sessionId, sparkStatementOptions, cancellationToken).ConfigureAwait(false);
public virtual SparkStatementOperation StartCreateSparkStatement(int sessionId, SparkStatementOptions sparkStatementOptions, CancellationToken cancellationToken = default)
=> StartCreateSparkStatementInternal (false, sessionId, sparkStatementOptions, cancellationToken).EnsureCompleted();
private async Task<SparkStatementOperation> StartCreateSparkStatementInternal (bool async, int sessionId, SparkStatementOptions sparkStatementOptions, CancellationToken cancellationToken = default)
{
using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(SparkSessionClient)}.{nameof(StartCreateSparkStatement)}");
scope.Start();
try
{
Response<SparkStatement> statementSession;
if (async)
{
statementSession = await RestClient.CreateSparkStatementAsync(sessionId, sparkStatementOptions, cancellationToken).ConfigureAwait(false);
}
else
{
statementSession = RestClient.CreateSparkStatement(sessionId, sparkStatementOptions, cancellationToken);
}
return new SparkStatementOperation(this, _clientDiagnostics, statementSession, sessionId);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
}
}
| 51.3 | 205 | 0.679142 | [
"MIT"
] | MahmoudYounes/azure-sdk-for-net | sdk/synapse/Azure.Analytics.Synapse.Spark/src/Customization/SparkSessionClient.cs | 5,132 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using DSharpPlus;
using DSharpPlus.CommandsNext;
using DSharpPlus.CommandsNext.Attributes;
using DSharpPlus.Entities;
using System.Linq;
using Octokit;
namespace DerpBot
{
public class UtilityCommands
{
[Command("sudo")][RequireOwner][Hidden]
[Description("Use a command as a defined user.")]
public async Task SudoCommand(CommandContext ctx, [Description("Member to execute as.")] DiscordMember user, [Description("Command to Execute")][RemainingText] string command = null)
{
await ctx.TriggerTypingAsync();
try
{
var cmds = ctx.CommandsNext;
if (command == null) await ctx.RespondAsync("Please enter a command, command can not be null. **See ``!help sudo``**");
else { await cmds.SudoAsync(user, ctx.Channel, command); await ctx.RespondAsync($"Successfully used {command} as {user.Username}"); }
}
catch (Exception ex)
{
ctx.Client.DebugLogger.LogMessage(LogLevel.Error, "DraxBot", $"Exception occured: {ex.Message}", DateTime.Now);
throw;
}
}
[Command("nick")][RequirePermissions(Permissions.ManageNicknames)]
[Description("Changes a users nickname (Requires Role: ManageNicknames)")]
public async Task Nickname(CommandContext ctx, [Description("The user you wish to change the nickname of.")] DiscordMember user, [Description("The nickname you wish to set for the user.")][RemainingText]string nickname = null)
{
await ctx.TriggerTypingAsync();
try
{
if (nickname == null) await ctx.RespondAsync($"There was an error, Please provide a nickname to set for {user.Username} **(More Info via ``!help nick``)**");
else { await user.ModifyAsync(nickname, reason: $"Changed by {ctx.User.Username} ({ctx.User.Id})"); await ctx.RespondAsync($"Successfully changed {user.Username}'s name to {nickname}."); }
}
catch (Exception ex)
{
ctx.Client.DebugLogger.LogMessage(LogLevel.Error, "DraxBot", $"Exception occured: {ex.Message}", DateTime.Now);
await ctx.RespondAsync("There was an error, Please contact your server Admin or Draxis");
throw;
}
}
[Command("server")]
[Description("Gets info about the discord server the command is used in.")]
public async Task ServerInfo(CommandContext ctx)
{
var builder = new DiscordEmbedBuilder()
.WithTitle($"Server Info | #{ctx.Guild.Name} (Id: {ctx.Guild.Id})")
.WithColor(new DiscordColor(138, 43, 226))
.AddField($"Channels", $"• {ctx.Guild.Channels.Where(x => x.Type == ChannelType.Text).Count()} Text, {ctx.Guild.Channels.Where(x => x.Type == ChannelType.Voice).Count()} Voice" +
$"\n• AFK: {ctx.Guild.AfkTimeout / 60} Min", true)
.AddField($"Member", $"• {ctx.Guild.MemberCount} Members" +
$"\n• Owner: {ctx.Guild.Owner.Mention}", true)
.AddField("Other", $"• Roles: {ctx.Guild.Roles.Count}" +
$"\n• Region: {ctx.Guild.RegionId}" +
$"\n• Created On: {ctx.Guild.CreationTimestamp.ToString("dddd, MMMM d, yyyy @ h:mm tt")}" +
$"\n• Verifcation Level: {ctx.Guild.VerificationLevel}", false)
.WithThumbnailUrl(ctx.Guild.IconUrl);
await ctx.RespondAsync("", false, builder);
}
[Command("game")][RequireOwner]
[Description("Sets the now playing game of the bot. (Requires Owner)")]
public async Task UpdateStatusAsync(CommandContext ctx, [Description("What you want to display as the now playing for the bot.")]string game)
{
UserStatus? user_status = default(UserStatus?);
DateTimeOffset? idle_since = default(DateTimeOffset?);
await ctx.Client.UpdateStatusAsync(new DiscordGame(game), user_status , idle_since);
}
[Command("info")]
[Description("Gets info about the bot.")]
public async Task BotInfo(CommandContext ctx)
{
var owner = "joelp53";
var reponame = "DerpBot";
var client = new GitHubClient(new ProductHeaderValue("DerpBot"));
var repo = await client.Repository.Get(owner, reponame);
var botUptime = DateTime.Now - Program.startTime; StringBuilder replyUptime = new StringBuilder();
#region UpitimeStuffs
if (botUptime.Days > 0 && botUptime.Days < 2) replyUptime.Append($"{botUptime.Days} Day, ");
if (botUptime.Days > 1) replyUptime.Append($"{botUptime.Days} Days, ");
if (botUptime.Hours > 0 && botUptime.Hours < 2) replyUptime.Append($"{botUptime.Hours} Hour, ");
if (botUptime.Hours > 1) replyUptime.Append($"{botUptime.Hours} Hours, ");
if (botUptime.Minutes > 0 && botUptime.Minutes < 2) replyUptime.Append($"{botUptime.Minutes} Min, ");
if (botUptime.Minutes > 1) replyUptime.Append($"{botUptime.Minutes} Mins, ");
if (botUptime.Seconds > 0) replyUptime.Append($"{botUptime.Seconds} Secconds");
#endregion
var builder = new DiscordEmbedBuilder()
.WithTimestamp(DateTime.UtcNow)
.WithColor(new DiscordColor(138, 43, 226))
.WithTitle("DerpBot Information")
.WithUrl($"{repo.HtmlUrl}")
.WithDescription($"DerpBot was created by Draxis with the main idea being to replace the previous bot DraxBot.")
.AddField("Latest Features: ",
"**• World Of Warcraft Class Help:**\n" +
"Find how to use this command via ``//help guide``\n" +
"**• Youtube Music:**\n" +
"Have DerpBot join your voice channel ``//join``\n" +
"Play music with ``//play [youtube link]``")
.AddField("Upcoming Features:", "``Wow Stats`` | ``Raider.IO Info`` | ``Overwatch Stats`` | ``Better Music``\nCurrently Accepting Requests for more commands.")
.AddField("Stats:",
$"**• Uptime:** {replyUptime.ToString()}\n" +
$"**• Created on:** {repo.CreatedAt.ToString("dddd, MMMM d, yyyy @ h:mm tt")}")
.WithThumbnailUrl(ctx.Client.CurrentUser.AvatarUrl)
.WithFooter($"This Embed works best when viewed on a PC.", ctx.Client.CurrentUser.AvatarUrl);
await ctx.RespondAsync("", false, builder);
}
}
} | 53.746032 | 234 | 0.595245 | [
"MIT"
] | joelp53/DerpBot | DraxbotDSharpPlus/Commands/UtilityCommands.cs | 6,798 | C# |
using System;
using EventStore.ClientAPI;
namespace EventStore.PositionRepository
{
public class ConnectionBuilder : IConnectionBuilder
{
public Uri ConnectionString { get; }
public ConnectionSettings ConnectionSettings { get; }
public string ConnectionName { get; }
public IEventStoreConnection Build()
{
return EventStoreConnection.Create(ConnectionSettings, ConnectionString, ConnectionName);
}
public ConnectionBuilder(Uri connectionString, ConnectionSettings connectionSettings, string connectionName)
{
ConnectionString = connectionString;
ConnectionSettings = connectionSettings;
ConnectionName = connectionName;
}
}
}
| 30.48 | 116 | 0.690289 | [
"Apache-2.0"
] | riccardone/EventStore.PositionRepository | src/EventStore.PositionRepository/ConnectionBuilder.cs | 764 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace TrivialJwt.Helpers
{
public static class SignatureAlgorithmHelper
{
/// <summary>
///
/// </summary>
/// <param name="jwa">String identifying the algorithm. Based on https://tools.ietf.org/html/rfc7518#section-3 </param>
public static string ConvertJWAToSignatureAlgorithm(string jwa)
{
return null;
}
public static bool IsSymmetric(string algo)
{
if (string.IsNullOrEmpty(algo))
throw new ArgumentException("Algorithm is missing", nameof(algo));
switch (algo) {
case "HS256":
case "HS384":
case "HS512":
return true;
case "RS256":
case "RS384":
case "RS512":
case "ES256":
case "ES384":
case "ES512":
case "PS256":
case "PS384":
case "PS512":
return false;
default:
throw new ArgumentException("Unknown algorithm", nameof(algo));
}
}
public static bool IsRsa(string algo)
{
if (string.IsNullOrEmpty(algo))
throw new ArgumentException("Algorithm is missing", nameof(algo));
switch (algo)
{
case "RS256":
case "RS384":
case "RS512":
return true;
default:
return false;
}
}
}
}
| 27.064516 | 127 | 0.463647 | [
"MIT"
] | r3dlin3/TrivialJwt | src/TrivialJwt/Helpers/SignatureAlgorithmHelper.cs | 1,680 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Model.SysMaster;
namespace BLL.IBLL.SysMaster
{
public interface ISysRoleMasterBL : IDataBaseCommandBL<Sys_RoleMaster_rlm_Info>, IExtraBL, IMainBL
{
}
}
| 19.923077 | 102 | 0.776062 | [
"BSD-3-Clause"
] | sndnvaps/OneCard_ | BLL/IBLL/SysMaster/ISysRoleMasterBL.cs | 261 | C# |
/*
* Copyright (c) 2018 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
namespace TencentCloud.Vpc.V20170312.Models
{
using Newtonsoft.Json;
using System.Collections.Generic;
using TencentCloud.Common;
public class DeleteServiceTemplateGroupResponse : AbstractModel
{
/// <summary>
/// 唯一请求ID,每次请求都会返回。定位问题时需要提供该次请求的RequestId。
/// </summary>
[JsonProperty("RequestId")]
public string RequestId{ get; set; }
/// <summary>
/// 内部实现,用户禁止调用
/// </summary>
internal override void ToMap(Dictionary<string, string> map, string prefix)
{
this.SetParamSimple(map, prefix + "RequestId", this.RequestId);
}
}
}
| 29.863636 | 83 | 0.667428 | [
"Apache-2.0"
] | geffzhang/tencentcloud-sdk-dotnet | TencentCloud/Vpc/V20170312/Models/DeleteServiceTemplateGroupResponse.cs | 1,394 | C# |
using System.Threading.Tasks;
using Flurl.Http;
using Keycloak.Net.Model.Clients;
using Keycloak.Net.Model.Common;
namespace Keycloak.Net
{
/// <remarks>
/// <include file='../../keycloak.xml' path='keycloak/docs/api' />#_clients_resource
/// </remarks>
public partial class KeycloakClient
{
/// <summary>
/// GET /{realm}/clients/{clientId}/management/permissions <br/>
/// Return object stating whether client Authorization permissions have been initialized or not and a reference.
/// </summary>
/// <param name="realm">realm name (not id!)</param>
/// <param name="clientId">id of client (not <see cref="Client.ClientId"/>)</param>
public async Task<ManagementPermission?> GetClientAuthorizationPermissionsInitializedAsync(string realm,
string clientId)
{
var response = await GetBaseUrl()
.AppendPathSegment($"/admin/realms/{realm}/clients/{clientId}/management/permissions")
.GetJsonAsync<ManagementPermission>()
.ConfigureAwait(false);
return response;
}
/// <summary>
/// PUT /{realm}/clients/{clientId}/management/permissions <br/>
/// Return object stating whether client Authorization permissions have been initialized or not and a reference.
/// </summary>
/// <param name="realm">realm name (not id!)</param>
/// <param name="clientId">id of client (not <see cref="Client.ClientId"/>)</param>
/// <param name="managementPermission"></param>
public async Task<ManagementPermission?> SetClientAuthorizationPermissionsInitializedAsync(
string realm,
string clientId,
ManagementPermission managementPermission)
{
var response = await GetBaseUrl()
.AppendPathSegment($"/admin/realms/{realm}/clients/{clientId}/management/permissions")
.PutJsonAsync(managementPermission)
.ReceiveJson<ManagementPermission>()
.ConfigureAwait(false);
return response;
}
}
} | 43.857143 | 120 | 0.625872 | [
"MIT"
] | egyptianbman/Keycloak.Net | src/core/Clients/Permission.cs | 2,151 | C# |
//___________________________________________________________________________________
//
// Copyright (C) 2020, Mariusz Postol LODZ POLAND.
//
// To be in touch join the community at GITTER: https://gitter.im/mpostol/OPC-UA-OOI
//___________________________________________________________________________________
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using UAOOI.Windows.Forms.Instrumentation;
namespace UAOOI.Windows.Forms
{
[TestClass]
public class AssemblyTraceEventUnitTest
{
[TestMethod]
public void AssemblyTraceEventTestMethod()
{
TraceSource _tracer = AssemblyTraceEvent.Tracer;
Assert.IsNotNull(_tracer);
Assert.AreEqual(1, _tracer.Listeners.Count);
Dictionary<string, TraceListener> _listeners = _tracer.Listeners.Cast<TraceListener>().ToDictionary<TraceListener, string>(x => x.Name);
Assert.IsTrue(_listeners.ContainsKey("LogFile"));
TraceListener _listener = _listeners["LogFile"];
Assert.IsNotNull(_listener);
Assert.IsInstanceOfType(_listener, typeof(DelimitedListTraceListener));
DelimitedListTraceListener _advancedListener = _listener as DelimitedListTraceListener;
Assert.IsNotNull(_advancedListener.Filter);
Assert.IsInstanceOfType(_advancedListener.Filter, typeof(EventTypeFilter));
EventTypeFilter _eventTypeFilter = _advancedListener.Filter as EventTypeFilter;
Assert.AreEqual(SourceLevels.All, _eventTypeFilter.EventType);
string _testPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
Assert.AreEqual<string>(Path.Combine(_testPath, @"UAOOIWindowsFormsUnitTests.log"), _advancedListener.GetFileName());
}
[TestMethod]
public void LogFileExistsTest()
{
TraceSource _tracer = AssemblyTraceEvent.Tracer;
TraceListener _listener = _tracer.Listeners.Cast<TraceListener>().Where<TraceListener>(x => x.Name == "LogFile").First<TraceListener>();
Assert.IsNotNull(_listener);
DelimitedListTraceListener _advancedListener = _listener as DelimitedListTraceListener;
Assert.IsNotNull(_advancedListener);
Assert.IsFalse(String.IsNullOrEmpty(_advancedListener.GetFileName()));
FileInfo _logFileInfo = new FileInfo(_advancedListener.GetFileName());
long _startLength = _logFileInfo.Exists ?_logFileInfo.Length : 0;
_tracer.TraceEvent(TraceEventType.Information, 0, "LogFileExistsTest is executed");
Assert.IsFalse(String.IsNullOrEmpty(_advancedListener.GetFileName()));
_logFileInfo.Refresh();
Assert.IsTrue(_logFileInfo.Exists);
Assert.IsTrue(_logFileInfo.Length > _startLength);
}
}
}
| 46.590164 | 143 | 0.754398 | [
"MIT"
] | mpostol/WindowsForms | CAS.Windows.Forms.UnitTests/AssemblyTraceEventUnitTest.cs | 2,844 | C# |
#pragma checksum "..\..\Window1.xaml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "8B69661E23AF603C7A0E31FBA4202D61FD648991"
//------------------------------------------------------------------------------
// <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 GUI_Example;
using System;
using System.Diagnostics;
using System.Windows;
using System.Windows.Automation;
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.Markup;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Effects;
using System.Windows.Media.Imaging;
using System.Windows.Media.Media3D;
using System.Windows.Media.TextFormatting;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Shell;
namespace GUI_Example {
/// <summary>
/// Window1
/// </summary>
public partial class Window1 : System.Windows.Window, System.Windows.Markup.IComponentConnector {
#line 1 "..\..\Window1.xaml"
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
internal GUI_Example.Window1 Diamond_Star_Racing_Login;
#line default
#line hidden
private bool _contentLoaded;
/// <summary>
/// InitializeComponent
/// </summary>
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")]
public void InitializeComponent() {
if (_contentLoaded) {
return;
}
_contentLoaded = true;
System.Uri resourceLocater = new System.Uri("/GUI Example;component/window1.xaml", System.UriKind.Relative);
#line 1 "..\..\Window1.xaml"
System.Windows.Application.LoadComponent(this, resourceLocater);
#line default
#line hidden
}
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")]
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes")]
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily")]
void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) {
switch (connectionId)
{
case 1:
this.Diamond_Star_Racing_Login = ((GUI_Example.Window1)(target));
return;
}
this._contentLoaded = true;
}
}
}
| 38.911111 | 142 | 0.636208 | [
"MIT"
] | ThomasOwca/C-WPF-XAML---Basic-Log-In-Screen | GUI Example/GUI Example/obj/Debug/Window1.g.cs | 3,504 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Syntax.InternalSyntax;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace SamLu.CodeAnalysis.Lua.Syntax.InternalSyntax
{
[Flags]
internal enum LexerMode
{
None = 0,
Syntax = 0x0001,
DebuggerSyntax = 0x0002,
MaskLexMode = 0xFFFF
}
/// <summary>
/// 针对Lua语言特定的词法解析器。
/// </summary>
internal partial class Lexer : AbstractLexer
{
private const int IdentifierBufferInitialCapacity = 32;
private const int TriviaListInitialCapacity = 8;
private readonly LuaParseOptions _options;
private LexerMode _mode;
private readonly StringBuilder _builder;
private char[] _identifierBuffer;
private int _identifierLength;
private readonly LexerCache _cache;
private int _badTokenCount; // 产生的坏标识符的累计数量。
public LuaParseOptions Options => this._options;
/// <summary>
/// 存放语法标识的必要信息。
/// </summary>
internal struct TokenInfo
{
/// <summary>
/// 直接语法类别。
/// </summary>
internal SyntaxKind Kind;
/// <summary>
/// 上下文语法类别。
/// </summary>
internal SyntaxKind ContextualKind;
/// <summary>
/// 语法标识的文本表示。
/// </summary>
internal string? Text;
/// <summary>
/// 语法标识的值类别。
/// </summary>
internal SpecialType ValueKind;
internal bool HasIdentifierEscapeSequence;
/// <summary>
/// 语法标识的字符串类型值。
/// </summary>
internal string? StringValue;
/// <summary>
/// 语法标识的32位整数类型值。
/// </summary>
internal int IntValue;
/// <summary>
/// 语法标识的64位整数类型值。
/// </summary>
internal long LongValue;
/// <summary>
/// 语法标识的32位单精度浮点数类型值。
/// </summary>
internal float FloatValue;
/// <summary>
/// 语法标识的64位双精度浮点数类型值。
/// </summary>
internal double DoubleValue;
/// <summary>
/// 语法标识是否为逐字。
/// </summary>
internal bool IsVerbatim;
}
public Lexer(SourceText text, LuaParseOptions options) : base(text)
{
this._options = options;
this._builder = new StringBuilder();
this._identifierBuffer = new char[Lexer.IdentifierBufferInitialCapacity];
this._cache = new();
this._createQuickTokenFunction = this.CreateQuickToken;
}
public override void Dispose()
{
this._cache.Free();
base.Dispose();
}
public void Reset(int position) => this.TextWindow.Reset(position);
private static LexerMode ModeOf(LexerMode mode) => mode & LexerMode.MaskLexMode;
private bool ModeIs(LexerMode mode) => Lexer.ModeOf(this._mode) == mode;
public SyntaxToken Lex(ref LexerMode mode)
{
var result = this.Lex(mode);
mode = this._mode;
return result;
}
public SyntaxToken Lex(LexerMode mode)
{
this._mode = mode;
switch (this._mode)
{
case LexerMode.Syntax:
case LexerMode.DebuggerSyntax:
return this.QuickScanSyntaxToken() ?? this.LexSyntaxToken();
}
switch (Lexer.ModeOf(this._mode))
{
default:
throw ExceptionUtilities.UnexpectedValue(ModeOf(_mode));
}
}
private SyntaxListBuilder _leadingTriviaCache = new(10);
private SyntaxListBuilder _trailingTriviaCache = new(10);
private static int GetFullWidth(SyntaxListBuilder? builder)
{
if (builder is null) return 0;
int width = 0;
for (int i = 0; i < builder.Count; i++)
{
var node = builder[i];
Debug.Assert(node is not null);
width += node.FullWidth;
}
return width;
}
private SyntaxToken LexSyntaxToken();
internal SyntaxTriviaList LexSyntaxLeadingTrivia();
internal SyntaxTriviaList LexSyntaxTrailingTrivia();
/// <summary>
/// 创建一个语法标识。
/// </summary>
/// <param name="info">语法标识的相关信息。</param>
/// <param name="leading">起始的语法列表构造器。</param>
/// <param name="trailing">结尾的语法列表构造器。</param>
/// <param name="errors">语法消息数组。</param>
/// <returns>新的语法标识。</returns>
private SyntaxToken Create(
ref TokenInfo info,
SyntaxListBuilder? leading,
SyntaxListBuilder? trailing,
SyntaxDiagnosticInfo[]? errors)
{
Debug.Assert(info.Kind != SyntaxKind.IdentifierToken || info.StringValue is not null);
GreenNode? leadingNode = leading?.ToListNode();
GreenNode? trailingNode = trailing?.ToListNode();
SyntaxToken token = info.Kind switch
{
// 标识符标识
SyntaxKind.IdentifierToken => SyntaxFactory.Identifier(info.ContextualKind, leadingNode, info.Text!, info.StringValue!, trailingNode),
// 数字字面量标识
SyntaxKind.NumericLiteralToken =>
info.ValueKind switch
{
// 32位整数
SpecialType.System_Int32 => SyntaxFactory.Literal(leadingNode, info.Text!, info.IntValue, trailingNode),
// 64为整数
SpecialType.System_Int64 => SyntaxFactory.Literal(leadingNode, info.Text!, info.LongValue, trailingNode),
// 32位单精度浮点数
SpecialType.System_Single => SyntaxFactory.Literal(leadingNode, info.Text!, info.FloatValue, trailingNode),
// 64为双精度浮点数
SpecialType.System_Double => SyntaxFactory.Literal(leadingNode, info.Text!, info.DoubleValue, trailingNode),
_ => throw ExceptionUtilities.UnexpectedValue(info.ValueKind),
},
// 字符串字面量标识
SyntaxKind.StringLiteralToken or
// 单行原始字符串字面量标识
SyntaxKind.SingleLineRawStringLiteralToken or
// 多行原始字符串字面量标识
SyntaxKind.MultiLineRawStringLiteralToken => SyntaxFactory.Literal(leadingNode, info.Text!, info.Kind, info.StringValue!, trailingNode),
SyntaxKind.EndOfFileToken => SyntaxFactory.Token(leadingNode, SyntaxKind.EndOfFileToken, trailingNode),
SyntaxKind.None => SyntaxFactory.BadToken(leadingNode, info.Text!, trailingNode),
_ => SyntaxFactory.Token(leadingNode, info.Kind, trailingNode)
};
// 为标识添加诊断。
if (errors is not null && this._options.DocumentationMode >= DocumentationMode.Diagnose)
token = token.WithDiagnosticsGreen(errors);
return token;
}
private void ScanSyntaxToken(ref TokenInfo info)
{
// 初始化以准备新的标识扫描。
info.Kind = SyntaxKind.None;
info.ContextualKind = SyntaxKind.None;
info.Text = null;
char c;
char surrogateCharacter = SlidingTextWindow.InvalidCharacter;
bool isEscaped = false;
int startingPosition = this.TextWindow.Position;
// 开始扫描标识。
c = this.TextWindow.PeekChar();
switch (c)
{
case '+':
this.TextWindow.AdvanceChar();
info.Kind = SyntaxKind.PlusToken;
break;
case '-':
this.TextWindow.AdvanceChar();
if (this.TextWindow.PeekChar() == '-')
{
this.TextWindow.AdvanceChar();
this.ScanComment(ref info);
}
else
info.Kind = SyntaxKind.MinusToken; break;
case '*':
this.TextWindow.AdvanceChar();
info.Kind = SyntaxKind.AsteriskToken;
break;
case '/':
this.TextWindow.AdvanceChar();
if (this.TextWindow.PeekChar() == '/')
{
this.TextWindow.AdvanceChar();
info.Kind = SyntaxKind.SlashSlashToken;
}
else
info.Kind = SyntaxKind.SlashToken;
break;
case '%':
this.TextWindow.AdvanceChar();
info.Kind = SyntaxKind.PersentToken;
break;
case '#':
this.TextWindow.AdvanceChar();
info.Kind = SyntaxKind.HashToken;
break;
case '&':
this.TextWindow.AdvanceChar();
info.Kind = SyntaxKind.AmpersandToken;
break;
case '~':
this.TextWindow.AdvanceChar();
if (this.TextWindow.PeekChar() == '=')
{
this.TextWindow.AdvanceChar();
info.Kind = SyntaxKind.TildeEqualsToken;
}
else
info.Kind = SyntaxKind.TildeToken;
break;
case '|':
this.TextWindow.AdvanceChar();
info.Kind = SyntaxKind.BarToken;
break;
case '<':
this.TextWindow.AdvanceChar();
switch (this.TextWindow.PeekChar())
{
case '=':
this.TextWindow.AdvanceChar();
info.Kind = SyntaxKind.LessThanEqualsToken;
break;
case '<':
this.TextWindow.AdvanceChar();
info.Kind = SyntaxKind.LessThanLessThenToken;
break;
default:
info.Kind = SyntaxKind.LessThanToken;
break;
}
break;
case '>':
this.TextWindow.AdvanceChar();
switch (this.TextWindow.PeekChar())
{
case '=':
this.TextWindow.AdvanceChar();
info.Kind = SyntaxKind.GreaterThanEqualsToken;
break;
case '<':
this.TextWindow.AdvanceChar();
info.Kind = SyntaxKind.GreaterThanGreaterThenToken;
break;
default:
info.Kind = SyntaxKind.GreaterThenToken;
break;
}
break;
case '=':
this.TextWindow.AdvanceChar();
if (this.TextWindow.PeekChar() == '=')
{
this.TextWindow.AdvanceChar();
info.Kind = SyntaxKind.EqualsEqualsToken;
}
else
info.Kind = SyntaxKind.EqualsToken;
break;
case '(':
this.TextWindow.AdvanceChar();
info.Kind = SyntaxKind.OpenParenToken;
break;
case ')':
this.TextWindow.AdvanceChar();
info.Kind = SyntaxKind.CloseParenToken;
break;
case '{':
this.TextWindow.AdvanceChar();
info.Kind = SyntaxKind.OpenBraceToken;
break;
case '}':
this.TextWindow.AdvanceChar();
info.Kind = SyntaxKind.CloseBraceToken;
break;
case '[':
switch (this.TextWindow.PeekChar(2))
{
case '[':
this.ScanMultiLineStringLiteral(ref info);
break;
case '=':
for (int i = 3; ; i++)
{
char nextChar = this.TextWindow.PeekChar(i);
if (nextChar == '=') continue;
else if (nextChar == '[')
this.ScanMultiLineStringLiteral(ref info, i - 2);
else goto default;
}
if (info.Kind == SyntaxKind.None) goto default; // 未匹配到完整的多行原始字符字面量的起始语法。
break;
default:
this.TextWindow.AdvanceChar();
info.Kind = SyntaxKind.OpenBracketToken;
break;
}
break;
case ']':
this.TextWindow.AdvanceChar();
info.Kind = SyntaxKind.CloseBracketToken;
break;
case ':':
this.TextWindow.AdvanceChar();
if (this.TextWindow.PeekChar() == ':')
{
this.TextWindow.AdvanceChar();
info.Kind = SyntaxKind.ColonColonToken;
}
else
info.Kind = SyntaxKind.ColonToken;
break;
case ';':
this.TextWindow.AdvanceChar();
info.Kind = SyntaxKind.SemicolonToken;
break;
case ',':
this.TextWindow.AdvanceChar();
info.Kind = SyntaxKind.CommanToken;
break;
case '.':
this.TextWindow.AdvanceChar();
if (this.TextWindow.PeekChar() == '.')
{
this.TextWindow.AdvanceChar();
if (this.TextWindow.PeekChar() == '.')
{
this.TextWindow.AdvanceChar();
info.Kind = SyntaxKind.DotDotDotToken;
}
else
info.Kind = SyntaxKind.DotDotToken;
}
else
info.Kind = SyntaxKind.DotToken;
break;
// 字符串字面量
case '\"':
case '\'':
this.ScanSingleStringLiteral(ref info);
break;
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
case 'g':
case 'h':
case 'i':
case 'j':
case 'k':
case 'l':
case 'm':
case 'n':
case 'o':
case 'p':
case 'q':
case 'r':
case 's':
case 't':
case 'u':
case 'v':
case 'w':
case 'x':
case 'y':
case 'z':
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
case 'G':
case 'H':
case 'I':
case 'J':
case 'K':
case 'L':
case 'M':
case 'N':
case 'O':
case 'P':
case 'Q':
case 'R':
case 'S':
case 'T':
case 'U':
case 'V':
case 'W':
case 'X':
case 'Y':
case 'Z':
case '_':
this.ScanIdentifierOrKeyword(ref info);
break;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
this.ScanNumericLiteral(ref info);
break;
case SlidingTextWindow.InvalidCharacter:
if (!this.TextWindow.IsReallyAtEnd())
goto default;
else
info.Kind = SyntaxKind.EndOfFileToken;
break;
default:
if (SyntaxFacts.IsIdentifierStartCharacter(this.TextWindow.PeekChar()))
goto case 'a';
this.TextWindow.AdvanceChar();
if (this._badTokenCount++ > 200)
{
//当遇到大量无法决定的字符时,将剩下的输出也合并入。
int end = this.TextWindow.Text.Length;
int width = end - startingPosition;
info.Text = this.TextWindow.Text.ToString(new(startingPosition, width));
this.TextWindow.Reset(end);
}
else
info.Text = this.TextWindow.GetText(intern: true);
this.AddError(ErrorCode.ERR_UnexpectedCharacter, info);
break;
}
}
#warning 未完成
}
}
| 33.880515 | 152 | 0.43199 | [
"MIT"
] | sanmuru/luna | src/Compilers/Lua/Portable/Parser/Lexer.cs | 19,139 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Xml.Linq;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.DotNet.Docker.Tests
{
[Trait("Category", "sample")]
public class SampleImageTests
{
private static readonly string s_samplesPath = Path.Combine(Config.SourceRepoRoot, "samples");
public SampleImageTests(ITestOutputHelper outputHelper)
{
OutputHelper = outputHelper;
DockerHelper = new DockerHelper(outputHelper);
}
protected DockerHelper DockerHelper { get; }
protected ITestOutputHelper OutputHelper { get; }
public static IEnumerable<object[]> GetImageData()
{
return TestData.GetSampleImageData()
.Select(imageData => new object[] { imageData });
}
[DotNetTheory]
[MemberData(nameof(GetImageData))]
public async Task VerifyDotnetSample(SampleImageData imageData)
{
if (imageData.DockerfileSuffix == "windowsservercore-iis-x64")
{
return;
}
await VerifySampleAsync(imageData, SampleImageType.Dotnetapp, (image, containerName) =>
{
string output = DockerHelper.Run(image, containerName);
Assert.True(output.Contains("42") || output.StartsWith("Hello"));
ValidateEnvironmentVariables(imageData, image, SampleImageType.Dotnetapp);
return Task.CompletedTask;
});
}
[DotNetTheory]
[MemberData(nameof(GetImageData))]
public async Task VerifyAspnetSample(SampleImageData imageData)
{
if (imageData.OS == OS.Bionic && imageData.DockerfileSuffix != "ubuntu-x64")
{
return;
}
await VerifySampleAsync(imageData, SampleImageType.Aspnetapp, async (image, containerName) =>
{
try
{
DockerHelper.Run(
image: image,
name: containerName,
detach: true,
optionalRunArgs: "-p 80");
if (!Config.IsHttpVerificationDisabled)
{
await ImageScenarioVerifier.VerifyHttpResponseFromContainerAsync(containerName, DockerHelper, OutputHelper);
}
ValidateEnvironmentVariables(imageData, image, SampleImageType.Aspnetapp);
}
finally
{
DockerHelper.DeleteContainer(containerName);
}
});
}
[Fact]
public void VerifyComplexAppSample()
{
string appTag = SampleImageData.GetImageName("complexapp-local-app");
string testTag = SampleImageData.GetImageName("complexapp-local-test");
string sampleFolder = Path.Combine(s_samplesPath, "complexapp");
string dockerfilePath = $"{sampleFolder}/Dockerfile";
string testContainerName = ImageData.GenerateContainerName("sample-complex-test");
string tempDir = null;
try
{
// Test that the app works
DockerHelper.Build(appTag, dockerfilePath, contextDir: sampleFolder, pull: Config.PullImages);
string containerName = ImageData.GenerateContainerName("sample-complex");
string output = DockerHelper.Run(appTag, containerName);
Assert.StartsWith("string: The quick brown fox jumps over the lazy dog", output);
if (!DockerHelper.IsLinuxContainerModeEnabled &&
DockerHelper.DockerArchitecture.StartsWith("arm", StringComparison.OrdinalIgnoreCase))
{
// Skipping run app tests due to a .NET issue: https://github.com/dotnet/runtime/issues/2082
return;
}
// Run the app's tests
DockerHelper.Build(testTag, dockerfilePath, target: "test", contextDir: sampleFolder);
DockerHelper.Run(testTag, testContainerName, skipAutoCleanup: true);
// Copy the test log from the container to the host
tempDir = Directory.CreateDirectory(
Path.Combine(Path.GetTempPath(), Path.GetRandomFileName())).FullName;
DockerHelper.Copy($"{testContainerName}:/source/tests/TestResults", tempDir);
string testLogFile = new DirectoryInfo($"{tempDir}/TestResults").GetFiles("*.trx").First().FullName;
// Open the test log file and verify the tests passed
XDocument doc = XDocument.Load(testLogFile);
XElement summary = doc.Root.Element(XName.Get("ResultSummary", doc.Root.Name.NamespaceName));
Assert.Equal("Completed", summary.Attribute("outcome").Value);
XElement counters = summary.Element(XName.Get("Counters", doc.Root.Name.NamespaceName));
Assert.Equal("2", counters.Attribute("total").Value);
Assert.Equal("2", counters.Attribute("passed").Value);
}
finally
{
if (tempDir != null)
{
Directory.Delete(tempDir, true);
}
DockerHelper.DeleteContainer(testContainerName);
DockerHelper.DeleteImage(testTag);
DockerHelper.DeleteImage(appTag);
}
}
private async Task VerifySampleAsync(
SampleImageData imageData,
SampleImageType sampleImageType,
Func<string, string, Task> verifyImageAsync)
{
string image = imageData.GetImage(sampleImageType, DockerHelper);
string imageType = Enum.GetName(typeof(SampleImageType), sampleImageType).ToLowerInvariant();
try
{
if (!imageData.IsPublished)
{
string sampleFolder = Path.Combine(s_samplesPath, imageType);
string dockerfilePath = $"{sampleFolder}/Dockerfile.{imageData.DockerfileSuffix}";
DockerHelper.Build(image, dockerfilePath, contextDir: sampleFolder, pull: Config.PullImages);
}
string containerName = imageData.GetIdentifier($"sample-{imageType}");
await verifyImageAsync(image, containerName);
}
finally
{
if (!imageData.IsPublished)
{
DockerHelper.DeleteImage(image);
}
}
}
private void ValidateEnvironmentVariables(SampleImageData imageData, string image, SampleImageType imageType)
{
List<EnvironmentVariableInfo> variables = new List<EnvironmentVariableInfo>();
variables.AddRange(ProductImageTests.GetCommonEnvironmentVariables());
if (imageType == SampleImageType.Aspnetapp)
{
variables.Add(new EnvironmentVariableInfo("ASPNETCORE_URLS", "http://+:80"));
}
EnvironmentVariableInfo.Validate(
variables,
image,
imageData,
DockerHelper);
}
}
}
| 39.921875 | 132 | 0.578343 | [
"MIT"
] | DiskCrasher/dotnet-docker | tests/Microsoft.DotNet.Docker.Tests/SampleImageTests.cs | 7,667 | C# |
/*
* 2015 Sizing Servers Lab, affiliated with IT bachelor degree NMCT
* University College of West-Flanders, Department GKG (www.sizingservers.be, www.nmct.be, www.howest.be/en)
*
* Author(s):
* Dieter Vandroemme
*/
using mshtml;
using System.Threading;
using System.Windows.Forms;
namespace Lupus_Titanium {
/// <summary>
/// Renders a webpage's content without executing scripts or following hrefs.
/// </summary>
public class WebRenderer : UserControl {
private WebBrowser webBrowser;
private HTMLBody _body;
/// <summary>
/// Renders a webpage's content without executing scripts or following hrefs.
/// </summary>
public WebRenderer() {
webBrowser = new WebBrowser();
SuspendLayout();
webBrowser.AllowNavigation = false;
webBrowser.AllowWebBrowserDrop = false;
webBrowser.Dock = DockStyle.Fill;
webBrowser.IsWebBrowserContextMenuEnabled = false;
webBrowser.ScriptErrorsSuppressed = true;
webBrowser.WebBrowserShortcutsEnabled = false;
Controls.Add(this.webBrowser);
Name = "Browser";
ResumeLayout(false);
}
/// <summary>
/// Renders a webpage's content without executing scripts or following hrefs.
/// </summary>
/// <param name="html"></param>
public void Render(string html) {
this.Cursor = Cursors.WaitCursor;
Init(); // Initiate by navigating to about:blank if _body == null.
_body.innerHTML = html;
StripDOM(); // Empty a hrefs, scripts and inputs.
this.Cursor = Cursors.Default;
}
private void Init() {
if (_body == null) {
webBrowser.DocumentCompleted += BrowserDocumentComplete;
webBrowser.Navigate("about:blank");
while (_body == null) {
Application.DoEvents();
Thread.Sleep(0);
}
}
}
private void BrowserDocumentComplete(object sender, WebBrowserDocumentCompletedEventArgs e) {
webBrowser.DocumentCompleted -= BrowserDocumentComplete;
var document = (HTMLDocument)this.webBrowser.Document.DomDocument;
_body = (HTMLBody)document.body;
}
private void StripDOM() {
IHTMLElementCollection anchors = _body.getElementsByTagName("A");
foreach (IHTMLElement element in anchors)
try {
var anchor = (IHTMLAnchorElement)element;
if (anchor.href != null) anchor.href = string.Empty;
if (anchor.target != null) anchor.target = string.Empty;
} catch {
//Ignore.
}
IHTMLElementCollection scripts = _body.getElementsByTagName("SCRIPT");
foreach (IHTMLElement element in scripts)
try {
var script = (IHTMLScriptElement)element;
if (script.src != null) script.src = string.Empty;
if (script.text != null) script.text = string.Empty;
} catch {
//Ignore.
}
IHTMLElementCollection forms = _body.getElementsByTagName("FORM");
foreach (IHTMLElement element in forms)
try {
var form = (IHTMLFormElement)element;
if (form.action != null) form.action = string.Empty;
if (form.onsubmit != null) form.onsubmit = string.Empty;
if (form.onreset != null) form.onreset = string.Empty;
} catch {
//Ignore.
}
}
}
}
| 37.769231 | 109 | 0.540479 | [
"MIT"
] | sizingservers/Lupus-Titanium | Lupus-Titanium/Controls and dialogs/WebRenderer.cs | 3,930 | C# |
using System;
using System.Collections.Generic;
using Bottles;
using Bottles.Diagnostics;
using FubuMVC.Core.Assets.Content;
using FubuCore;
namespace FubuMVC.Core.Assets
{
public class MimetypeRegistrationActivator : IActivator
{
private readonly IEnumerable<ITransformerPolicy> _policies;
public MimetypeRegistrationActivator(IEnumerable<ITransformerPolicy> policies)
{
_policies = policies;
}
public void Activate(IEnumerable<IPackageInfo> packages, IPackageLog log)
{
_policies.Each(p =>
{
p.Extensions.Each(ext =>
{
p.MimeType.AddExtension(ext);
var trace = "Registered extension {0} with MimeType {1}".ToFormat(ext, p.MimeType.Value);
log.Trace(trace);
});
});
}
public override string ToString()
{
return "Registering file extensions for asset transformations to the appropriate MimeType's";
}
}
} | 29.837838 | 110 | 0.57971 | [
"Apache-2.0"
] | ketiko/fubumvc | src/FubuMVC.Core/Assets/MimetypeRegistrationActivator.cs | 1,104 | C# |
using UnityEngine;
using UnityEditor;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using ProBuilder2.Common;
using ProBuilder2.MeshOperations;
using ProBuilder2.Math;
public class ExpandSelection : Editor
{
// [MenuItem("Tools/" + pb_Constant.PRODUCT_NAME + "/Selection/Grow Selection %&g", true, pb_Constant.MENU_SELECTION + 1)]
[MenuItem("Tools/" + pb_Constant.PRODUCT_NAME + "/Selection/Grow Selection &g", true, pb_Constant.MENU_SELECTION + 1)]
[MenuItem("Tools/" + pb_Constant.PRODUCT_NAME + "/Selection/Shrink Selection &#g", true, pb_Constant.MENU_SELECTION + 1)]
public static bool VerifySelectionCommand()
{
return pb_Editor.instance != null && pb_Editor.instance.selectedVertexCount > 0;
}
[MenuItem("Tools/" + pb_Constant.PRODUCT_NAME + "/Selection/Grow Selection &g", false, pb_Constant.MENU_SELECTION + 1)]
public static void MenuGrowSelection()
{
pb_Menu_Commands.MenuGrowSelection(pbUtil.GetComponents<pb_Object>(Selection.transforms));
}
[MenuItem("Tools/" + pb_Constant.PRODUCT_NAME + "/Selection/Shrink Selection &#g", false, pb_Constant.MENU_SELECTION + 1)]
public static void MenuShrinkSelection()
{
pb_Menu_Commands.MenuShrinkSelection(pbUtil.GetComponents<pb_Object>(Selection.transforms));
}
}
| 38.636364 | 123 | 0.772549 | [
"MIT"
] | bird1235456/hotfix | Unity/Assets/NewBirdAshScene/ProCore/ProBuilder/Editor/MenuItems/Selection/ExpandSelection.cs | 1,275 | C# |
using System;
using System.Globalization;
namespace Sirius.Parser.Semantic.Tokens {
public class TestConstant<T>: TestValue
where T: struct, IConvertible {
private readonly T constant;
[Terminal(typeof(TestToken), "Integer", @"[0-9]+", GenericTypeParameter = typeof(int))]
[Terminal(typeof(TestToken), "Float", @"[0-9]*\.[0-9]+(e[+-]?[0-9]+)?", CaseInsensitive = true, GenericTypeParameter = typeof(double))]
public TestConstant(string constant) {
this.constant = (T)Convert.ChangeType(constant, typeof(T), NumberFormatInfo.InvariantInfo);
}
public override double Compute() {
return this.constant.ToDouble(NumberFormatInfo.InvariantInfo);
}
}
}
| 34.65 | 138 | 0.701299 | [
"MIT"
] | siriusch/Sirius.Parser | tests/Sirius.Parser.Tests/Semantic/Tokens/TestConstant.cs | 693 | C# |
namespace System.Colors
{
using System.Diagnostics.CodeAnalysis;
using System.Drawing;
/// <summary>Represents a <see href="https://en.wikipedia.org/wiki/CIELUV">CIELUV</see> color.</summary>
[SuppressMessage("ReSharper", "InconsistentNaming", Justification = "The names of the properties correspond to the names in the CIELUV definition for clarity.")]
public sealed class CieLuv : ColorSpace
{
#region Constants
private const double Kappa = 24389d / 27;
#endregion
#region Properties
private static double WhiteDenominator => CieLuv.GetDenominator(CieXyz.WhiteReference);
/// <summary>Gets or sets the lightness from black (0) to white (100).</summary>
public double L { get; set; }
/// <summary>A component of a <see href="https://en.wikipedia.org/wiki/White_point">white point</see>.</summary>
public double u { get; set; }
/// <summary>A component of a <see href="https://en.wikipedia.org/wiki/White_point">white point</see>.</summary>
public double v { get; set; }
#endregion
#region Methods
private static double GetDenominator(CieXyz cieXyz) => cieXyz.X + 15.0 * cieXyz.Y + 3.0 * cieXyz.Z;
/// <inheritdoc/>
public override void FromColor(Color color)
{
var cieXyz = new CieXyz();
cieXyz.FromColor(color);
var white = CieXyz.WhiteReference;
var y = cieXyz.Y / CieXyz.WhiteReference.Y;
this.L = y > CieXyz.T0 ? 116 * Math.Pow(y, 1d / 3) - 16 : CieLuv.Kappa * y;
var targetDenominator = CieLuv.GetDenominator(cieXyz);
var referenceDenominator = CieLuv.WhiteDenominator;
// ReSharper disable CompareOfFloatsByEqualityOperator
var xTarget = targetDenominator == 0 ? 0 : 4 * cieXyz.X / targetDenominator - 4 * white.X / referenceDenominator;
var yTarget = targetDenominator == 0 ? 0 : 9 * cieXyz.Y / targetDenominator - 9 * white.Y / referenceDenominator;
// ReSharper restore CompareOfFloatsByEqualityOperator
this.u = 13 * this.L * xTarget;
this.v = 13 * this.L * yTarget;
}
/// <inheritdoc/>
public override Color ToColor()
{
var white = CieXyz.WhiteReference;
const double c = -1.0 / 3.0;
var a = 1.0 / 3.0 * (52.0 * this.L / (this.u + 13 * this.L * (4.0 * white.X / CieLuv.WhiteDenominator)) - 1.0);
var y = this.L > CieLuv.Kappa * CieXyz.T0 ? Math.Pow((this.L + 16.0) / 116.0, 3) : this.L / CieLuv.Kappa;
var b = -5.0 * y;
var d = y * (39.0 * this.L / (this.v + 13.0 * this.L * (9.0 * white.Y / CieLuv.WhiteDenominator)) - 5.0);
var x = (d - b) / (a - c);
var z = x * a + b;
return new CieXyz { X = 100 * x, Y = 100 * y, Z = 100 * z }.ToColor();
}
#endregion
}
} | 53.6 | 165 | 0.586839 | [
"MIT"
] | lperezperez/System.Colors | System.Colors/CieLuv.cs | 2,950 | C# |
// This file is part of Silk.NET.
//
// You may modify and distribute Silk.NET under the terms
// of the MIT license. See the LICENSE file for details.
using System;
using System.Runtime.InteropServices;
using System.Text;
using Silk.NET.Core.Native;
using Ultz.SuperInvoke;
#pragma warning disable 1591
namespace Silk.NET.Vulkan
{
public unsafe struct Queue
{
public Queue
(
IntPtr handle = default
)
{
Handle = handle;
}
public IntPtr Handle;
}
}
| 17.387097 | 57 | 0.630798 | [
"MIT"
] | AzyIsCool/Silk.NET | src/Vulkan/Silk.NET.Vulkan/Structs/Queue.gen.cs | 539 | C# |
// <auto-generated>
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/ads/googleads/v8/errors/string_format_error.proto
// </auto-generated>
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace Google.Ads.GoogleAds.V8.Errors {
/// <summary>Holder for reflection information generated from google/ads/googleads/v8/errors/string_format_error.proto</summary>
public static partial class StringFormatErrorReflection {
#region Descriptor
/// <summary>File descriptor for google/ads/googleads/v8/errors/string_format_error.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static StringFormatErrorReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"Cjhnb29nbGUvYWRzL2dvb2dsZWFkcy92OC9lcnJvcnMvc3RyaW5nX2Zvcm1h",
"dF9lcnJvci5wcm90bxIeZ29vZ2xlLmFkcy5nb29nbGVhZHMudjguZXJyb3Jz",
"Ghxnb29nbGUvYXBpL2Fubm90YXRpb25zLnByb3RvInEKFVN0cmluZ0Zvcm1h",
"dEVycm9yRW51bSJYChFTdHJpbmdGb3JtYXRFcnJvchIPCgtVTlNQRUNJRklF",
"RBAAEgsKB1VOS05PV04QARIRCg1JTExFR0FMX0NIQVJTEAISEgoOSU5WQUxJ",
"RF9GT1JNQVQQA0LxAQoiY29tLmdvb2dsZS5hZHMuZ29vZ2xlYWRzLnY4LmVy",
"cm9yc0IWU3RyaW5nRm9ybWF0RXJyb3JQcm90b1ABWkRnb29nbGUuZ29sYW5n",
"Lm9yZy9nZW5wcm90by9nb29nbGVhcGlzL2Fkcy9nb29nbGVhZHMvdjgvZXJy",
"b3JzO2Vycm9yc6ICA0dBQaoCHkdvb2dsZS5BZHMuR29vZ2xlQWRzLlY4LkVy",
"cm9yc8oCHkdvb2dsZVxBZHNcR29vZ2xlQWRzXFY4XEVycm9yc+oCIkdvb2ds",
"ZTo6QWRzOjpHb29nbGVBZHM6OlY4OjpFcnJvcnNiBnByb3RvMw=="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::Google.Api.AnnotationsReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Ads.GoogleAds.V8.Errors.StringFormatErrorEnum), global::Google.Ads.GoogleAds.V8.Errors.StringFormatErrorEnum.Parser, null, null, new[]{ typeof(global::Google.Ads.GoogleAds.V8.Errors.StringFormatErrorEnum.Types.StringFormatError) }, null, null)
}));
}
#endregion
}
#region Messages
/// <summary>
/// Container for enum describing possible string format errors.
/// </summary>
public sealed partial class StringFormatErrorEnum : pb::IMessage<StringFormatErrorEnum>
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
, pb::IBufferMessage
#endif
{
private static readonly pb::MessageParser<StringFormatErrorEnum> _parser = new pb::MessageParser<StringFormatErrorEnum>(() => new StringFormatErrorEnum());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<StringFormatErrorEnum> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Ads.GoogleAds.V8.Errors.StringFormatErrorReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public StringFormatErrorEnum() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public StringFormatErrorEnum(StringFormatErrorEnum other) : this() {
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public StringFormatErrorEnum Clone() {
return new StringFormatErrorEnum(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as StringFormatErrorEnum);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(StringFormatErrorEnum other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
output.WriteRawMessage(this);
#else
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) {
if (_unknownFields != null) {
_unknownFields.WriteTo(ref output);
}
}
#endif
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(StringFormatErrorEnum other) {
if (other == null) {
return;
}
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
input.ReadRawMessage(this);
#else
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
}
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
}
}
}
#endif
#region Nested types
/// <summary>Container for nested types declared in the StringFormatErrorEnum message type.</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static partial class Types {
/// <summary>
/// Enum describing possible string format errors.
/// </summary>
public enum StringFormatError {
/// <summary>
/// Enum unspecified.
/// </summary>
[pbr::OriginalName("UNSPECIFIED")] Unspecified = 0,
/// <summary>
/// The received error code is not known in this version.
/// </summary>
[pbr::OriginalName("UNKNOWN")] Unknown = 1,
/// <summary>
/// The input string value contains disallowed characters.
/// </summary>
[pbr::OriginalName("ILLEGAL_CHARS")] IllegalChars = 2,
/// <summary>
/// The input string value is invalid for the associated field.
/// </summary>
[pbr::OriginalName("INVALID_FORMAT")] InvalidFormat = 3,
}
}
#endregion
}
#endregion
}
#endregion Designer generated code
| 36.823529 | 307 | 0.699681 | [
"Apache-2.0"
] | deni-skaraudio/google-ads-dotnet | src/V8/Types/StringFormatError.g.cs | 8,138 | C# |
using SystemChecker.Model.Data.Entities;
using SystemChecker.Model.Data.Interfaces;
using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
namespace SystemChecker.Model.Data.Repositories
{
public class UserRepository : Repository<User>, IUserRepository
{
public UserRepository(ICheckerContext context)
: base(context) { }
public async Task<User> GetByUsername(string username, bool? isWindowsUser = null)
{
var query = base.GetAll();
if (isWindowsUser.HasValue)
{
query = query.Where(x => x.IsWindowsUser == isWindowsUser);
}
return await query.FirstOrDefaultAsync(x => x.Username == username);
}
public async Task<User> GetDetails(string username)
{
return await base.GetAll()
.Include(x => x.ApiKeys)
.FirstOrDefaultAsync(x => x.Username == username);
}
public async Task<User> GetDetails(int id)
{
return await base.GetAll()
.Include(x => x.ApiKeys)
.FirstOrDefaultAsync(x => x.ID == id);
}
}
}
| 29 | 90 | 0.593596 | [
"MIT"
] | MattJeanes/SystemChecker | SystemChecker.Model/Data/Repositories/UserRepository.cs | 1,220 | C# |
using System;
namespace ConsoleUI.Elements.Containers.GridContainer
{
public class CellUpdatedEventArgs : EventArgs
{
public UInt16 RowIndex { get; }
public UInt16 ColumnIndex { get; }
public CellUpdatedEventArgs( UInt16 _columnIndex, UInt16 _rowIndex )
{
ColumnIndex = _columnIndex;
RowIndex = _rowIndex;
}
}
} | 19.647059 | 70 | 0.742515 | [
"MIT"
] | Arganancer/PathfindingBenchmark_Console | ConsoleUI/Elements/Containers/GridContainer/CellUpdatedEventArgs.cs | 336 | C# |
using UnityEngine;
using System.Collections;
using DG.Tweening;
public class Whisperer : MonoBehaviour
{
Game game;
void Start ()
{
game = GetComponentInParent<Game> ();
}
void OnMouseOver ()
{
game.SetHelpText (Whisperer.Description ());
}
void OnMouseExit ()
{
game.HideHelpText ();
}
public static int WhispererMoves (Unit whisperer)
{
int moves = 0x0;
Zone zone = whisperer.Zone;
// Whisperer must move exactly 3 squares but cannot land on walls. It can moves through obstacle.
// Can only capture playable units
int speed = 3;
for (int step = 0; step <= speed; ++step) {
// SW
int row = whisperer.Row + step;
int column = whisperer.Column - (speed - step);
if (column < zone.columns && row < zone.rows && column >= 0 && row >= 0) {
Tile tile = zone.Tiles [column, row];
if (tile.Unit == null || (tile.Unit.Player != null && tile.Unit.Player != whisperer.Player && whisperer.CanDestroyUnit ())) {
moves = Zone.SetIndex (moves, tile.Index);
}
}
// SE
row = whisperer.Row + step;
column = whisperer.Column + (speed - step);
if (column < zone.columns && row < zone.rows && column >= 0 && row >= 0) {
Tile tile = zone.Tiles [column, row];
if (tile.Unit == null || (tile.Unit.Player != null && tile.Unit.Player != whisperer.Player && whisperer.CanDestroyUnit ())) {
moves = Zone.SetIndex (moves, tile.Index);
}
}
// NE
row = whisperer.Row - step;
column = whisperer.Column + (speed - step);
if (column < zone.columns && row < zone.rows && column >= 0 && row >= 0) {
Tile tile = zone.Tiles [column, row];
if (tile.Unit == null || (tile.Unit.Player != null && tile.Unit.Player != whisperer.Player && whisperer.CanDestroyUnit ())) {
moves = Zone.SetIndex (moves, tile.Index);
}
}
// NW
row = whisperer.Row - step;
column = whisperer.Column - (speed - step);
if (column < zone.columns && row < zone.rows && column >= 0 && row >= 0) {
Tile tile = zone.Tiles [column, row];
if (tile.Unit == null || (tile.Unit.Player != null && tile.Unit.Player != whisperer.Player && whisperer.CanDestroyUnit ())) {
moves = Zone.SetIndex (moves, tile.Index);
}
}
}
return moves;
}
public static void ShowWhispererMoves (Unit whisperer)
{
Zone zone = whisperer.Zone;
zone.HighlightTile (whisperer.Column, whisperer.Row);
int moves = WhispererMoves (whisperer);
int tilesNum = zone.TilesNum;
for (int bit = 0; bit < tilesNum; bit++) {
if (Zone.IsIndexSet (moves, bit)) {
zone.HighlightTile (zone.ColumnFromIndex (bit), zone.RowFromIndex (bit));
}
}
}
public static string Description ()
{
return "Knight moves exactly 3 tiles in any directions. Can attack.\n\nRespawn: " + PlayableUnit.REGEN_TURNS + " turns";
}
// Factory methods
public static Unit CreateWhisperer (Player player, Zone zone, int column, int row)
{
string path = "";
if (player.IsRed) {
path = "Prefabs/RedWhisperer";
} else {
path = "Prefabs/BlueWhisperer";
}
GameObject obj = Instantiate (Resources.Load (path)) as GameObject;
obj.GetComponent<Renderer>().sortingLayerName = Unit.UNIT_RENDER_LAYER;
obj.tag = player.IsRed ? Unit.RED_WHISPERER : Unit.BLUE_WHISPERER;
obj.transform.SetParent (zone.transform);
Unit unit = obj.GetComponent<Unit> ();
player.OnCapturedUnit (unit);
zone.SpawnUnit (unit, column, row);
return unit;
}
}
| 35.364407 | 141 | 0.528157 | [
"MIT",
"Unlicense"
] | trungtle/shires | Assets/Resources/Scripts/Whisperer.cs | 4,175 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Concurrent;
using JetBrains.Annotations;
using Microsoft.EntityFrameworkCore.Internal;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Metadata.Conventions;
using Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using Microsoft.EntityFrameworkCore.Utilities;
namespace Microsoft.EntityFrameworkCore.Infrastructure
{
/// <summary>
/// <para>
/// An implementation of <see cref="IModelSource" /> that produces a model based on
/// the <see cref="DbSet{TEntity}" /> properties exposed on the context. The model is cached to avoid
/// recreating it every time it is requested.
/// </para>
/// <para>
/// This type is typically used by database providers (and other extensions). It is generally
/// not used in application code.
/// </para>
/// </summary>
public class ModelSource : IModelSource
{
private readonly ConcurrentDictionary<object, IModel> _models = new ConcurrentDictionary<object, IModel>();
/// <summary>
/// This API supports the Entity Framework Core infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
public ModelSource([NotNull] ModelSourceDependencies dependencies)
{
Check.NotNull(dependencies, nameof(dependencies));
Dependencies = dependencies;
}
/// <summary>
/// Dependencies used to create a <see cref="ModelSource" />
/// </summary>
protected virtual ModelSourceDependencies Dependencies { get; }
/// <summary>
/// Returns the model from the cache, or creates a model if it is not present in the cache.
/// </summary>
/// <param name="context"> The context the model is being produced for. </param>
/// <param name="conventionSetBuilder"> The convention set to use when creating the model. </param>
/// <param name="validator"> The validator to verify the model can be successfully used with the context. </param>
/// <returns> The model to be used. </returns>
public virtual IModel GetModel(DbContext context, IConventionSetBuilder conventionSetBuilder, IModelValidator validator)
=> _models.GetOrAdd(
Dependencies.ModelCacheKeyFactory.Create(context),
k => CreateModel(context, conventionSetBuilder, validator));
/// <summary>
/// Creates the model. This method is called when the model was not found in the cache.
/// </summary>
/// <param name="context"> The context the model is being produced for. </param>
/// <param name="conventionSetBuilder"> The convention set to use when creating the model. </param>
/// <param name="validator"> The validator to verify the model can be successfully used with the context. </param>
/// <returns> The model to be used. </returns>
protected virtual IModel CreateModel(
[NotNull] DbContext context,
[NotNull] IConventionSetBuilder conventionSetBuilder,
[NotNull] IModelValidator validator)
{
Check.NotNull(context, nameof(context));
Check.NotNull(validator, nameof(validator));
var conventionSet = CreateConventionSet(conventionSetBuilder);
var modelBuilder = new ModelBuilder(conventionSet);
var internalModelBuilder = ((IInfrastructure<InternalModelBuilder>)modelBuilder).Instance;
internalModelBuilder.Metadata.SetProductVersion(ProductInfo.GetVersion());
FindSets(modelBuilder, context);
FindFunctions(modelBuilder, context);
Dependencies.ModelCustomizer.Customize(modelBuilder, context);
internalModelBuilder.Validate();
validator.Validate(modelBuilder.Model);
return modelBuilder.Model;
}
/// <summary>
/// Creates the convention set to be used for the model. Only uses the <see cref="CoreConventionSetBuilder" />
/// if <paramref name="conventionSetBuilder" /> is null.
/// </summary>
/// <param name="conventionSetBuilder"> The provider convention set builder to be used. </param>
/// <returns> The convention set to be used. </returns>
protected virtual ConventionSet CreateConventionSet([NotNull] IConventionSetBuilder conventionSetBuilder)
=> conventionSetBuilder.AddConventions(Dependencies.CoreConventionSetBuilder.CreateConventionSet());
/// <summary>
/// Adds the entity types found in <see cref="DbSet{TEntity}" /> properties on the context to the model.
/// </summary>
/// <param name="modelBuilder"> The <see cref="ModelBuilder" /> being used to build the model. </param>
/// <param name="context"> The context to find <see cref="DbSet{TEntity}" /> properties on. </param>
protected virtual void FindSets([NotNull] ModelBuilder modelBuilder, [NotNull] DbContext context)
{
foreach (var setInfo in Dependencies.SetFinder.FindSets(context))
{
modelBuilder.Entity(setInfo.ClrType);
}
}
/// <summary>
/// Adds the user defined database functions found in <see cref="DbContext" /> to the model.
/// </summary>
/// <param name="modelBuilder"> The <see cref="ModelBuilder"/> being used to build the model. </param>
/// <param name="context"> The context to find <see cref="DbSet{TEntity}"/> properties on. </param>
protected virtual void FindFunctions([NotNull] ModelBuilder modelBuilder, [NotNull] DbContext context)
{
foreach (var dbFunctionMethodInfo in DbFunctionFinder.FindFunctions(context))
{
modelBuilder.DbFunction(dbFunctionMethodInfo);
}
}
}
}
| 48.620155 | 128 | 0.65354 | [
"Apache-2.0"
] | pmiddleton/EntityFramework | src/EFCore/Infrastructure/ModelSource.cs | 6,272 | C# |
//------------------------------------------------------------------------------
// <auto-generated />
//
// This file was automatically generated by SWIG (http://www.swig.org).
// Version 3.0.12
//
// Do not make changes to this file unless you know what you are doing--modify
// the SWIG interface file instead.
//------------------------------------------------------------------------------
namespace EliteQuant {
public class CapFloorTermVolatilityStructureHandle : global::System.IDisposable {
private global::System.Runtime.InteropServices.HandleRef swigCPtr;
protected bool swigCMemOwn;
internal CapFloorTermVolatilityStructureHandle(global::System.IntPtr cPtr, bool cMemoryOwn) {
swigCMemOwn = cMemoryOwn;
swigCPtr = new global::System.Runtime.InteropServices.HandleRef(this, cPtr);
}
internal static global::System.Runtime.InteropServices.HandleRef getCPtr(CapFloorTermVolatilityStructureHandle obj) {
return (obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr;
}
~CapFloorTermVolatilityStructureHandle() {
Dispose();
}
public virtual void Dispose() {
lock(this) {
if (swigCPtr.Handle != global::System.IntPtr.Zero) {
if (swigCMemOwn) {
swigCMemOwn = false;
NQuantLibcPINVOKE.delete_CapFloorTermVolatilityStructureHandle(swigCPtr);
}
swigCPtr = new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero);
}
global::System.GC.SuppressFinalize(this);
}
}
public CapFloorTermVolatilityStructureHandle(CapFloorTermVolatilityStructure arg0) : this(NQuantLibcPINVOKE.new_CapFloorTermVolatilityStructureHandle__SWIG_0(CapFloorTermVolatilityStructure.getCPtr(arg0)), true) {
if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
}
public CapFloorTermVolatilityStructureHandle() : this(NQuantLibcPINVOKE.new_CapFloorTermVolatilityStructureHandle__SWIG_1(), true) {
if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
}
public CapFloorTermVolatilityStructure __deref__() {
CapFloorTermVolatilityStructure ret = new CapFloorTermVolatilityStructure(NQuantLibcPINVOKE.CapFloorTermVolatilityStructureHandle___deref__(swigCPtr), true);
if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
return ret;
}
public bool empty() {
bool ret = NQuantLibcPINVOKE.CapFloorTermVolatilityStructureHandle_empty(swigCPtr);
if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
return ret;
}
public Observable asObservable() {
Observable ret = new Observable(NQuantLibcPINVOKE.CapFloorTermVolatilityStructureHandle_asObservable(swigCPtr), true);
if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
return ret;
}
public double volatility(Period length, double strike, bool extrapolate) {
double ret = NQuantLibcPINVOKE.CapFloorTermVolatilityStructureHandle_volatility__SWIG_0(swigCPtr, Period.getCPtr(length), strike, extrapolate);
if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
return ret;
}
public double volatility(Period length, double strike) {
double ret = NQuantLibcPINVOKE.CapFloorTermVolatilityStructureHandle_volatility__SWIG_1(swigCPtr, Period.getCPtr(length), strike);
if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
return ret;
}
public double volatility(Date end, double strike, bool extrapolate) {
double ret = NQuantLibcPINVOKE.CapFloorTermVolatilityStructureHandle_volatility__SWIG_2(swigCPtr, Date.getCPtr(end), strike, extrapolate);
if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
return ret;
}
public double volatility(Date end, double strike) {
double ret = NQuantLibcPINVOKE.CapFloorTermVolatilityStructureHandle_volatility__SWIG_3(swigCPtr, Date.getCPtr(end), strike);
if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
return ret;
}
public double volatility(double end, double strike, bool extrapolate) {
double ret = NQuantLibcPINVOKE.CapFloorTermVolatilityStructureHandle_volatility__SWIG_4(swigCPtr, end, strike, extrapolate);
if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
return ret;
}
public double volatility(double end, double strike) {
double ret = NQuantLibcPINVOKE.CapFloorTermVolatilityStructureHandle_volatility__SWIG_5(swigCPtr, end, strike);
if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
return ret;
}
public void enableExtrapolation() {
NQuantLibcPINVOKE.CapFloorTermVolatilityStructureHandle_enableExtrapolation(swigCPtr);
if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
}
public void disableExtrapolation() {
NQuantLibcPINVOKE.CapFloorTermVolatilityStructureHandle_disableExtrapolation(swigCPtr);
if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
}
public bool allowsExtrapolation() {
bool ret = NQuantLibcPINVOKE.CapFloorTermVolatilityStructureHandle_allowsExtrapolation(swigCPtr);
if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve();
return ret;
}
}
}
| 46.935484 | 215 | 0.775258 | [
"Apache-2.0"
] | qg0/EliteQuant_Excel | SwigConversionLayer/csharp/CapFloorTermVolatilityStructureHandle.cs | 5,820 | C# |
using System;
using System.Threading.Tasks;
using Cosmos.Serialization.Yaml.SharpYaml;
// ReSharper disable once CheckNamespace
namespace Cosmos.Serialization.Yaml
{
/// <summary>
/// SharpYaml extensions
/// </summary>
public static partial class Extensions
{
/// <summary>
/// From Yaml
/// </summary>
/// <param name="str"></param>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static T FromSharpYaml<T>(this string str)
{
return SharpYamlHelper.Deserialize<T>(str);
}
/// <summary>
/// From Yaml
/// </summary>
/// <param name="str"></param>
/// <param name="type"></param>
/// <returns></returns>
public static object FromSharpYaml(this string str, Type type)
{
return SharpYamlHelper.Deserialize(str, type);
}
/// <summary>
/// From Yaml async
/// </summary>
/// <param name="str"></param>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static Task<T> FromSharpYamlAsync<T>(this string str)
{
return SharpYamlHelper.DeserializeAsync<T>(str);
}
/// <summary>
/// From Yaml async
/// </summary>
/// <param name="str"></param>
/// <param name="type"></param>
/// <returns></returns>
public static Task<object> FromSharpYamlAsync(this string str, Type type)
{
return SharpYamlHelper.DeserializeAsync(str, type);
}
}
} | 28.526316 | 81 | 0.536285 | [
"Apache-2.0"
] | alexinea/dotnet-static-pages | src/Cosmos.Serialization.SharpYaml/Cosmos/Serialization/Yaml/Extensions/Extensions.SharpYaml.String.cs | 1,626 | C# |
using System.Net;
using System.Text.RegularExpressions;
using System.Xml.Linq;
namespace Jox.UiPathCoverageReport;
class Tree : TreeNode
{
public Tree(string name) : base(name)
{
}
public bool AddComment(string comment) => GetOrAdd($"({comment})").IsMetadata = true;
public void AddFile(string path)
{
if (Directory.Exists(path))
{
path = Path.Combine(path, "project.json");
}
AddFile(new FileInfo(path));
}
private void AddFile(FileInfo mainFile)
{
var projectDir = mainFile.Directory;
if (mainFile.Name.Equals("project.json", StringComparison.OrdinalIgnoreCase))
{
// JSON parsing would be better but requires additional dll
var mainRegex = new Regex(@"""main"": ""(?<filename>[^""]+\.xaml)"",");
foreach (var line in File.ReadLines(mainFile.FullName))
{
var match = mainRegex.Match(line);
if (match.Success)
{
mainFile = new FileInfo(Path.Combine(mainFile.DirectoryName, match.Groups["filename"].Value));
break;
}
}
}
AddUiPathXaml(mainFile, projectDir);
}
private void AddUiPathXaml(FileInfo xamlFile, DirectoryInfo projectDir)
{
var doc = XDocument.Load(xamlFile.FullName);
var controls = doc.Descendants("{http://schemas.uipath.com/workflow/activities}Target");
foreach (var control in controls)
{
AddSelector(control);
}
// if the UiPath XAML file references other files, add them to the tree as well
var externalFiles = doc.Descendants("{http://schemas.uipath.com/workflow/activities}InvokeWorkflowFile");
foreach (var externalFile in externalFiles)
{
var externalFileName = externalFile.Attribute("WorkflowFileName").Value;
if (AddComment($"including {externalFileName}"))
{
// only process external file the first time we see it
AddUiPathXaml(new FileInfo(Path.Combine(projectDir.FullName, externalFileName)), projectDir);
}
}
}
private void AddSelector(XElement control)
{
var windowScope = control.Ancestors("{http://schemas.uipath.com/workflow/activities}WindowScope").FirstOrDefault();
var lineage = XElement.Parse($"<x>{ParseSelectorAttribute(windowScope)}{ParseSelectorAttribute(control)}</x>").Elements();
TreeNode app;
TreeNode parent = this;
foreach (var wnd in lineage)
{
var appName = wnd.Attribute("app")?.Value;
if (appName != null)
{
app = GetOrAdd(appName);
parent = app;
}
var controlName = wnd.Attribute("ctrlname")?.Value;
if (controlName != null)
{
parent = parent.GetOrAdd(controlName);
}
}
}
private static string ParseSelectorAttribute(XElement element)
{
if (element == null)
{
return string.Empty;
}
var attributeValue = element.Attribute("Selector").Value;
if (attributeValue == "{x:Null}")
{
return string.Empty;
}
var decoded = WebUtility.HtmlDecode(attributeValue);
if (decoded.Length > 4 && decoded.Substring(0, 2) == "[\"")
{
decoded = decoded.Substring(2, decoded.Length - 4);
}
return decoded.Replace("omit:", "").Replace("&", "");
}
public static Tree Build(IReadOnlyList<string> files)
{
Tree tree;
if (files.Count == 1)
{
var xamlFile = files.First();
tree = new Tree(xamlFile);
tree.AddFile(xamlFile);
}
else
{
tree = new Tree("[multiple sources]");
foreach (var file in files)
{
tree.AddComment($"given source: {file}");
tree.AddFile(file);
}
}
return tree;
}
}
| 31.393939 | 130 | 0.556708 | [
"Unlicense"
] | jopabe/uipath-coveragereport | src/Jox.UiPathCoverageReport/Tree.cs | 4,146 | C# |
using System.Collections.Generic;
using BuildingBlocks.CQRS.QueryHandling;
using EcommerceDDD.Application.Customers.ViewModels;
using FluentValidation;
using FluentValidation.Results;
namespace EcommerceDDD.Application.Products.ListProducts
{
public class ListProductsQuery : Query<IList<ProductViewModel>>
{
public string Currency { get; }
public ListProductsQuery(string currency)
{
Currency = currency;
}
public override ValidationResult Validate()
{
return new ListProductsQueryValidator().Validate(this);
}
}
public class ListProductsQueryValidator : AbstractValidator<ListProductsQuery>
{
public ListProductsQueryValidator()
{
RuleFor(x => x.Currency).NotEmpty().WithMessage("Currency is empty.");
}
}
}
| 26.71875 | 82 | 0.680702 | [
"MIT"
] | AELMOUMNI/EcommerceDDD | src/EcommerceDDD.Application/Products/ListProducts/ListProductsQuery.cs | 857 | C# |
#region BSD License
/*
* Use of this source code is governed by a BSD-style
* license that can be found in the LICENSE.md file or at
* https://github.com/Wagnerp/Krypton-Toolkit-Suite-Extended-NET-5.462/blob/master/LICENSE
*
*/
#endregion
///////////////////////////////////////////////////////////////////////////////
// SAMPLE: Generates random password, which complies with the strong password
// rules and does not contain ambiguous characters.
//
// To run this sample, create a new Visual C# project using the Console
// Application template and replace the contents of the Class1.cs file with
// the code below.
//
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
// EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
//
// Copyright (C) 2004 Obviex(TM). All rights reserved.
//
using System;
using System.Security.Cryptography;
namespace Persistence.Classes.Security
{
/// <summary>
/// This class can generate random passwords, which do not include ambiguous
/// characters, such as I, l, and 1. The generated password will be made of
/// 7-bit ASCII symbols. Every four characters will include one lower case
/// character, one upper case character, one number, and one special symbol
/// (such as '%') in a random order. The password will always start with an
/// alpha-numeric character; it will not start with a special symbol (we do
/// this because some back-end systems do not like certain special
/// characters in the first position).
/// </summary>
public class RandomPassword
{
// Define default min and max password lengths.
private static int DEFAULT_MIN_PASSWORD_LENGTH = 8;
private static int DEFAULT_MAX_PASSWORD_LENGTH = 10;
// Define supported password characters divided into groups.
// You can add (or remove) characters to (from) these groups.
private static string PASSWORD_CHARS_LCASE = "abcdefgijkmnopqrstwxyz";
private static string PASSWORD_CHARS_UCASE = "ABCDEFGHJKLMNPQRSTWXYZ";
private static string PASSWORD_CHARS_NUMERIC = "23456789";
private static string PASSWORD_CHARS_SPECIAL = "*$-+?_&=!%{}/";
/// <summary>
/// Generates a random password.
/// </summary>
/// <returns>
/// Randomly generated password.
/// </returns>
/// <remarks>
/// The length of the generated password will be determined at
/// random. It will be no shorter than the minimum default and
/// no longer than maximum default.
/// </remarks>
public static string Generate()
{
return Generate(DEFAULT_MIN_PASSWORD_LENGTH,
DEFAULT_MAX_PASSWORD_LENGTH);
}
/// <summary>
/// Generates a random password of the exact length.
/// </summary>
/// <param name="length">
/// Exact password length.
/// </param>
/// <returns>
/// Randomly generated password.
/// </returns>
public static string Generate(int length)
{
return Generate(length, length);
}
/// <summary>
/// Generates a random password.
/// </summary>
/// <param name="minLength">
/// Minimum password length.
/// </param>
/// <param name="maxLength">
/// Maximum password length.
/// </param>
/// <returns>
/// Randomly generated password.
/// </returns>
/// <remarks>
/// The length of the generated password will be determined at
/// random and it will fall with the range determined by the
/// function parameters.
/// </remarks>
public static string Generate(int minLength,
int maxLength)
{
// Make sure that input parameters are valid.
if (minLength <= 0 || maxLength <= 0 || minLength > maxLength)
return null;
// Create a local array containing supported password characters
// grouped by types. You can remove character groups from this
// array, but doing so will weaken the password strength.
char[][] charGroups = new char[][]
{
PASSWORD_CHARS_LCASE.ToCharArray(),
PASSWORD_CHARS_UCASE.ToCharArray(),
PASSWORD_CHARS_NUMERIC.ToCharArray(),
PASSWORD_CHARS_SPECIAL.ToCharArray()
};
// Use this array to track the number of unused characters in each
// character group.
int[] charsLeftInGroup = new int[charGroups.Length];
// Initially, all characters in each group are not used.
for (int i = 0; i < charsLeftInGroup.Length; i++)
charsLeftInGroup[i] = charGroups[i].Length;
// Use this array to track (iterate through) unused character groups.
int[] leftGroupsOrder = new int[charGroups.Length];
// Initially, all character groups are not used.
for (int i = 0; i < leftGroupsOrder.Length; i++)
leftGroupsOrder[i] = i;
// Because we cannot use the default randomizer, which is based on the
// current time (it will produce the same "random" number within a
// second), we will use a random number generator to seed the
// randomizer.
// Use a 4-byte array to fill it with random bytes and convert it then
// to an integer value.
byte[] randomBytes = new byte[4];
// Generate 4 random bytes.
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
rng.GetBytes(randomBytes);
// Convert 4 bytes into a 32-bit integer value.
int seed = BitConverter.ToInt32(randomBytes, 0);
// Now, this is real randomization.
Random random = new Random(seed);
// This array will hold password characters.
char[] password = null;
// Allocate appropriate memory for the password.
if (minLength < maxLength)
password = new char[random.Next(minLength, maxLength + 1)];
else
password = new char[minLength];
// Index of the next character to be added to password.
int nextCharIdx;
// Index of the next character group to be processed.
int nextGroupIdx;
// Index which will be used to track not processed character groups.
int nextLeftGroupsOrderIdx;
// Index of the last non-processed character in a group.
int lastCharIdx;
// Index of the last non-processed group.
int lastLeftGroupsOrderIdx = leftGroupsOrder.Length - 1;
// Generate password characters one at a time.
for (int i = 0; i < password.Length; i++)
{
// If only one character group remained unprocessed, process it;
// otherwise, pick a random character group from the unprocessed
// group list. To allow a special character to appear in the
// first position, increment the second parameter of the Next
// function call by one, i.e. lastLeftGroupsOrderIdx + 1.
if (lastLeftGroupsOrderIdx == 0)
nextLeftGroupsOrderIdx = 0;
else
nextLeftGroupsOrderIdx = random.Next(0,
lastLeftGroupsOrderIdx);
// Get the actual index of the character group, from which we will
// pick the next character.
nextGroupIdx = leftGroupsOrder[nextLeftGroupsOrderIdx];
// Get the index of the last unprocessed characters in this group.
lastCharIdx = charsLeftInGroup[nextGroupIdx] - 1;
// If only one unprocessed character is left, pick it; otherwise,
// get a random character from the unused character list.
if (lastCharIdx == 0)
nextCharIdx = 0;
else
nextCharIdx = random.Next(0, lastCharIdx + 1);
// Add this character to the password.
password[i] = charGroups[nextGroupIdx][nextCharIdx];
// If we processed the last character in this group, start over.
if (lastCharIdx == 0)
charsLeftInGroup[nextGroupIdx] =
charGroups[nextGroupIdx].Length;
// There are more unprocessed characters left.
else
{
// Swap processed character with the last unprocessed character
// so that we don't pick it until we process all characters in
// this group.
if (lastCharIdx != nextCharIdx)
{
char temp = charGroups[nextGroupIdx][lastCharIdx];
charGroups[nextGroupIdx][lastCharIdx] =
charGroups[nextGroupIdx][nextCharIdx];
charGroups[nextGroupIdx][nextCharIdx] = temp;
}
// Decrement the number of unprocessed characters in
// this group.
charsLeftInGroup[nextGroupIdx]--;
}
// If we processed the last group, start all over.
if (lastLeftGroupsOrderIdx == 0)
lastLeftGroupsOrderIdx = leftGroupsOrder.Length - 1;
// There are more unprocessed groups left.
else
{
// Swap processed group with the last unprocessed group
// so that we don't pick it until we process all groups.
if (lastLeftGroupsOrderIdx != nextLeftGroupsOrderIdx)
{
int temp = leftGroupsOrder[lastLeftGroupsOrderIdx];
leftGroupsOrder[lastLeftGroupsOrderIdx] =
leftGroupsOrder[nextLeftGroupsOrderIdx];
leftGroupsOrder[nextLeftGroupsOrderIdx] = temp;
}
// Decrement the number of unprocessed groups.
lastLeftGroupsOrderIdx--;
}
}
// Convert password characters into a string and return the result.
return new string(password);
}
}
}
///// <summary>
///// Illustrates the use of the RandomPassword class.
///// </summary>
//public class RandomPasswordTest
//{
// /// <summary>
// /// The main entry point for the application.
// /// </summary>
// [STAThread]
// static void Main(string[] args)
// {
// // Print 100 randomly generated passwords (8-to-10 char long).
// for (int i = 0; i < 100; i++)
// Console.WriteLine(RandomPassword.Generate(8, 10));
// }
//} | 41.803704 | 90 | 0.566847 | [
"BSD-3-Clause"
] | Krypton-Suite-Legacy/Krypton-Toolkit-Suite-Extended-NET-5.462 | Source/Krypton Toolkit Suite Extended/Shared/Persistence/Classes/Security/RandomPassword.cs | 11,289 | C# |
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OvertimeManager.MVC5.Web;
using OvertimeManager.MVC5.Web.Controllers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
namespace OvertimeManager.MVC5.Web.Tests.Controllers
{
[TestClass]
public class HomeControllerTest
{
[TestMethod]
public void Index()
{
// Arrange
HomeController controller = new HomeController();
// Act
ViewResult result = controller.Index() as ViewResult;
// Assert
Assert.IsNotNull(result);
}
[TestMethod]
public void About()
{
// Arrange
HomeController controller = new HomeController();
// Act
ViewResult result = controller.About() as ViewResult;
// Assert
Assert.AreEqual("Your application description page.", result.ViewBag.Message);
}
[TestMethod]
public void Contact()
{
// Arrange
HomeController controller = new HomeController();
// Act
ViewResult result = controller.Contact() as ViewResult;
// Assert
Assert.IsNotNull(result);
}
}
}
| 25 | 91 | 0.558545 | [
"MIT"
] | roughcutsoftware/OvertimeManager | tests/OvertimeManager.MVC5.Web.Tests/Controllers/HomeControllerTest.cs | 1,377 | C# |
using EngineeringUnits.Units;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
namespace EngineeringUnits.Units
{
public class ElectricConductivityUnit : Enumeration
{
public static readonly ElectricConductivityUnit SI = new(ElectricAdmittanceUnit.SI, LengthUnit.SI);
public static readonly ElectricConductivityUnit SiemensPerMeter = new(ElectricAdmittanceUnit.Siemens, LengthUnit.Meter);
public static readonly ElectricConductivityUnit SiemensPerInch = new(ElectricAdmittanceUnit.Siemens, LengthUnit.Inch);
public static readonly ElectricConductivityUnit SiemensPerFoot = new(ElectricAdmittanceUnit.Siemens, LengthUnit.Foot);
public ElectricConductivityUnit(ElectricAdmittanceUnit electricAdmittance, LengthUnit Length)
{
Unit = new UnitSystem(electricAdmittance / Length,
$"{electricAdmittance}/{Length}");
}
}
} | 30.3125 | 128 | 0.740206 | [
"MIT"
] | ikijano/EngineeringUnits | EngineeringUnits/CombinedUnits/ElectricConductivity/ElectricConductivityEnum.cs | 972 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MySql.Data;
using System.Data;
using DPS.Classes;
namespace DPS.DAO
{
public class Cliente
{
public IEnumerable<Models.Cliente> Get()
{
string comando = @"SELECT telefone_residencial, latitude, longitude, nome
FROM clientes ";
DataTable data = Conexao.leitura(comando);
try
{
IEnumerable<Models.Cliente> items = data.AsEnumerable().Select(row =>
new Models.Cliente
{
nome = row.Field<string>("nome"),
telefone = row.Field<string>("telefone_residencial"),
latitude = row["latitude"].ToString().Replace(",", "."),
longitude = row["longitude"].ToString().Replace(",", ".")
}).ToList();
return items;
}
catch {
IEnumerable<Models.Cliente> items = data.AsEnumerable().Select(row =>
new Models.Cliente
{
nome = "",
telefone = "",
latitude = "",
longitude = ""
}).ToList();
return items;
}
}
}
} | 28.666667 | 86 | 0.457849 | [
"Apache-2.0"
] | AntonioDantas/DPS | DPS/DAO/Cliente.cs | 1,378 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Money.Events
{
/// <summary>
/// An event raised when the income is deleted.
/// </summary>
public class IncomeDeleted : UserEvent
{ }
}
| 18.875 | 51 | 0.695364 | [
"Apache-2.0"
] | ScriptBox21/Money | src/Money/Events/IncomeDeleted.cs | 304 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace DMTestWebAuto.Compilador.Tokens
{
public enum EnumComandos
{
Acesse,
Click,
Aguarde,
VeriqueSeExiste
}
}
| 15.2 | 41 | 0.649123 | [
"MIT"
] | JDouglasMendes/tools-web-test-driver | DMTestWebAuto/DMTestWebAuto.Compilador/Utils/EnumComandos.cs | 230 | C# |
using Wyam.Common.Execution;
namespace Wyam.SearchIndex
{
/// <summary>
/// Represents an item in the search index.
/// </summary>
public interface ISearchIndexItem
{
/// <summary>
/// The title of the search item.
/// </summary>
string Title { get; }
/// <summary>
/// The description of the search item.
/// </summary>
string Description { get; }
/// <summary>
/// The content of the search item.
/// </summary>
string Content { get; }
/// <summary>
/// Any tags for the search item.
/// </summary>
string Tags { get; }
/// <summary>
/// Gets a link to the search item result.
/// </summary>
/// <param name="context">The current execution context.</param>
/// <param name="includeHost"><c>true</c> to include the hostname, <c>false otherwise</c>.</param>
/// <returns>A link to the search item.</returns>
string GetLink(IExecutionContext context, bool includeHost);
}
} | 28.578947 | 106 | 0.541436 | [
"MIT"
] | FBoucher/Wyam | src/extensions/Wyam.SearchIndex/ISearchIndexItem.cs | 1,088 | 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.DataFactory.V20180601.Outputs
{
[OutputType]
public sealed class ServiceNowObjectDatasetResponse
{
/// <summary>
/// List of tags that can be used for describing the Dataset.
/// </summary>
public readonly ImmutableArray<object> Annotations;
/// <summary>
/// Dataset description.
/// </summary>
public readonly string? Description;
/// <summary>
/// The folder that this Dataset is in. If not specified, Dataset will appear at the root level.
/// </summary>
public readonly Outputs.DatasetResponseFolder? Folder;
/// <summary>
/// Linked service reference.
/// </summary>
public readonly Outputs.LinkedServiceReferenceResponse LinkedServiceName;
/// <summary>
/// Parameters for dataset.
/// </summary>
public readonly ImmutableDictionary<string, Outputs.ParameterSpecificationResponse>? Parameters;
/// <summary>
/// Columns that define the physical type schema of the dataset. Type: array (or Expression with resultType array), itemType: DatasetSchemaDataElement.
/// </summary>
public readonly object? Schema;
/// <summary>
/// Columns that define the structure of the dataset. Type: array (or Expression with resultType array), itemType: DatasetDataElement.
/// </summary>
public readonly object? Structure;
/// <summary>
/// The table name. Type: string (or Expression with resultType string).
/// </summary>
public readonly object? TableName;
/// <summary>
/// Type of dataset.
/// Expected value is 'ServiceNowObject'.
/// </summary>
public readonly string Type;
[OutputConstructor]
private ServiceNowObjectDatasetResponse(
ImmutableArray<object> annotations,
string? description,
Outputs.DatasetResponseFolder? folder,
Outputs.LinkedServiceReferenceResponse linkedServiceName,
ImmutableDictionary<string, Outputs.ParameterSpecificationResponse>? parameters,
object? schema,
object? structure,
object? tableName,
string type)
{
Annotations = annotations;
Description = description;
Folder = folder;
LinkedServiceName = linkedServiceName;
Parameters = parameters;
Schema = schema;
Structure = structure;
TableName = tableName;
Type = type;
}
}
}
| 34.313953 | 159 | 0.621823 | [
"Apache-2.0"
] | pulumi-bot/pulumi-azure-native | sdk/dotnet/DataFactory/V20180601/Outputs/ServiceNowObjectDatasetResponse.cs | 2,951 | C# |
/*
Copyright (C) 2019 Alex Watt (alexwatt@hotmail.com)
This file is part of Highlander Project https://github.com/alexanderwatt/Highlander.Net
Highlander is free software: you can redistribute it and/or modify it
under the terms of the Highlander license. You should have received a
copy of the license along with this program; if not, license is
available at <https://github.com/alexanderwatt/Highlander.Net/blob/develop/LICENSE>.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the license for more details.
*/
#region Usings
using System;
using System.Collections.Generic;
#endregion
namespace FpML.V5r3.Reporting
{
public partial class Fra
{
/// <summary>
/// Gets and sets the required pricing structures to value this leg.
/// </summary>
public override List<string> GetRequiredPricingStructures()
{
var result = new List<string>();
if (notional.currency != null)
{
var discountCurve = CurveNameHelpers.GetDiscountCurveName(notional.currency, true);
result.Add(discountCurve);
}
if (floatingRateIndex != null && indexTenor!=null)
{
result.Add(CurveNameHelpers.GetForecastCurveName(floatingRateIndex, indexTenor[0]));
}
return result;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public override List<String> GetRequiredCurrencies()
{
var result = new List<string> {notional.currency.Value};
return result;
}
}
}
| 31.875 | 100 | 0.636415 | [
"BSD-3-Clause"
] | mmrath/Highlander.Net | Metadata/FpML.V5r3/FpML.V5r3.Reporting/Fra.cs | 1,787 | C# |
using Newtonsoft.Json;
using System;
using System.Text.RegularExpressions;
namespace Taviloglu.Wrike.Core
{
/// <summary>
/// Metadata entry key-value pair.
/// Metadata entries are isolated on per-client(application) basis
/// </summary>
public sealed class WrikeMetadata : IWrikeObject
{
/// <summary>
/// Initializes a new instance of the <see cref="WrikeMetadata"/> class.
/// </summary>
/// <param name="key">Key should be less than 50 symbols and match following regular expression ([A-Za-z0-9_-]+)</param>
/// <param name="value">Value should be less than 1000 symbols, compatible with JSON string. Use JSON 'null' in order to remove metadata entry</param>
public WrikeMetadata(string key, string value)
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
if (key.Trim() == string.Empty)
{
throw new ArgumentException("value can not be empty", nameof(key));
}
if (key.Length > 49)
{
throw new ArgumentException("value must be less than 50 characters",nameof(key));
}
if (!Regex.IsMatch(key, "([A-Za-z0-9_-]+)"))
{
throw new ArgumentException("key must match ([A-Za-z0-9_-]+)", nameof(key));
}
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
if (value.Trim() == string.Empty)
{
throw new ArgumentException("value can not be empty", nameof(value));
}
if (value.Length > 999)
{
throw new ArgumentException("value must be less than 1000 characters", nameof(value));
}
Key = key;
Value = value;
}
/// <summary>
/// Key
/// </summary>
[JsonProperty("key")]
public string Key { get; private set; }
/// <summary>
/// Value
/// </summary>
[JsonProperty("value")]
public string Value { get; private set; }
}
}
| 31.239437 | 158 | 0.522092 | [
"MIT"
] | hannesb/Taviloglu.Wrike.ApiClient | Taviloglu.Wrike.Core/WrikeMetadata.cs | 2,220 | C# |
/*
This code is derived from jgit (http://eclipse.org/jgit).
Copyright owners are documented in jgit's IP log.
This program and the accompanying materials are made available
under the terms of the Eclipse Distribution License v1.0 which
accompanies this distribution, is reproduced below, and is
available at http://www.eclipse.org/org/documents/edl-v10.php
All rights reserved.
Redistribution and use in source and binary forms, with or
without modification, are permitted provided that the following
conditions are met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
- Neither the name of the Eclipse Foundation, Inc. nor the
names of its contributors may be used to endorse or promote
products derived from this software without specific prior
written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.IO;
using System.Reflection;
using NGit.Junit;
using NGit.Storage.File;
using NGit.Util;
using NUnit.Framework;
using Sharpen;
using System.IO;
namespace NGit.Junit
{
public abstract class JGitTestUtil
{
public static readonly string CLASSPATH_TO_RESOURCES = "org/eclipse/jgit/test/resources/";
public JGitTestUtil()
{
throw new NotSupportedException();
}
/* Implemented in Sharpen.Extensions
public static string GetName()
{
JGitTestUtil.GatherStackTrace stack;
try
{
throw new JGitTestUtil.GatherStackTrace();
}
catch (JGitTestUtil.GatherStackTrace wanted)
{
stack = wanted;
}
try
{
foreach (StackTraceElement stackTrace in stack.GetStackTrace())
{
string className = stackTrace.GetClassName();
string methodName = stackTrace.GetMethodName();
MethodInfo method;
try
{
method = Sharpen.Runtime.GetType(className).GetMethod(methodName, (Type[])null);
}
catch (NoSuchMethodException)
{
//
// could be private, i.e. not a test method
// could have arguments, not handled
continue;
}
NUnit.Framework.Test annotation = method.GetAnnotation<NUnit.Framework.Test>();
if (annotation != null)
{
return methodName;
}
}
}
catch (TypeLoadException)
{
}
// Fall through and crash.
throw new Exception("Cannot determine name of current test");
}
*/
[System.Serializable]
private class GatherStackTrace : Exception
{
// Thrown above to collect the stack frame.
}
public static void AssertEquals(byte[] exp, byte[] act)
{
NUnit.Framework.Assert.AreEqual(S(exp), S(act));
}
private static string S(byte[] raw)
{
return RawParseUtils.Decode(raw);
}
public static FilePath GetTestResourceFile(string fileName)
{
if (fileName == null || fileName.Length <= 0)
{
return null;
}
string path = Path.Combine (AppDomain.CurrentDomain.BaseDirectory, "resources");
path = Path.Combine (path, "global");
return new FilePath (Path.Combine (path, fileName));
}
/// <exception cref="System.IO.IOException"></exception>
public static FilePath WriteTrashFile(FileRepository db, string name, string data
)
{
FilePath path = new FilePath(db.WorkTree, name);
Write(path, data);
return path;
}
/// <exception cref="System.IO.IOException"></exception>
public static FilePath WriteTrashFile(FileRepository db, string subdir, string name
, string data)
{
FilePath path = new FilePath(db.WorkTree + "/" + subdir, name);
Write(path, data);
return path;
}
/// <summary>Write a string as a UTF-8 file.</summary>
/// <remarks>Write a string as a UTF-8 file.</remarks>
/// <param name="f">
/// file to write the string to. Caller is responsible for making
/// sure it is in the trash directory or will otherwise be cleaned
/// up at the end of the test. If the parent directory does not
/// exist, the missing parent directories are automatically
/// created.
/// </param>
/// <param name="body">content to write to the file.</param>
/// <exception cref="System.IO.IOException">the file could not be written.</exception>
public static void Write(FilePath f, string body)
{
FileUtils.Mkdirs(f.GetParentFile(), true);
TextWriter w = new OutputStreamWriter(new FileOutputStream(f), "UTF-8");
try
{
w.Write(body);
}
finally
{
w.Close();
}
}
/// <summary>Fully read a UTF-8 file and return as a string.</summary>
/// <remarks>Fully read a UTF-8 file and return as a string.</remarks>
/// <param name="file">file to read the content of.</param>
/// <returns>
/// UTF-8 decoded content of the file, empty string if the file
/// exists but has no content.
/// </returns>
/// <exception cref="System.IO.IOException">the file does not exist, or could not be read.
/// </exception>
public static string Read(FilePath file)
{
byte[] body = IOUtil.ReadFully(file);
return Sharpen.Runtime.GetStringForBytes(body, 0, body.Length, "UTF-8");
}
/// <exception cref="System.IO.IOException"></exception>
public static string Read(FileRepository db, string name)
{
FilePath file = new FilePath(db.WorkTree, name);
return Read(file);
}
/// <exception cref="System.IO.IOException"></exception>
public static void DeleteTrashFile(FileRepository db, string name)
{
FilePath path = new FilePath(db.WorkTree, name);
FileUtils.Delete(path);
}
}
}
| 30.109005 | 92 | 0.711003 | [
"BSD-3-Clause"
] | Kavisha90/IIT-4th-year | NGit.Test/NGit.Junit/JGitTestUtil.cs | 6,353 | C# |
// ==========================================================================
// AppCommandMiddlewareTests.cs
// Squidex Headless CMS
// ==========================================================================
// Copyright (c) Squidex Group
// All rights reserved.
// ==========================================================================
using System;
using System.Threading.Tasks;
using FakeItEasy;
using Squidex.Domain.Apps.Read.Apps;
using Squidex.Domain.Apps.Read.Apps.Repositories;
using Squidex.Domain.Apps.Read.Apps.Services;
using Squidex.Domain.Apps.Read.Apps.Services.Implementations;
using Squidex.Domain.Apps.Write.Apps.Commands;
using Squidex.Domain.Apps.Write.TestHelpers;
using Squidex.Infrastructure;
using Squidex.Infrastructure.CQRS.Commands;
using Squidex.Shared.Users;
using Xunit;
namespace Squidex.Domain.Apps.Write.Apps
{
public class AppCommandMiddlewareTests : HandlerTestBase<AppDomainObject>
{
private readonly IAppRepository appRepository = A.Fake<IAppRepository>();
private readonly IAppPlansProvider appPlansProvider = A.Fake<IAppPlansProvider>();
private readonly IAppPlanBillingManager appPlansBillingManager = A.Fake<IAppPlanBillingManager>();
private readonly IUserResolver userResolver = A.Fake<IUserResolver>();
private readonly AppCommandMiddleware sut;
private readonly AppDomainObject app;
private readonly Language language = Language.DE;
private readonly string contributorId = Guid.NewGuid().ToString();
private readonly string clientName = "client";
public AppCommandMiddlewareTests()
{
app = new AppDomainObject(AppId, -1);
sut = new AppCommandMiddleware(Handler, appRepository, appPlansProvider, appPlansBillingManager, userResolver);
}
[Fact]
public async Task Create_should_throw_exception_if_a_name_with_same_name_already_exists()
{
var context = CreateContextForCommand(new CreateApp { Name = AppName, AppId = AppId });
A.CallTo(() => appRepository.FindAppAsync(AppName))
.Returns(A.Dummy<IAppEntity>());
await TestCreate(app, async _ =>
{
await Assert.ThrowsAsync<ValidationException>(async () => await sut.HandleAsync(context));
}, false);
A.CallTo(() => appRepository.FindAppAsync(AppName)).MustHaveHappened();
}
[Fact]
public async Task Create_should_create_app_if_name_is_free()
{
var context = CreateContextForCommand(new CreateApp { Name = AppName, AppId = AppId });
A.CallTo(() => appRepository.FindAppAsync(AppName))
.Returns((IAppEntity)null);
await TestCreate(app, async _ =>
{
await sut.HandleAsync(context);
});
Assert.Equal(AppId, context.Result<EntityCreatedResult<Guid>>().IdOrValue);
}
[Fact]
public async Task AssignContributor_should_throw_exception_if_user_not_found()
{
CreateApp();
var context = CreateContextForCommand(new AssignContributor { ContributorId = contributorId });
A.CallTo(() => userResolver.FindByIdAsync(contributorId))
.Returns((IUser)null);
await TestUpdate(app, async _ =>
{
await Assert.ThrowsAsync<ValidationException>(() => sut.HandleAsync(context));
}, false);
}
[Fact]
public async Task AssignContributor_throw_exception_if_reached_max_contributor_size()
{
A.CallTo(() => appPlansProvider.GetPlan(null))
.Returns(new ConfigAppLimitsPlan { MaxContributors = 2 });
CreateApp()
.AssignContributor(CreateCommand(new AssignContributor { ContributorId = "1" }))
.AssignContributor(CreateCommand(new AssignContributor { ContributorId = "2" }));
var context = CreateContextForCommand(new AssignContributor { ContributorId = contributorId });
A.CallTo(() => userResolver.FindByIdAsync(A<string>.Ignored))
.Returns(A.Dummy<IUser>());
await TestUpdate(app, async _ =>
{
await Assert.ThrowsAsync<ValidationException>(() => sut.HandleAsync(context));
}, false);
}
[Fact]
public async Task AssignContributor_should_throw_exception_if_null_user_not_found()
{
CreateApp();
var context = CreateContextForCommand(new AssignContributor { ContributorId = contributorId });
A.CallTo(() => userResolver.FindByIdAsync(contributorId))
.Returns((IUser)null);
await TestUpdate(app, async _ =>
{
await Assert.ThrowsAsync<ValidationException>(() => sut.HandleAsync(context));
}, false);
}
[Fact]
public async Task AssignContributor_should_assign_if_user_found()
{
A.CallTo(() => appPlansProvider.GetPlan(null))
.Returns(new ConfigAppLimitsPlan { MaxContributors = -1 });
CreateApp();
var context = CreateContextForCommand(new AssignContributor { ContributorId = contributorId });
A.CallTo(() => userResolver.FindByIdAsync(contributorId))
.Returns(A.Dummy<IUser>());
await TestUpdate(app, async _ =>
{
await sut.HandleAsync(context);
});
}
[Fact]
public async Task RemoveContributor_should_update_domain_object()
{
CreateApp()
.AssignContributor(CreateCommand(new AssignContributor { ContributorId = contributorId }));
var context = CreateContextForCommand(new RemoveContributor { ContributorId = contributorId });
await TestUpdate(app, async _ =>
{
await sut.HandleAsync(context);
});
}
[Fact]
public async Task AttachClient_should_update_domain_object()
{
CreateApp();
var context = CreateContextForCommand(new AttachClient { Id = clientName });
await TestUpdate(app, async _ =>
{
await sut.HandleAsync(context);
});
}
[Fact]
public async Task ChangePlan_should_throw_if_plan_not_found()
{
A.CallTo(() => appPlansProvider.IsConfiguredPlan("my-plan"))
.Returns(false);
CreateApp()
.AttachClient(CreateCommand(new AttachClient { Id = clientName }));
var context = CreateContextForCommand(new ChangePlan { PlanId = "my-plan" });
await TestUpdate(app, async _ =>
{
await Assert.ThrowsAsync<ValidationException>(() => sut.HandleAsync(context));
}, false);
}
[Fact]
public async Task RenameClient_should_update_domain_object()
{
CreateApp()
.AttachClient(CreateCommand(new AttachClient { Id = clientName }));
var context = CreateContextForCommand(new UpdateClient { Id = clientName, Name = "New Name" });
await TestUpdate(app, async _ =>
{
await sut.HandleAsync(context);
});
}
[Fact]
public async Task RevokeClient_should_update_domain_object()
{
CreateApp()
.AttachClient(CreateCommand(new AttachClient { Id = clientName }));
var context = CreateContextForCommand(new RevokeClient { Id = clientName });
await TestUpdate(app, async _ =>
{
await sut.HandleAsync(context);
});
}
[Fact]
public async Task ChangePlan_should_update_domain_object()
{
A.CallTo(() => appPlansProvider.IsConfiguredPlan("my-plan"))
.Returns(true);
CreateApp();
var context = CreateContextForCommand(new ChangePlan { PlanId = "my-plan" });
await TestUpdate(app, async _ =>
{
await sut.HandleAsync(context);
});
A.CallTo(() => appPlansBillingManager.ChangePlanAsync(User.Identifier, app.Id, app.Name, "my-plan")).MustHaveHappened();
}
[Fact]
public async Task ChangePlan_should_not_make_update_for_redirect_result()
{
A.CallTo(() => appPlansProvider.IsConfiguredPlan("my-plan"))
.Returns(true);
A.CallTo(() => appPlansBillingManager.ChangePlanAsync(User.Identifier, app.Id, app.Name, "my-plan"))
.Returns(CreateRedirectResult());
CreateApp();
var context = CreateContextForCommand(new ChangePlan { PlanId = "my-plan" });
await TestUpdate(app, async _ =>
{
await sut.HandleAsync(context);
});
Assert.Null(app.PlanId);
}
[Fact]
public async Task ChangePlan_should_not_call_billing_manager_for_callback()
{
A.CallTo(() => appPlansProvider.IsConfiguredPlan("my-plan"))
.Returns(true);
CreateApp();
var context = CreateContextForCommand(new ChangePlan { PlanId = "my-plan", FromCallback = true });
await TestUpdate(app, async _ =>
{
await sut.HandleAsync(context);
});
A.CallTo(() => appPlansBillingManager.ChangePlanAsync(User.Identifier, app.Id, app.Name, "my-plan")).MustNotHaveHappened();
}
[Fact]
public async Task AddLanguage_should_update_domain_object()
{
CreateApp();
var context = CreateContextForCommand(new AddLanguage { Language = language });
await TestUpdate(app, async _ =>
{
await sut.HandleAsync(context);
});
}
[Fact]
public async Task RemoveLanguage_should_update_domain_object()
{
CreateApp()
.AddLanguage(CreateCommand(new AddLanguage { Language = language }));
var context = CreateContextForCommand(new RemoveLanguage { Language = language });
await TestUpdate(app, async _ =>
{
await sut.HandleAsync(context);
});
}
[Fact]
public async Task UpdateLanguage_should_update_domain_object()
{
CreateApp()
.AddLanguage(CreateCommand(new AddLanguage { Language = language }));
var context = CreateContextForCommand(new UpdateLanguage { Language = language });
await TestUpdate(app, async _ =>
{
await sut.HandleAsync(context);
});
}
private AppDomainObject CreateApp()
{
app.Create(CreateCommand(new CreateApp { Name = AppName }));
return app;
}
private static Task<IChangePlanResult> CreateRedirectResult()
{
return Task.FromResult<IChangePlanResult>(new RedirectToCheckoutResult(new Uri("http://squidex.io")));
}
}
}
| 34.23565 | 135 | 0.579951 | [
"MIT"
] | andrewhoi/squidex | tests/Squidex.Domain.Apps.Write.Tests/Apps/AppCommandMiddlewareTests.cs | 11,334 | C# |
// ScannerErrors.cs
//
// Copyright 2010 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.Ajax.Utilities;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace JSUnitTest
{
[TestClass]
public class ScannerErrors
{
[TestMethod()]
public void BadHexDigit()
{
TestHelper.Instance.RunErrorTest(JSError.BadNumericLiteral);
}
[TestMethod()]
public void StringEOF()
{
TestHelper.Instance.RunErrorTest(JSError.UnterminatedString);
}
[TestMethod()]
public void StringEOL()
{
TestHelper.Instance.RunErrorTest(JSError.UnterminatedString, JSError.SemicolonInsertion);
}
[TestMethod()]
public void UnexpectedNull()
{
TestHelper.Instance.RunErrorTest(JSError.IllegalChar);
}
}
}
| 26.52 | 97 | 0.715686 | [
"MIT"
] | Microsoft/ajaxmin | JSUnitTest/ScannerErrors.cs | 1,328 | 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("Photosphere.NativeEmit.Tests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Photosphere.NativeEmit.Tests")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[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("3882d8c7-104d-4f53-b8de-00a2e1c02e62")]
// 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.621622 | 84 | 0.748076 | [
"MIT"
] | sunloving/photosphere-asmemit | src/Photosphere.NativeEmit.Tests/Properties/AssemblyInfo.cs | 1,432 | C# |
// Copyright 2017 Serilog Contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Globalization;
using Xunit;
using Serilog.Sinks.PeriodicBatching;
namespace Seq.Extensions.Logging.Tests.Serilog.Sinks
{
public class BatchedConnectionStatusTests
{
readonly TimeSpan DefaultPeriod = TimeSpan.FromSeconds(2);
[Fact]
public void WhenNoFailuresHaveOccurredTheRegularIntervalIsUsed()
{
var bcs = new BatchedConnectionStatus(DefaultPeriod);
Assert.Equal(DefaultPeriod, bcs.NextInterval);
}
[Fact]
public void WhenOneFailureHasOccurredTheRegularIntervalIsUsed()
{
var bcs = new BatchedConnectionStatus(DefaultPeriod);
bcs.MarkFailure();
Assert.Equal(DefaultPeriod, bcs.NextInterval);
}
[Fact]
public void WhenTwoFailuresHaveOccurredTheIntervalBacksOff()
{
var bcs = new BatchedConnectionStatus(DefaultPeriod);
bcs.MarkFailure();
bcs.MarkFailure();
Assert.Equal(TimeSpan.FromSeconds(10), bcs.NextInterval);
}
[Fact]
public void WhenABatchSucceedsTheStatusResets()
{
var bcs = new BatchedConnectionStatus(DefaultPeriod);
bcs.MarkFailure();
bcs.MarkFailure();
bcs.MarkSuccess();
Assert.Equal(DefaultPeriod, bcs.NextInterval);
}
[Fact]
public void WhenThreeFailuresHaveOccurredTheIntervalBacksOff()
{
var bcs = new BatchedConnectionStatus(DefaultPeriod);
bcs.MarkFailure();
bcs.MarkFailure();
bcs.MarkFailure();
Assert.Equal(TimeSpan.FromSeconds(20), bcs.NextInterval);
Assert.False(bcs.ShouldDropBatch);
}
[Fact]
public void When8FailuresHaveOccurredTheIntervalBacksOffAndBatchIsDropped()
{
var bcs = new BatchedConnectionStatus(DefaultPeriod);
for (var i = 0; i < 8; ++i)
{
Assert.False(bcs.ShouldDropBatch);
bcs.MarkFailure();
}
Assert.Equal(TimeSpan.FromMinutes(10), bcs.NextInterval);
Assert.True(bcs.ShouldDropBatch);
Assert.False(bcs.ShouldDropQueue);
}
[Fact]
public void When10FailuresHaveOccurredTheQueueIsDropped()
{
var bcs = new BatchedConnectionStatus(DefaultPeriod);
for (var i = 0; i < 10; ++i)
{
Assert.False(bcs.ShouldDropQueue);
bcs.MarkFailure();
}
Assert.True(bcs.ShouldDropQueue);
}
[Fact]
public void AtTheDefaultIntervalRetriesFor10MinutesBeforeDroppingBatch()
{
var bcs = new BatchedConnectionStatus(DefaultPeriod);
var cumulative = TimeSpan.Zero;
do
{
bcs.MarkFailure();
if (!bcs.ShouldDropBatch)
cumulative += bcs.NextInterval;
} while (!bcs.ShouldDropBatch);
Assert.False(bcs.ShouldDropQueue);
Assert.Equal(TimeSpan.Parse("00:10:32", CultureInfo.InvariantCulture), cumulative);
}
[Fact]
public void AtTheDefaultIntervalRetriesFor30MinutesBeforeDroppingQueue()
{
var bcs = new BatchedConnectionStatus(DefaultPeriod);
var cumulative = TimeSpan.Zero;
do
{
bcs.MarkFailure();
if (!bcs.ShouldDropQueue)
cumulative += bcs.NextInterval;
} while (!bcs.ShouldDropQueue);
Assert.Equal(TimeSpan.Parse("00:30:32", CultureInfo.InvariantCulture), cumulative);
}
}
}
| 33.145038 | 95 | 0.60456 | [
"Apache-2.0"
] | ArminShoeibi/seq-extensions-logging | test/Seq.Extensions.Logging.Tests/Serilog/Sinks/BatchedConnectionStatusTests.cs | 4,344 | C# |
//---------------------------------------------------------
// <auto-generated>
// This code was generated by a tool. Changes to this
// file may cause incorrect behavior and will be lost
// if the code is regenerated.
//
// Generated on 2020 October 09 05:04:32 UTC
// </auto-generated>
//---------------------------------------------------------
using System;
using System.CodeDom.Compiler;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
#nullable enable
namespace go
{
public static partial class syscall_package
{
[GeneratedCode("go2cs", "0.1.0.0")]
public partial struct Timespec
{
// Constructors
public Timespec(NilType _)
{
this.Sec = default;
this.Nsec = default;
}
public Timespec(long Sec = default, long Nsec = default)
{
this.Sec = Sec;
this.Nsec = Nsec;
}
// Enable comparisons between nil and Timespec struct
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator ==(Timespec value, NilType nil) => value.Equals(default(Timespec));
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator !=(Timespec value, NilType nil) => !(value == nil);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator ==(NilType nil, Timespec value) => value == nil;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator !=(NilType nil, Timespec value) => value != nil;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static implicit operator Timespec(NilType nil) => default(Timespec);
}
[GeneratedCode("go2cs", "0.1.0.0")]
public static Timespec Timespec_cast(dynamic value)
{
return new Timespec(value.Sec, value.Nsec);
}
}
} | 33.274194 | 107 | 0.575376 | [
"MIT"
] | GridProtectionAlliance/go2cs | src/go-src-converted/syscall/ztypes_linux_s390x_TimespecStruct.cs | 2,063 | C# |
using System.Globalization;
using IBuyStuff.Application.Commands;
using IBuyStuff.Application.ViewModels.Orders;
using IBuyStuff.Domain.Repositories;
using IBuyStuff.Domain.Services;
using IBuyStuff.Domain.Services.Impl;
using IBuyStuff.Persistence.Repositories;
namespace IBuyStuff.Application.Handlers
{
public class ProcessOrderAfterPaymentHandler
: ICommandHandler<ProcessOrderAfterPaymentCommand, OrderProcessedViewModel>
{
private readonly IOrderRepository _orderRepository;
private readonly ICatalogService _catalogService;
private readonly IOrderRequestService _requestService;
private readonly IShipmentService _shipmentService;
public ProcessOrderAfterPaymentHandler()
: this(new OrderRepository(), new CatalogService(), new OrderRequestService(), new ShipmentService())
{
}
public ProcessOrderAfterPaymentHandler(IOrderRepository orderRepository, ICatalogService catalogService, IOrderRequestService requestService, IShipmentService shipmentService)
{
_orderRepository = orderRepository;
_catalogService = catalogService;
_requestService = requestService;
_shipmentService = shipmentService;
}
public OrderProcessedViewModel Handle(ProcessOrderAfterPaymentCommand command)
{
// 1. Create order ID
var tempOrderId = _requestService.GenerateTemporaryOrderId();
// 2. Register order in the system
var order = Domain.Orders.Order.CreateFromShoppingCart(tempOrderId, command.ShoppingCart.OrderRequest);
var orderId = _orderRepository.AddAndReturnKey(order);
// 3. Ship
var shipmentDetails = _shipmentService.SendRequestForDelivery(order);
// 4. Update fidelity card and membership status
// Prepare model
var model = new OrderProcessedViewModel
{
OrderId = orderId.ToString(CultureInfo.InvariantCulture),
PaymentDetails = { TransactionId = command.TransactionId },
ShippingDetails = shipmentDetails
};
return model;
}
}
} | 39.087719 | 183 | 0.695242 | [
"MIT"
] | nodashin/DDD-OnionArchitecture-Traning | Samples/IBuyStuff/IBuyStuff-cqrs/src/Site/IBuyStuff.Application/Handlers/ProcessOrderAfterPaymentHandler.cs | 2,230 | C# |
using Xunit;
namespace Demo.Tests
{
public class CalculadoraTests
{
[Fact]
public void Calculadora_Somar_RetornarValorSoma()
{
// Arrange
var calculadora = new Calculadora();
// Act
var resultado = calculadora.Somar(2, 2);
// Assert
Assert.Equal(4, resultado);
}
[Theory]
[InlineData(1, 1, 2)]
[InlineData(2, 2, 4)]
[InlineData(4, 2, 6)]
[InlineData(6, 6, 12)]
[InlineData(8, 8, 16)]
public void Calculadora_Somar_RetornarValoresSomaCorretos(double v1, double v2, double total)
{
// Arrange
var calculadora = new Calculadora();
// Act
var resultado = calculadora.Somar(v1, v2);
// Assert
Assert.Equal(total, resultado);
}
}
} | 23.473684 | 101 | 0.51009 | [
"Apache-2.0"
] | ferjesusjs8/TestsDevIo | TesteDeSoftwareDevIo/Demo.Tests/01 - CalculadoraTests.cs | 894 | C# |
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
public partial class AdminPos_ProductStatusDisplay : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
showPos_ProductStatusGrid();
}
}
protected void btnAdd_Click(object sender, EventArgs e)
{
Response.Redirect("AdminPos_ProductStatusInsertUpdate.aspx?pos_ProductStatusID=0");
}
protected void lbSelect_Click(object sender, EventArgs e)
{
LinkButton linkButton = new LinkButton();
linkButton = (LinkButton)sender;
int id;
id = Convert.ToInt32(linkButton.CommandArgument);
Response.Redirect("AdminPos_ProductStatusInsertUpdate.aspx?pos_ProductStatusID=" + id);
}
protected void lbDelete_Click(object sender, EventArgs e)
{
LinkButton linkButton = new LinkButton();
linkButton = (LinkButton)sender;
bool result = Pos_ProductStatusManager.DeletePos_ProductStatus(Convert.ToInt32(linkButton.CommandArgument));
showPos_ProductStatusGrid();
}
private void showPos_ProductStatusGrid()
{
gvPos_ProductStatus.DataSource = Pos_ProductStatusManager.GetAllPos_ProductStatuss();
gvPos_ProductStatus.DataBind();
}
}
| 31.55102 | 116 | 0.717335 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | anam/abs | V1/POS/AdminPos_ProductStatusDisplay.aspx.cs | 1,546 | C# |
// <auto-generated />
using EventAPI.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
namespace EventAPI.Migrations
{
[DbContext(typeof(EventContext))]
[Migration("20190927211645_Finall")]
partial class Finall
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "2.1.11-servicing-32099")
.HasAnnotation("Relational:MaxIdentifierLength", 128)
.HasAnnotation("Relational:Sequence:.category_hilo", "'category_hilo', '', '1', '10', '', '', 'Int64', 'False'")
.HasAnnotation("Relational:Sequence:.events_hilo", "'events_hilo', '', '1', '10', '', '', 'Int64', 'False'")
.HasAnnotation("Relational:Sequence:.eventtype_hilo", "'eventtype_hilo', '', '1', '10', '', '', 'Int64', 'False'")
.HasAnnotation("Relational:Sequence:.price_hilo", "'price_hilo', '', '1', '10', '', '', 'Int64', 'False'")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("EventAPI.Domain.Event", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasAnnotation("SqlServer:HiLoSequenceName", "events_hilo")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.SequenceHiLo);
b.Property<int>("DateTime")
.HasMaxLength(100);
b.Property<string>("Description")
.IsRequired()
.HasMaxLength(100);
b.Property<int>("EventCategoryID");
b.Property<int>("EventTypeID");
b.Property<string>("Location")
.IsRequired()
.HasMaxLength(100);
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(100);
b.HasKey("Id");
b.HasIndex("EventCategoryID");
b.HasIndex("EventTypeID");
b.ToTable("event");
});
modelBuilder.Entity("EventAPI.Domain.EventCategory", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasAnnotation("SqlServer:HiLoSequenceName", "category_hilo")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.SequenceHiLo);
b.Property<string>("CategoryName")
.IsRequired()
.HasMaxLength(1000);
b.HasKey("Id");
b.ToTable("Category");
});
modelBuilder.Entity("EventAPI.Domain.EventPrice", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasAnnotation("SqlServer:HiLoSequenceName", "price_hilo")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.SequenceHiLo);
b.Property<decimal>("Price");
b.HasKey("Id");
b.ToTable("Price");
});
modelBuilder.Entity("EventAPI.Domain.EventType", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasAnnotation("SqlServer:HiLoSequenceName", "eventtype_hilo")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.SequenceHiLo);
b.Property<string>("Typename")
.IsRequired()
.HasMaxLength(1000);
b.HasKey("Id");
b.ToTable("Type");
});
modelBuilder.Entity("EventAPI.Domain.Event", b =>
{
b.HasOne("EventAPI.Domain.EventCategory", "EventCategory")
.WithMany()
.HasForeignKey("EventCategoryID")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("EventAPI.Domain.EventType", "EventType")
.WithMany()
.HasForeignKey("EventTypeID")
.OnDelete(DeleteBehavior.Cascade);
});
#pragma warning restore 612, 618
}
}
}
| 39.572581 | 130 | 0.513756 | [
"MIT"
] | Janani-Sankar/janani-assignments | Assignment3a/WebApplication1/Migrations/20190927211645_Finall.Designer.cs | 4,909 | C# |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ReflectionHelper.cs" company="Kephas Software SRL">
// Copyright (c) Kephas Software SRL. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// </copyright>
// <summary>
// Helper class for reflection.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace Kephas.Reflection
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
/// <summary>
/// Helper class for reflection.
/// </summary>
public static class ReflectionHelper
{
private static readonly Func<AssemblyName, bool> IsSystemAssemblyFuncValue = assemblyName =>
{
var assemblyFullName = assemblyName.FullName;
return assemblyFullName.StartsWith("System")
|| assemblyFullName.StartsWith("mscorlib")
|| assemblyFullName.StartsWith("Microsoft")
|| assemblyFullName.StartsWith("netstandard")
|| assemblyFullName.StartsWith("vshost32")
|| assemblyFullName.StartsWith("Mono");
};
/// <summary>
/// Gets or sets the function to check whether an assembly is a system assembly.
/// </summary>
/// <value>
/// A function delegate that yields a bool.
/// </value>
public static Func<AssemblyName, bool> IsSystemAssemblyFunc { get; set; } = IsSystemAssemblyFuncValue;
/// <summary>
/// Indicates whether the identifier is private.
/// </summary>
/// <param name="identifier">The identifier to act on.</param>
/// <returns>
/// True if the identifier is private, false if not.
/// </returns>
public static bool IsPrivate(this string identifier)
{
return identifier.StartsWith("_") || identifier.StartsWith("#");
}
/// <summary>
/// Retrieves the property name from a lambda expression.
/// </summary>
/// <typeparam name="T">The type from which the property name is extracted.</typeparam>
/// <param name="expression">The property expression.</param>
/// <returns>The property name.</returns>
public static string GetPropertyName<T>(Expression<Func<T, object>> expression)
{
return GetPropertyName<T, object>(expression);
}
/// <summary>
/// Retrieves the property name from a lambda expression.
/// </summary>
/// <typeparam name="T">The type from which the property name is extracted.</typeparam>
/// <typeparam name="TValue">The type of the value.</typeparam>
/// <param name="expression">The property expression.</param>
/// <returns>
/// The property name.
/// </returns>
/// <exception cref="System.ArgumentException">Expected property expression.</exception>
public static string GetPropertyName<T, TValue>(Expression<Func<T, TValue>> expression)
{
MemberExpression? memberExpression;
// if the return value had to be cast to object, the body will be an UnaryExpression
if (expression.Body is UnaryExpression unary)
{
// the operand is the "real" property access
memberExpression = unary.Operand as MemberExpression;
}
else
{
// in case the property is of type object the body itself is the correct expression
memberExpression = expression.Body as MemberExpression;
}
// as before:
if (memberExpression?.Member is not PropertyInfo)
{
throw new ArgumentException("Expected property expression.");
}
return memberExpression.Member.Name;
}
/// <summary>
/// Retrieves the property name from a lambda expression.
/// </summary>
/// <param name="expression">The property expression.</param>
/// <returns>The property name.</returns>
public static string GetStaticPropertyName(Expression<Func<object>> expression)
{
MemberExpression? memberExpression;
// if the return value had to be cast to object, the body will be an UnaryExpression
if (expression.Body is UnaryExpression unary)
{
// the operand is the "real" property access
memberExpression = unary.Operand as MemberExpression;
}
else
{
// in case the property is of type object the body itself is the correct expression
memberExpression = expression.Body as MemberExpression;
}
// as before:
if (memberExpression == null || !(memberExpression.Member is PropertyInfo))
{
throw new ArgumentException("Expected property expression");
}
return memberExpression.Member.Name;
}
/// <summary>
/// Gets the method indicated by the given expression.
/// The given expression must be a lambda expression.
/// </summary>
/// <param name="expression">The expression.</param>
/// <returns>A <see cref="MethodInfo"/>.</returns>
public static MethodInfo GetMethodOf(Expression expression)
{
return ((MethodCallExpression)((LambdaExpression)expression).Body).Method;
}
/// <summary>
/// Gets the generic method indicated by the given expression.
/// The given expression must be a lambda expression.
/// </summary>
/// <param name="expression">The expression.</param>
/// <returns>A <see cref="MethodInfo"/>.</returns>
public static MethodInfo GetGenericMethodOf(Expression expression)
{
return ((MethodCallExpression)((LambdaExpression)expression).Body).Method.GetGenericMethodDefinition();
}
/// <summary>
/// Gets the method indicated by the given expression.
/// The given expression must be a lambda expression.
/// </summary>
/// <typeparam name="TReturn">The type of the return.</typeparam>
/// <param name="expression">The expression.</param>
/// <returns>A <see cref="MethodInfo"/>.</returns>
public static MethodInfo GetMethodOf<TReturn>(Expression<Func<object, TReturn>> expression)
{
return GetMethodOf((Expression)expression);
}
/// <summary>
/// Gets the generic method indicated by the given expression.
/// The given expression must be a lambda expression.
/// </summary>
/// <typeparam name="TReturn">The type of the return.</typeparam>
/// <param name="expression">The expression.</param>
/// <returns>A <see cref="MethodInfo"/>.</returns>
public static MethodInfo GetGenericMethodOf<TReturn>(Expression<Func<object, TReturn>> expression)
{
return GetGenericMethodOf((Expression)expression);
}
/// <summary>
/// Gets the assembly qualified name without the version and public key information.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>
/// The assembly qualified name without the version and public key information.
/// </returns>
public static string GetAssemblyQualifiedShortName(this Type type)
{
type = type ?? throw new ArgumentNullException(nameof(type));
return string.Concat(type.FullName, ", ", IntrospectionExtensions.GetTypeInfo(type).Assembly.GetName().Name);
}
/// <summary>
/// Gets the full name of the non generic type with the same base name as the provided type.
/// </summary>
/// <param name="typeInfo">The type information.</param>
/// <returns>The full name of the non generic type.</returns>
public static string GetNonGenericFullName(this TypeInfo typeInfo)
{
typeInfo = typeInfo ?? throw new ArgumentNullException(nameof(typeInfo));
var fullName = typeInfo.FullName!;
if (!typeInfo.IsGenericType)
{
return fullName;
}
fullName = fullName.Substring(0, fullName.IndexOf('`'));
return fullName;
}
/// <summary>
/// Gets the full name of the non generic type with the same base name as the provided type.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>
/// The full name of the non generic type.
/// </returns>
public static string GetNonGenericFullName(this Type type)
{
type = type ?? throw new ArgumentNullException(nameof(type));
return GetNonGenericFullName(IntrospectionExtensions.GetTypeInfo(type));
}
/// <summary>
/// Creates the static delegate for the provided static method.
/// </summary>
/// <typeparam name="T">The delegate type.</typeparam>
/// <param name="methodInfo">The method information.</param>
/// <returns>A static delegate for the provided static method.</returns>
public static T CreateStaticDelegate<T>(this MethodInfo methodInfo)
{
methodInfo = methodInfo ?? throw new ArgumentNullException(nameof(methodInfo));
return (T)(object)methodInfo.CreateDelegate(typeof(T));
}
/// <summary>
/// Gets a value indicating whether the provided assembly is a system assembly.
/// </summary>
/// <param name="assembly">The assembly to be checked.</param>
/// <returns>
/// <c>true</c> if the assembly is a system assembly, <c>false</c> if not.
/// </returns>
public static bool IsSystemAssembly(this Assembly assembly)
{
return IsSystemAssemblyFunc?.Invoke(assembly.GetName()) ?? false;
}
/// <summary>
/// Gets a value indicating whether the provided assembly is a system assembly.
/// </summary>
/// <param name="assemblyName">The assembly to be checked.</param>
/// <returns>
/// <c>true</c> if the assembly is a system assembly, <c>false</c> if not.
/// </returns>
public static bool IsSystemAssembly(this AssemblyName assemblyName)
{
return IsSystemAssemblyFunc?.Invoke(assemblyName) ?? false;
}
/// <summary>
/// Gets the location directory for the provided assembly.
/// </summary>
/// <param name="assembly">The assembly to be checked.</param>
/// <returns>
/// The assembly location directory.
/// </returns>
public static string GetLocationDirectory(this Assembly assembly)
{
assembly = assembly ?? throw new ArgumentNullException(nameof(assembly));
var location = Path.GetDirectoryName(assembly.Location)!;
return location;
}
/// <summary>
/// Invokes the <paramref name="methodInfo"/> with the provided parameters,
/// ensuring in case of an exception that the original exception is thrown.
/// </summary>
/// <param name="methodInfo">The method information.</param>
/// <param name="instance">The instance.</param>
/// <param name="arguments">A variable-length parameters list containing arguments.</param>
/// <returns>
/// The invocation result.
/// </returns>
public static object? Call(this MethodInfo methodInfo, object? instance, params object?[]? arguments)
{
try
{
var result = methodInfo.Invoke(instance, arguments);
return result;
}
catch (TargetInvocationException tie)
{
throw tie.InnerException!;
}
}
/// <summary>
/// Gets the type's proper properties: public, non-static, and without parameters.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An enumeration of property infos.</returns>
public static IEnumerable<PropertyInfo> GetTypeProperties(Type type)
{
return type.GetRuntimeProperties()
.Where(p => p.GetMethod != null && !p.GetMethod.IsStatic && p.GetMethod.IsPublic
&& p.GetIndexParameters().Length == 0);
}
}
} | 41.471154 | 121 | 0.580261 | [
"MIT"
] | kephas-software/kephas | src/Kephas.Core.Abstractions/Reflection/ReflectionHelper.cs | 12,941 | C# |
namespace MySpheroLibrary
{
using RobotKit;
using System;
using System.Threading.Tasks;
using Windows.Foundation;
public sealed class SpheroControl
{
Sphero sphero;
int r;
int g;
int b;
int rotation;
float backlightBrightness;
private SpheroControl(Sphero sphero)
{
this.sphero = sphero;
this.r = this.g = this.b = 0;
this.backlightBrightness = 0.0f;
this.rotation = 0;
}
public int Red
{
get
{
return (this.r);
}
set
{
this.r = value;
this.SetColour();
}
}
public int Green
{
get
{
return (this.g);
}
set
{
this.g = value;
this.SetColour();
}
}
public int Blue
{
get
{
return (this.b);
}
set
{
this.b = value;
this.SetColour();
}
}
public float BacklightBrightness
{
get
{
return (this.backlightBrightness);
}
set
{
this.backlightBrightness = value;
this.sphero.SetBackLED(this.backlightBrightness);
}
}
void SetColour()
{
this.sphero.SetRGBLED(this.r, this.g, this.b);
}
public int Rotation
{
get
{
return (this.rotation);
}
set
{
this.rotation = value;
this.sphero.Roll(this.rotation, 0);
}
}
public void Roll(float speed)
{
this.sphero.Roll(this.rotation, speed);
}
public void Roll2(float speed, int rotation)
{
this.sphero.Roll(rotation, speed);
}
public static IAsyncOperation<SpheroControl> GetFirstConnectedSpheroAsync()
{
Task<SpheroControl> task = InternalGetFirstConnectedSpheroAsync();
return (task.AsAsyncOperation());
}
static Task<SpheroControl> InternalGetFirstConnectedSpheroAsync()
{
TaskCompletionSource<SpheroControl> task = new TaskCompletionSource<SpheroControl>();
var provider = RobotProvider.GetSharedProvider();
EventHandler<Robot> handler = null;
handler = (s, robot) =>
{
provider.DiscoveredRobotEvent -= handler;
handler = (sender, cxnRobot) =>
{
provider.ConnectedRobotEvent -= handler;
task.SetResult(new SpheroControl((Sphero)cxnRobot));
};
provider.ConnectedRobotEvent += handler;
provider.ConnectRobot(robot);
};
provider.DiscoveredRobotEvent += handler;
provider.FindRobots();
return (task.Task);
}
}
} | 21.265625 | 92 | 0.534901 | [
"Apache-2.0"
] | pasupulaphani/Sphero-Slalom | MySpheroLibrary/SpheroControl.cs | 2,724 | C# |
// Copyright (c) Dolittle. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Linq;
using Dolittle.Runtime.Events.Processing.EventHandlers;
using Machine.Specifications;
namespace Integration.Tests.Events.Processing.EventHandlers.with_a_single.unscoped.partitioned.event_handler.without_implicit_filter.processing_one_event_type.needing_catchup;
class without_problems : given.single_tenant_and_event_handlers
{
static IEventHandler event_handler;
Establish context = () =>
{
commit_events_for_each_event_type((4, "some_source"));
event_handler = setup_event_handler();
};
Because of = () =>
{
commit_events_after_starting_event_handler((2, "some_source"));
};
It should_the_correct_number_of_events_in_stream = () => expect_number_of_filtered_events(event_handler, committed_events_for_event_types(1).LongCount());
It should_have_persisted_correct_stream = () => expect_stream_definition(event_handler);
It should_have_the_correct_stream_processor_states = () => expect_stream_processor_state_without_failure(event_handler);
} | 39.6 | 175 | 0.782828 | [
"MIT"
] | dolittle-runtime/Runtime | Integration/Tests/Events.Processing/EventHandlers/with_a_single/unscoped/partitioned/event_handler/without_implicit_filter/processing_one_event_type/needing_catchup/withoutout_problems.cs | 1,188 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using InformedProteomics.Graphics;
using NUnit.Framework;
namespace InformedProteomics.Test
{
[TestFixture]
class TestLcMsFeatureMap
{
[Test]
[STAThread]
public void TestFeatureMapGeneration()
{
Console.WriteLine("Testing Working");
var methodName = MethodBase.GetCurrentMethod().Name;
TestUtils.ShowStarting(methodName);
const string testFile = @"\\protoapps\UserData\Jungkap\Joshua\FeatureMap\QC_Shew_Intact_26Sep14_Bane_C2Column3.ms1ft";
const string outputFile = @"\\protoapps\UserData\Jungkap\Joshua\";
var map = new LcMsFeatureMap(testFile,185);
map.SaveImage(outputFile + "test.png",100);
}
}
}
| 29.580645 | 131 | 0.654308 | [
"Apache-2.0"
] | PNNL-Comp-Mass-Spec/Informed-Proteomics | InformedProteomics.Test/TestLcMsFeatureMap.cs | 919 | C# |
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Gov.Jag.PillPressRegistry.Interfaces
{
using Microsoft.Rest;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Customaddressincidentaddressofbusinessthathasgivenorloaned operations.
/// </summary>
public partial interface ICustomaddressincidentaddressofbusinessthathasgivenorloaned
{
/// <summary>
/// Get
/// bcgov_customaddress_incident_AddressofBusinessthathasGivenorLoaned
/// from bcgov_customaddresses
/// </summary>
/// <param name='bcgovCustomaddressid'>
/// key: bcgov_customaddressid of bcgov_customaddress
/// </param>
/// <param name='top'>
/// </param>
/// <param name='skip'>
/// </param>
/// <param name='search'>
/// </param>
/// <param name='filter'>
/// </param>
/// <param name='count'>
/// </param>
/// <param name='orderby'>
/// Order items by property values
/// </param>
/// <param name='select'>
/// Select properties to be returned
/// </param>
/// <param name='expand'>
/// Expand related entities
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<HttpOperationResponse<MicrosoftDynamicsCRMincidentCollection>> GetWithHttpMessagesAsync(string bcgovCustomaddressid, int? top = default(int?), int? skip = default(int?), string search = default(string), string filter = default(string), bool? count = default(bool?), IList<string> orderby = default(IList<string>), IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get
/// bcgov_customaddress_incident_AddressofBusinessthathasGivenorLoaned
/// from bcgov_customaddresses
/// </summary>
/// <param name='bcgovCustomaddressid'>
/// key: bcgov_customaddressid of bcgov_customaddress
/// </param>
/// <param name='incidentid'>
/// key: incidentid of incident
/// </param>
/// <param name='select'>
/// Select properties to be returned
/// </param>
/// <param name='expand'>
/// Expand related entities
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<HttpOperationResponse<MicrosoftDynamicsCRMincident>> AddressofBusinessthathasGivenorLoanedByKeyWithHttpMessagesAsync(string bcgovCustomaddressid, string incidentid, IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| 44.434343 | 542 | 0.629007 | [
"Apache-2.0"
] | GeorgeWalker/jag-pill-press-registry | pill-press-interfaces/Dynamics-Autorest/ICustomaddressincidentaddressofbusinessthathasgivenorloaned.cs | 4,399 | C# |
using BobsBuddy;
using BobsBuddy.Simulation;
using BobsGraphPlugin;
using System;
using System.Windows;
namespace GraphTest
{
/// <summary>
/// Interaktionslogik für MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private Random _rand;
private BobsGraphUI _graphUI;
public MainWindow()
{
InitializeComponent();
_rand = new Random();
_graphUI = new BobsGraphUI();
TestCanvas.Children.Add(_graphUI);
}
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Generate(object sender, RoutedEventArgs e)
{
var min = _rand.Next(-20, 5);
var max = Math.Max(min, _rand.Next(-5, 20));
var fakeResult = new TestOutput
{
friendlyHealth = _rand.Next(1, 15),
opponentHealth = _rand.Next(1, 15),
myDeathRate = (float)_rand.NextDouble() * 0.5f,
theirDeathRate = (float)_rand.NextDouble() * 0.5f
};
for (int i = 0; i < 100; i++)
{
fakeResult.result.Add(new FightTrace()
{
damage = _rand.Next(min, max)
});
}
_graphUI.Update(fakeResult);
}
}
}
| 25.553571 | 65 | 0.497554 | [
"MIT"
] | Wasserwecken/BobsGraph | GraphTest/MainWindow.xaml.cs | 1,434 | C# |
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
// Ported from um/winnt.h in the Windows SDK for Windows 10.0.22000.0
// Original source is Copyright © Microsoft. All rights reserved.
using System;
namespace TerraFX.Interop.Windows;
/// <include file='ANON_OBJECT_HEADER_V2.xml' path='doc/member[@name="ANON_OBJECT_HEADER_V2"]/*' />
public partial struct ANON_OBJECT_HEADER_V2
{
/// <include file='ANON_OBJECT_HEADER_V2.xml' path='doc/member[@name="ANON_OBJECT_HEADER_V2.Sig1"]/*' />
[NativeTypeName("WORD")]
public ushort Sig1;
/// <include file='ANON_OBJECT_HEADER_V2.xml' path='doc/member[@name="ANON_OBJECT_HEADER_V2.Sig2"]/*' />
[NativeTypeName("WORD")]
public ushort Sig2;
/// <include file='ANON_OBJECT_HEADER_V2.xml' path='doc/member[@name="ANON_OBJECT_HEADER_V2.Version"]/*' />
[NativeTypeName("WORD")]
public ushort Version;
/// <include file='ANON_OBJECT_HEADER_V2.xml' path='doc/member[@name="ANON_OBJECT_HEADER_V2.Machine"]/*' />
[NativeTypeName("WORD")]
public ushort Machine;
/// <include file='ANON_OBJECT_HEADER_V2.xml' path='doc/member[@name="ANON_OBJECT_HEADER_V2.TimeDateStamp"]/*' />
[NativeTypeName("DWORD")]
public uint TimeDateStamp;
/// <include file='ANON_OBJECT_HEADER_V2.xml' path='doc/member[@name="ANON_OBJECT_HEADER_V2.ClassID"]/*' />
[NativeTypeName("CLSID")]
public Guid ClassID;
/// <include file='ANON_OBJECT_HEADER_V2.xml' path='doc/member[@name="ANON_OBJECT_HEADER_V2.SizeOfData"]/*' />
[NativeTypeName("DWORD")]
public uint SizeOfData;
/// <include file='ANON_OBJECT_HEADER_V2.xml' path='doc/member[@name="ANON_OBJECT_HEADER_V2.Flags"]/*' />
[NativeTypeName("DWORD")]
public uint Flags;
/// <include file='ANON_OBJECT_HEADER_V2.xml' path='doc/member[@name="ANON_OBJECT_HEADER_V2.MetaDataSize"]/*' />
[NativeTypeName("DWORD")]
public uint MetaDataSize;
/// <include file='ANON_OBJECT_HEADER_V2.xml' path='doc/member[@name="ANON_OBJECT_HEADER_V2.MetaDataOffset"]/*' />
[NativeTypeName("DWORD")]
public uint MetaDataOffset;
}
| 41.358491 | 145 | 0.712591 | [
"MIT"
] | reflectronic/terrafx.interop.windows | sources/Interop/Windows/Windows/um/winnt/ANON_OBJECT_HEADER_V2.cs | 2,194 | C# |
public interface IEquipment
{
int Attack { get; set; }
int AttackChance { get; set; }
int Awareness { get; set; }
int Defense { get; set; }
int DefenseChance { get; set; }
int Gold { get; set; }
int Health { get; set; }
int MaxHealth { get; set; }
string Name { get; set; }
int Speed { get; set; }
}
| 22.733333 | 35 | 0.565982 | [
"MIT"
] | KuaileY/RogueCsharpUnityTraining | Assets/Scripts/Interfaces/IEquipment.cs | 341 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.Linq;
public class FootballLeague
{
public static void Main()
{
string key = Console.ReadLine();
string input = Console.ReadLine();
Dictionary<string, long> teamsAndPoints = new Dictionary<string, long>();
Dictionary<string, long> teamsAndGoals = new Dictionary<string, long>();
while (!input.Equals("final"))
{
int firstIndex = input.IndexOf(key, 0);
int nextIndex = input.IndexOf(key, firstIndex + 1);
string firstTeamName = input.Substring(firstIndex + key.Length, nextIndex - (firstIndex + key.Length)).ToUpper();
firstIndex = input.IndexOf(key, nextIndex + key.Length);
nextIndex = input.IndexOf(key, firstIndex + 1);
string secondTeamName = input.Substring(firstIndex + key.Length, nextIndex - (firstIndex + key.Length)).ToUpper();
firstTeamName = GetTeamName(firstTeamName);
secondTeamName = GetTeamName(secondTeamName);
string pattern = @"(\d+):(\d+)";
Regex regex = new Regex(pattern);
Match match = regex.Match(input);
long firstTeamGoals = long.Parse(match.Groups[1].Value);
long secondTeamGoals = long.Parse(match.Groups[2].Value);
long firstTeamPoints = 0;
long secondTeamPoints = 0;
if (firstTeamGoals > secondTeamGoals)
{
firstTeamPoints += 3;
}
else if (firstTeamGoals < secondTeamGoals)
{
secondTeamPoints += 3;
}
else
{
firstTeamPoints += 1;
secondTeamPoints += 1;
}
if (!teamsAndPoints.ContainsKey(firstTeamName) && !teamsAndGoals.ContainsKey(firstTeamName))
{
teamsAndPoints.Add(firstTeamName, 0L);
teamsAndGoals.Add(firstTeamName, 0L);
}
teamsAndPoints[firstTeamName] += firstTeamPoints;
teamsAndGoals[firstTeamName] += firstTeamGoals;
if (!teamsAndPoints.ContainsKey(secondTeamName) && !teamsAndGoals.ContainsKey(secondTeamName))
{
teamsAndPoints.Add(secondTeamName, 0L);
teamsAndGoals.Add(secondTeamName, 0L);
}
teamsAndPoints[secondTeamName] += secondTeamPoints;
teamsAndGoals[secondTeamName] += secondTeamGoals;
input = Console.ReadLine();
}
Console.WriteLine($"League standings:");
int place = 1;
foreach (var team in teamsAndPoints.OrderByDescending(p => p.Value).ThenBy(n => n.Key))
{
Console.WriteLine($"{place}. {team.Key} {team.Value}");
place++;
}
Console.WriteLine($"Top 3 scored goals:");
place = 1;
foreach (var team in teamsAndGoals.OrderByDescending(g => g.Value).ThenBy(n => n.Key).Take(3))
{
Console.WriteLine($"- {team.Key} -> {team.Value}");
}
}
public static string GetTeamName(string currentTeamName)
{
StringBuilder sb = new StringBuilder();
for (int i = currentTeamName.Length - 1; i >= 0; i--)
{
sb.Append(currentTeamName[i]);
}
return currentTeamName = sb.ToString();
}
} | 34.838384 | 126 | 0.575239 | [
"MIT"
] | yani-valeva/Programming-Fundamentals | ExamPreparation/Football-League/FootballLeague.cs | 3,451 | C# |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="CurrentRoomPlayerTtlProperty.cs" company="Exit Games GmbH">
// Part of: Pun Cockpit
// </copyright>
// <author>developer@exitgames.com</author>
// --------------------------------------------------------------------------------------------------------------------
using UnityEngine.UI;
namespace Photon.Pun.Demo.Cockpit
{
/// <summary>
/// PhotonNetwork.CurrentRoom.PlayerTtl UI property.
/// </summary>
public class CurrentRoomPlayerTtlProperty : PropertyListenerBase
{
public Text Text;
int _cache = -1;
void Update()
{
if (PhotonNetwork.CurrentRoom != null)
{
if (PhotonNetwork.CurrentRoom.PlayerTtl != _cache)
{
_cache = PhotonNetwork.CurrentRoom.PlayerTtl;
Text.text = _cache.ToString();
this.OnValueChanged();
}
}
else
{
if (_cache != -1)
{
_cache = -1;
Text.text = "n/a";
}
}
}
}
} | 29.488372 | 120 | 0.392744 | [
"Unlicense"
] | 23SAMY23/Meet-and-Greet-MR | Meet & Greet MR (AR)/Assets/Photon/PhotonUnityNetworking/Demos/PunCockpit/Scripts/ReadOnlyProperties/CurrentRoomPlayerTtlProperty.cs | 1,270 | C# |
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using FingertipsUploadService.ProfileData.Repositories;
namespace FingertipsUploadService.ProfileDataTest.Respositories
{
[TestClass]
public class WhenUsingLoggingRepository
{
private LoggingRepository _loggingRepository;
[TestInitialize]
public void Init()
{
_loggingRepository = new LoggingRepository();
}
[TestMethod]
public void UpdateFusCheckedJobs_Can_Be_Called()
{
_loggingRepository.UpdateFusCheckedJobs();
}
}
}
| 24.12 | 63 | 0.686567 | [
"MIT"
] | PublicHealthEngland/fingertips-open | FingertipsUploadService/ProfileTest/Respositories/WhenUsingLoggingRepository.cs | 605 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SqlServerDataAdapter.Infrastruction
{
public class TopNumber
{
public int NO { get; set; }
}
}
| 17.357143 | 45 | 0.720165 | [
"Apache-2.0"
] | nxjcproject/DataAdapter | DataAdapter/SqlServerDataAdapter/Infrastruction/TopNumber.cs | 245 | C# |
// (c) Copyright Microsoft Corporation.
// This source is subject to the Microsoft Public License (Ms-PL).
// Please see http://go.microsoft.com/fwlink/?LinkID=131993 for details.
// All other rights reserved.
using System;
using System.ComponentModel;
using System.Globalization;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Media;
using Microsoft.Phone.Controls.Primitives;
namespace Microsoft.Phone.Controls
{
/// <summary>
/// Represents a switch that can be toggled between two states.
/// </summary>
/// <QualityBand>Preview</QualityBand>
[TemplateVisualState(Name = NormalState, GroupName = CommonStates)]
[TemplateVisualState(Name = DisabledState, GroupName = CommonStates)]
[TemplatePart(Name = SwitchPart, Type = typeof(ToggleSwitchButton))]
public class ToggleSwitch : ContentControl
{
/// <summary>
/// Common visual states.
/// </summary>
private const string CommonStates = "CommonStates";
/// <summary>
/// Normal visual state.
/// </summary>
private const string NormalState = "Normal";
/// <summary>
/// Disabled visual state.
/// </summary>
private const string DisabledState = "Disabled";
/// <summary>
/// The ToggleButton that drives this.
/// </summary>
private const string SwitchPart = "Switch";
/// <summary>
/// Identifies the Header DependencyProperty.
/// </summary>
public static readonly DependencyProperty HeaderProperty =
DependencyProperty.Register("Header", typeof(object), typeof(ToggleSwitch), new PropertyMetadata(null));
/// <summary>
/// Gets or sets the header.
/// </summary>
public object Header
{
get { return GetValue(HeaderProperty); }
set { SetValue(HeaderProperty, value); }
}
/// <summary>
/// Identifies the HeaderTemplate DependencyProperty.
/// </summary>
public static readonly DependencyProperty HeaderTemplateProperty =
DependencyProperty.Register("HeaderTemplate", typeof(DataTemplate), typeof(ToggleSwitch), new PropertyMetadata(null));
/// <summary>
/// Gets or sets the template used to display the control's header.
/// </summary>
public DataTemplate HeaderTemplate
{
get { return (DataTemplate)GetValue(HeaderTemplateProperty); }
set { SetValue(HeaderTemplateProperty, value); }
}
/// <summary>
/// Identifies the SwitchForeground DependencyProperty.
/// </summary>
public static readonly DependencyProperty SwitchForegroundProperty =
DependencyProperty.Register("SwitchForeground", typeof(Brush), typeof(ToggleSwitch), null);
/// <summary>
/// Gets or sets the switch foreground.
/// </summary>
public Brush SwitchForeground
{
get { return (Brush)GetValue(SwitchForegroundProperty); }
set { SetValue(SwitchForegroundProperty, value); }
}
/// <summary>
/// Gets or sets whether the ToggleSwitch is checked.
/// </summary>
[TypeConverter(typeof(NullableBoolConverter))]
public bool? IsChecked
{
get { return (bool?)GetValue(IsCheckedProperty); }
set {
// Testing the value before calling SetValue will preserve the OneWay databindings (because IsCheked is called as a result of transfering the value to the inner switch control)
if (IsChecked != value)
{
SetValue(IsCheckedProperty, value);
}
}
}
/// <summary>
/// Identifies the IsChecked DependencyProperty.
/// </summary>
public static readonly DependencyProperty IsCheckedProperty =
DependencyProperty.Register("IsChecked", typeof(bool?), typeof(ToggleSwitch), new PropertyMetadata(false, OnIsCheckedChanged));
/// <summary>
/// Invoked when the IsChecked DependencyProperty is changed.
/// </summary>
/// <param name="d">The event sender.</param>
/// <param name="e">The event information.</param>
private static void OnIsCheckedChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
ToggleSwitch toggleSwitch = (ToggleSwitch)d;
if (toggleSwitch._toggleButton != null)
{
toggleSwitch._toggleButton.IsChecked = (bool?)e.NewValue;
}
}
/// <summary>
/// Occurs when the
/// <see cref="T:Microsoft.Phone.Controls.ToggleSwitch"/>
/// is checked.
/// </summary>
public event EventHandler<RoutedEventArgs> Checked;
/// <summary>
/// Occurs when the
/// <see cref="T:Microsoft.Phone.Controls.ToggleSwitch"/>
/// is unchecked.
/// </summary>
public event EventHandler<RoutedEventArgs> Unchecked;
/// <summary>
/// Occurs when the
/// <see cref="T:Microsoft.Phone.Controls.ToggleSwitch"/>
/// is indeterminate.
/// </summary>
public event EventHandler<RoutedEventArgs> Indeterminate;
/// <summary>
/// Occurs when the
/// <see cref="System.Windows.Controls.Primitives.ToggleButton"/>
/// is clicked.
/// </summary>
public event EventHandler<RoutedEventArgs> Click;
/// <summary>
/// The
/// <see cref="System.Windows.Controls.Primitives.ToggleButton"/>
/// template part.
/// </summary>
private ToggleSwitchButton _toggleButton;
/// <summary>
/// Whether the content was set.
/// </summary>
private bool _wasContentSet;
/// <summary>
/// Initializes a new instance of the ToggleSwitch class.
/// </summary>
public ToggleSwitch()
{
DefaultStyleKey = typeof(ToggleSwitch);
}
/// <summary>
/// Makes the content an "Off" or "On" string to match the state.
/// </summary>
private void SetDefaultContent()
{
Binding binding = new Binding("IsChecked") { Source = this, Converter = new OffOnConverter() };
SetBinding(ContentProperty, binding);
}
/// <summary>
/// Change the visual state.
/// </summary>
/// <param name="useTransitions">Indicates whether to use animation transitions.</param>
private void ChangeVisualState(bool useTransitions)
{
if (IsEnabled)
{
VisualStateManager.GoToState(this, NormalState, useTransitions);
}
else
{
VisualStateManager.GoToState(this, DisabledState, useTransitions);
}
}
/// <summary>
/// Makes the content an "Off" or "On" string to match the state if the content is set to null in the design tool.
/// </summary>
/// <param name="oldContent">The old content.</param>
/// <param name="newContent">The new content.</param>
protected override void OnContentChanged(object oldContent, object newContent)
{
base.OnContentChanged(oldContent, newContent);
_wasContentSet = true;
if (DesignerProperties.IsInDesignTool && newContent == null && GetBindingExpression(ContentProperty) == null)
{
SetDefaultContent();
}
}
/// <summary>
/// Gets all the template parts and initializes the corresponding state.
/// </summary>
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
if (!_wasContentSet && GetBindingExpression(ContentProperty) == null)
{
SetDefaultContent();
}
if (_toggleButton != null)
{
_toggleButton.Checked -= OnChecked;
_toggleButton.Unchecked -= OnUnchecked;
_toggleButton.Indeterminate -= OnIndeterminate;
_toggleButton.Click -= OnClick;
}
_toggleButton = GetTemplateChild(SwitchPart) as ToggleSwitchButton;
if (_toggleButton != null)
{
_toggleButton.Checked += OnChecked;
_toggleButton.Unchecked += OnUnchecked;
_toggleButton.Indeterminate += OnIndeterminate;
_toggleButton.Click += OnClick;
_toggleButton.IsChecked = IsChecked;
}
IsEnabledChanged += delegate
{
ChangeVisualState(true);
};
ChangeVisualState(false);
}
/// <summary>
/// Mirrors the
/// <see cref="E:System.Windows.Controls.Primitives.ToggleButton.Checked"/>
/// event.
/// </summary>
/// <param name="sender">The event sender.</param>
/// <param name="e">The event information.</param>
private void OnChecked(object sender, RoutedEventArgs e)
{
IsChecked = true;
SafeRaise.Raise(Checked, this, e);
}
/// <summary>
/// Mirrors the
/// <see cref="E:System.Windows.Controls.Primitives.ToggleButton.Unchecked"/>
/// event.
/// </summary>
/// <param name="sender">The event sender.</param>
/// <param name="e">The event information.</param>
private void OnUnchecked(object sender, RoutedEventArgs e)
{
IsChecked = false;
SafeRaise.Raise(Unchecked, this, e);
}
/// <summary>
/// Mirrors the
/// <see cref="E:System.Windows.Controls.Primitives.ToggleButton.Indeterminate"/>
/// event.
/// </summary>
/// <param name="sender">The event sender.</param>
/// <param name="e">The event information.</param>
private void OnIndeterminate(object sender, RoutedEventArgs e)
{
IsChecked = null;
SafeRaise.Raise(Indeterminate, this, e);
}
/// <summary>
/// Mirrors the
/// <see cref="E:System.Windows.Controls.Primitives.ToggleButton.Click"/>
/// event.
/// </summary>
/// <param name="sender">The event sender.</param>
/// <param name="e">The event information.</param>
private void OnClick(object sender, RoutedEventArgs e)
{
SafeRaise.Raise(Click, this, e);
}
/// <summary>
/// Returns a
/// <see cref="T:System.String"/>
/// that represents the current
/// <see cref="T:System.Object"/>
/// .
/// </summary>
/// <returns></returns>
public override string ToString()
{
return string.Format(
CultureInfo.InvariantCulture,
"{{ToggleSwitch IsChecked={0}, Content={1}}}",
IsChecked,
Content
);
}
}
} | 35.309375 | 192 | 0.571024 | [
"MIT"
] | misenhower/WPRemote | CommonLibraries/Libraries/Microsoft.Phone.Controls.Toolkit/Microsoft.Phone.Controls.Toolkit/ToggleSwitch/ToggleSwitch.cs | 11,301 | C# |
// <copyright file="AspNetCoreMvc31Tests.cs" company="Datadog">
// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License.
// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc.
// </copyright>
#if NETCOREAPP3_1
#pragma warning disable SA1402 // File may only contain a single class
#pragma warning disable SA1649 // File name must match first type name
using System.Net;
using System.Threading.Tasks;
using Datadog.Trace.TestHelpers;
using VerifyXunit;
using Xunit;
using Xunit.Abstractions;
namespace Datadog.Trace.ClrProfiler.IntegrationTests.AspNetCore
{
public class AspNetCoreMvc31TestsCallTarget : AspNetCoreMvc31Tests
{
public AspNetCoreMvc31TestsCallTarget(AspNetCoreTestFixture fixture, ITestOutputHelper output)
: base(fixture, output, enableRouteTemplateResourceNames: false)
{
}
}
public class AspNetCoreMvc31TestsCallTargetWithFeatureFlag : AspNetCoreMvc31Tests
{
public AspNetCoreMvc31TestsCallTargetWithFeatureFlag(AspNetCoreTestFixture fixture, ITestOutputHelper output)
: base(fixture, output, enableRouteTemplateResourceNames: true)
{
}
}
public abstract class AspNetCoreMvc31Tests : AspNetCoreMvcTestBase
{
private readonly string _testName;
protected AspNetCoreMvc31Tests(AspNetCoreTestFixture fixture, ITestOutputHelper output, bool enableRouteTemplateResourceNames)
: base("AspNetCoreMvc31", fixture, output, enableRouteTemplateResourceNames)
{
_testName = GetTestName(nameof(AspNetCoreMvc31Tests));
}
[SkippableTheory]
[Trait("Category", "EndToEnd")]
[Trait("RunOnWindows", "True")]
[MemberData(nameof(Data))]
public async Task MeetsAllAspNetCoreMvcExpectations(string path, HttpStatusCode statusCode)
{
await Fixture.TryStartApp(this);
var spans = await Fixture.WaitForSpans(path);
var sanitisedPath = VerifyHelper.SanitisePathsForVerify(path);
var settings = VerifyHelper.GetSpanVerifierSettings(sanitisedPath, (int)statusCode);
// Overriding the type name here as we have multiple test classes in the file
// Ensures that we get nice file nesting in Solution Explorer
await Verifier.Verify(spans, settings)
.UseMethodName("_")
.UseTypeName(_testName);
}
}
}
#endif
| 38.298507 | 134 | 0.706157 | [
"Apache-2.0"
] | DataDog/dd-trace-csharp | tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/AspNetCore/AspNetCoreMvc31Tests.cs | 2,566 | C# |
using CommandLine;
using CommandLine.Text;
using System.Diagnostics;
using System;
namespace PbixTools.CLI {
class Options {
[Option('r', "read", Required = true, HelpText = "Input file to be p rocessed.")]
public string InputFile { get; set; }
[Option('w', "write", Required = true, HelpText = "Output file to be created.")]
public string OutputFile { get; set; }
[Option('v', "verbose", DefaultValue = false, HelpText = "Prints all messages to standard output.")]
public bool Verbose { get; set; }
[Option( "remove", DefaultValue = true, HelpText = "Remove unused visuals.")]
public bool Remove { get; set; }
[ParserState]
public IParserState LastParserState { get; set; }
[HelpOption]
public string GetUsage() {
return HelpText.AutoBuild(this, (HelpText current) => HelpText.DefaultParsingErrorsHandler(this, current));
}
}
class Program {
static void Main(string[] args) {
var options = new Options();
if (CommandLine.Parser.Default.ParseArguments(args, options)) {
// Set trace level
TraceSwitch traceSwitch = new TraceSwitch("General", "Entire Application");
traceSwitch.Level = (options.Verbose ? TraceLevel.Verbose : TraceLevel.Info);
Trace.Listeners.Add(new ConsoleTraceListener());
Globbing files = new Globbing(traceSwitch);
PbixUtils utils = new PbixUtils(traceSwitch);
foreach (var file in files.Glob(options.InputFile, options.OutputFile))
{
Console.WriteLine(file.Item1, file.Item2);
if (options.Remove)
utils.RemoveUnusedVisuals(file.Item1, file.Item2);
}
}
}
}
}
| 34.907407 | 119 | 0.586207 | [
"MIT"
] | okviz/PbixTools | PbixTools.CLI/Program.cs | 1,887 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using ConcurrentCollections;
using WalletWasabi.Backend.Models;
using WalletWasabi.Exceptions;
using WalletWasabi.Helpers;
using WalletWasabi.KeyManagement;
using WalletWasabi.Logging;
using WalletWasabi.Models;
using WalletWasabi.TorSocks5;
using NBitcoin;
using NBitcoin.Policy;
using NBitcoin.Protocol;
using Nito.AsyncEx;
using System.Collections.ObjectModel;
using WalletWasabi.WebClients.Wasabi;
using Newtonsoft.Json;
using System.Collections.Concurrent;
namespace WalletWasabi.Services
{
public class WalletService : IDisposable
{
public KeyManager KeyManager { get; }
public IndexDownloader IndexDownloader { get; }
public CcjClient ChaumianClient { get; }
public MemPoolService MemPool { get; }
public NodesGroup Nodes { get; }
public string BlocksFolderPath { get; }
public string TransactionsFolderPath { get; }
public string TransactionsFilePath { get; }
private AsyncLock HandleFiltersLock { get; }
private AsyncLock BlockDownloadLock { get; }
private AsyncLock BlockFolderLock { get; }
public SortedDictionary<Height, uint256> WalletBlocks { get; }
public ConcurrentDictionary<uint256, (Height height, DateTimeOffset dateTime)> ProcessedBlocks { get; }
private AsyncLock WalletBlocksLock { get; }
public NotifyingConcurrentHashSet<SmartCoin> Coins { get; }
public ConcurrentHashSet<SmartTransaction> TransactionCache { get; }
public event EventHandler<FilterModel> NewFilterProcessed;
public event EventHandler<SmartCoin> CoinSpentOrSpenderConfirmed;
public event EventHandler<Block> NewBlockProcessed;
public Network Network => IndexDownloader.Network;
/// <summary>
/// 0: Not started, 1: Running, 2: Stopping, 3: Stopped
/// </summary>
private long _running;
public bool IsRunning => Interlocked.Read(ref _running) == 1;
public bool IsStopping => Interlocked.Read(ref _running) == 2;
public WalletService(KeyManager keyManager, IndexDownloader indexDownloader, CcjClient chaumianClient, MemPoolService memPool, NodesGroup nodes, string workFolderDir)
{
KeyManager = Guard.NotNull(nameof(keyManager), keyManager);
Nodes = Guard.NotNull(nameof(nodes), nodes);
IndexDownloader = Guard.NotNull(nameof(indexDownloader), indexDownloader);
ChaumianClient = Guard.NotNull(nameof(chaumianClient), chaumianClient);
MemPool = Guard.NotNull(nameof(memPool), memPool);
WalletBlocks = new SortedDictionary<Height, uint256>();
ProcessedBlocks = new ConcurrentDictionary<uint256, (Height height, DateTimeOffset dateTime)>();
WalletBlocksLock = new AsyncLock();
HandleFiltersLock = new AsyncLock();
Coins = new NotifyingConcurrentHashSet<SmartCoin>();
TransactionCache = new ConcurrentHashSet<SmartTransaction>();
BlocksFolderPath = Path.Combine(workFolderDir, "Blocks", Network.ToString());
TransactionsFolderPath = Path.Combine(workFolderDir, "Transactions", Network.ToString());
BlockFolderLock = new AsyncLock();
BlockDownloadLock = new AsyncLock();
AssertCleanKeysIndexed(21);
_running = 0;
if (Directory.Exists(BlocksFolderPath))
{
if (IndexDownloader.Network == Network.RegTest)
{
Directory.Delete(BlocksFolderPath, true);
Directory.CreateDirectory(BlocksFolderPath);
}
}
else
{
Directory.CreateDirectory(BlocksFolderPath);
}
if (Directory.Exists(TransactionsFolderPath))
{
if (IndexDownloader.Network == Network.RegTest)
{
Directory.Delete(TransactionsFolderPath, true);
Directory.CreateDirectory(TransactionsFolderPath);
}
}
else
{
Directory.CreateDirectory(TransactionsFolderPath);
}
var walletName = "UnnamedWallet";
if (!string.IsNullOrWhiteSpace(KeyManager.FilePath))
{
walletName = Path.GetFileNameWithoutExtension(KeyManager.FilePath);
}
TransactionsFilePath = Path.Combine(TransactionsFolderPath, $"{walletName}Transactions.json");
IndexDownloader.NewFilter += IndexDownloader_NewFilterAsync;
IndexDownloader.Reorged += IndexDownloader_ReorgedAsync;
MemPool.TransactionReceived += MemPool_TransactionReceived;
}
private void MemPool_TransactionReceived(object sender, SmartTransaction tx)
{
ProcessTransaction(tx, keys: null);
}
private async void IndexDownloader_ReorgedAsync(object sender, uint256 invalidBlockHash)
{
using (HandleFiltersLock.Lock())
using (WalletBlocksLock.Lock())
{
var elem = WalletBlocks.FirstOrDefault(x => x.Value == invalidBlockHash);
await DeleteBlockAsync(invalidBlockHash);
WalletBlocks.RemoveByValue(invalidBlockHash);
ProcessedBlocks.TryRemove(invalidBlockHash, out _);
if (elem.Key != default(Height))
{
foreach (var toRemove in Coins.Where(x => x.Height == elem.Key).ToHashSet())
{
RemoveCoinRecursively(toRemove);
}
}
}
}
private void RemoveCoinRecursively(SmartCoin toRemove)
{
if (toRemove.SpenderTransactionId != null)
{
foreach (var toAlsoRemove in Coins.Where(x => x.TransactionId == toRemove.SpenderTransactionId).ToHashSet())
{
RemoveCoinRecursively(toAlsoRemove);
}
}
Coins.TryRemove(toRemove);
}
private async void IndexDownloader_NewFilterAsync(object sender, FilterModel filterModel)
{
using (HandleFiltersLock.Lock())
using (WalletBlocksLock.Lock())
{
if (filterModel.Filter != null && !WalletBlocks.ContainsValue(filterModel.BlockHash))
{
await ProcessFilterModelAsync(filterModel, CancellationToken.None);
}
}
NewFilterProcessed?.Invoke(this, filterModel);
}
public async Task InitializeAsync(CancellationToken cancel)
{
if (!IndexDownloader.IsRunning)
{
throw new NotSupportedException($"{nameof(IndexDownloader)} is not running.");
}
using (HandleFiltersLock.Lock())
using (WalletBlocksLock.Lock())
{
// Go through the filters and que to download the matches.
var filters = IndexDownloader.GetFiltersIncluding(IndexDownloader.StartingFilter.BlockHeight);
foreach (FilterModel filterModel in filters.Where(x => x.Filter != null && !WalletBlocks.ContainsValue(x.BlockHash))) // Filter can be null if there is no bech32 tx.
{
await ProcessFilterModelAsync(filterModel, cancel);
}
// Load in dummy mempool
if (File.Exists(TransactionsFilePath))
{
string jsonString = File.ReadAllText(TransactionsFilePath, Encoding.UTF8);
var serializedTransactions = JsonConvert.DeserializeObject<IEnumerable<SmartTransaction>>(jsonString);
foreach (SmartTransaction tx in serializedTransactions.Where(x => !x.Confirmed))
{
try
{
await SendTransactionAsync(tx);
ProcessTransaction(tx, keys: null);
}
catch (Exception ex)
{
Logger.LogWarning<WalletService>(ex);
}
}
try
{
File.Delete(TransactionsFilePath);
}
catch (Exception ex)
{
// Don't fail because of this. It's not important.
Logger.LogWarning<WalletService>(ex);
}
}
}
}
private async Task ProcessFilterModelAsync(FilterModel filterModel, CancellationToken cancel)
{
if (ProcessedBlocks.ContainsKey(filterModel.BlockHash))
{
return;
}
var matchFound = filterModel.Filter.MatchAny(KeyManager.GetKeys().Select(x => x.GetP2wpkhScript().ToCompressedBytes()), filterModel.FilterKey);
if (!matchFound)
{
return;
}
Block currentBlock = await GetOrDownloadBlockAsync(filterModel.BlockHash, cancel); // Wait until not downloaded.
WalletBlocks.AddOrReplace(filterModel.BlockHeight, filterModel.BlockHash);
if (currentBlock.GetHash() == WalletBlocks.Last().Value) // If this is the latest block then no need for deep gothrough.
{
ProcessBlock(filterModel.BlockHeight, currentBlock);
}
else // must go through all the blocks in order
{
foreach (var blockRef in WalletBlocks)
{
var block = await GetOrDownloadBlockAsync(blockRef.Value, CancellationToken.None);
ProcessedBlocks.Clear();
Coins.Clear();
ProcessBlock(blockRef.Key, block);
}
}
}
public HdPubKey GetReceiveKey(string label, IEnumerable<HdPubKey> dontTouch = null)
{
label = Guard.Correct(label);
// Make sure there's always 21 clean keys generated and indexed.
AssertCleanKeysIndexed(21, false);
IEnumerable<HdPubKey> keys = KeyManager.GetKeys(KeyState.Clean, isInternal: false);
if (dontTouch != null)
{
keys = keys.Except(dontTouch);
if (!keys.Any())
{
throw new InvalidOperationException($"{nameof(dontTouch)} covers all the possible keys.");
}
}
var foundLabelless = keys.FirstOrDefault(x => !x.HasLabel()); // return the first labelless
HdPubKey ret = foundLabelless ?? keys.RandomElement(); // return the first, because that's the oldest
ret.SetLabel(label, KeyManager);
return ret;
}
public List<SmartCoin> GetHistory(SmartCoin coin, IEnumerable<SmartCoin> current)
{
Guard.NotNull(nameof(coin), coin);
if (current.Contains(coin))
{
return current.ToList();
}
var history = current.Concat(new List<SmartCoin> { coin }).ToList(); // the coin is the firs elem in its history
// If the script is the same then we have a match, no matter of the anonimity set.
foreach (var c in Coins)
{
if (c.ScriptPubKey == coin.ScriptPubKey)
{
if (!history.Contains(c))
{
var h = GetHistory(c, history);
foreach (var hr in h)
{
if (!history.Contains(hr))
{
history.Add(hr);
}
}
}
}
}
// If it spends someone and haven't been sufficiently anonimized.
if (coin.AnonymitySet < 50)
{
var c = Coins.FirstOrDefault(x => x.SpenderTransactionId == coin.TransactionId && !history.Contains(x));
if (c != default)
{
var h = GetHistory(c, history);
foreach (var hr in h)
{
if (!history.Contains(hr))
{
history.Add(hr);
}
}
}
}
// If it's being spent by someone and that someone haven't been sufficiently anonimized.
if (!coin.Unspent)
{
var c = Coins.FirstOrDefault(x => x.TransactionId == coin.SpenderTransactionId && !history.Contains(x));
if (c != default)
{
if (c.AnonymitySet < 50)
{
if (c != default)
{
var h = GetHistory(c, history);
foreach (var hr in h)
{
if (!history.Contains(hr))
{
history.Add(hr);
}
}
}
}
}
}
return history;
}
/// <summary>
/// Make sure there's always clean keys generated and indexed.
/// </summary>
private bool AssertCleanKeysIndexed(int howMany = 21, bool? isInternal = null)
{
var generated = false;
if (isInternal == null)
{
while (KeyManager.GetKeys(KeyState.Clean, true).Count() < howMany)
{
KeyManager.GenerateNewKey("", KeyState.Clean, true, toFile: false);
generated = true;
}
while (KeyManager.GetKeys(KeyState.Clean, false).Count() < howMany)
{
KeyManager.GenerateNewKey("", KeyState.Clean, false, toFile: false);
generated = true;
}
}
else
{
while (KeyManager.GetKeys(KeyState.Clean, isInternal).Count() < howMany)
{
KeyManager.GenerateNewKey("", KeyState.Clean, (bool)isInternal, toFile: false);
generated = true;
}
}
if (generated)
{
KeyManager.ToFile();
}
return generated;
}
private void ProcessBlock(Height height, Block block)
{
var keys = KeyManager.GetKeys().ToList();
foreach (var tx in block.Transactions)
{
ProcessTransaction(new SmartTransaction(tx, height), keys);
}
ProcessedBlocks.TryAdd(block.GetHash(), (height, block.Header.BlockTime));
NewBlockProcessed?.Invoke(this, block);
}
private void ProcessTransaction(SmartTransaction tx, List<HdPubKey> keys = null)
{
if (tx.Height.Type == HeightType.Chain)
{
MemPool.TransactionHashes.TryRemove(tx.GetHash()); // If we have in mempool, remove.
SmartTransaction foundTx = TransactionCache.FirstOrDefault(x => x == tx); // If we have in cache, update height.
if (foundTx != default(SmartTransaction))
{
foundTx.SetHeight(tx.Height);
}
}
//iterate tx
// if already have the coin
// if NOT mempool
// update height
//if double spend
// if mempool
// if all double spent coins are mempool and RBF
// remove double spent coins(if other coin spends it, remove that too and so on) // will add later if they came to our keys
// else
// return
// else // new confirmation always enjoys priority
// remove double spent coins recursively(if other coin spends it, remove that too and so on)// will add later if they came to our keys
//iterate tx
// if came to our keys
// add coin
// If key list is not provided refresh the key list.
if (keys == null)
{
keys = KeyManager.GetKeys().ToList();
}
for (var i = 0; i < tx.Transaction.Outputs.Count; i++)
{
// If we already had it, just update the height. Maybe got from mempool to block or reorged.
SmartCoin foundCoin = Coins.FirstOrDefault(x => x.TransactionId == tx.GetHash() && x.Index == i);
if (foundCoin != default)
{
// If tx height is mempool then don't, otherwise update the height.
if (tx.Height != Height.MemPool)
{
foundCoin.Height = tx.Height;
}
}
}
// If double spend:
List<SmartCoin> doubleSpends = Coins
.Where(x => tx.Transaction.Inputs.Any(y => x.SpentOutputs.Select(z => z.ToOutPoint()).Contains(y.PrevOut)))
.ToList();
if (doubleSpends.Any())
{
if (tx.Height == Height.MemPool)
{
// if all double spent coins are mempool and RBF
if (doubleSpends.All(x => x.Height == Height.MemPool && x.RBF))
{
// remove double spent coins(if other coin spends it, remove that too and so on) // will add later if they came to our keys
foreach (var doubleSpentCoin in doubleSpends)
{
RemoveCoinRecursively(doubleSpentCoin);
}
}
else
{
return;
}
}
else // new confirmation always enjoys priority
{
// remove double spent coins recursively (if other coin spends it, remove that too and so on), will add later if they came to our keys
foreach (var doubleSpentCoin in doubleSpends)
{
RemoveCoinRecursively(doubleSpentCoin);
}
}
}
for (var i = 0U; i < tx.Transaction.Outputs.Count; i++)
{
// If transaction received to any of the wallet keys:
var output = tx.Transaction.Outputs[i];
HdPubKey foundKey = keys.SingleOrDefault(x => x.GetP2wpkhScript() == output.ScriptPubKey);
if (foundKey != default)
{
foundKey.SetKeyState(KeyState.Used, KeyManager);
List<SmartCoin> spentOwnCoins = Coins.Where(x => tx.Transaction.Inputs.Any(y => y.PrevOut.Hash == x.TransactionId && y.PrevOut.N == x.Index)).ToList();
var mixin = tx.Transaction.GetMixin(i);
if (spentOwnCoins.Count != 0)
{
mixin += spentOwnCoins.Min(x => x.Mixin);
}
var coin = new SmartCoin(tx.GetHash(), i, output.ScriptPubKey, output.Value, tx.Transaction.Inputs.ToTxoRefs().ToArray(), tx.Height, tx.Transaction.RBF, mixin, foundKey.Label, spenderTransactionId: null, locked: false); // Don't inherit locked status from key, that's different.
Coins.TryAdd(coin);
TransactionCache.Add(tx);
if (coin.Unspent && coin.Label == "ZeroLink Change" && ChaumianClient.OnePiece != null)
{
Task.Run(async () =>
{
try
{
await ChaumianClient.QueueCoinsToMixAsync(ChaumianClient.OnePiece, coin);
}
catch (Exception ex)
{
Logger.LogError<WalletService>(ex);
}
});
}
// Make sure there's always 21 clean keys generated and indexed.
if (AssertCleanKeysIndexed(21, foundKey.IsInternal()))
{
// If it generated a new key refresh the keys:
keys = KeyManager.GetKeys().ToList();
}
}
}
// If spends any of our coin
for (var i = 0; i < tx.Transaction.Inputs.Count; i++)
{
var input = tx.Transaction.Inputs[i];
var foundCoin = Coins.FirstOrDefault(x => x.TransactionId == input.PrevOut.Hash && x.Index == input.PrevOut.N);
if (foundCoin != null)
{
foundCoin.SpenderTransactionId = tx.GetHash();
TransactionCache.Add(tx);
CoinSpentOrSpenderConfirmed?.Invoke(this, foundCoin);
}
}
}
/// <exception cref="OperationCanceledException"></exception>
public async Task<Block> GetOrDownloadBlockAsync(uint256 hash, CancellationToken cancel)
{
// Try get the block
using (await BlockFolderLock.LockAsync())
{
foreach (var filePath in Directory.EnumerateFiles(BlocksFolderPath))
{
var fileName = Path.GetFileName(filePath);
try
{
if (hash == new uint256(fileName))
{
var blockBytes = await File.ReadAllBytesAsync(filePath);
return Block.Load(blockBytes, IndexDownloader.Network);
}
}
catch (FormatException)
{
Logger.LogTrace<WalletService>($"Filename is not a hash: {fileName}.");
}
}
}
cancel.ThrowIfCancellationRequested();
// Download the block
Block block = null;
using (await BlockDownloadLock.LockAsync())
{
while (true)
{
cancel.ThrowIfCancellationRequested();
try
{
// If no connection, wait then continue.
while (Nodes.ConnectedNodes.Count == 0)
{
await Task.Delay(100);
}
Node node = Nodes.ConnectedNodes.RandomElement();
if (node == default(Node))
{
await Task.Delay(100);
continue;
}
if (!node.IsConnected && !(IndexDownloader.Network != Network.RegTest))
{
await Task.Delay(100);
continue;
}
try
{
using (var cts = new CancellationTokenSource(TimeSpan.FromSeconds(32))) // ADSL 512 kbit/s 00:00:32
{
block = node.GetBlocks(new uint256[] { hash }, cts.Token)?.Single();
}
if (block == null)
{
Logger.LogInfo<WalletService>("Disconnected node, because couldn't parse received block.");
node.DisconnectAsync("Couldn't parse block.");
continue;
}
if (!block.Check())
{
Logger.LogInfo<WalletService>("Disconnected node, because block invalid block received.");
node.DisconnectAsync("Invalid block received.");
continue;
}
}
catch (TimeoutException)
{
Logger.LogInfo<WalletService>("Disconnected node, because block download took too long.");
node.DisconnectAsync("Block download took too long.");
continue;
}
catch (OperationCanceledException)
{
Logger.LogInfo<WalletService>("Disconnected node, because block download took too long.");
node.DisconnectAsync("Block download took too long.");
continue;
}
catch (Exception ex)
{
Logger.LogDebug<WalletService>(ex);
Logger.LogInfo<WalletService>($"Disconnected node, because block download failed: {ex.Message}");
node.DisconnectAsync("Block download failed.");
continue;
}
break; // If got this far break, then we have the block, it's valid. Break.
}
catch (Exception ex)
{
Logger.LogDebug<WalletService>(ex);
}
}
}
// Save the block
using (await BlockFolderLock.LockAsync())
{
var path = Path.Combine(BlocksFolderPath, hash.ToString());
await File.WriteAllBytesAsync(path, block.ToBytes());
}
return block;
}
/// <remarks>
/// Use it at reorgs.
/// </remarks>
public async Task DeleteBlockAsync(uint256 hash)
{
using (await BlockFolderLock.LockAsync())
{
var filePaths = Directory.EnumerateFiles(BlocksFolderPath);
var fileNames = filePaths.Select(x => Path.GetFileName(x));
var hashes = fileNames.Select(x => new uint256(x));
if (hashes.Contains(hash))
{
File.Delete(Path.Combine(BlocksFolderPath, hash.ToString()));
}
}
}
public async Task<int> CountBlocksAsync()
{
using (await BlockFolderLock.LockAsync())
{
return Directory.EnumerateFiles(BlocksFolderPath).Count();
}
}
public class Operation
{
public Script Script { get; }
public Money Amount { get; }
public string Label { get; }
public Operation(Script script, Money amount, string label)
{
Script = Guard.NotNull(nameof(script), script);
Amount = Guard.NotNull(nameof(amount), amount);
Label = label ?? "";
}
}
/// <param name="toSend">If Money.Zero then spends all available amount. Doesn't generate change.</param>
/// <param name="allowUnconfirmed">Allow to spend unconfirmed transactions, if necessary.</param>
/// <param name="allowedInputs">Only these inputs allowed to be used to build the transaction. The wallet must know the corresponding private keys.</param>
/// <param name="subtractFeeFromAmountIndex">If null, fee is substracted from the change. Otherwise it denotes the index in the toSend array.</param>
/// <exception cref="ArgumentException"></exception>
/// <exception cref="ArgumentNullException"></exception>
/// <exception cref="ArgumentOutOfRangeException"></exception>
public async Task<BuildTransactionResult> BuildTransactionAsync(string password,
Operation[] toSend,
int feeTarget,
bool allowUnconfirmed = false,
int? subtractFeeFromAmountIndex = null,
Script customChange = null,
IEnumerable<TxoRef> allowedInputs = null)
{
password = password ?? ""; // Correction.
toSend = Guard.NotNullOrEmpty(nameof(toSend), toSend);
if (toSend.Any(x => x == null))
{
throw new ArgumentNullException($"{nameof(toSend)} cannot contain null element.");
}
if (toSend.Any(x => x.Amount < Money.Zero))
{
throw new ArgumentException($"{nameof(toSend)} cannot contain negative element.");
}
long sum = toSend.Select(x => x.Amount).Sum().Satoshi;
if (sum < 0 || sum > Constants.MaximumNumberOfSatoshis)
{
throw new ArgumentOutOfRangeException($"{nameof(toSend)} sum cannot be smaller than 0 or greater than {Constants.MaximumNumberOfSatoshis}.");
}
int spendAllCount = toSend.Count(x => x.Amount == Money.Zero);
if (spendAllCount > 1)
{
throw new ArgumentException($"Only one {nameof(toSend)} element can contain Money.Zero. Money.Zero means add the change to the value of this output.");
}
if (spendAllCount == 1 && customChange != null)
{
throw new ArgumentException($"{nameof(customChange)} and send all to destination cannot be specified the same time.");
}
Guard.InRangeAndNotNull(nameof(feeTarget), feeTarget, 0, 1008); // Allow 0 and 1, and correct later.
if (feeTarget < 2) // Correct 0 and 1 to 2.
{
feeTarget = 2;
}
if (subtractFeeFromAmountIndex != null) // If not null, make sure not out of range. If null fee is substracted from the change.
{
if (subtractFeeFromAmountIndex < 0)
{
throw new ArgumentOutOfRangeException($"{nameof(subtractFeeFromAmountIndex)} cannot be smaller than 0.");
}
if (subtractFeeFromAmountIndex > toSend.Length - 1)
{
throw new ArgumentOutOfRangeException($"{nameof(subtractFeeFromAmountIndex)} can be maximum {nameof(toSend)}.Length - 1. {nameof(subtractFeeFromAmountIndex)}: {subtractFeeFromAmountIndex}, {nameof(toSend)}.Length - 1: {toSend.Length - 1}.");
}
}
// Get allowed coins to spend.
List<SmartCoin> allowedSmartCoinInputs; // Inputs those can be used to build the transaction.
if (allowedInputs != null) // If allowedInputs are specified then select the coins from them.
{
if (!allowedInputs.Any())
{
throw new ArgumentException($"{nameof(allowedInputs)} is not null, but empty.");
}
if (allowUnconfirmed)
{
allowedSmartCoinInputs = Coins.Where(x => !x.SpentOrCoinJoinInProcess && allowedInputs.Any(y => y.TransactionId == x.TransactionId && y.Index == x.Index)).ToList();
}
else
{
allowedSmartCoinInputs = Coins.Where(x => !x.SpentOrCoinJoinInProcess && x.Confirmed && allowedInputs.Any(y => y.TransactionId == x.TransactionId && y.Index == x.Index)).ToList();
}
}
else
{
if (allowUnconfirmed)
{
allowedSmartCoinInputs = Coins.Where(x => !x.SpentOrCoinJoinInProcess).ToList();
}
else
{
allowedSmartCoinInputs = Coins.Where(x => !x.SpentOrCoinJoinInProcess && x.Confirmed).ToList();
}
}
// 4. Get and calculate fee
Logger.LogInfo<WalletService>("Calculating dynamic transaction fee...");
Money feePerBytes = null;
using (var client = new WasabiClient(IndexDownloader.WasabiClient.TorClient.DestinationUri, IndexDownloader.WasabiClient.TorClient.TorSocks5EndPoint))
{
var fees = await client.GetFeesAsync(feeTarget);
feePerBytes = new Money(fees.Single().Value.Conservative);
}
bool spendAll = spendAllCount == 1;
int inNum;
if (spendAll)
{
inNum = allowedSmartCoinInputs.Count;
}
else
{
int expectedMinTxSize = 1 * Constants.P2wpkhInputSizeInBytes + 1 * Constants.OutputSizeInBytes + 10;
inNum = SelectCoinsToSpend(allowedSmartCoinInputs, toSend.Select(x => x.Amount).Sum() + feePerBytes * expectedMinTxSize).Count();
}
// https://bitcoincore.org/en/segwit_wallet_dev/#transaction-fee-estimation
// https://bitcoin.stackexchange.com/a/46379/26859
int outNum = spendAll ? toSend.Length : toSend.Length + 1; // number of addresses to send + 1 for change
var origTxSize = inNum * Constants.P2pkhInputSizeInBytes + outNum * Constants.OutputSizeInBytes + 10;
var newTxSize = inNum * Constants.P2wpkhInputSizeInBytes + outNum * Constants.OutputSizeInBytes + 10; // BEWARE: This assumes segwit only inputs!
var vSize = (int)Math.Ceiling(((3 * newTxSize) + origTxSize) / 4m);
Logger.LogInfo<WalletService>($"Estimated tx size: {vSize} bytes.");
Money fee = feePerBytes * vSize;
Logger.LogInfo<WalletService>($"Fee: {fee.ToString(fplus: false, trimExcessZero: true)}");
// 5. How much to spend?
long toSendAmountSumInSatoshis = toSend.Select(x => x.Amount).Sum(); // Does it work if I simply go with Money class here? Is that copied by reference of value?
var realToSend = new(Script script, Money amount, string label)[toSend.Length];
for (int i = 0; i < toSend.Length; i++) // clone
{
realToSend[i] = (
new Script(toSend[i].Script.ToString()),
new Money(toSend[i].Amount.Satoshi),
toSend[i].Label);
}
for (int i = 0; i < realToSend.Length; i++)
{
if (realToSend[i].amount == Money.Zero) // means spend all
{
realToSend[i].amount = allowedSmartCoinInputs.Select(x => x.Amount).Sum();
realToSend[i].amount -= new Money(toSendAmountSumInSatoshis);
if (subtractFeeFromAmountIndex == null)
{
realToSend[i].amount -= fee;
}
}
if (subtractFeeFromAmountIndex == i)
{
realToSend[i].amount -= fee;
}
if (realToSend[i].amount < Money.Zero)
{
throw new InsufficientBalanceException(fee + 1, realToSend[i].amount + fee);
}
}
var toRemoveList = new List<(Script script, Money money, string label)>(realToSend);
toRemoveList.RemoveAll(x => x.money == Money.Zero);
realToSend = toRemoveList.ToArray();
// 1. Get the possible changes.
Script changeScriptPubKey;
var sb = new StringBuilder();
foreach (var item in realToSend)
{
sb.Append(item.label ?? "?");
sb.Append(", ");
}
var changeLabel = $"change of ({sb.ToString().TrimEnd(',', ' ')})";
if (customChange == null)
{
AssertCleanKeysIndexed(21, true);
var changeHdPubKey = KeyManager.GetKeys(KeyState.Clean, true).RandomElement();
changeHdPubKey.SetLabel(changeLabel, KeyManager);
changeScriptPubKey = changeHdPubKey.GetP2wpkhScript();
}
else
{
changeScriptPubKey = customChange;
}
// 6. Do some checks
Money totalOutgoingAmountNoFee = realToSend.Select(x => x.amount).Sum();
Money totalOutgoingAmount = totalOutgoingAmountNoFee + fee;
decimal feePc = (100 * fee.ToDecimal(MoneyUnit.BTC)) / totalOutgoingAmountNoFee.ToDecimal(MoneyUnit.BTC);
if (feePc > 1)
{
Logger.LogInfo<WalletService>($"The transaction fee is {feePc:0.#}% of your transaction amount."
+ Environment.NewLine + $"Sending:\t {totalOutgoingAmount.ToString(fplus: false, trimExcessZero: true)} BTC."
+ Environment.NewLine + $"Fee:\t\t {fee.ToString(fplus: false, trimExcessZero: true)} BTC.");
}
if (feePc > 100)
{
throw new InvalidOperationException($"The transaction fee is more than twice as much as your transaction amount: {feePc:0.#}%.");
}
var confirmedAvailableAmount = allowedSmartCoinInputs.Where(x => x.Confirmed).Select(x => x.Amount).Sum();
var spendsUnconfirmed = false;
if (confirmedAvailableAmount < totalOutgoingAmount)
{
spendsUnconfirmed = true;
Logger.LogInfo<WalletService>("Unconfirmed transaction are being spent.");
}
// 7. Select coins
Logger.LogInfo<WalletService>("Selecting coins...");
IEnumerable<SmartCoin> coinsToSpend = SelectCoinsToSpend(allowedSmartCoinInputs, totalOutgoingAmount);
// 8. Get signing keys
IEnumerable<ExtKey> signingKeys = KeyManager.GetSecrets(password, coinsToSpend.Select(x => x.ScriptPubKey).ToArray());
// 9. Build the transaction
Logger.LogInfo<WalletService>("Signing transaction...");
var builder = new TransactionBuilder();
builder = builder
.AddCoins(coinsToSpend.Select(x => x.GetCoin()))
.AddKeys(signingKeys.ToArray());
foreach ((Script scriptPubKey, Money amount, string label) output in realToSend)
{
builder = builder.Send(output.scriptPubKey, output.amount);
}
var tx = builder
.SetChange(changeScriptPubKey)
.SendFees(fee)
.Shuffle()
.BuildTransaction(true);
TransactionPolicyError[] checkResults = builder.Check(tx, fee);
if (checkResults.Length > 0)
{
throw new InvalidTxException(tx, checkResults);
}
List<SmartCoin> spentCoins = Coins.Where(x => tx.Inputs.Any(y => y.PrevOut.Hash == x.TransactionId && y.PrevOut.N == x.Index)).ToList();
TxoRef[] spentOutputs = spentCoins.Select(x => new TxoRef(x.TransactionId, x.Index)).ToArray();
var outerWalletOutputs = new List<SmartCoin>();
var innerWalletOutputs = new List<SmartCoin>();
for (var i = 0U; i < tx.Outputs.Count; i++)
{
TxOut output = tx.Outputs[i];
var mixin = tx.GetMixin(i) + spentCoins.Min(x => x.Mixin);
var coin = new SmartCoin(tx.GetHash(), i, output.ScriptPubKey, output.Value, tx.Inputs.ToTxoRefs().ToArray(), Height.Unknown, tx.RBF, mixin);
if (KeyManager.GetKeys(KeyState.Clean).Select(x => x.GetP2wpkhScript()).Contains(coin.ScriptPubKey))
{
coin.Label = changeLabel;
innerWalletOutputs.Add(coin);
}
else
{
outerWalletOutputs.Add(coin);
}
}
Logger.LogInfo<WalletService>($"Transaction is successfully built: {tx.GetHash()}.");
return new BuildTransactionResult(new SmartTransaction(tx, Height.Unknown), spendsUnconfirmed, fee, feePc, outerWalletOutputs, innerWalletOutputs, spentCoins);
}
private IEnumerable<SmartCoin> SelectCoinsToSpend(IEnumerable<SmartCoin> unspentCoins, Money totalOutAmount)
{
var coinsToSpend = new HashSet<SmartCoin>();
var unspentConfirmedCoins = new List<SmartCoin>();
var unspentUnconfirmedCoins = new List<SmartCoin>();
foreach (var coin in unspentCoins)
if (coin.Confirmed) unspentConfirmedCoins.Add(coin);
else unspentUnconfirmedCoins.Add(coin);
bool haveEnough = SelectCoins(ref coinsToSpend, totalOutAmount, unspentConfirmedCoins);
if (!haveEnough)
haveEnough = SelectCoins(ref coinsToSpend, totalOutAmount, unspentUnconfirmedCoins);
if (!haveEnough)
throw new InsufficientBalanceException(totalOutAmount, unspentConfirmedCoins.Select(x => x.Amount).Sum() + unspentUnconfirmedCoins.Select(x => x.Amount).Sum());
return coinsToSpend;
}
private bool SelectCoins(ref HashSet<SmartCoin> coinsToSpend, Money totalOutAmount, IEnumerable<SmartCoin> unspentCoins)
{
var haveEnough = false;
foreach (var coin in unspentCoins.OrderByDescending(x => x.Amount))
{
coinsToSpend.Add(coin);
// if doesn't reach amount, continue adding next coin
if (coinsToSpend.Select(x => x.Amount).Sum() < totalOutAmount) continue;
haveEnough = true;
break;
}
return haveEnough;
}
public void Renamelabel(SmartCoin coin, string newLabel)
{
newLabel = Guard.Correct(newLabel);
coin.Label = newLabel;
var key = KeyManager.GetKeys().SingleOrDefault(x => x.GetP2wpkhScript() == coin.ScriptPubKey);
if (key != null)
{
key.SetLabel(newLabel, KeyManager);
}
}
public async Task SendTransactionAsync(SmartTransaction transaction)
{
using (var client = new WasabiClient(IndexDownloader.WasabiClient.TorClient.DestinationUri, IndexDownloader.WasabiClient.TorClient.TorSocks5EndPoint))
{
await client.BroadcastAsync(transaction);
}
ProcessTransaction(new SmartTransaction(transaction.Transaction, Height.MemPool));
MemPool.TransactionHashes.Add(transaction.GetHash());
Logger.LogInfo<WalletService>($"Transaction is successfully broadcasted: {transaction.GetHash()}.");
}
#region IDisposable Support
private volatile bool _disposedValue = false; // To detect redundant calls
protected virtual void Dispose(bool disposing)
{
if (!_disposedValue)
{
if (disposing)
{
IndexDownloader.NewFilter -= IndexDownloader_NewFilterAsync;
IndexDownloader.Reorged -= IndexDownloader_ReorgedAsync;
MemPool.TransactionReceived -= MemPool_TransactionReceived;
var directoryPath = Path.GetDirectoryName(Path.GetFullPath(TransactionsFilePath));
Directory.CreateDirectory(directoryPath);
string jsonString = JsonConvert.SerializeObject(TransactionCache, Formatting.Indented);
File.WriteAllText(TransactionsFilePath,
jsonString,
Encoding.UTF8);
}
_disposedValue = true;
}
}
// This code added to correctly implement the disposable pattern.
public void Dispose()
{
// Do not change this code. Put cleanup code in Dispose(bool disposing) above.
Dispose(true);
// GC.SuppressFinalize(this);
}
#endregion IDisposable Support
}
}
| 32.634906 | 283 | 0.681063 | [
"MIT"
] | ferdeen/WalletWasabi | WalletWasabi/Services/WalletService.cs | 34,595 | C# |
using Microsoft.Office.Core;
using Microsoft.Office.Interop.Outlook;
using Schillings.SwordPhish.Shared;
using Schillings.SwordPhish.Shared.Properties;
using System;
using System.Drawing;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using Office = Microsoft.Office.Core;
namespace Schillings.SwordPhish
{
[ComVisible(true)]
public class Ribbon : IRibbonExtensibility
{
private IRibbonUI ribbon;
public Ribbon()
{
}
public void ReportMailItem(IRibbonControl control)
{
Globals.ThisAddIn.SendReport(GetMailItemBasedOnControl(control));
ribbon.InvalidateControl(control.Id);
}
public bool GetButtonEnabled(IRibbonControl control)
{
MailItem mailItem = GetMailItemBasedOnControl(control);
return Globals.ThisAddIn.HasConfig
&& mailItem != null
&& !Helpers.GetUserProperty<bool>(mailItem, Constants.EMAIL_REPORTED);
}
public string GetButtonLabel(IRibbonControl control)
{
MailItem mailItem = GetMailItemBasedOnControl(control);
if (mailItem == null)
return Resources.ReportButton;
return Helpers.GetUserProperty<bool>(mailItem, Constants.EMAIL_REPORTED)
? Resources.Reported
: Resources.ReportButton;
}
public string GetButtonSuperTip(IRibbonControl control)
{
var mailItem = GetMailItemBasedOnControl(control);
if (mailItem == null)
return Resources.ReportButtonHelp;
return Helpers.GetUserProperty<bool>(mailItem, Constants.EMAIL_REPORTED)
? String.Format(Resources.ReportedDate, Helpers.GetUserProperty<string>(mailItem, Constants.EMAIL_REPORTED_DATE))
: Resources.ReportButtonHelp;
}
public Bitmap GetButtonImage(IRibbonControl control)
{
var mailItem = GetMailItemBasedOnControl(control);
if (mailItem == null)
return Resources.icon;
return Helpers.GetUserProperty<bool>(GetMailItemBasedOnControl(control), Constants.EMAIL_REPORTED)
? Resources.icon_reported
: Resources.icon;
}
public String GetGroupLabel(IRibbonControl control)
{
return Resources.GroupLabel;
}
private MailItem GetMailItemBasedOnControl(IRibbonControl control)
{
Object selectedObjected = null;
if (control.Id.Equals("buttonMailReport"))
selectedObjected = Globals.ThisAddIn.Application.ActiveExplorer().Selection[1];
else if (control.Id.Equals("buttonReadReport"))
selectedObjected = Globals.ThisAddIn.Application.ActiveInspector().CurrentItem;
if (selectedObjected != null && selectedObjected is MailItem)
return selectedObjected as MailItem;
return null;
}
#region IRibbonExtensibility Members
public string GetCustomUI(string ribbonID)
{
return GetResourceText("Schillings.SwordPhish.Ribbon.xml");
}
#endregion
#region Ribbon Callbacks
//Create callback methods here. For more information about adding callback methods, visit https://go.microsoft.com/fwlink/?LinkID=271226
public void Ribbon_Load(Office.IRibbonUI ribbonUI)
{
this.ribbon = ribbonUI;
Globals.ThisAddIn.Ribbon = ribbonUI;
}
#endregion
#region Helpers
private static string GetResourceText(string resourceName)
{
Assembly asm = Assembly.GetExecutingAssembly();
string[] resourceNames = asm.GetManifestResourceNames();
for (int i = 0; i < resourceNames.Length; ++i)
{
if (string.Compare(resourceName, resourceNames[i], StringComparison.OrdinalIgnoreCase) == 0)
{
using (StreamReader resourceReader = new StreamReader(asm.GetManifestResourceStream(resourceNames[i])))
{
if (resourceReader != null)
{
return resourceReader.ReadToEnd();
}
}
}
}
return null;
}
#endregion
}
}
| 32.273381 | 144 | 0.608783 | [
"Apache-2.0"
] | Schillings/SwordPhish | Schillings.SwordPhish/Ribbon.cs | 4,488 | C# |
// <auto-generated />
using System;
using CourseManagement.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
namespace CourseManagement.Data.Migrations
{
[DbContext(typeof(ApplicationDbContext))]
[Migration("20210917141041_Second")]
partial class Second
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("Relational:MaxIdentifierLength", 128)
.HasAnnotation("ProductVersion", "5.0.9")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("CourseManagement.Data.Models.ApplicationUser", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<DateTime>("CreatedOn")
.HasColumnType("datetime2");
b.Property<string>("FirstName")
.HasColumnType("nvarchar(max)");
b.Property<decimal?>("Geo_Lat")
.HasColumnType("decimal(18,2)");
b.Property<decimal?>("Geo_Lng")
.HasColumnType("decimal(18,2)");
b.Property<bool>("IsBlocked")
.HasColumnType("bit");
b.Property<string>("LastName")
.HasColumnType("nvarchar(max)");
b.Property<string>("Password")
.HasColumnType("nvarchar(max)");
b.Property<int>("RoleId")
.HasColumnType("int");
b.Property<string>("Token")
.HasColumnType("nvarchar(max)");
b.Property<DateTime?>("UpdatedOn")
.HasColumnType("datetime2");
b.Property<string>("Username")
.HasColumnType("nvarchar(450)");
b.HasKey("Id");
b.HasIndex("RoleId");
b.HasIndex("Username")
.IsUnique()
.HasFilter("[Username] IS NOT NULL");
b.ToTable("Users");
b.HasData(
new
{
Id = 1,
CreatedOn = new DateTime(2021, 9, 17, 14, 10, 40, 232, DateTimeKind.Utc).AddTicks(5978),
FirstName = "Admin",
IsBlocked = false,
LastName = "Adminov",
Password = "Sb123456",
RoleId = 2,
Username = "admin@test.com"
});
});
modelBuilder.Entity("CourseManagement.Data.Models.Course", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<int>("AuthorId")
.HasColumnType("int");
b.Property<string>("Content")
.HasColumnType("nvarchar(max)");
b.Property<byte[]>("ContentBytes")
.HasColumnType("varbinary(max)");
b.Property<DateTime?>("ContentBytesCreatedOn")
.HasColumnType("datetime2");
b.Property<DateTime>("CreatedOn")
.HasColumnType("datetime2");
b.Property<double>("Rating")
.HasColumnType("float");
b.Property<string>("Summary")
.HasColumnType("nvarchar(max)");
b.Property<string>("Title")
.HasColumnType("nvarchar(max)");
b.Property<DateTime?>("UpdatedOn")
.HasColumnType("datetime2");
b.HasKey("Id");
b.HasIndex("AuthorId");
b.ToTable("Courses");
});
modelBuilder.Entity("CourseManagement.Data.Models.FavoriteCourse", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<int>("CourseId")
.HasColumnType("int");
b.Property<int>("UserId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("CourseId");
b.HasIndex("UserId");
b.ToTable("FavoriteCourses");
});
modelBuilder.Entity("CourseManagement.Data.Models.Role", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("Name")
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("Roles");
b.HasData(
new
{
Id = 1,
Name = "User"
},
new
{
Id = 2,
Name = "Admin"
});
});
modelBuilder.Entity("CourseManagement.Data.Models.UserCourse", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<int>("CourseId")
.HasColumnType("int");
b.Property<int>("State")
.HasColumnType("int");
b.Property<int>("UserId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("CourseId");
b.HasIndex("UserId");
b.ToTable("UserCourses");
});
modelBuilder.Entity("CourseManagement.Data.Models.ApplicationUser", b =>
{
b.HasOne("CourseManagement.Data.Models.Role", "Role")
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.OwnsMany("CourseManagement.Data.Models.RefreshToken", "RefreshTokens", b1 =>
{
b1.Property<int>("ApplicationUserId")
.HasColumnType("int");
b1.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b1.Property<DateTime>("Created")
.HasColumnType("datetime2");
b1.Property<string>("CreatedByIp")
.HasColumnType("nvarchar(max)");
b1.Property<DateTime>("Expires")
.HasColumnType("datetime2");
b1.Property<string>("ReplacedByToken")
.HasColumnType("nvarchar(max)");
b1.Property<DateTime?>("Revoked")
.HasColumnType("datetime2");
b1.Property<string>("RevokedByIp")
.HasColumnType("nvarchar(max)");
b1.Property<string>("Token")
.HasColumnType("nvarchar(max)");
b1.HasKey("ApplicationUserId", "Id");
b1.ToTable("RefreshToken");
b1.WithOwner()
.HasForeignKey("ApplicationUserId");
});
b.Navigation("RefreshTokens");
b.Navigation("Role");
});
modelBuilder.Entity("CourseManagement.Data.Models.Course", b =>
{
b.HasOne("CourseManagement.Data.Models.ApplicationUser", "Author")
.WithMany("Courses")
.HasForeignKey("AuthorId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Author");
});
modelBuilder.Entity("CourseManagement.Data.Models.FavoriteCourse", b =>
{
b.HasOne("CourseManagement.Data.Models.Course", "Course")
.WithMany("Favorites")
.HasForeignKey("CourseId")
.OnDelete(DeleteBehavior.NoAction)
.IsRequired();
b.HasOne("CourseManagement.Data.Models.ApplicationUser", "User")
.WithMany("Favorites")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.NoAction)
.IsRequired();
b.Navigation("Course");
b.Navigation("User");
});
modelBuilder.Entity("CourseManagement.Data.Models.UserCourse", b =>
{
b.HasOne("CourseManagement.Data.Models.Course", "Course")
.WithMany("UserCourses")
.HasForeignKey("CourseId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("CourseManagement.Data.Models.ApplicationUser", "User")
.WithMany("UserCourses")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Course");
b.Navigation("User");
});
modelBuilder.Entity("CourseManagement.Data.Models.ApplicationUser", b =>
{
b.Navigation("Courses");
b.Navigation("Favorites");
b.Navigation("UserCourses");
});
modelBuilder.Entity("CourseManagement.Data.Models.Course", b =>
{
b.Navigation("Favorites");
b.Navigation("UserCourses");
});
#pragma warning restore 612, 618
}
}
}
| 36.755418 | 133 | 0.440954 | [
"MIT"
] | ewgeni-dinew/Course-Management | CourseManagement_BE/CourseManagement.Data/Migrations/20210917141041_Second.Designer.cs | 11,874 | C# |
#region copyright
/*
* This code is from the Lawo/ember-plus GitHub repository and is licensed with
*
* Boost Software License - Version 1.0 - August 17th, 2003
*
* Permission is hereby granted, free of charge, to any person or organization
* obtaining a copy of the software and accompanying documentation covered by
* this license (the "Software") to use, reproduce, display, distribute,
* execute, and transmit the Software, and to prepare derivative works of the
* Software, and to permit third-parties to whom the Software is furnished to
* do so, all subject to the following:
*
* The copyright notices in the Software and this entire statement, including
* the above license grant, this restriction and the following disclaimer,
* must be included in all copies of the Software, in whole or in part, and
* all derivative works of the Software, unless such copies or derivative
* works are solely in the form of machine-executable object code generated by
* a source language processor.
*
* 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT
* SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
* FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
#endregion
using System.Collections.Generic;
using EmberPlusProviderClassLib.Model.Parameters;
namespace EmberPlusProviderClassLib.Model
{
public class Signal
{
public Signal(int number, StringParameter labelParameter)
{
Number = number;
LabelParameter = labelParameter;
}
public int Number { get; }
public StringParameter LabelParameter { get; }
public IEnumerable<Signal> ConnectedSources => _connectedSources;
public int ConnectedSourcesCount => _connectedSources.Count;
public bool HasConnectedSources => _connectedSources.Count > 0;
public void Connect(IEnumerable<Signal> sources, bool isAbsolute)
{
if (isAbsolute)
{
_connectedSources.Clear();
_connectedSources.AddRange(sources);
}
else
{
foreach(var source in sources)
{
if(_connectedSources.Contains(source) == false)
_connectedSources.Add(source);
}
}
}
public void Disconnect(IEnumerable<Signal> sources)
{
foreach(var signal in sources)
_connectedSources.Remove(signal);
}
readonly List<Signal> _connectedSources = new List<Signal>();
}
} | 37.230769 | 79 | 0.676309 | [
"BSD-3-Clause"
] | IrisBroadcast/LarkspurEmberPlusProvider | src/EmberPlusProviderClassLib/Model/Signal.cs | 2,906 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.ComponentModel.DataAnnotations;
using System.Xml;
using System.Configuration;
namespace Marvin.Persistence.ModelMaps
{
/// <summary>
/// Classe que realiza o mapeamento entre uma Entidade e uma tabela do banco.
/// </summary>
public class ModelMap
{
/// <summary>
/// Dicionário estático de entidades mapeadas
/// </summary>
private static Dictionary<Type, ModelMap> _modelsMap = new Dictionary<Type, ModelMap>();
/// <summary>
/// Retorna um mapeamento da entidade em questão
/// </summary>
/// <param name="type">Tipo da entidade a ser mapeada</param>
/// <returns>Mapeamento da entidade</returns>
public static ModelMap GetModelMap(Type type)
{
ModelMap modelMap = null;
if (_modelsMap.ContainsKey(type))
modelMap = _modelsMap[type];
else
{
try
{
modelMap = LoadModelXml(type);
if (modelMap == null)
modelMap = LoadModelAttributes(type);
if (modelMap != null)
{
modelMap._baseModelMap = GetModelMap(type.BaseType);
_modelsMap.Add(type, modelMap);
if (modelMap.InheritanceMode == DataAnnotations.ERBridge.InheritanceMode.UniqueTable)
{
if (modelMap._baseModelMap == null && type.BaseType.IsSubclassOf(typeof(Layers.Model)))
_modelsMap.Add(type.BaseType, modelMap);
}
}
}
catch (Exception ex)
{
Commons.Utilities.Logger.Error(ex);
}
}
return modelMap;
}
/// <summary>
/// Preenche o mapeamentos das colunas da entidade
/// </summary>
/// <param name="type">Tipo da entidade</param>
/// <param name="modelMap">Mapeamento da entidade</param>
public static void FillColumnMap(Type type, ModelMap modelMap)
{
foreach (System.Reflection.PropertyInfo property in type.GetProperties())
{
object[] att = property.GetCustomAttributes(typeof(DataAnnotations.ERBridge.Column), true);
DataAnnotations.ERBridge.Column columnAtt = (att != null && att.Length > 0) ? (DataAnnotations.ERBridge.Column)att[0] : null;
att = property.GetCustomAttributes(typeof(DataAnnotations.ERBridge.Reference), true);
DataAnnotations.ERBridge.Reference referenceAtt = (att != null && att.Length > 0) ? (DataAnnotations.ERBridge.Reference)att[0] : null;
att = property.GetCustomAttributes(typeof(DataAnnotations.ERBridge.CollectionReference), true);
DataAnnotations.ERBridge.CollectionReference collectionAtt = (att != null && att.Length > 0) ? (DataAnnotations.ERBridge.CollectionReference)att[0] : null;
att = property.GetCustomAttributes(typeof(KeyAttribute), true);
KeyAttribute keyAtt = (att != null && att.Length > 0) ? (KeyAttribute)att[0] : null;
if (columnAtt != null)
{
ColumnMap columnMap = new ColumnMap(property.Name, columnAtt.Name, columnAtt.DataType, columnAtt.AutoIncremented, columnAtt.SequenceName, columnAtt.Required, (keyAtt != null), (referenceAtt != null), columnAtt.Length, columnAtt.Precision);
modelMap.ColumnsMap.Add(columnMap.Property, columnMap);
if (columnMap.IsReference)
{
ReferenceMapInfo referenceMap = new ReferenceMapInfo(property.Name, property.PropertyType, referenceAtt.ReferenceKey, referenceAtt.FetchType);
modelMap.ReferencesMap.Add(referenceMap.Property, referenceMap);
modelMap.Columns.Add(columnMap.Column, columnMap.Property + "." + referenceMap.ReferenceKey);
modelMap.ColumnsMap.Add(columnMap.Property + "." + referenceMap.ReferenceKey, columnMap);
if (columnMap.IsKey)
modelMap.Keys.Add(columnMap.Property + "." + referenceMap.ReferenceKey);
}
else
{
modelMap.Columns.Add(columnMap.Column, columnMap.Property);
if (columnMap.IsKey)
modelMap.Keys.Add(columnMap.Property);
}
}
if (collectionAtt != null)
{
Type itemType = (property.PropertyType.IsGenericType) ? property.PropertyType.GetGenericArguments()[0] : null;
if (itemType != null)
{
CollectionReferenceMapInfo collectionMap = new CollectionReferenceMapInfo(property.Name, itemType, collectionAtt.ItemReferenceKey, collectionAtt.FetchType, collectionAtt.AssociationTableName, collectionAtt.MainColumnKey, collectionAtt.SecundaryColumnKey);
modelMap.CollectionsReferencesMap.Add(property.Name, collectionMap);
}
}
}
}
public static Dictionary<string, object> GetModelValues<TModel>(TModel model)
{
//TODO:Tratar exceções
Type modelType = model.GetType();
ModelMap modelMap = ModelMap.GetModelMap(modelType);
Dictionary<string, object> modelValues = new Dictionary<string, object>();
foreach (string propertyName in modelMap.GetPropertiesNamesList())
{
try
{
object value = modelType.GetProperty(propertyName).GetValue(model, null);
if (value != null && modelMap.GetColumnMap(propertyName).DataType == DataAnnotations.ERBridge.DataType.Xml)
{
XmlDocument xml = new XmlDocument();
xml.InnerXml = Commons.Utilities.ClassToXML.SerializeObject(value, propertyName);
value = xml.FirstChild.InnerXml;
}
else if (modelMap.GetColumnMap(propertyName).DataType == DataAnnotations.ERBridge.DataType.DateTime && DateTime.MinValue.Equals(value))
value = null;
ReferenceMapInfo referenceMap = modelMap.GetReferencesMap(propertyName);
if (value != null && referenceMap != null)
{
object keyValue = value.GetType().GetProperty(referenceMap.ReferenceKey).GetValue(value, null);
modelValues.Add(propertyName + "." + referenceMap.ReferenceKey, keyValue);
}
else
{
modelValues.Add(propertyName, value);
}
}
catch (Exception ex){
Commons.Utilities.Logger.Error(ex);
}
}
return modelValues;
}
private static ModelMap LoadModelXml(Type type)
{
try
{
Config.Settings essentialsSettings = (Config.Settings)ConfigurationManager.GetSection("essentialsSettings");
XmlDocument xml = new XmlDocument();
xml.Load(essentialsSettings.XmlModelsPath);
XmlNode modelNode = xml.SelectSingleNode("/Models/Model[@type='" + type.FullName + "']");
modelNode = (modelNode == null) ? xml.SelectSingleNode("/Models/Model[@baseModelType='" + type.FullName + "']") : modelNode;
if (modelNode != null)
{
ModelMap modelMap = new ModelMap(table: modelNode.Attributes["table"].Value);
if (modelNode.Attributes["dataBaseName"] != null)
modelMap._databaseName = modelNode.Attributes["dataBaseName"].Value;
if (modelNode.Attributes["inheritanceMode"] != null && modelNode.Attributes["inheritanceMode"].Value == "JoinTables")
{
modelMap.InheritanceMode = DataAnnotations.ERBridge.InheritanceMode.JoinTables;
modelMap.ParentTableReferenceColumn = modelNode.Attributes["parentTableReferenceColumn"].Value;
}
//Colunas
foreach (XmlNode columnNode in modelNode.SelectNodes("ColumnMap"))
{
if (type.GetProperty(columnNode.Attributes["property"].Value) != null)
{
ColumnMap columnMap = new ColumnMap(
property: columnNode.Attributes["property"].Value,
column: columnNode.Attributes["column"].Value,
dataType: (DataAnnotations.ERBridge.DataType)Enum.Parse(typeof(DataAnnotations.ERBridge.DataType),
columnNode.Attributes["dbType"].Value),
isAutoIncremented: (columnNode.Attributes["isAutoIncremented"] != null ? bool.Parse(columnNode.Attributes["isAutoIncremented"].Value) : false),
sequenceName: (columnNode.Attributes["sequenceName"] != null ? columnNode.Attributes["sequenceName"].Value : null),
isRequired: (columnNode.Attributes["isRequired"] != null ? bool.Parse(columnNode.Attributes["isRequired"].Value) : false),
isKey: (columnNode.Attributes["isKey"] != null ? bool.Parse(columnNode.Attributes["isKey"].Value) : false),
isReference: (columnNode.Attributes["isReference"] != null ? bool.Parse(columnNode.Attributes["isReference"].Value) : false));
modelMap.ColumnsMap.Add(columnMap.Property, columnMap);
if (columnMap.IsKey)
modelMap.Keys.Add(columnMap.Property);
//Referências
if (columnMap.IsReference)
{
XmlNode referenceNode = modelNode.SelectSingleNode("ReferenceMap[@property='" + columnMap.Property + "']");
ReferenceMapInfo referenceMap = new ReferenceMapInfo(
property: referenceNode.Attributes["property"].Value,
referenceKey: referenceNode.Attributes["referenceKey"].Value,
fetchType: columnNode.Attributes["fetchType"] != null ? (DataAnnotations.ERBridge.Fetch)Enum.Parse(typeof(DataAnnotations.ERBridge.Fetch), columnNode.Attributes["fetchType"].Value) : DataAnnotations.ERBridge.Fetch.LAZY,
referencedModelType: type.GetProperty(referenceNode.Attributes["property"].Value).PropertyType
);
modelMap.ReferencesMap.Add(referenceMap.Property, referenceMap);
modelMap.ColumnsMap.Add(columnMap.Property + "." + referenceMap.ReferenceKey, columnMap);
modelMap.Columns.Add(columnMap.Column, columnMap.Property + "." + referenceMap.ReferenceKey);
}
else
{
modelMap.Columns.Add(columnMap.Column, columnMap.Property);
}
}
}
//Coleções
foreach (XmlNode collectionNode in modelNode.SelectNodes("ColletionReferenceMap"))
{
if (type.GetProperty(collectionNode.Attributes["property"].Value) != null)
{
System.Reflection.PropertyInfo property = type.GetProperty(collectionNode.Attributes["property"].Value);
Type itemType = (property.PropertyType.IsGenericType) ? property.PropertyType.GetGenericArguments()[0] : null;
if (itemType != null)
{
CollectionReferenceMapInfo collectionMap = new CollectionReferenceMapInfo(
property: property.Name,
collectionItemType: itemType,
itemReferenceKey: collectionNode.Attributes["itemReferenceKey"].Value,
collectionFetchType: collectionNode.Attributes["fetchType"] != null ? (DataAnnotations.ERBridge.Fetch)Enum.Parse(typeof(DataAnnotations.ERBridge.Fetch), collectionNode.Attributes["fetchType"].Value) : DataAnnotations.ERBridge.Fetch.LAZY,
associationTableName: (collectionNode.Attributes["associationTable"] != null ? collectionNode.Attributes["associationTable"].Value : null),
mainColumnKey: (collectionNode.Attributes["mainColumnKey"] != null ? collectionNode.Attributes["mainColumnKey"].Value : null),
secundaryColumnKey: (collectionNode.Attributes["secundaryColumnKey"] != null ? collectionNode.Attributes["secundaryColumnKey"].Value : null)
);
modelMap.CollectionsReferencesMap.Add(property.Name, collectionMap);
}
}
}
//Procedures
foreach (XmlNode procedureNode in modelNode.SelectNodes("ProcedureMap"))
{
ProcedureMapInfo procedureMap = new ProcedureMapInfo(procedureNode.Attributes["name"].Value);
foreach (XmlNode parameterNode in procedureNode.SelectNodes("Parameter"))
{
ProcedureParameter parameter = new ProcedureParameter();
parameter.Name = parameterNode.Attributes["name"].Value;
parameter.DataType = (DataAnnotations.ERBridge.DataType)Enum.Parse(typeof(DataAnnotations.ERBridge.DataType), parameterNode.Attributes["dbType"].Value);
parameter.DefaultValue = parameterNode.Attributes["defaultValue"] != null ? parameterNode.Attributes["defaultValue"].Value : null;
parameter.Direction = parameterNode.Attributes["direction"] != null ? (ParameterDirection)Enum.Parse(typeof(ParameterDirection), parameterNode.Attributes["direction"].Value): ParameterDirection.Input;
parameter.Size = parameterNode.Attributes["size"] != null ? int.Parse(parameterNode.Attributes["size"].Value) : 0;
procedureMap.Parameters.Add(parameterNode.Attributes["field"].Value, parameter);
}
modelMap.ProceduresMap.Add(procedureNode.Attributes["procedureKey"].Value, procedureMap);
}
return modelMap;
}
}
catch(Exception ex)
{
Console.Write(ex);
}
return null;
}
private static ModelMap LoadModelAttributes(Type type)
{
object[] att = type.GetCustomAttributes(typeof(DataAnnotations.ERBridge.Table), true);
DataAnnotations.ERBridge.Table tableAtt = (att != null && att.Length > 0) ? (DataAnnotations.ERBridge.Table)att[0] : null;
ModelMap baseModelMap = GetModelMap(type.BaseType);
if (tableAtt != null || baseModelMap != null)
{
ModelMap modelMap = new ModelMap();
if (tableAtt != null)
{
modelMap._table = tableAtt.Name;
modelMap._databaseName = tableAtt.DatabaseName;
if (tableAtt.InheritanceMode == DataAnnotations.ERBridge.InheritanceMode.JoinTables && baseModelMap != null)
{
modelMap.InheritanceMode = tableAtt.InheritanceMode;
modelMap.ParentTableReferenceColumn = tableAtt.ParentTableReferenceColumn;
}
}
FillColumnMap(type, modelMap);
att = type.GetCustomAttributes(typeof(DataAnnotations.ERBridge.Procedure), true);
if (att != null)
{
foreach (DataAnnotations.ERBridge.Procedure proc in att)
{
if (!modelMap.ProceduresMap.ContainsKey(proc.ProcedureKey))
modelMap.ProceduresMap.Add(proc.ProcedureKey, new ProcedureMapInfo(proc.Name));
}
}
att = type.GetCustomAttributes(typeof(DataAnnotations.ERBridge.ProcedureParameter), true);
if (att != null)
{
foreach (DataAnnotations.ERBridge.ProcedureParameter param in att)
{
if (!modelMap.ProceduresMap[param.ProcedureKey].Parameters.ContainsKey(param.Field))
modelMap.ProceduresMap[param.ProcedureKey].Parameters.Add(param.Field, new ProcedureParameter() { Name = param.Name, DataType = param.DataType, DefaultValue = param.DefaultValue, Direction = param.Direction, Size = param.Size });
}
}
return modelMap;
}
return null;
}
/// <summary>
/// Nome da tabela no banco de dados
/// </summary>
private string _table;
/// <summary>
/// Retorna o nome da tabela no banco de dados
/// </summary>
public string Table
{
get { return (string.IsNullOrEmpty(_table) && _baseModelMap != null) ? _baseModelMap._table : _table; }
}
/// <summary>
/// Armazena o nome do banco de dados em que a tabela se encontra.
/// </summary>
private string _databaseName;
/// <summary>
/// Devolve o nome do banco de dados em que a tabela se encontra.
/// </summary>
public string DatabaseName
{
get { return (string.IsNullOrEmpty(_databaseName) && _baseModelMap != null) ? _baseModelMap._databaseName : _databaseName; }
}
private DataAnnotations.ERBridge.InheritanceMode InheritanceMode { get; set; }
private string ParentTableReferenceColumn { get; set; }
protected Dictionary<string, ColumnMap> ColumnsMap { get; private set; }
protected Dictionary<string, string> Columns { get; private set; }
protected List<string> Keys { get; private set; }
protected Dictionary<string, ReferenceMapInfo> ReferencesMap { get; private set; }
protected Dictionary<string, CollectionReferenceMapInfo> CollectionsReferencesMap { get; private set; }
protected Dictionary<string, ProcedureMapInfo> ProceduresMap { get; private set; }
private ModelMap _baseModelMap;
/// <summary>
/// Cria um novo mapeamento para uma entidade
/// </summary>
/// <param name="table">Nome da tabela</param>
/// <param name="columnsMap">Dicionário com mapeamento das colunas "Nome da propriedade" x ColumnMap</param>
/// <param name="columns">Dicionário coluna x propriedade</param>
/// <param name="keys">Lista de propriedades chaves da entidade</param>
/// <param name="referencesMap">Dicionário com mapa de referências da entidade "Nome da propriedade" x ReferenceMapInfo</param>
/// <param name="collectionsReferencesMap">Dicionário com o mapa de referÊncias das coleções da entidade "Nome da propriedade" x CollectionReferenceMapInfo</param>
/// <param name="databaseName">Nome do banco onde a tabela está armazenada</param>
private ModelMap(string table = null, Dictionary<string, ColumnMap> columnsMap = null, Dictionary<string, string> columns = null, List<string> keys = null, Dictionary<string, ReferenceMapInfo> referencesMap = null, Dictionary<string, CollectionReferenceMapInfo> collectionsReferencesMap = null, string databaseName = null, Dictionary<string, ProcedureMapInfo> proceduresMap = null, DataAnnotations.ERBridge.InheritanceMode inheritanceMode = DataAnnotations.ERBridge.InheritanceMode.NoInheritance, string parentTableReferenceColumn = null)
{
_table = table;
_databaseName = databaseName;
ColumnsMap = columnsMap == null ? new Dictionary<string, ColumnMap>() : columnsMap;
Columns = columns == null ? new Dictionary<string, string>() : columns;
Keys = keys == null ? new List<string>() : keys;
ReferencesMap = referencesMap == null ? new Dictionary<string, ReferenceMapInfo>() : referencesMap;
CollectionsReferencesMap = collectionsReferencesMap == null ? new Dictionary<string, CollectionReferenceMapInfo>() : collectionsReferencesMap;
ProceduresMap = proceduresMap == null ? new Dictionary<string, ProcedureMapInfo>() : proceduresMap;
InheritanceMode = inheritanceMode;
ParentTableReferenceColumn = parentTableReferenceColumn;
}
/// <summary>
/// Retorna o conjunto de parâmetros da procedure com os respectivos valores
/// </summary>
/// <param name="procudureMapKey">Chave do Mapa da procedure</param>
/// <param name="fieldParameters">Dicionários de campos e valores</param>
/// <returns>Dicionários de parâmetros e valores</returns>
public List<ProcedureParameter> GetProcedureParameters(string procudureMapKey, Dictionary<string, object> fieldParameters)
{
//TODO:Tratar exceções
List<ProcedureParameter> procedureParameters = new List<ProcedureParameter>();
ProcedureMapInfo procedureMap = GetProcedureMap(procudureMapKey);
foreach (string field in procedureMap.Parameters.Keys)
{
ProcedureParameter parameter = procedureMap.Parameters[field];
if ((fieldParameters != null && fieldParameters.ContainsKey(field)) || parameter.DefaultValue != null || parameter.Direction != ParameterDirection.Input)
{
ProcedureParameter newParameter = new ProcedureParameter() { Name = parameter.Name, DataType = parameter.DataType, Value = parameter.DefaultValue, Direction = parameter.Direction, Size = parameter.Size };
if (fieldParameters != null && fieldParameters.ContainsKey(field) && fieldParameters[field] != null)
if (fieldParameters[field].GetType() != typeof(DateTime) || Convert.ToDateTime(fieldParameters[field]) != DateTime.MinValue)
newParameter.Value = fieldParameters[field];
procedureParameters.Add(newParameter);
}
}
return procedureParameters;
}
public ProcedureMapInfo GetProcedureMap(string procedureKey)
{
if (ProceduresMap.ContainsKey(procedureKey))
return ProceduresMap[procedureKey];
if (_baseModelMap != null)
return _baseModelMap.GetProcedureMap(procedureKey);
return null;
}
public List<ProcedureMapInfo> GetProceduresMapList() {
List<ProcedureMapInfo> list = ProceduresMap.Values.ToList();
if (_baseModelMap != null)
list.AddRange(_baseModelMap.GetProceduresMapList());
return list;
}
public ColumnMap GetColumnMap(string propertyName)
{
if (ColumnsMap.ContainsKey(propertyName))
return ColumnsMap[propertyName];
if (_baseModelMap != null)
return _baseModelMap.GetColumnMap(propertyName);
return null;
}
public ColumnMap GetMappedColumnMap(string propertyName)
{
ColumnMap mappedColumnMap = GetColumnMap(propertyName);
if (mappedColumnMap == null)
{
string[] propertyParts = propertyName.Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries);
if (propertyParts.Length > 1)
{
ReferenceMapInfo reference = GetReferencesMapList().FirstOrDefault(r => r.Property == propertyParts[0]);
if (reference != null)
{
ModelMap referenceModelMap = ModelMap.GetModelMap(reference.ReferencedModelType);
if (referenceModelMap != null)
mappedColumnMap = referenceModelMap.GetColumnMap(propertyName.Remove(0, (propertyParts[0] + ".").Length));
}
}
}
return mappedColumnMap;
}
public List<ColumnMap> GetColumnsMapList()
{
List<ColumnMap> list = ColumnsMap.Values.Distinct().ToList();
if (_baseModelMap != null)
list.AddRange(_baseModelMap.GetColumnsMapList());
return list;
}
public string GetPropertyName(string columnName)
{
if (Columns.ContainsKey(columnName))
return Columns[columnName];
if (_baseModelMap != null)
return _baseModelMap.GetPropertyName(columnName);
return null;
}
public string GetMappedPropertyName(string column)
{
string mappedPropertyName = GetPropertyName(column);
if (string.IsNullOrEmpty(mappedPropertyName))
{
string[] columnParts = column.Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries);
if (columnParts.Length > 1)
{
foreach (ReferenceMapInfo reference in GetReferencesMapList())
{
ModelMap referenceModelMap = ModelMap.GetModelMap(reference.ReferencedModelType);
if (referenceModelMap != null && (referenceModelMap.Table == columnParts[0] || columnParts[0] == reference.Property))
{
mappedPropertyName = reference.Property;
mappedPropertyName += "." + referenceModelMap.GetMappedPropertyName(column.Remove(0, (columnParts[0] + ".").Length));
break;
}
}
}
}
return mappedPropertyName;
}
public List<string> GetPropertiesNamesList()
{
List<string> list = ColumnsMap.Keys.ToList();
if (_baseModelMap != null)
list.AddRange(_baseModelMap.GetPropertiesNamesList());
return list;
}
public string GetColumnName(string propertyName)
{
ColumnMap columnMap = GetColumnMap(propertyName);
if (columnMap != null)
return columnMap.Column;
return null;
}
public List<string> ColumnsNamesList()
{
List<string> list = Columns.Keys.ToList();
if (_baseModelMap != null)
list.AddRange(_baseModelMap.ColumnsNamesList().Where(i => !list.Contains(i)));
return list;
}
public CollectionReferenceMapInfo GetCollectionReferenceMap(string collectionName)
{
if (CollectionsReferencesMap.ContainsKey(collectionName))
return CollectionsReferencesMap[collectionName];
if (_baseModelMap != null)
return _baseModelMap.GetCollectionReferenceMap(collectionName);
return null;
}
public List<CollectionReferenceMapInfo> GetCollectionsReferencesMapList()
{
List<CollectionReferenceMapInfo> list = CollectionsReferencesMap.Values.ToList();
if (_baseModelMap != null)
list.AddRange(_baseModelMap.GetCollectionsReferencesMapList());
return list;
}
public ReferenceMapInfo GetReferencesMap(string referenceName)
{
if (ReferencesMap.ContainsKey(referenceName))
return ReferencesMap[referenceName];
if (_baseModelMap != null)
return _baseModelMap.GetReferencesMap(referenceName);
return null;
}
public List<ReferenceMapInfo> GetReferencesMapList()
{
List<ReferenceMapInfo> list = ReferencesMap.Values.ToList();
if (_baseModelMap != null)
list.AddRange(_baseModelMap.GetReferencesMapList());
return list;
}
public List<string> GetKeys(){
List<string> list = new List<string>();
list.AddRange(Keys);
if (_baseModelMap != null)
list.AddRange(_baseModelMap.GetKeys().Where(i => !list.Contains(i)));
return list;
}
}
/// <summary>
/// Realiza o mapeamento entre um propriedade da entidade e uma coluna da tabela
/// </summary>
public class ColumnMap
{
#region Atributos e Propiedades
public string Property { get; private set; }
public string Column { get; private set; }
public DataAnnotations.ERBridge.DataType DataType { get; private set; }
public bool IsAutoIncremented { get; private set; }
public string SequenceName { get; private set; }
public bool IsRequired { get; private set; }
public bool IsKey { get; private set; }
public bool IsReference { get; private set; }
public int Length { get; private set; }
public int Precision { get; private set; }
#endregion
#region Construtores
/// <summary>
/// Cria uma nova estrutura de mapeamento entro a propriedade da entidade e uma coluna da tabela.
/// </summary>
/// <param name="property">Nome da propriedade</param>
/// <param name="column">Nome da coluna</param>
/// <param name="dataType">Tipo de dado da coluna</param>
/// <param name="isAutoIncremented">Define se a coluna é autoincrementada</param>
/// <param name="sequenceName">Nome da sequência da coluna</param>
/// <param name="isRequired">Define se a coluna é requerida</param>
/// <param name="isKey">Define se a coluna é uma chave da tebela</param>
/// <param name="isReference">Define a coluna é uma chave de refrência</param>
public ColumnMap(string property, string column, DataAnnotations.ERBridge.DataType dataType, bool isAutoIncremented = false, string sequenceName = null, bool isRequired = false, bool isKey = false, bool isReference = false, int length = 0, int precision = 0)
{
Property = property;
Column = column;
DataType = dataType;
IsAutoIncremented = isAutoIncremented;
SequenceName = sequenceName;
IsRequired = isRequired;
IsKey = isKey;
IsReference = isReference;
Length = length;
Precision = precision;
}
#endregion
}
/// <summary>
/// Armazena informações de mapeamento para referência entre tabelas.
/// </summary>
public class ReferenceMapInfo
{
#region Atributos e Propiedades
public string Property { get; private set; }
public Type ReferencedModelType { get; private set; }
public string ReferenceKey { get; private set; }
public DataAnnotations.ERBridge.Fetch FetchType { get; private set; }
#endregion
#region Construtores
/// <summary>
/// Cria um novo mapeamento de refrência entre entidades
/// </summary>
/// <param name="property">Nome da propriedade</param>
/// <param name="referencedModelType">Tipo da entidade referenciada</param>
/// <param name="referenceKey">Propriedade chave na entidade referênciada</param>
/// <param name="fetchType">Tipo de busca aplicada à entidade refrênciada</param>
public ReferenceMapInfo(string property, Type referencedModelType, string referenceKey, DataAnnotations.ERBridge.Fetch fetchType = DataAnnotations.ERBridge.Fetch.LAZY)
{
Property = property;
ReferencedModelType = referencedModelType;
ReferenceKey = referenceKey;
FetchType = fetchType;
}
#endregion
}
/// <summary>
/// Armazena informações de mapeamento para referência em uma coleção de entidades.
/// </summary>
public class CollectionReferenceMapInfo
{
#region Atributos e Propiedades
public string Property { get; private set; }
public Type CollectionItemType { get; private set; }
public DataAnnotations.ERBridge.Fetch FetchType { get; private set; }
public string ItemReferenceKey { get; private set; }
public string AssociationTableName { get; private set; }
public string MainColumnKey { get; private set; }
public string SecundaryColumnKey { get; private set; }
#endregion
#region Construtores
/// <summary>
/// Cria um novo mapeamento de referências em uma coleção de entidades.
/// </summary>
/// <param name="property">Nome da prpriedade</param>
/// <param name="collectionItemType">Tipo do item da coleção</param>
/// <param name="itemReferenceKey">Campo de referência dos itens da coleção para a entidade principal (quando não houver tabela de associação)</param>
/// <param name="collectionFetchType">Tipo de busca aplicada à coleção</param>
/// <param name="itemFetchType">Tipo de busca aplicada aos itens da coleção</param>
/// <param name="associationTableName">Tabela de associação multipla entre as entidades</param>
/// <param name="mainColumnKey">Nome da coluna chave que referencia a entidade principal (quando houver tabela de associação)</param>
/// <param name="secundaryColumnKey">Nome da coluna chave que referencia os itens da coleção (quando houver tabela de associação)</param>
public CollectionReferenceMapInfo(string property, Type collectionItemType, string itemReferenceKey, DataAnnotations.ERBridge.Fetch collectionFetchType = DataAnnotations.ERBridge.Fetch.LAZY, string associationTableName = null, string mainColumnKey = null, string secundaryColumnKey = null)
{
Property = property;
CollectionItemType = collectionItemType;
ItemReferenceKey = itemReferenceKey;
FetchType = collectionFetchType;
AssociationTableName = associationTableName;
MainColumnKey = mainColumnKey;
SecundaryColumnKey = secundaryColumnKey;
}
#endregion
}
/// <summary>
/// Mapeamento de procedures padrão da entidade
/// </summary>
public class ProcedureMapInfo
{
public string Name { get; private set; }
public Dictionary<string, ProcedureParameter> Parameters { get; private set; }
/// <summary>
/// Cria um novo mapeamento de precedures padrão da entidade
/// </summary>
/// <param name="name">Nome da preocedure</param>
/// <param name="parameters">Parâmetros da preocedure</param>
public ProcedureMapInfo(string name)
{
Name = name;
Parameters = new Dictionary<string, ProcedureParameter>();
}
}
public class ProcedureParameter
{
public string Name { get; set; }
public object DefaultValue { get; set; }
public object Value { get; set; }
public DataAnnotations.ERBridge.DataType DataType { get; set; }
public ParameterDirection Direction { get; set; }
public int Size { get; set; }
}
}
| 50.651452 | 546 | 0.584828 | [
"MIT"
] | viniciuscs84/Marvin | Core/Marvin/Persistence/ModelMaps.cs | 36,691 | C# |
using System;
using CoreGraphics;
using Foundation;
using UIKit;
namespace SimpleBackgroundTransfer {
public partial class SimpleBackgroundTransferViewController : UIViewController {
const string Identifier = "com.SimpleBackgroundTransfer.BackgroundSession";
const string DownloadUrlString = "https://atmire.com/dspace-labs3/bitstream/handle/123456789/7618/earth-map-huge.jpg";
public NSUrlSessionDownloadTask downloadTask;
public NSUrlSession session;
public SimpleBackgroundTransferViewController (IntPtr handle) : base (handle)
{
}
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
if (session == null)
session = InitBackgroundSession ();
// Perform any additional setup after loading the view, typically from a nib.
progressView.Progress = 0;
imageView.Hidden = false;
progressView.Hidden = true;
startButton.Clicked += Start;
// Force the app to crash
crashButton.Clicked += delegate {
string s = null;
s.ToString ();
};
}
void Start (object sender, EventArgs e)
{
if (downloadTask != null)
return;
using (var url = NSUrl.FromString (DownloadUrlString))
using (var request = NSUrlRequest.FromUrl (url)) {
downloadTask = session.CreateDownloadTask (request);
downloadTask.Resume ();
}
imageView.Hidden = true;
progressView.Hidden = false;
}
public NSUrlSession InitBackgroundSession ()
{
Console.WriteLine ("InitBackgroundSession");
using (var configuration = NSUrlSessionConfiguration.BackgroundSessionConfiguration (Identifier)) {
return NSUrlSession.FromConfiguration (configuration, new UrlSessionDelegate (this), null);
}
}
public UIProgressView ProgressView {
get { return progressView; }
}
public UIImageView ImageView {
get { return imageView; }
}
}
public class UrlSessionDelegate : NSUrlSessionDownloadDelegate
{
public SimpleBackgroundTransferViewController controller;
public UrlSessionDelegate (SimpleBackgroundTransferViewController controller)
{
this.controller = controller;
}
public override void DidWriteData (NSUrlSession session, NSUrlSessionDownloadTask downloadTask, long bytesWritten, long totalBytesWritten, long totalBytesExpectedToWrite)
{
Console.WriteLine ("Set Progress");
if (downloadTask == controller.downloadTask) {
float progress = totalBytesWritten / (float)totalBytesExpectedToWrite;
Console.WriteLine (string.Format ("DownloadTask: {0} progress: {1}", downloadTask, progress));
InvokeOnMainThread( () => {
controller.ProgressView.Progress = progress;
});
}
}
public override void DidFinishDownloading (NSUrlSession session, NSUrlSessionDownloadTask downloadTask, NSUrl location)
{
Console.WriteLine ("Finished");
Console.WriteLine ("File downloaded in : {0}", location);
NSFileManager fileManager = NSFileManager.DefaultManager;
var URLs = fileManager.GetUrls (NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomain.User);
NSUrl documentsDictionry = URLs [0];
NSUrl originalURL = downloadTask.OriginalRequest.Url;
NSUrl destinationURL = documentsDictionry.Append ("image1.png", false);
NSError removeCopy;
NSError errorCopy;
fileManager.Remove (destinationURL, out removeCopy);
bool success = fileManager.Copy (location, destinationURL, out errorCopy);
if (success) {
// we do not need to be on the main/UI thread to load the UIImage
UIImage image = UIImage.FromFile (destinationURL.Path);
InvokeOnMainThread (() => {
controller.ImageView.Image = image;
controller.ImageView.Hidden = false;
controller.ProgressView.Hidden = true;
});
} else {
Console.WriteLine ("Error during the copy: {0}", errorCopy.LocalizedDescription);
}
}
public override void DidCompleteWithError (NSUrlSession session, NSUrlSessionTask task, NSError error)
{
Console.WriteLine ("DidComplete");
if (error == null)
Console.WriteLine ("Task: {0} completed successfully", task);
else
Console.WriteLine ("Task: {0} completed with error: {1}", task, error.LocalizedDescription);
float progress = task.BytesReceived / (float)task.BytesExpectedToReceive;
InvokeOnMainThread (() => {
controller.ProgressView.Progress = progress;
});
controller.downloadTask = null;
}
public override void DidResume (NSUrlSession session, NSUrlSessionDownloadTask downloadTask, long resumeFileOffset, long expectedTotalBytes)
{
Console.WriteLine ("DidResume");
}
public override void DidFinishEventsForBackgroundSession (NSUrlSession session)
{
AppDelegate appDelegate = UIApplication.SharedApplication.Delegate as AppDelegate;
var handler = appDelegate.BackgroundSessionCompletionHandler;
if (handler != null) {
appDelegate.BackgroundSessionCompletionHandler = null;
handler ();
}
Console.WriteLine ("All tasks are finished");
}
}
}
| 31.273885 | 172 | 0.738493 | [
"Apache-2.0"
] | dannycabrera/monotouch-samples | SimpleBackgroundTransfer/SimpleBackgroundTransfer/SimpleBackgroundTransferViewController.cs | 4,910 | 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 macie-2017-12-19.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.Macie.Model
{
/// <summary>
/// Container for the parameters to the AssociateS3Resources operation.
/// Associates specified S3 resources with Amazon Macie Classic for monitoring and data
/// classification. If memberAccountId isn't specified, the action associates specified
/// S3 resources with Macie Classic for the current Macie Classic administrator account.
/// If memberAccountId is specified, the action associates specified S3 resources with
/// Macie Classic for the specified member account.
/// </summary>
public partial class AssociateS3ResourcesRequest : AmazonMacieRequest
{
private string _memberAccountId;
private List<S3ResourceClassification> _s3Resources = new List<S3ResourceClassification>();
/// <summary>
/// Gets and sets the property MemberAccountId.
/// <para>
/// The ID of the Amazon Macie Classic member account whose resources you want to associate
/// with Macie Classic.
/// </para>
/// </summary>
public string MemberAccountId
{
get { return this._memberAccountId; }
set { this._memberAccountId = value; }
}
// Check to see if MemberAccountId property is set
internal bool IsSetMemberAccountId()
{
return this._memberAccountId != null;
}
/// <summary>
/// Gets and sets the property S3Resources.
/// <para>
/// The S3 resources that you want to associate with Amazon Macie Classic for monitoring
/// and data classification.
/// </para>
/// </summary>
[AWSProperty(Required=true)]
public List<S3ResourceClassification> S3Resources
{
get { return this._s3Resources; }
set { this._s3Resources = value; }
}
// Check to see if S3Resources property is set
internal bool IsSetS3Resources()
{
return this._s3Resources != null && this._s3Resources.Count > 0;
}
}
} | 35.25 | 103 | 0.661601 | [
"Apache-2.0"
] | ChristopherButtars/aws-sdk-net | sdk/src/Services/Macie/Generated/Model/AssociateS3ResourcesRequest.cs | 2,961 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.KeyVault.Models
{
using System;
using System.Linq;
using System.Collections.Generic;
using Newtonsoft.Json;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Microsoft.Rest.Azure;
/// <summary>
/// The issuer for Key Vault certificate
/// </summary>
public partial class IssuerBundle
{
/// <summary>
/// Initializes a new instance of the IssuerBundle class.
/// </summary>
public IssuerBundle() { }
/// <summary>
/// Initializes a new instance of the IssuerBundle class.
/// </summary>
/// <param name="id">Identifier for the issuer object.</param>
/// <param name="provider">The issuer provider.</param>
/// <param name="credentials">The credentials to be used for the
/// issuer.</param>
/// <param name="organizationDetails">Details of the organization as
/// provided to the issuer.</param>
/// <param name="attributes">Attributes of the issuer object.</param>
public IssuerBundle(string id = default(string), string provider = default(string), IssuerCredentials credentials = default(IssuerCredentials), OrganizationDetails organizationDetails = default(OrganizationDetails), IssuerAttributes attributes = default(IssuerAttributes))
{
Id = id;
Provider = provider;
Credentials = credentials;
OrganizationDetails = organizationDetails;
Attributes = attributes;
}
/// <summary>
/// Gets identifier for the issuer object.
/// </summary>
[JsonProperty(PropertyName = "id")]
public string Id { get; private set; }
/// <summary>
/// Gets or sets the issuer provider.
/// </summary>
[JsonProperty(PropertyName = "provider")]
public string Provider { get; set; }
/// <summary>
/// Gets or sets the credentials to be used for the issuer.
/// </summary>
[JsonProperty(PropertyName = "credentials")]
public IssuerCredentials Credentials { get; set; }
/// <summary>
/// Gets or sets details of the organization as provided to the issuer.
/// </summary>
[JsonProperty(PropertyName = "org_details")]
public OrganizationDetails OrganizationDetails { get; set; }
/// <summary>
/// Gets or sets attributes of the issuer object.
/// </summary>
[JsonProperty(PropertyName = "attributes")]
public IssuerAttributes Attributes { get; set; }
}
}
| 36.8125 | 280 | 0.626486 | [
"MIT"
] | dnelly/azure-sdk-for-net | src/KeyVault/Microsoft.Azure.KeyVault/Generated/Models/IssuerBundle.cs | 2,945 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace MoAppDevAssignmentOne
{
public partial class ChatForm : Form
{
delegate void AddTextCallback(string inputMessage, string sender);
private static ChatForm chatForm = null;
NetCommunicationClass netCommunicationClass = new NetCommunicationClass();
NetCommunicationClass.TcpServerClass tcpServer;
NetCommunicationClass.TcpClientClass tcpClient;
NetCommunicationClass.UdpServerClass udpServer;
NetCommunicationClass.UdpClientClass udpClient;
int selectedRoleIndex;
public ChatForm()
{
InitializeComponent();
chatForm = this;
}
private void StartButton_Click(object sender, EventArgs e)
{
bool initialised = false;
switch (roleListBox.SelectedIndex)
{
case 0:
tcpServer = new NetCommunicationClass.TcpServerClass(remoteIpAddressTextBox, localPortNumberTextBox, outputTextBox, inputTextBox, this);
initialised = true;
break;
case 1:
tcpClient = new NetCommunicationClass.TcpClientClass(remoteIpAddressTextBox, remotePortNumberTextBox, outputTextBox, inputTextBox, this);
initialised = true;
break;
case 2:
udpServer = new NetCommunicationClass.UdpServerClass(remoteIpAddressTextBox, localPortNumberTextBox, outputTextBox, inputTextBox, this);
initialised = true;
break;
case 3:
udpClient = new NetCommunicationClass.UdpClientClass(remoteIpAddressTextBox, remotePortNumberTextBox, outputTextBox, inputTextBox, this);
initialised = true;
break;
default:
break;
}
if (initialised)
{
remoteIpAddressTextBox.Enabled = false;
remotePortNumberTextBox.Enabled = false;
localPortNumberTextBox.Enabled = false;
roleListBox.Enabled = false;
StartButton.Enabled = false;
}
}
public void SendButton_Click(object sender, EventArgs e)
{
}
private void InputTextBox_KeyPress(object sender, KeyPressEventArgs e)
{
}
public void AddText(string inputMessage, string sender)
{
if (this.outputTextBox.InvokeRequired)
{
AddTextCallback d = new AddTextCallback(AddText);
Invoke(d, new object[] { inputMessage, sender });
}
else
{
outputTextBox.Text = outputTextBox.Text + sender + inputMessage;
}
}
private void roleListBox_SelectedIndexChanged(object sender, EventArgs e)
{
selectedRoleIndex = roleListBox.SelectedIndex;
Console.WriteLine(roleListBox.SelectedIndex);
Console.WriteLine(roleListBox.SelectedItem);
}
}
}
| 33.04902 | 157 | 0.591813 | [
"MIT"
] | Truperton/Mobile-Application-Development-Assignment-One | chatForm.cs | 3,373 | 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("Backend")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("HP Inc.")]
[assembly: AssemblyProduct("Backend")]
[assembly: AssemblyCopyright("Copyright © HP Inc. 2017")]
[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("02255720-a754-4603-a7af-0d9b61d2fa19")]
// 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.666667 | 84 | 0.749263 | [
"MIT"
] | Alexisrecio/TorneoPredicciones | TorneoPredicciones/Backend/Properties/AssemblyInfo.cs | 1,359 | C# |
/*
MIT License
Copyright (c) 2022 ShuheiOi
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.
*/
namespace AdolescenceNovel
{
public class Notcompare : SystemCommand
{
// TODO: プロパティを宣言
// コマンド引数以外でも必要なら自由にここに追加して良い
// (NotcompareInitialなどのExecute()の第1引数Notcompare nowstateから参照可能)
// // description
public IValue statement;
public IValue line_num_false;
// public string arg;
// 状態を表す変数
private INotcompareContext state;
// TODO: コンストラクタに引数を追加
// 全ての引数が与えられる場合
// public Notcompare(IValue arg)
public Notcompare(IValue statement,IValue line_num_false)
{
// arg.Value(ref this.arg);
this.statement = statement;
this.line_num_false = line_num_false;
state = new NotcompareContext();
}
// TODO: 必要なら引数を省略したときのコンストラクタを同様に追加
public override bool Execute(ref int now, ref string nowFile, ref bool stop)
{
return state.Execute(this);
}
}
}
| 34.306452 | 85 | 0.67607 | [
"MIT"
] | ShuheiOi/AdolescenceNovel | Assets/Sources/Novel/Command/SystemCommand/notcompare/Notcompare.cs | 2,345 | C# |
// c:\program files (x86)\windows kits\10\include\10.0.18362.0\shared\ks.h(481,9)
using System;
using System.Runtime.InteropServices;
namespace DirectN
{
[StructLayout(LayoutKind.Sequential)]
public partial struct KSCOMPONENTID
{
public Guid Manufacturer;
public Guid Product;
public Guid Component;
public Guid Name;
public uint Version;
public uint Revision;
}
}
| 23.944444 | 82 | 0.670534 | [
"MIT"
] | bbday/DirectN | DirectN/DirectN/Generated/KSCOMPONENTID.cs | 433 | C# |
using Common.Classes.Encryption;
using ImplantSide.Classes.ErrorHandler;
using ImplantSide.Classes.Helpers;
using ImplantSide.Interfaces;
using SocksProxy.Classes.Extensions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
namespace ImplantSide.Classes.Comms
{
public class CommandCommunicationHandler
{
IEncryptionHelper _encryption;
public IImplantLog ImplantComms { get; set; }
AutoResetEvent Timeout = new AutoResetEvent(false);
SocksClientConfiguration _config;
Random _urlRandomizer = new Random(); //Yes yes this is a terrible random number generator
InternalErrorHandler _error;
bool? InitialConnectionSucceded;
public CommandCommunicationHandler(IEncryptionHelper encryption, SocksClientConfiguration config, InternalErrorHandler error)
{
_encryption = encryption;
this._config = config;
_error = error;
}
public List<byte> Send(String sessionPayload, List<byte> payload)
{
return Send(sessionPayload, "nochange", payload);
}
public List<byte> Send(String sessionPayload, String status, List<byte> payload)
{
if (String.IsNullOrWhiteSpace(status))
status = "nochange";
var sessionAndStatus = sessionPayload + ":" + status;
var encryptedSessionPayload = _encryption.Encrypt(UTF8Encoding.UTF8.GetBytes(sessionAndStatus).ToList());
var cookies = new CookieContainer();
WebClientEx wc = null;
if (!String.IsNullOrWhiteSpace(_config.HostHeader))
wc = new WebClientEx(cookies, _config.HostHeader, _config.InsecureSSL) { UserAgent = _config.UserAgent };
else
wc = new WebClientEx(cookies, _config.InsecureSSL) { UserAgent = _config.UserAgent };
if (_config.UseProxy)
if (null == _config.WebProxy)
wc.Proxy = HttpWebRequest.GetSystemWebProxy();
else
wc.Proxy = _config.WebProxy;
wc.Headers.Add("Host", _config.HostHeader);
cookies.Add(new Cookie($"{_config.SessionCookieName}", $"{encryptedSessionPayload}") { Domain = (!String.IsNullOrWhiteSpace(_config.HostHeader)) ? _config.HostHeader.Split(':')[0] : _config.URL.Host });
string encPayload = null;
if (null != payload && payload.Count > 0)
{
try
{
encPayload = _encryption.Encrypt(payload);
if (String.IsNullOrWhiteSpace(encPayload))
{
_error.LogError("Encrypted payload was null, it shouldn't be");
if (!InitialConnectionSucceded.HasValue)
InitialConnectionSucceded = false;
return null;
}
}
catch (Exception ex)
{
_error.LogError(ex.Message);
return null;
}
}
bool retryRequired = false;
Int32 retryInterval = 2000;
UInt16 retryCount = 0;
Guid errorId = Guid.NewGuid();
//This is only if the command channel has failed first time
bool errorQuestionAsked = false;
do
{
try
{
String response = null;
if (encPayload != null && encPayload.Count() > 4096)
response = wc.UploadString(BuildServerURI(), encPayload);
else
{
if (null != _config.HostHeader)
{
if (wc.Headers.AllKeys.Contains("Host"))
{
if (wc.Headers["Host"] != _config.HostHeader)
wc.Headers["Host"] = _config.HostHeader;
}
else
wc.Headers.Add("Host", _config.HostHeader);
}
if (payload != null && payload.Count() > 0)
cookies.Add(new Cookie($"{_config.PayloadCookieName}", $"{encPayload}") { Domain = (!String.IsNullOrWhiteSpace(_config.HostHeader)) ? _config.HostHeader.Split(':')[0] : _config.URL.Host });
response = wc.DownloadString(BuildServerURI());
}
if (!InitialConnectionSucceded.HasValue)
InitialConnectionSucceded = true;
if (null != response && response.Count() > 0)
return _encryption.Decrypt(response);
else
return new List<byte>();
}
catch (System.Net.WebException ex)
{
var lst = new List<String>();
if (WebExceptionAnalyzer.IsTransient(ex))
{
if (15 > retryCount++)
{
_error.LogError($"Error has occured and looks like it's transient going to retry in {retryInterval} milliseconds: {ex.Message}");
retryRequired = true;
if (retryInterval++ > 2)
retryInterval += retryInterval;
Timeout.WaitOne(retryInterval);
}
else
{
_error.FailError($"Kept trying but afraid error isn't going away {retryInterval} {ex.Message} {ex.Status.ToString()} {_config.CommandServerUI.ToString()} {errorId.ToString()}");
}
}
else if (sessionPayload == _config.CommandChannelSessionId)
{
retryRequired = true;
_error.LogError("Command Channel failed to connect" + ((errorQuestionAsked) ? ": retry interval " + retryInterval + "ms" : ""));
if (InitialConnectionSucceded.HasValue && !InitialConnectionSucceded.Value)
{
if (!RetryUntilFailure(ref retryCount, ref retryRequired, ref retryInterval))
{
lst.Add("Command channel re-tried connection 5 times giving up");
ReportErrorWebException(ex, lst, errorId);
}
}
}
else
{
//ReportErrorWebException(ex, lst, errorId);
if (HttpStatusCode.NotFound == ((HttpWebResponse)ex.Response).StatusCode)
{
if (_error.VerboseErrors)
_error.LogError(String.Format($"Connection on server has been killed"));
}
else
_error.LogError(String.Format($"Send to {_config.URL} failed with {ex.Message}"));
retryRequired = false;
return null;
}
}
} while (retryRequired);
if (!InitialConnectionSucceded.HasValue)
InitialConnectionSucceded = false;
return null;
}
bool RetryUntilFailure(ref UInt16 retryCount, ref bool retryRequired, ref Int32 retryInterval)
{
if (5 <= retryCount++)
{
retryRequired = false;
}
else
{
if (retryCount > 2)
retryInterval += retryInterval;
Timeout.WaitOne(retryInterval);
}
return true;
}
Uri BuildServerURI(String payload = null)
{
if (null != _config.Tamper)
return new Uri(_config.Tamper.TamperUri(_config.CommandServerUI, payload));
if (_config.URLPaths.Count() == 0 )
return new Uri(_config.URL, "Upload");
else
{
var path = _config.URLPaths[_urlRandomizer.Next(0, _config.URLPaths.Count())];
return new Uri(_config.URL, path);
}
}
void ReportErrorWebException(System.Net.WebException ex, List<String> lst, Guid errorId)
{
lst.Add(ex.Message);
lst.Add(ex.Status.ToString());
lst.Add(_config.CommandServerUI.ToString());
lst.Add(errorId.ToString());
_error.FailError(lst);
}
}
}
| 41.829493 | 217 | 0.491021 | [
"BSD-3-Clause"
] | FDlucifer/SharpSocks | SharpSocksImplant/SharpSocksImplantCore/Classes/Comms/CommandCommunicationHandler.cs | 9,079 | C# |
using System;
namespace _08.FuelTank
{
class Program
{
static void Main(string[] args)
{
string text = Console.ReadLine();
double litresFuel = double.Parse(Console.ReadLine());
switch (text)
{
case "Diesel":
if (litresFuel>=25)
{
Console.WriteLine("You have enough diesel.");
}
else
{
Console.WriteLine("Fill your tank with diesel!");
}
break;
case "Gasoline":
if (litresFuel >= 25)
{
Console.WriteLine("You have enough gasoline.");
}
else
{
Console.WriteLine("Fill your tank with gasoline!");
}
break;
case "Gas":
if (litresFuel >= 25)
{
Console.WriteLine("You have enough gas.");
}
else
{
Console.WriteLine("Fill your tank with gas!");
}
break;
default:
Console.WriteLine("Invalid fuel!");
break;
}
}
}
}
| 28.823529 | 75 | 0.338776 | [
"MIT"
] | dinikolaeva/Basics-CSharp | ConditionalStatements-Exe/ConditionalStatements-MoreExercises/08.FuelTank/Program.cs | 1,472 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using CoreSharp.Common.Attributes;
using CoreSharp.GraphQL.Configuration;
using GraphQL;
using GraphQL.Types;
using GraphQL.Utilities;
using DefaultValueAttribute = CoreSharp.Common.Attributes.DefaultValueAttribute;
namespace CoreSharp.GraphQL
{
public class AutoInputGraphType<TSourceType> : InputObjectGraphType<TSourceType>
where TSourceType : class
{
private readonly IGraphQLConfiguration _configuration;
private readonly ITypeConfiguration _typeConfiguration;
public AutoInputGraphType(IGraphQLConfiguration configuration)
{
_configuration = configuration;
_typeConfiguration = _configuration.GetModelConfiguration<TSourceType>();
Name = GetTypeName(typeof(TSourceType)) + "Input";
Metadata["Type"] = typeof(TSourceType);
var properties = GetRegisteredProperties().ToList();
foreach (var propertyInfo in properties)
{
var fieldConfiguration = _typeConfiguration.GetFieldConfiguration(propertyInfo.Name);
var field = Field(
type: propertyInfo.PropertyType.ToGraphType(),
name: fieldConfiguration?.FieldName ?? GetFieldName(propertyInfo),
description: propertyInfo.Description(),
deprecationReason: propertyInfo.ObsoleteMessage()
);
field.DefaultValue = (propertyInfo.GetCustomAttributes(typeof(DefaultValueAttribute), false).FirstOrDefault() as DefaultValueAttribute)?.Value;
field.Metadata["PropertyInfo"] = propertyInfo;
}
}
private static string GetFieldName(PropertyInfo property)
{
if (!property.PropertyType.Namespace.StartsWith("System") && property.PropertyType.IsGenericType)
{
return GetTypeName(property.PropertyType);
}
return property.Name;
}
private static string GetTypeName(Type type)
{
if (type.IsGenericType)
{
var genericTypeName = type.Name.Remove(type.Name.IndexOf('`'));
var genericParametersName = type.GetGenericArguments().Select(x => x.Name).ToList();
return genericTypeName + string.Join("", genericParametersName);
}
return type.Name;
}
private static bool IsNullableProperty(PropertyInfo propertyInfo)
{
if (Attribute.IsDefined(propertyInfo, typeof(RequiredAttribute))) return false;
if (Attribute.IsDefined(propertyInfo, typeof(NotNullAttribute))) return false;
if (Attribute.IsDefined(propertyInfo, typeof(NotNullOrEmptyAttribute))) return false;
if (!propertyInfo.PropertyType.IsValueType) return true;
return propertyInfo.PropertyType.IsGenericType && propertyInfo.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>);
}
private static string GetPropertyName(Expression<Func<TSourceType, object>> expression)
{
if (expression.Body is MemberExpression m1)
return m1.Member.Name;
if (expression.Body is UnaryExpression u && u.Operand is MemberExpression m2)
return m2.Member.Name;
throw new NotSupportedException($"Unsupported type of expression: {expression.GetType().Name}");
}
protected virtual IEnumerable<PropertyInfo> GetRegisteredProperties()
{
return typeof(TSourceType)
.GetProperties(BindingFlags.Public | BindingFlags.Instance)
.Where(p => IsEnabledForRegister(p, p.PropertyType, true));
}
protected virtual bool IsEnabledForRegister(PropertyInfo propertyInfo, Type propertyType, bool firstCall)
{
if (propertyInfo.GetCustomAttribute<IgnoreAttribute>() != null)
{
return false;
}
if (propertyType == typeof(string)) return true;
if (propertyType.IsValueType) return true; // TODO: requires discussion: Nullable<T>, enums, any struct
if (GraphTypeTypeRegistry.Contains(propertyType)) return true;
if (propertyType == typeof(ResolveFieldContext)) return false;
if (firstCall)
{
var realType = GetRealType(propertyType);
if (realType != propertyType)
return IsEnabledForRegister(propertyInfo, realType, false);
}
var fieldConfiguration = _typeConfiguration.GetFieldConfiguration(propertyInfo.Name);
if (fieldConfiguration?.Ignored == true || fieldConfiguration?.Input == false)
{
return false;
}
if (!propertyType.IsValueType && propertyType.IsClass)
{
var type = typeof(AutoInputGraphType<>).MakeGenericType(propertyType);
GraphTypeTypeRegistry.Register(propertyType, type);
return true;
}
return false;
}
private static Type GetRealType(Type propertyType)
{
if (propertyType.IsGenericType && propertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
{
return propertyType.GetGenericArguments()[0];
}
if (propertyType.IsArray)
{
return propertyType.GetElementType();
}
if (propertyType != typeof(string) && typeof(IEnumerable).IsAssignableFrom(propertyType))
{
var genericArguments = propertyType.GetGenericArguments();
return genericArguments.Any() ? genericArguments.First() : typeof(object);
}
return propertyType;
}
}
}
| 36.733333 | 159 | 0.626134 | [
"MIT"
] | maca88/CoreSharp | CoreSharp.GraphQL/AutoInputGraphType.cs | 6,061 | C# |
#region License
//
// Copyright (c) 2007-2009, Sean Chambers <schambers80@gmail.com>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
using System.Collections.Generic;
namespace FluentMigrator.Runner
{
public interface IMigrationLoader
{
SortedList<long, IMigration> Migrations { get; }
}
} | 30.925926 | 75 | 0.734132 | [
"Apache-2.0"
] | ivara/fluentmigrator | src/FluentMigrator.Runner/IMigrationLoader.cs | 835 | C# |
namespace Hexalith.Application.Abstractions.Tests.Fixture
{
using Hexalith.Domain.ValueTypes;
public sealed class TestId : BusinessId
{
public TestId()
{
}
public TestId(string id) : base(id)
{
}
public TestId(TestId id) : base(id)
{
}
public static implicit operator TestId(string value) => new(value);
}
public class TestIdCommand
{
public TestIdCommand()
{
}
public TestIdCommand(TestId testId)
{
TestId = testId;
}
public string TestId { get; }
}
} | 18.171429 | 75 | 0.531447 | [
"MIT"
] | Hexalith/Hexalith | test/Hexalith.Application.Abstractions.Tests/Fixtures/Command.cs | 638 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.