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 |
|---|---|---|---|---|---|---|---|---|
//===================================================================================
// Microsoft patterns & practices
// Composite Application Guidance for Windows Presentation Foundation and Silverlight
//===================================================================================
// Copyright (c) Microsoft Corporation. All rights reserved.
// 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
// FITNESS FOR A PARTICULAR PURPOSE.
//===================================================================================
// The example companies, organizations, products, domain names,
// e-mail addresses, logos, people, places, and events depicted
// herein are fictitious. No association with any real company,
// organization, product, domain name, email address, logo, person,
// places, or events is intended or should be inferred.
//===================================================================================
//===================================================================================
// Microsoft patterns & practices
// Prism Guidance for Windows Presentation Foundation and Silverlight
//===================================================================================
// Copyright (c) Microsoft Corporation. All rights reserved.
// 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
// FITNESS FOR A PARTICULAR PURPOSE.
//===================================================================================
// The example companies, organizations, products, domain names,
// e-mail addresses, logos, people, places, and events depicted
// herein are fictitious. No association with any real company,
// organization, product, domain name, email address, logo, person,
// places, or events is intended or should be inferred.
//===================================================================================
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("EventAggregation.Tests.AcceptanceTest")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft Corporation")]
[assembly: AssemblyProduct("EventAggregation.Tests.AcceptanceTest")]
[assembly: AssemblyCopyright("Copyright (c) 2008,2009 Microsoft Corporation. All rights reserved.")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM componenets. 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("3eda901b-9479-45e8-ada8-435f87481860")]
// 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")]
| 53.970588 | 102 | 0.610354 | [
"MIT"
] | cointoss1973/Prism4.1-WPF | Quickstarts/EventAggregation/EventAggregation.Tests.AcceptanceTest/EventAggregation.Tests.AcceptanceTest/Properties/AssemblyInfo.cs | 3,670 | C# |
namespace KafkaFlow.TypedHandler
{
internal class TypedHandlerConfiguration
{
public HandlerTypeMapping HandlerMapping { get; } = new HandlerTypeMapping();
}
} | 25.571429 | 85 | 0.726257 | [
"MIT"
] | fab60/kafka-flow | src/KafkaFlow.TypedHandler/TypedHandlerConfiguration.cs | 179 | C# |
using DotNetNuke.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Web;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Entities.Portals;
namespace Dnn.PersonaBar.Themes.Components.DTO
{
[Serializable]
[DataContract]
public class ThemeInfo
{
[DataMember(Name = "packageName")]
public string PackageName { get; set; }
[DataMember(Name = "type")]
public ThemeType Type { get; set; }
[DataMember(Name = "path")]
public string Path { get; set; }
[DataMember(Name = "defaultThemeFile")]
public string DefaultThemeFile { get; set; }
[DataMember(Name = "thumbnail")]
public string Thumbnail { get; set; }
[DataMember(Name = "canDelete")]
public bool CanDelete { get; set; } = true;
[DataMember(Name = "level")]
public ThemeLevel Level => ThemesController.GetThemeLevel(Path);
}
} | 26.756757 | 72 | 0.648485 | [
"MIT"
] | DNN-Connect/Dnn.AdminExperience | Extensions/Manage/Dnn.PersonaBar.Themes/Components/DTO/ThemeInfo.cs | 992 | C# |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using NodaTime;
using QuantConnect.Data;
using QuantConnect.Data.Auxiliary;
using QuantConnect.Data.Market;
using QuantConnect.Logging;
using QuantConnect.Securities;
using QuantConnect.Securities.Future;
using static QuantConnect.StringExtensions;
namespace QuantConnect.Util
{
/// <summary>
/// Provides methods for generating lean data file content
/// </summary>
public static class LeanData
{
/// <summary>
/// The different <see cref="SecurityType"/> used for data paths
/// </summary>
/// <remarks>This includes 'alternative'</remarks>
public static IReadOnlyList<string> SecurityTypeAsDataPath => Enum.GetNames(typeof(SecurityType))
.Select(x => x.ToLowerInvariant()).Union(new[] { "alternative" }).ToList();
/// <summary>
/// Converts the specified base data instance into a lean data file csv line.
/// This method takes into account the fake that base data instances typically
/// are time stamped in the exchange time zone, but need to be written to disk
/// in the data time zone.
/// </summary>
public static string GenerateLine(IBaseData data, Resolution resolution, DateTimeZone exchangeTimeZone, DateTimeZone dataTimeZone)
{
var clone = data.Clone();
clone.Time = data.Time.ConvertTo(exchangeTimeZone, dataTimeZone);
return GenerateLine(clone, clone.Symbol.ID.SecurityType, resolution);
}
/// <summary>
/// Converts the specified base data instance into a lean data file csv line
/// </summary>
public static string GenerateLine(IBaseData data, SecurityType securityType, Resolution resolution)
{
var milliseconds = data.Time.TimeOfDay.TotalMilliseconds.ToString(CultureInfo.InvariantCulture);
var longTime = data.Time.ToStringInvariant(DateFormat.TwelveCharacter);
switch (securityType)
{
case SecurityType.Equity:
switch (resolution)
{
case Resolution.Tick:
var tick = (Tick) data;
if (tick.TickType == TickType.Trade)
{
return ToCsv(milliseconds, Scale(tick.LastPrice), tick.Quantity, tick.ExchangeCode, tick.SaleCondition, tick.Suspicious ? "1" : "0");
}
if (tick.TickType == TickType.Quote)
{
return ToCsv(milliseconds, Scale(tick.BidPrice), tick.BidSize, Scale(tick.AskPrice), tick.AskSize, tick.ExchangeCode, tick.SaleCondition, tick.Suspicious ? "1" : "0");
}
break;
case Resolution.Minute:
case Resolution.Second:
var tradeBar = data as TradeBar;
if (tradeBar != null)
{
return ToCsv(milliseconds, Scale(tradeBar.Open), Scale(tradeBar.High), Scale(tradeBar.Low), Scale(tradeBar.Close), tradeBar.Volume);
}
var quoteBar = data as QuoteBar;
if (quoteBar != null)
{
return ToCsv(milliseconds,
ToScaledCsv(quoteBar.Bid), quoteBar.LastBidSize,
ToScaledCsv(quoteBar.Ask), quoteBar.LastAskSize);
}
break;
case Resolution.Hour:
case Resolution.Daily:
var bigTradeBar = data as TradeBar;
if (bigTradeBar != null)
{
return ToCsv(longTime, Scale(bigTradeBar.Open), Scale(bigTradeBar.High), Scale(bigTradeBar.Low), Scale(bigTradeBar.Close), bigTradeBar.Volume);
}
var bigQuoteBar = data as QuoteBar;
if (bigQuoteBar != null)
{
return ToCsv(longTime,
ToScaledCsv(bigQuoteBar.Bid), bigQuoteBar.LastBidSize,
ToScaledCsv(bigQuoteBar.Ask), bigQuoteBar.LastAskSize);
}
break;
}
break;
case SecurityType.Crypto:
switch (resolution)
{
case Resolution.Tick:
var tick = data as Tick;
if (tick == null)
{
throw new ArgumentException("Crypto tick could not be created", nameof(data));
}
if (tick.TickType == TickType.Trade)
{
return ToCsv(milliseconds, tick.LastPrice, tick.Quantity, tick.Suspicious ? "1" : "0");
}
if (tick.TickType == TickType.Quote)
{
return ToCsv(milliseconds, tick.BidPrice, tick.BidSize, tick.AskPrice, tick.AskSize, tick.Suspicious ? "1" : "0");
}
throw new ArgumentException("Cryto tick could not be created");
case Resolution.Second:
case Resolution.Minute:
var quoteBar = data as QuoteBar;
if (quoteBar != null)
{
return ToCsv(milliseconds,
ToNonScaledCsv(quoteBar.Bid), quoteBar.LastBidSize,
ToNonScaledCsv(quoteBar.Ask), quoteBar.LastAskSize);
}
var tradeBar = data as TradeBar;
if (tradeBar != null)
{
return ToCsv(milliseconds, tradeBar.Open, tradeBar.High, tradeBar.Low, tradeBar.Close, tradeBar.Volume);
}
throw new ArgumentException("Cryto minute/second bar could not be created", nameof(data));
case Resolution.Hour:
case Resolution.Daily:
var bigQuoteBar = data as QuoteBar;
if (bigQuoteBar != null)
{
return ToCsv(longTime,
ToNonScaledCsv(bigQuoteBar.Bid), bigQuoteBar.LastBidSize,
ToNonScaledCsv(bigQuoteBar.Ask), bigQuoteBar.LastAskSize);
}
var bigTradeBar = data as TradeBar;
if (bigTradeBar != null)
{
return ToCsv(longTime,
bigTradeBar.Open,
bigTradeBar.High,
bigTradeBar.Low,
bigTradeBar.Close,
bigTradeBar.Volume);
}
throw new ArgumentException("Cryto hour/daily bar could not be created", nameof(data));
}
break;
case SecurityType.Forex:
case SecurityType.Cfd:
switch (resolution)
{
case Resolution.Tick:
var tick = data as Tick;
if (tick == null)
{
throw new ArgumentException("Expected data of type 'Tick'", nameof(data));
}
return ToCsv(milliseconds, tick.BidPrice, tick.AskPrice);
case Resolution.Second:
case Resolution.Minute:
var bar = data as QuoteBar;
if (bar == null)
{
throw new ArgumentException("Expected data of type 'QuoteBar'", nameof(data));
}
return ToCsv(milliseconds,
ToNonScaledCsv(bar.Bid), bar.LastBidSize,
ToNonScaledCsv(bar.Ask), bar.LastAskSize);
case Resolution.Hour:
case Resolution.Daily:
var bigBar = data as QuoteBar;
if (bigBar == null)
{
throw new ArgumentException("Expected data of type 'QuoteBar'", nameof(data));
}
return ToCsv(longTime,
ToNonScaledCsv(bigBar.Bid), bigBar.LastBidSize,
ToNonScaledCsv(bigBar.Ask), bigBar.LastAskSize);
}
break;
case SecurityType.Index:
switch (resolution)
{
case Resolution.Tick:
var tick = (Tick) data;
return ToCsv(milliseconds, tick.LastPrice, tick.Quantity, string.Empty, string.Empty, "0");
case Resolution.Second:
case Resolution.Minute:
var bar = data as TradeBar;
if (bar == null)
{
throw new ArgumentException("Expected data of type 'TradeBar'", nameof(data));
}
return ToCsv(milliseconds, bar.Open, bar.High, bar.Low, bar.Close, bar.Volume);
case Resolution.Hour:
case Resolution.Daily:
var bigTradeBar = data as TradeBar;
return ToCsv(longTime, bigTradeBar.Open, bigTradeBar.High, bigTradeBar.Low, bigTradeBar.Close, bigTradeBar.Volume);
}
break;
case SecurityType.Option:
case SecurityType.IndexOption:
switch (resolution)
{
case Resolution.Tick:
var tick = (Tick)data;
if (tick.TickType == TickType.Trade)
{
return ToCsv(milliseconds,
Scale(tick.LastPrice), tick.Quantity, tick.ExchangeCode, tick.SaleCondition, tick.Suspicious ? "1" : "0");
}
if (tick.TickType == TickType.Quote)
{
return ToCsv(milliseconds,
Scale(tick.BidPrice), tick.BidSize, Scale(tick.AskPrice), tick.AskSize, tick.ExchangeCode, tick.Suspicious ? "1" : "0");
}
if (tick.TickType == TickType.OpenInterest)
{
return ToCsv(milliseconds, tick.Value);
}
break;
case Resolution.Second:
case Resolution.Minute:
// option and future data can be quote or trade bars
var quoteBar = data as QuoteBar;
if (quoteBar != null)
{
return ToCsv(milliseconds,
ToScaledCsv(quoteBar.Bid), quoteBar.LastBidSize,
ToScaledCsv(quoteBar.Ask), quoteBar.LastAskSize);
}
var tradeBar = data as TradeBar;
if (tradeBar != null)
{
return ToCsv(milliseconds,
Scale(tradeBar.Open), Scale(tradeBar.High), Scale(tradeBar.Low), Scale(tradeBar.Close), tradeBar.Volume);
}
var openInterest = data as OpenInterest;
if (openInterest != null)
{
return ToCsv(milliseconds, openInterest.Value);
}
break;
case Resolution.Hour:
case Resolution.Daily:
// option and future data can be quote or trade bars
var bigQuoteBar = data as QuoteBar;
if (bigQuoteBar != null)
{
return ToCsv(longTime,
ToScaledCsv(bigQuoteBar.Bid), bigQuoteBar.LastBidSize,
ToScaledCsv(bigQuoteBar.Ask), bigQuoteBar.LastAskSize);
}
var bigTradeBar = data as TradeBar;
if (bigTradeBar != null)
{
return ToCsv(longTime, ToScaledCsv(bigTradeBar), bigTradeBar.Volume);
}
var bigOpenInterest = data as OpenInterest;
if (bigOpenInterest != null)
{
return ToCsv(milliseconds, bigOpenInterest.Value);
}
break;
default:
throw new ArgumentOutOfRangeException(nameof(resolution), resolution, null);
}
break;
case SecurityType.FutureOption:
switch (resolution)
{
case Resolution.Tick:
var tick = (Tick)data;
if (tick.TickType == TickType.Trade)
{
return ToCsv(milliseconds,
tick.LastPrice, tick.Quantity, tick.ExchangeCode, tick.SaleCondition, tick.Suspicious ? "1" : "0");
}
if (tick.TickType == TickType.Quote)
{
return ToCsv(milliseconds,
tick.BidPrice, tick.BidSize, tick.AskPrice, tick.AskSize, tick.ExchangeCode, tick.Suspicious ? "1" : "0");
}
if (tick.TickType == TickType.OpenInterest)
{
return ToCsv(milliseconds, tick.Value);
}
break;
case Resolution.Second:
case Resolution.Minute:
// option and future data can be quote or trade bars
var quoteBar = data as QuoteBar;
if (quoteBar != null)
{
return ToCsv(milliseconds,
ToNonScaledCsv(quoteBar.Bid), quoteBar.LastBidSize,
ToNonScaledCsv(quoteBar.Ask), quoteBar.LastAskSize);
}
var tradeBar = data as TradeBar;
if (tradeBar != null)
{
return ToCsv(milliseconds,
tradeBar.Open, tradeBar.High, tradeBar.Low, tradeBar.Close, tradeBar.Volume);
}
var openInterest = data as OpenInterest;
if (openInterest != null)
{
return ToCsv(milliseconds, openInterest.Value);
}
break;
case Resolution.Hour:
case Resolution.Daily:
// option and future data can be quote or trade bars
var bigQuoteBar = data as QuoteBar;
if (bigQuoteBar != null)
{
return ToCsv(longTime,
ToNonScaledCsv(bigQuoteBar.Bid), bigQuoteBar.LastBidSize,
ToNonScaledCsv(bigQuoteBar.Ask), bigQuoteBar.LastAskSize);
}
var bigTradeBar = data as TradeBar;
if (bigTradeBar != null)
{
return ToCsv(longTime, ToNonScaledCsv(bigTradeBar), bigTradeBar.Volume);
}
var bigOpenInterest = data as OpenInterest;
if (bigOpenInterest != null)
{
return ToCsv(milliseconds, bigOpenInterest.Value);
}
break;
default:
throw new ArgumentOutOfRangeException(nameof(resolution), resolution, null);
}
break;
case SecurityType.Future:
switch (resolution)
{
case Resolution.Tick:
var tick = (Tick)data;
if (tick.TickType == TickType.Trade)
{
return ToCsv(milliseconds,
tick.LastPrice, tick.Quantity, tick.ExchangeCode, tick.SaleCondition, tick.Suspicious ? "1": "0");
}
if (tick.TickType == TickType.Quote)
{
return ToCsv(milliseconds,
tick.BidPrice, tick.BidSize, tick.AskPrice, tick.AskSize, tick.ExchangeCode, tick.Suspicious ? "1" : "0");
}
if (tick.TickType == TickType.OpenInterest)
{
return ToCsv(milliseconds, tick.Value);
}
break;
case Resolution.Second:
case Resolution.Minute:
// option and future data can be quote or trade bars
var quoteBar = data as QuoteBar;
if (quoteBar != null)
{
return ToCsv(milliseconds,
ToNonScaledCsv(quoteBar.Bid), quoteBar.LastBidSize,
ToNonScaledCsv(quoteBar.Ask), quoteBar.LastAskSize);
}
var tradeBar = data as TradeBar;
if (tradeBar != null)
{
return ToCsv(milliseconds,
tradeBar.Open, tradeBar.High, tradeBar.Low, tradeBar.Close, tradeBar.Volume);
}
var openInterest = data as OpenInterest;
if (openInterest != null)
{
return ToCsv(milliseconds, openInterest.Value);
}
break;
case Resolution.Hour:
case Resolution.Daily:
// option and future data can be quote or trade bars
var bigQuoteBar = data as QuoteBar;
if (bigQuoteBar != null)
{
return ToCsv(longTime,
ToNonScaledCsv(bigQuoteBar.Bid), bigQuoteBar.LastBidSize,
ToNonScaledCsv(bigQuoteBar.Ask), bigQuoteBar.LastAskSize);
}
var bigTradeBar = data as TradeBar;
if (bigTradeBar != null)
{
return ToCsv(longTime, ToNonScaledCsv(bigTradeBar), bigTradeBar.Volume);
}
var bigOpenInterest = data as OpenInterest;
if (bigOpenInterest != null)
{
return ToCsv(longTime, bigOpenInterest.Value);
}
break;
default:
throw new ArgumentOutOfRangeException(nameof(resolution), resolution, null);
}
break;
default:
throw new ArgumentOutOfRangeException(nameof(securityType), securityType, null);
}
throw new NotImplementedException(Invariant(
$"LeanData.GenerateLine has not yet been implemented for security type: {securityType} at resolution: {resolution}"
));
}
/// <summary>
/// Gets the data type required for the specified combination of resolution and tick type
/// </summary>
/// <param name="resolution">The resolution, if Tick, the Type returned is always Tick</param>
/// <param name="tickType">The <see cref="TickType"/> that primarily dictates the type returned</param>
/// <returns>The Type used to create a subscription</returns>
public static Type GetDataType(Resolution resolution, TickType tickType)
{
if (resolution == Resolution.Tick) return typeof(Tick);
if (tickType == TickType.OpenInterest) return typeof(OpenInterest);
if (tickType == TickType.Quote) return typeof(QuoteBar);
return typeof(TradeBar);
}
/// <summary>
/// Determines if the Type is a 'common' type used throughout lean
/// This method is helpful in creating <see cref="SubscriptionDataConfig"/>
/// </summary>
/// <param name="baseDataType">The Type to check</param>
/// <returns>A bool indicating whether the type is of type <see cref="TradeBar"/>
/// <see cref="QuoteBar"/> or <see cref="OpenInterest"/></returns>
public static bool IsCommonLeanDataType(Type baseDataType)
{
if (baseDataType == typeof(TradeBar) ||
baseDataType == typeof(QuoteBar) ||
baseDataType == typeof(OpenInterest))
{
return true;
}
return false;
}
/// <summary>
/// Generates the full zip file path rooted in the <paramref name="dataDirectory"/>
/// </summary>
public static string GenerateZipFilePath(string dataDirectory, Symbol symbol, DateTime date, Resolution resolution, TickType tickType)
{
return Path.Combine(dataDirectory, GenerateRelativeZipFilePath(symbol, date, resolution, tickType));
}
/// <summary>
/// Generates the full zip file path rooted in the <paramref name="dataDirectory"/>
/// </summary>
public static string GenerateZipFilePath(string dataDirectory, string symbol, SecurityType securityType, string market, DateTime date, Resolution resolution)
{
return Path.Combine(dataDirectory, GenerateRelativeZipFilePath(symbol, securityType, market, date, resolution));
}
/// <summary>
/// Generates the relative zip directory for the specified symbol/resolution
/// </summary>
public static string GenerateRelativeZipFileDirectory(Symbol symbol, Resolution resolution)
{
var isHourOrDaily = resolution == Resolution.Hour || resolution == Resolution.Daily;
var securityType = symbol.SecurityType.SecurityTypeToLower();
var market = symbol.ID.Market.ToLowerInvariant();
var res = resolution.ResolutionToLower();
var directory = Path.Combine(securityType, market, res);
switch (symbol.ID.SecurityType)
{
case SecurityType.Base:
case SecurityType.Equity:
case SecurityType.Index:
case SecurityType.Forex:
case SecurityType.Cfd:
case SecurityType.Crypto:
return !isHourOrDaily ? Path.Combine(directory, symbol.Value.ToLowerInvariant()) : directory;
case SecurityType.Option:
case SecurityType.IndexOption:
// options uses the underlying symbol for pathing.
return !isHourOrDaily ? Path.Combine(directory, symbol.Underlying.Value.ToLowerInvariant()) : directory;
case SecurityType.FutureOption:
// For futures options, we use the canonical option ticker plus the underlying's expiry
// since it can differ from the underlying's ticker. We differ from normal futures
// because the option chain can be extraordinarily large compared to equity option chains.
var futureOptionPath = Path.Combine(symbol.ID.Symbol, symbol.Underlying.ID.Date.ToStringInvariant(DateFormat.EightCharacter))
.ToLowerInvariant();
return !isHourOrDaily ? Path.Combine(directory, futureOptionPath) : directory;
case SecurityType.Future:
return !isHourOrDaily ? Path.Combine(directory, symbol.ID.Symbol.ToLowerInvariant()) : directory;
case SecurityType.Commodity:
default:
throw new ArgumentOutOfRangeException();
}
}
/// <summary>
/// Generates relative factor file paths for equities
/// </summary>
public static string GenerateRelativeFactorFilePath(Symbol symbol)
{
return Path.Combine(Globals.DataFolder,
"equity",
symbol.ID.Market,
"factor_files",
symbol.Value.ToLowerInvariant() + ".csv");
}
/// <summary>
/// Generates the relative zip file path rooted in the /Data directory
/// </summary>
public static string GenerateRelativeZipFilePath(Symbol symbol, DateTime date, Resolution resolution, TickType tickType)
{
return Path.Combine(GenerateRelativeZipFileDirectory(symbol, resolution), GenerateZipFileName(symbol, date, resolution, tickType));
}
/// <summary>
/// Generates the relative zip file path rooted in the /Data directory
/// </summary>
public static string GenerateRelativeZipFilePath(string symbol, SecurityType securityType, string market, DateTime date, Resolution resolution)
{
var directory = Path.Combine(securityType.SecurityTypeToLower(), market.ToLowerInvariant(), resolution.ResolutionToLower());
if (resolution != Resolution.Daily && resolution != Resolution.Hour)
{
directory = Path.Combine(directory, symbol.ToLowerInvariant());
}
return Path.Combine(directory, GenerateZipFileName(symbol, securityType, date, resolution));
}
/// <summary>
/// Generate's the zip entry name to hold the specified data.
/// </summary>
public static string GenerateZipEntryName(Symbol symbol, DateTime date, Resolution resolution, TickType tickType)
{
var formattedDate = date.ToStringInvariant(DateFormat.EightCharacter);
var isHourOrDaily = resolution == Resolution.Hour || resolution == Resolution.Daily;
switch (symbol.ID.SecurityType)
{
case SecurityType.Base:
case SecurityType.Equity:
case SecurityType.Index:
case SecurityType.Forex:
case SecurityType.Cfd:
case SecurityType.Crypto:
if (resolution == Resolution.Tick && symbol.SecurityType == SecurityType.Equity)
{
return Invariant($"{formattedDate}_{symbol.Value.ToLowerInvariant()}_{tickType}_{resolution}.csv");
}
if (isHourOrDaily)
{
return $"{symbol.Value.ToLowerInvariant()}.csv";
}
return Invariant($"{formattedDate}_{symbol.Value.ToLowerInvariant()}_{resolution.ResolutionToLower()}_{tickType.TickTypeToLower()}.csv");
case SecurityType.Option:
case SecurityType.IndexOption:
var optionPath = symbol.Underlying.Value.ToLowerInvariant();
if (isHourOrDaily)
{
return string.Join("_",
optionPath,
tickType.TickTypeToLower(),
symbol.ID.OptionStyle.ToLower(),
symbol.ID.OptionRight.ToLower(),
Scale(symbol.ID.StrikePrice),
symbol.ID.Date.ToStringInvariant(DateFormat.EightCharacter)
) + ".csv";
}
return string.Join("_",
formattedDate,
optionPath,
resolution.ResolutionToLower(),
tickType.TickTypeToLower(),
symbol.ID.OptionStyle.ToLower(),
symbol.ID.OptionRight.ToLower(),
Scale(symbol.ID.StrikePrice),
symbol.ID.Date.ToStringInvariant(DateFormat.EightCharacter)
) + ".csv";
case SecurityType.FutureOption:
// We want the future option ticker as the lookup name inside the ZIP file
var futureOptionPath = symbol.ID.Symbol.ToLowerInvariant();
if (isHourOrDaily)
{
return string.Join("_",
futureOptionPath,
tickType.TickTypeToLower(),
symbol.ID.OptionStyle.ToLower(),
symbol.ID.OptionRight.ToLower(),
Scale(symbol.ID.StrikePrice),
symbol.ID.Date.ToStringInvariant(DateFormat.EightCharacter)
) + ".csv";
}
return string.Join("_",
formattedDate,
futureOptionPath,
resolution.ResolutionToLower(),
tickType.TickTypeToLower(),
symbol.ID.OptionStyle.ToLower(),
symbol.ID.OptionRight.ToLower(),
Scale(symbol.ID.StrikePrice),
symbol.ID.Date.ToStringInvariant(DateFormat.EightCharacter)
) + ".csv";
case SecurityType.Future:
var expiryDate = symbol.ID.Date;
var monthsToAdd = FuturesExpiryUtilityFunctions.GetDeltaBetweenContractMonthAndContractExpiry(symbol.ID.Symbol, expiryDate.Date);
var contractYearMonth = expiryDate.AddMonths(monthsToAdd).ToStringInvariant(DateFormat.YearMonth);
if (isHourOrDaily)
{
return string.Join("_",
symbol.ID.Symbol.ToLowerInvariant(),
tickType.TickTypeToLower(),
contractYearMonth,
expiryDate.ToStringInvariant(DateFormat.EightCharacter)
) + ".csv";
}
return string.Join("_",
formattedDate,
symbol.ID.Symbol.ToLowerInvariant(),
resolution.ResolutionToLower(),
tickType.TickTypeToLower(),
contractYearMonth,
expiryDate.ToStringInvariant(DateFormat.EightCharacter)
) + ".csv";
case SecurityType.Commodity:
default:
throw new ArgumentOutOfRangeException();
}
}
/// <summary>
/// Generates the zip file name for the specified date of data.
/// </summary>
public static string GenerateZipFileName(Symbol symbol, DateTime date, Resolution resolution, TickType tickType)
{
var tickTypeString = tickType.TickTypeToLower();
var formattedDate = date.ToStringInvariant(DateFormat.EightCharacter);
var isHourOrDaily = resolution == Resolution.Hour || resolution == Resolution.Daily;
switch (symbol.ID.SecurityType)
{
case SecurityType.Base:
case SecurityType.Index:
case SecurityType.Equity:
case SecurityType.Forex:
case SecurityType.Cfd:
if (isHourOrDaily)
{
return $"{symbol.Value.ToLowerInvariant()}.zip";
}
return $"{formattedDate}_{tickTypeString}.zip";
case SecurityType.Crypto:
if (isHourOrDaily)
{
return $"{symbol.Value.ToLowerInvariant()}_{tickTypeString}.zip";
}
return $"{formattedDate}_{tickTypeString}.zip";
case SecurityType.Option:
case SecurityType.IndexOption:
if (isHourOrDaily)
{
var optionPath = symbol.Underlying.Value.ToLowerInvariant();
return $"{optionPath}_{tickTypeString}_{symbol.ID.OptionStyle.ToLower()}.zip";
}
return $"{formattedDate}_{tickTypeString}_{symbol.ID.OptionStyle.ToLower()}.zip";
case SecurityType.FutureOption:
if (isHourOrDaily)
{
var futureOptionPath = symbol.ID.Symbol.ToLowerInvariant();
return $"{futureOptionPath}_{tickTypeString}_{symbol.ID.OptionStyle.ToLower()}.zip";
}
return $"{formattedDate}_{tickTypeString}_{symbol.ID.OptionStyle.ToLower()}.zip";
case SecurityType.Future:
if (isHourOrDaily)
{
return $"{symbol.ID.Symbol.ToLowerInvariant()}_{tickTypeString}.zip";
}
return $"{formattedDate}_{tickTypeString}.zip";
case SecurityType.Commodity:
default:
throw new ArgumentOutOfRangeException();
}
}
/// <summary>
/// Creates the zip file name for a QC zip data file
/// </summary>
public static string GenerateZipFileName(string symbol, SecurityType securityType, DateTime date, Resolution resolution, TickType? tickType = null)
{
if (resolution == Resolution.Hour || resolution == Resolution.Daily)
{
return $"{symbol.ToLowerInvariant()}.zip";
}
var zipFileName = date.ToStringInvariant(DateFormat.EightCharacter);
if (tickType == null)
{
if (securityType == SecurityType.Forex || securityType == SecurityType.Cfd) {
tickType = TickType.Quote;
}
else
{
tickType = TickType.Trade;
}
}
var suffix = Invariant($"_{tickType.Value.TickTypeToLower()}.zip");
return zipFileName + suffix;
}
/// <summary>
/// Gets the tick type most commonly associated with the specified security type
/// </summary>
/// <param name="securityType">The security type</param>
/// <returns>The most common tick type for the specified security type</returns>
public static TickType GetCommonTickType(SecurityType securityType)
{
if (securityType == SecurityType.Forex || securityType == SecurityType.Cfd || securityType == SecurityType.Crypto)
{
return TickType.Quote;
}
return TickType.Trade;
}
/// <summary>
/// Creates a symbol from the specified zip entry name
/// </summary>
/// <param name="symbol">The root symbol of the output symbol</param>
/// <param name="resolution">The resolution of the data source producing the zip entry name</param>
/// <param name="zipEntryName">The zip entry name to be parsed</param>
/// <returns>A new symbol representing the zip entry name</returns>
public static Symbol ReadSymbolFromZipEntry(Symbol symbol, Resolution resolution, string zipEntryName)
{
var isHourlyOrDaily = resolution == Resolution.Hour || resolution == Resolution.Daily;
var parts = zipEntryName.Replace(".csv", string.Empty).Split('_');
switch (symbol.ID.SecurityType)
{
case SecurityType.Option:
case SecurityType.FutureOption:
case SecurityType.IndexOption:
if (isHourlyOrDaily)
{
var style = (OptionStyle)Enum.Parse(typeof(OptionStyle), parts[2], true);
var right = (OptionRight)Enum.Parse(typeof(OptionRight), parts[3], true);
var strike = Parse.Decimal(parts[4]) / 10000m;
var expiry = Parse.DateTimeExact(parts[5], DateFormat.EightCharacter);
return Symbol.CreateOption(symbol.Underlying, symbol.ID.Market, style, right, strike, expiry);
}
else
{
var style = (OptionStyle)Enum.Parse(typeof(OptionStyle), parts[4], true);
var right = (OptionRight)Enum.Parse(typeof(OptionRight), parts[5], true);
var strike = Parse.Decimal(parts[6]) / 10000m;
var expiry = DateTime.ParseExact(parts[7], DateFormat.EightCharacter, CultureInfo.InvariantCulture);
return Symbol.CreateOption(symbol.Underlying, symbol.ID.Market, style, right, strike, expiry);
}
case SecurityType.Future:
if (isHourlyOrDaily)
{
var expiryYearMonth = Parse.DateTimeExact(parts[2], DateFormat.YearMonth);
var futureExpiryFunc = FuturesExpiryFunctions.FuturesExpiryFunction(symbol);
var futureExpiry = futureExpiryFunc(expiryYearMonth);
return Symbol.CreateFuture(parts[0], symbol.ID.Market, futureExpiry);
}
else
{
var expiryYearMonth = Parse.DateTimeExact(parts[4], DateFormat.YearMonth);
var futureExpiryFunc = FuturesExpiryFunctions.FuturesExpiryFunction(symbol);
var futureExpiry = futureExpiryFunc(expiryYearMonth);
return Symbol.CreateFuture(parts[1], symbol.ID.Market, futureExpiry);
}
default:
throw new NotImplementedException(Invariant(
$"ReadSymbolFromZipEntry is not implemented for {symbol.ID.SecurityType} {symbol.ID.Market} {resolution}"
));
}
}
/// <summary>
/// Scale and convert the resulting number to deci-cents int.
/// </summary>
private static long Scale(decimal value)
{
return (long)(value*10000);
}
/// <summary>
/// Create a csv line from the specified arguments
/// </summary>
private static string ToCsv(params object[] args)
{
// use culture neutral formatting for decimals
for (var i = 0; i < args.Length; i++)
{
var value = args[i];
if (value is decimal)
{
args[i] = ((decimal) value).Normalize();
}
}
return string.Join(",", args);
}
/// <summary>
/// Creates a scaled csv line for the bar, if null fills in empty strings
/// </summary>
private static string ToScaledCsv(IBar bar)
{
if (bar == null)
{
return ToCsv(string.Empty, string.Empty, string.Empty, string.Empty);
}
return ToCsv(Scale(bar.Open), Scale(bar.High), Scale(bar.Low), Scale(bar.Close));
}
/// <summary>
/// Creates a non scaled csv line for the bar, if null fills in empty strings
/// </summary>
private static string ToNonScaledCsv(IBar bar)
{
if (bar == null)
{
return ToCsv(string.Empty, string.Empty, string.Empty, string.Empty);
}
return ToCsv(bar.Open, bar.High, bar.Low, bar.Close);
}
/// <summary>
/// Get the <see cref="TickType"/> for common Lean data types.
/// If not a Lean common data type, return a TickType of Trade.
/// </summary>
/// <param name="type">A Type used to determine the TickType</param>
/// <param name="securityType">The SecurityType used to determine the TickType</param>
/// <returns>A TickType corresponding to the type</returns>
public static TickType GetCommonTickTypeForCommonDataTypes(Type type, SecurityType securityType)
{
if (type == typeof(TradeBar))
{
return TickType.Trade;
}
if (type == typeof(QuoteBar))
{
return TickType.Quote;
}
if (type == typeof(OpenInterest))
{
return TickType.OpenInterest;
}
if (type == typeof(ZipEntryName))
{
return TickType.Quote;
}
if (type == typeof(Tick))
{
if (securityType == SecurityType.Forex ||
securityType == SecurityType.Cfd ||
securityType == SecurityType.Crypto)
{
return TickType.Quote;
}
}
return TickType.Trade;
}
/// <summary>
/// Matches a data path security type with the <see cref="SecurityType"/>
/// </summary>
/// <remarks>This includes 'alternative'</remarks>
/// <param name="securityType">The data path security type</param>
/// <returns>The matching security type for the given data path</returns>
public static SecurityType ParseDataSecurityType(string securityType)
{
if (securityType.Equals("alternative", StringComparison.InvariantCultureIgnoreCase))
{
return SecurityType.Base;
}
return (SecurityType) Enum.Parse(typeof(SecurityType), securityType, true);
}
/// <summary>
/// Parses file name into a <see cref="Security"/> and DateTime
/// </summary>
/// <param name="fileName">File name to be parsed</param>
/// <param name="securityType">The securityType as parsed from the fileName</param>
public static bool TryParseSecurityType(string fileName, out SecurityType securityType)
{
securityType = SecurityType.Base;
try
{
var info = SplitDataPath(fileName);
// find the securityType and parse it
var typeString = info.Find(x => SecurityTypeAsDataPath.Contains(x.ToLowerInvariant()));
securityType = ParseDataSecurityType(typeString);
}
catch (Exception e)
{
Log.Error($"LeanData.TryParsePath(): Error encountered while parsing the path {fileName}. Error: {e.GetBaseException()}");
return false;
}
return true;
}
/// <summary>
/// Parses file name into a <see cref="Security"/> and DateTime
/// </summary>
/// <param name="filePath">File path to be parsed</param>
/// <param name="symbol">The symbol as parsed from the fileName</param>
/// <param name="date">Date of data in the file path. Only returned if the resolution is lower than Hourly</param>
/// <param name="resolution">The resolution of the symbol as parsed from the filePath</param>
/// <param name="tickType">The tick type</param>
/// <param name="dataType">The data type</param>
public static bool TryParsePath(string filePath, out Symbol symbol, out DateTime date,
out Resolution resolution, out TickType tickType, out Type dataType)
{
symbol = default;
tickType = default;
dataType = default;
date = default;
resolution = default;
try
{
if (!TryParsePath(filePath, out symbol, out date, out resolution))
{
return false;
}
tickType = GetCommonTickType(symbol.SecurityType);
var fileName = Path.GetFileNameWithoutExtension(filePath);
if (fileName.Contains("_"))
{
tickType = (TickType)Enum.Parse(typeof(TickType), fileName.Split('_')[1], true);
}
dataType = GetDataType(resolution, tickType);
return true;
}
catch (Exception ex)
{
Log.Debug($"LeanData.TryParsePath(): Error encountered while parsing the path {filePath}. Error: {ex.GetBaseException()}");
}
return false;
}
/// <summary>
/// Parses file name into a <see cref="Security"/> and DateTime
/// </summary>
/// <param name="fileName">File name to be parsed</param>
/// <param name="symbol">The symbol as parsed from the fileName</param>
/// <param name="date">Date of data in the file path. Only returned if the resolution is lower than Hourly</param>
/// <param name="resolution">The resolution of the symbol as parsed from the filePath</param>
public static bool TryParsePath(string fileName, out Symbol symbol, out DateTime date, out Resolution resolution)
{
symbol = null;
resolution = Resolution.Daily;
date = default(DateTime);
try
{
var info = SplitDataPath(fileName);
// find where the useful part of the path starts - i.e. the securityType
var startIndex = info.FindIndex(x => SecurityTypeAsDataPath.Contains(x.ToLowerInvariant()));
var securityType = ParseDataSecurityType(info[startIndex]);
var market = Market.USA;
string ticker;
if (securityType == SecurityType.Base)
{
if (!Enum.TryParse(info[startIndex + 2], true, out resolution))
{
resolution = Resolution.Daily;
}
// the last part of the path is the file name
var fileNameNoPath = info[info.Count - 1].Split('_').First();
if (!DateTime.TryParseExact(fileNameNoPath,
DateFormat.EightCharacter,
DateTimeFormatInfo.InvariantInfo,
DateTimeStyles.None,
out date))
{
// if parsing the date failed we assume filename is ticker
ticker = fileNameNoPath;
}
else
{
// ticker must be the previous part of the path
ticker = info[info.Count - 2];
}
}
else
{
resolution = (Resolution)Enum.Parse(typeof(Resolution), info[startIndex + 2], true);
// Gather components used to create the security
market = info[startIndex + 1];
ticker = info[startIndex + 3];
// If resolution is Daily or Hour, we do not need to set the date and tick type
if (resolution < Resolution.Hour)
{
date = Parse.DateTimeExact(info[startIndex + 4].Substring(0, 8), DateFormat.EightCharacter);
}
if (securityType == SecurityType.Crypto)
{
ticker = ticker.Split('_').First();
}
}
symbol = Symbol.Create(ticker, securityType, market);
}
catch (Exception ex)
{
Log.Debug($"LeanData.TryParsePath(): Error encountered while parsing the path {fileName}. Error: {ex.GetBaseException()}");
return false;
}
return true;
}
private static List<string> SplitDataPath(string fileName)
{
var pathSeparators = new[] { '/', '\\' };
// Removes file extension
fileName = fileName.Replace(fileName.GetExtension(), string.Empty);
// remove any relative file path
while (fileName.First() == '.' || pathSeparators.Any(x => x == fileName.First()))
{
fileName = fileName.Remove(0, 1);
}
// split path into components
return fileName.Split(pathSeparators, StringSplitOptions.RemoveEmptyEntries).ToList();
}
/// <summary>
/// Aggregates a list of second/minute bars at the requested resolution
/// </summary>
/// <param name="bars">List of <see cref="TradeBar"/>s</param>
/// <param name="symbol">Symbol of all tradeBars</param>
/// <param name="resolution">Desired resolution for new <see cref="TradeBar"/>s</param>
/// <returns>List of aggregated <see cref="TradeBar"/>s</returns>
public static IEnumerable<TradeBar> AggregateTradeBars(IEnumerable<TradeBar> bars, Symbol symbol, TimeSpan resolution)
{
return
from b in bars
group b by b.Time.RoundDown(resolution)
into g
select new TradeBar
{
Symbol = symbol,
Time = g.Key,
Open = g.First().Open,
High = g.Max(b => b.High),
Low = g.Min(b => b.Low),
Close = g.Last().Close,
Value = g.Last().Close,
DataType = MarketDataType.TradeBar,
Period = resolution
};
}
/// <summary>
/// Aggregates a list of second/minute bars at the requested resolution
/// </summary>
/// <param name="bars">List of <see cref="QuoteBar"/>s</param>
/// <param name="symbol">Symbol of all QuoteBars</param>
/// <param name="resolution">Desired resolution for new <see cref="QuoteBar"/>s</param>
/// <returns>List of aggregated <see cref="QuoteBar"/>s</returns>
public static IEnumerable<QuoteBar> AggregateQuoteBars(IEnumerable<QuoteBar> bars, Symbol symbol, TimeSpan resolution)
{
return
from b in bars
group b by b.Time.RoundDown(resolution)
into g
select new QuoteBar
{
Symbol = symbol,
Time = g.Key,
Bid = new Bar
{
Open = g.First().Bid.Open,
High = g.Max(b => b.Bid.High),
Low = g.Min(b => b.Bid.Low),
Close = g.Last().Bid.Close
},
Ask = new Bar
{
Open = g.First().Ask.Open,
High = g.Max(b => b.Ask.High),
Low = g.Min(b => b.Ask.Low),
Close = g.Last().Ask.Close
},
Period = resolution
};
}
/// <summary>
/// Aggregates a list of ticks at the requested resolution
/// </summary>
/// <param name="ticks">List of <see cref="QuoteBar"/>s</param>
/// <param name="symbol">Symbol of all QuoteBars</param>
/// <param name="resolution">Desired resolution for new <see cref="QuoteBar"/>s</param>
/// <returns>List of aggregated <see cref="QuoteBar"/>s</returns>
public static IEnumerable<QuoteBar> AggregateTicks(IEnumerable<Tick> ticks, Symbol symbol, TimeSpan resolution)
{
return
from t in ticks
group t by t.Time.RoundDown(resolution)
into g
select new QuoteBar
{
Symbol = symbol,
Time = g.Key,
Bid = new Bar
{
Open = g.First().BidPrice,
High = g.Max(b => b.BidPrice),
Low = g.Min(b => b.BidPrice),
Close = g.Last().BidPrice
},
Ask = new Bar
{
Open = g.First().AskPrice,
High = g.Max(b => b.AskPrice),
Low = g.Min(b => b.AskPrice),
Close = g.Last().AskPrice
},
Period = resolution
};
}
}
}
| 46.5905 | 199 | 0.48076 | [
"Apache-2.0"
] | EmilioFreire/Lean | Common/Util/LeanData.cs | 56,887 | C# |
using FluentValidation;
namespace Gear.ProjectManagement.Manager.Domain.Projects.Commands.ProjectSstp
{
internal class ProjectSstpCommandValidator : AbstractValidator<ProjectSstpCommand>
{
public ProjectSstpCommandValidator()
{
RuleFor(x => x.ProjectId).NotNull().NotEmpty();
}
}
}
| 25.538462 | 86 | 0.698795 | [
"MIT"
] | indrivo/bizon360_pm | IndrivoPM/Gear.ProjectManagement.Application/Domain/Projects/Commands/ProjectSstp/ProjectSstpCommandValidator.cs | 334 | C# |
#region Copyrights
/*
Gibbo2D License - Version 1.0
Copyright (c) 2013 - Gibbo2D Team
Founders Joao Alves <joao.cpp.sca@gmail.com> & Luis Fernandes <luisapidcloud@hotmail.com>
Permission is granted to use this software and associated documentation files (the "Software") free of charge,
to any person or company. The code can be used, modified and merged without restrictions, but you cannot sell
the software itself and parts where this license applies. Still, permission is granted for anyone to sell
applications made using this software (for example, a game). This software cannot be claimed as your own,
except for copyright holders. This license notes should also be available on any of the changed or added files.
The software is provided "as is", without warranty of any kind, express or implied, including but not limited to
the warranties of merchantability, fitness for a particular purpose and non-infrigement. In no event shall the
authors or copyright holders be liable for any claim, damages or other liability.
The license applies to all versions of the software, both newer and older than the one listed, unless a newer copy
of the license is available, in which case the most recent copy of the license supercedes all others.
*/
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace Gibbo.Editor
{
public enum FileTemplate { None, Component };
public static class FileHelper
{
/// <summary>
/// Checks if the input filename is available, if it isn't, returns the next available name
/// Structure : [filename]{number}.[extension]
/// </summary>
/// <param name="filename"></param>
/// <returns>An available filename [filename]{number}.[extension]</returns>
public static string ResolveFilename(string filename)
{
// The file does not exist?
if (!File.Exists(filename)) return filename;
string extension = Path.GetExtension(filename);
string nameNoExtension = Path.GetFileNameWithoutExtension(filename);
string _filename = Path.GetDirectoryName(filename) + "\\" + nameNoExtension;
int cnt = 1;
while (File.Exists(_filename + cnt + extension)) cnt++;
_filename += cnt + extension;
return _filename;
}
/// <summary>
/// Creates a file with the given input
/// </summary>
/// <param name="path"></param>
/// <returns>The path of the created file</returns>
public static string CreateFile(string path, FileTemplate template)
{
// Resolve the selected filename
path = ResolveFilename(path);
// Create a file or append
using (System.IO.FileStream fs = new System.IO.FileStream(path, FileMode.Append))
{
}
switch (template)
{
case FileTemplate.Component:
//File.WriteAllText(path, Properties.Settings.Default.NewComponentTemplate);
break;
}
return path;
}
}
}
| 37.383721 | 115 | 0.65661 | [
"MIT"
] | Whitebeard86/Gibbo2D | Gibbo.Editor.Model/Classes/FileHelper.cs | 3,217 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using LanguageExt;
using SJP.Schematic.Core;
using SJP.Schematic.Core.Extensions;
namespace SJP.Schematic.Reporting.Html.ViewModels;
/// <summary>
/// Internal. Not intended to be used outside of this assembly. Only required for templating.
/// </summary>
public sealed class View : ITemplateParameter
{
public View(
Identifier viewName,
string rootPath,
string definition,
IEnumerable<Column> columns,
IEnumerable<HtmlString> referencedObjects
)
{
if (viewName == null)
throw new ArgumentNullException(nameof(viewName));
if (referencedObjects == null)
throw new ArgumentNullException(nameof(referencedObjects));
Name = viewName.ToVisibleName();
ViewUrl = viewName.ToSafeKey();
RootPath = rootPath ?? throw new ArgumentNullException(nameof(rootPath));
Definition = definition ?? throw new ArgumentNullException(nameof(definition));
Columns = columns ?? throw new ArgumentNullException(nameof(columns));
ColumnsCount = columns.UCount();
ColumnsTableClass = ColumnsCount > 0 ? CssClasses.DataTableClass : string.Empty;
ReferencedObjects = new HtmlString(
referencedObjects.Select(ro => ro.ToHtmlString()).Join(", ")
);
ReferencedObjectsCount = referencedObjects.UCount();
}
public ReportTemplate Template { get; } = ReportTemplate.View;
public string RootPath { get; }
public string Name { get; }
public string ViewUrl { get; }
public string Definition { get; }
public IEnumerable<Column> Columns { get; }
public uint ColumnsCount { get; }
public HtmlString ColumnsTableClass { get; }
public uint ReferencedObjectsCount { get; }
public HtmlString ReferencedObjects { get; }
/// <summary>
/// Internal. Not intended to be used outside of this assembly. Only required for templating.
/// </summary>
public sealed class Column
{
public Column(
string columnName,
int ordinal,
bool isNullable,
string typeDefinition,
Option<string> defaultValue
)
{
ColumnName = columnName ?? throw new ArgumentNullException(nameof(columnName));
Ordinal = ordinal;
TitleNullable = isNullable ? "Nullable" : string.Empty;
NullableText = isNullable ? "✓" : "✗";
Type = typeDefinition ?? string.Empty;
DefaultValue = defaultValue.Match(static def => def ?? string.Empty, static () => string.Empty);
}
public int Ordinal { get; }
public string ColumnName { get; }
public string TitleNullable { get; }
public string NullableText { get; }
public string Type { get; }
public string DefaultValue { get; }
}
} | 31.520833 | 109 | 0.620291 | [
"MIT"
] | sjp/SJP.Schema | src/SJP.Schematic.Reporting/Html/ViewModels/View.cs | 2,937 | C# |
using System;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using Microsoft.Data.OData;
using Moq;
#pragma warning disable 3008
namespace Simple.OData.Client.Tests.Core
{
public abstract class CoreTestBase : IDisposable
{
protected readonly IODataClient _client;
internal ISession _session;
protected CoreTestBase()
{
_client = CreateClient(this.MetadataFile);
}
public IODataClient CreateClient(string metadataFile, INameMatchResolver matchResolver = null)
{
var baseUri = new Uri("http://localhost/" + metadataFile);
var metadataString = GetResourceAsString(@"Resources." + metadataFile);
var settings = new ODataClientSettings
{
BaseUri = baseUri,
MetadataDocument = metadataString,
NameMatchResolver = matchResolver,
};
_session = Session.FromMetadata(baseUri, metadataString);
return new ODataClient(settings);
}
public abstract string MetadataFile { get; }
public abstract IFormatSettings FormatSettings { get; }
public void Dispose()
{
}
public static string GetResourceAsString(string resourceName)
{
var assembly = Assembly.GetExecutingAssembly();
var resourceNames = assembly.GetManifestResourceNames();
string completeResourceName = resourceNames.FirstOrDefault(o => o.EndsWith("." + resourceName, StringComparison.CurrentCultureIgnoreCase));
using (Stream resourceStream = assembly.GetManifestResourceStream(completeResourceName))
{
TextReader reader = new StreamReader(resourceStream);
return reader.ReadToEnd();
}
}
public IODataResponseMessageAsync SetUpResourceMock(string resourceName)
{
var document = GetResourceAsString(resourceName);
var mock = new Mock<IODataResponseMessageAsync>();
mock.Setup(x => x.GetStreamAsync()).ReturnsAsync(new MemoryStream(Encoding.UTF8.GetBytes(document)));
mock.Setup(x => x.GetStream()).Returns(new MemoryStream(Encoding.UTF8.GetBytes(document)));
mock.Setup(x => x.GetHeader("Content-Type")).Returns(() => "application/atom+xml; type=feed; charset=utf-8");
return mock.Object;
}
}
}
| 36.761194 | 151 | 0.63987 | [
"MIT"
] | 3-PRO/Simple.OData.Client | src/Simple.OData.Client.UnitTests/Core/CoreTestBase.cs | 2,465 | C# |
// <auto-generated />
using System;
using GoodToCode.Locality.Infrastructure;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
namespace GoodToCode.Locality.Infrastructure.Persistence.Migrations.Migrations
{
[DbContext(typeof(LocalityDbContextDeploy))]
[Migration("20201025024420_20201024-194355")]
partial class _20201024194355
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "3.1.9")
.HasAnnotation("Relational:MaxIdentifierLength", 128)
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("GoodToCode.Locality.Models.AssociateLocation", b =>
{
b.Property<Guid>("RowKey")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<Guid>("AssociateKey")
.HasColumnType("uniqueidentifier");
b.Property<Guid>("AssociateLocationKey")
.HasColumnType("uniqueidentifier");
b.Property<Guid>("LocationKey")
.HasColumnType("uniqueidentifier");
b.Property<Guid?>("LocationTypeKey")
.HasColumnType("uniqueidentifier");
b.Property<string>("PartitionKey")
.HasColumnType("nvarchar(max)");
b.HasKey("RowKey");
b.HasIndex("AssociateKey", "LocationKey")
.IsUnique()
.HasName("IX_AssociateLocation_All");
b.ToTable("AssociateLocation","Locality");
});
modelBuilder.Entity("GoodToCode.Locality.Models.GeoDistance", b =>
{
b.Property<Guid>("RowKey")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<Guid>("EndLatLongKey")
.HasColumnType("uniqueidentifier");
b.Property<Guid>("GeoDistanceKey")
.HasColumnType("uniqueidentifier");
b.Property<string>("PartitionKey")
.HasColumnType("nvarchar(max)");
b.Property<Guid>("StartLatLongKey")
.HasColumnType("uniqueidentifier");
b.HasKey("RowKey");
b.HasIndex("GeoDistanceKey")
.IsUnique()
.HasName("IX_GeoDistance_Key");
b.ToTable("GeoDistance","Locality");
});
modelBuilder.Entity("GoodToCode.Locality.Models.LatLong", b =>
{
b.Property<Guid>("RowKey")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<Guid>("LatLongKey")
.HasColumnType("uniqueidentifier");
b.Property<double>("Latitude")
.HasColumnType("float");
b.Property<double>("Longitude")
.HasColumnType("float");
b.Property<string>("PartitionKey")
.HasColumnType("nvarchar(max)");
b.HasKey("RowKey");
b.HasIndex("LatLongKey")
.IsUnique()
.HasName("IX_LatLong_Key");
b.ToTable("LatLong","Locality");
});
modelBuilder.Entity("GoodToCode.Locality.Models.Location", b =>
{
b.Property<Guid>("RowKey")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<string>("LocationDescription")
.HasColumnType("nvarchar(2000)")
.HasMaxLength(2000);
b.Property<Guid>("LocationKey")
.HasColumnType("uniqueidentifier");
b.Property<string>("LocationName")
.IsRequired()
.HasColumnType("nvarchar(50)")
.HasMaxLength(50);
b.Property<string>("PartitionKey")
.HasColumnType("nvarchar(max)");
b.HasKey("RowKey");
b.HasIndex("LocationKey")
.IsUnique();
b.ToTable("Location","Locality");
});
modelBuilder.Entity("GoodToCode.Locality.Models.LocationArea", b =>
{
b.Property<Guid>("RowKey")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<Guid>("LocationAreaKey")
.HasColumnType("uniqueidentifier");
b.Property<Guid>("LocationKey")
.HasColumnType("uniqueidentifier");
b.Property<string>("PartitionKey")
.HasColumnType("nvarchar(max)");
b.Property<Guid>("PolygonKey")
.HasColumnType("uniqueidentifier");
b.HasKey("RowKey");
b.HasIndex("LocationAreaKey")
.IsUnique()
.HasName("IX_LocationArea_Key");
b.HasIndex("LocationKey")
.HasName("IX_LocationArea_LocationId");
b.HasIndex("LocationKey", "PolygonKey")
.IsUnique()
.HasName("IX_LocationArea_All");
b.ToTable("LocationArea","Locality");
});
modelBuilder.Entity("GoodToCode.Locality.Models.LocationType", b =>
{
b.Property<Guid>("RowKey")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<string>("LocationTypeDescription")
.HasColumnType("nvarchar(250)")
.HasMaxLength(250);
b.Property<Guid>("LocationTypeKey")
.HasColumnType("uniqueidentifier");
b.Property<string>("LocationTypeName")
.IsRequired()
.HasColumnType("nvarchar(50)")
.HasMaxLength(50);
b.Property<string>("PartitionKey")
.HasColumnType("nvarchar(max)");
b.HasKey("RowKey");
b.HasIndex("LocationTypeKey")
.IsUnique()
.HasName("IX_LocationType_Key");
b.ToTable("LocationType","Locality");
});
modelBuilder.Entity("GoodToCode.Locality.Models.ResourceLocation", b =>
{
b.Property<Guid>("RowKey")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<Guid>("LocationKey")
.HasColumnType("uniqueidentifier");
b.Property<Guid?>("LocationTypeKey")
.HasColumnType("uniqueidentifier");
b.Property<string>("PartitionKey")
.HasColumnType("nvarchar(max)");
b.Property<Guid>("ResourceKey")
.HasColumnType("uniqueidentifier");
b.Property<Guid>("ResourceLocationKey")
.HasColumnType("uniqueidentifier");
b.HasKey("RowKey");
b.HasIndex("ResourceKey", "LocationKey")
.IsUnique()
.HasName("IX_ResourceLocation_All");
b.ToTable("ResourceLocation","Locality");
});
modelBuilder.Entity("GoodToCode.Locality.Models.VentureLocation", b =>
{
b.Property<Guid>("RowKey")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<Guid>("LocationKey")
.HasColumnType("uniqueidentifier");
b.Property<Guid?>("LocationTypeKey")
.HasColumnType("uniqueidentifier");
b.Property<string>("PartitionKey")
.HasColumnType("nvarchar(max)");
b.Property<Guid>("VentureKey")
.HasColumnType("uniqueidentifier");
b.Property<Guid>("VentureLocationKey")
.HasColumnType("uniqueidentifier");
b.HasKey("RowKey");
b.HasIndex("VentureLocationKey")
.IsUnique()
.HasName("IX_VentureLocation_Key");
b.HasIndex("VentureKey", "LocationKey")
.IsUnique()
.HasName("IX_VentureLocation_All");
b.ToTable("VentureLocation","Locality");
});
#pragma warning restore 612, 618
}
}
}
| 36.44403 | 117 | 0.475991 | [
"Apache-2.0"
] | goodtocode/stack | deploy/Locality.Infrastructure.Persistence.Migrations/Migrations/20201025024420_20201024-194355.Designer.cs | 9,769 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Immutable;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
/// <summary>
/// State machine interface property implementation.
/// </summary>
internal class SynthesizedStateMachineProperty : PropertySymbol, ISynthesizedMethodBodyImplementationSymbol
{
private readonly SynthesizedStateMachineMethod _getter;
private readonly string _name;
internal SynthesizedStateMachineProperty(
MethodSymbol interfacePropertyGetter,
StateMachineTypeSymbol stateMachineType)
{
_name = ExplicitInterfaceHelpers.GetMemberName(interfacePropertyGetter.AssociatedSymbol.Name, interfacePropertyGetter.ContainingType, aliasQualifierOpt: null);
var getterName = ExplicitInterfaceHelpers.GetMemberName(interfacePropertyGetter.Name, interfacePropertyGetter.ContainingType, aliasQualifierOpt: null);
_getter = new SynthesizedStateMachineDebuggerHiddenMethod(
getterName,
interfacePropertyGetter,
stateMachineType,
associatedProperty: this,
hasMethodBodyDependency: false);
}
public override string Name
{
get { return _name; }
}
public override RefKind RefKind
{
get { return RefKind.None; }
}
public override TypeWithAnnotations TypeWithAnnotations
{
get { return _getter.ReturnTypeWithAnnotations; }
}
public override ImmutableArray<CustomModifier> RefCustomModifiers
{
get { return _getter.RefCustomModifiers; }
}
public override ImmutableArray<ParameterSymbol> Parameters
{
get { return _getter.Parameters; }
}
public override bool IsIndexer
{
get { return !_getter.Parameters.IsEmpty; }
}
internal override bool HasSpecialName
{
get { return false; }
}
public override MethodSymbol GetMethod
{
get { return _getter; }
}
public override MethodSymbol SetMethod
{
get { return null; }
}
internal override Cci.CallingConvention CallingConvention
{
get { return _getter.CallingConvention; }
}
internal override bool MustCallMethodsDirectly
{
get { return false; }
}
private PropertySymbol ImplementedProperty
{
get
{
return (PropertySymbol)_getter.ExplicitInterfaceImplementations[0].AssociatedSymbol;
}
}
public override ImmutableArray<PropertySymbol> ExplicitInterfaceImplementations
{
get { return ImmutableArray.Create(ImplementedProperty); }
}
public override Symbol ContainingSymbol
{
get { return _getter.ContainingSymbol; }
}
public override ImmutableArray<Location> Locations
{
get { return ImmutableArray<Location>.Empty; }
}
public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences
{
get { return ImmutableArray<SyntaxReference>.Empty; }
}
public override Accessibility DeclaredAccessibility
{
get { return _getter.DeclaredAccessibility; }
}
public override bool IsStatic
{
get { return _getter.IsStatic; }
}
public override bool IsVirtual
{
get { return _getter.IsVirtual; }
}
public override bool IsOverride
{
get { return false; }
}
public override bool IsAbstract
{
get { return false; }
}
public override bool IsSealed
{
get { return false; }
}
public override bool IsExtern
{
get { return false; }
}
internal override ObsoleteAttributeData ObsoleteAttributeData
{
get { return null; }
}
bool ISynthesizedMethodBodyImplementationSymbol.HasMethodBodyDependency
{
get { return _getter.HasMethodBodyDependency; }
}
IMethodSymbol ISynthesizedMethodBodyImplementationSymbol.Method
{
get { return ((ISynthesizedMethodBodyImplementationSymbol)ContainingSymbol).Method; }
}
}
}
| 28.418182 | 171 | 0.608232 | [
"Apache-2.0"
] | GKotfis/roslyn | src/Compilers/CSharp/Portable/Lowering/StateMachineRewriter/SynthesizedStateMachineProperty.cs | 4,691 | C# |
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace LeetCode.Test
{
[TestClass]
public class _0767_ReorganizeString_Test
{
[TestMethod]
public void ReorganizeString_1()
{
var solution = new _0767_ReorganizeString();
var result = solution.ReorganizeString("aab");
Assert.AreEqual("aba", result);
}
[TestMethod]
public void ReorganizeString_2()
{
var solution = new _0767_ReorganizeString();
var result = solution.ReorganizeString("aaab");
Assert.AreEqual("", result);
}
[TestMethod]
public void ReorganizeString_3()
{
var solution = new _0767_ReorganizeString();
var result = solution.ReorganizeString("vvvlo");
Assert.AreEqual("vovlv", result);
}
}
}
| 26.787879 | 60 | 0.582579 | [
"MIT"
] | BigEggStudy/LeetCode-CS | LeetCode.Test/0751-0800/0767-ReorganizeString-Test.cs | 884 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using ProductMonitor.Domain.Model;
using ProductMonitor.Domain.Interface;
namespace ProductMonitor.Desktop.ViewModel
{
public class ProductViewModel : BaseViewModel
{
#region Private Fields
private Product _product = new Product();
private int _index = 0;
#endregion
#region Public / Protected Properties
public Product Model
{
get { return _product; }
}
public int Index
{
get { return _index; }
set
{
if (_index != value)
{
_index = value;
this.RaisePropertyChanged(() => this.Index);
}
}
}
public string Name
{
get { return _product.Name; }
set
{
if (_product.Name != value)
{
_product.Name = value;
this.RaisePropertyChanged(() => this.Name);
}
}
}
public string Price
{
get { return _product.Price; }
set
{
if (_product.Price != value)
{
_product.Price = value;
this.RaisePropertyChanged(() => this.Price);
}
}
}
public bool HasProduct
{
get { return _product.HasProduct; }
set
{
if (_product.HasProduct != value)
{
_product.HasProduct = value;
this.RaisePropertyChanged(() => this.HasProduct);
}
}
}
public string Url
{
get { return _product.Url; }
set
{
if (_product.Url != value)
{
_product.Url = value;
this.RaisePropertyChanged(() => this.Url);
}
}
}
#endregion
#region Command / Event
public ICommand DeleteCommand { get; set; }
#endregion
#region Constructor
public ProductViewModel()
{
}
public ProductViewModel(Product product)
{
_product = product;
}
#endregion
#region Private Methods
#endregion
#region Public /Protected Methods
#endregion
}
}
| 21.264 | 69 | 0.446576 | [
"MIT"
] | AlexQianjin/ProductMonitor | ProductMonitor.Desktop/ViewModel/ProductViewModel.cs | 2,660 | C# |
using System.Configuration;
namespace CompositeC1Contrib.Teasers.Configuration
{
public class TeasersSection : ConfigurationSection
{
[ConfigurationProperty("designs", IsRequired = false)]
public TeasersDesignCollection Designs
{
get { return (TeasersDesignCollection)this["designs"]; }
set { this["designs"] = value; }
}
[ConfigurationProperty("positions", IsRequired = true)]
public TeasersPositionCollection Positions
{
get { return (TeasersPositionCollection)this["positions"]; }
set { this["positions"] = value; }
}
[ConfigurationProperty("templates", IsRequired = true)]
public TeasersTemplateCollection Templates
{
get { return (TeasersTemplateCollection)this["templates"]; }
set { this["templates"] = value; }
}
public static TeasersSection GetSection()
{
return ConfigurationManager.GetSection("compositeC1Contrib/teasers") as TeasersSection;
}
}
}
| 31.735294 | 100 | 0.624652 | [
"MIT"
] | burningice2866/CompositeC1Contrib | Teasers/Configuration/TeasersSection.cs | 1,081 | C# |
using System;
using System.Threading;
namespace Common.Logging
{
/// <summary>
/// Correlation context.
/// </summary>
/// <remarks>Propagates correlation id.</remarks>
public static class CorrelationContext
{
private const string CorrelationIdIsAlreadySpecified = "Correlation id is already specified.";
private static readonly AsyncLocal<string> Id = new ();
/// <summary>
/// Gets correlation id.
/// </summary>
public static string CorrelationId
{
get => Id.Value;
internal set
{
if (Id.Value == null)
{
Id.Value = value;
}
else
{
throw new InvalidOperationException(CorrelationIdIsAlreadySpecified);
}
}
}
/// <summary>
/// Gets a value indicating whether correlation id is specified.
/// </summary>
internal static bool IsSpecified => Id.Value != null;
}
} | 27.538462 | 102 | 0.521415 | [
"MIT"
] | tonynuke/Shop | Shared/Common.Logging/CorrelationContext.cs | 1,076 | C# |
/*
* Copyright(c) 2018 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using Tizen.NUI.Binding;
using Tizen.NUI.Binding.Internals;
namespace Tizen.NUI
{
/**
* @brief Event arguments that passed via NUIApplicationInit signal
*
*/
internal class NUIApplicationInitEventArgs : EventArgs
{
private Application _application;
/**
* @brief Application - is the application that is being initialized
*
*/
public Application Application
{
get
{
return _application;
}
set
{
_application = value;
}
}
}
/**
* @brief Event arguments that passed via NUIApplicationTerminate signal
*
*/
internal class NUIApplicationTerminatingEventArgs : EventArgs
{
private Application _application;
/**
* @brief Application - is the application that is being Terminated
*
*/
public Application Application
{
get
{
return _application;
}
set
{
_application = value;
}
}
}
/**
* @brief Event arguments that passed via NUIApplicationPause signal
*
*/
internal class NUIApplicationPausedEventArgs : EventArgs
{
private Application _application;
/**
* @brief Application - is the application that is being Paused
*
*/
public Application Application
{
get
{
return _application;
}
set
{
_application = value;
}
}
}
/**
* @brief Event arguments that passed via NUIApplicationResume signal
*
*/
internal class NUIApplicationResumedEventArgs : EventArgs
{
private Application _application;
/**
* @brief Application - is the application that is being Resumed
*
*/
public Application Application
{
get
{
return _application;
}
set
{
_application = value;
}
}
}
/**
* @brief Event arguments that passed via NUIApplicationReset signal
*
*/
internal class NUIApplicationResetEventArgs : EventArgs
{
private Application _application;
/**
* @brief Application - is the application that is being Reset
*
*/
public Application Application
{
get
{
return _application;
}
set
{
_application = value;
}
}
}
/**
* @brief Event arguments that passed via NUIApplicationLanguageChanged signal
*
*/
internal class NUIApplicationLanguageChangedEventArgs : EventArgs
{
private Application _application;
/**
* @brief Application - is the application that is being affected with Device's language change
*
*/
public Application Application
{
get
{
return _application;
}
set
{
_application = value;
}
}
}
/**
* @brief Event arguments that passed via NUIApplicationRegionChanged signal
*
*/
internal class NUIApplicationRegionChangedEventArgs : EventArgs
{
private Application _application;
/**
* @brief Application - is the application that is being affected with Device's region change
*
*/
public Application Application
{
get
{
return _application;
}
set
{
_application = value;
}
}
}
/**
* @brief Event arguments that passed via NUIApplicationBatteryLow signal
*
*/
internal class NUIApplicationBatteryLowEventArgs : EventArgs
{
private Application.BatteryStatus _status;
/**
* @brief Application - is the application that is being affected when the battery level of the device is low
*
*/
public Application.BatteryStatus BatteryStatus
{
get
{
return _status;
}
set
{
_status = value;
}
}
}
/**
* @brief Event arguments that passed via NUIApplicationMemoryLow signal
*
*/
internal class NUIApplicationMemoryLowEventArgs : EventArgs
{
private Application.MemoryStatus _status;
/**
* @brief Application - is the application that is being affected when the memory level of the device is low
*
*/
public Application.MemoryStatus MemoryStatus
{
get
{
return _status;
}
set
{
_status = value;
}
}
}
/**
* @brief Event arguments that passed via NUIApplicationAppControl signal
*
*/
internal class NUIApplicationAppControlEventArgs : EventArgs
{
private Application _application;
private IntPtr _voidp;
/**
* @brief Application - is the application that is receiving the launch request from another application
*
*/
public Application Application
{
get
{
return _application;
}
set
{
_application = value;
}
}
/**
* @brief VoidP - contains the information about why the application is launched
*
*/
public IntPtr VoidP
{
get
{
return _voidp;
}
set
{
_voidp = value;
}
}
}
/// <summary>
/// A class to get resources in current application.
/// </summary>
public class GetResourcesProvider
{
/// <summary>
/// Get resources in current application.
/// </summary>
static public IResourcesProvider Get()
{
return Tizen.NUI.Application.Current;
}
}
internal class Application : BaseHandle, IResourcesProvider, IElementConfiguration<Application>
{
static Application s_current;
ReadOnlyCollection<Element> _logicalChildren;
static SemaphoreSlim SaveSemaphore = new SemaphoreSlim(1, 1);
[EditorBrowsable(EditorBrowsableState.Never)]
public static void SetCurrentApplication(Application value) => Current = value;
public static Application Current
{
get { return s_current; }
set
{
if (s_current == value)
return;
if (value == null)
s_current = null; //Allow to reset current for unittesting
s_current = value;
}
}
internal override ReadOnlyCollection<Element> LogicalChildrenInternal
{
get { return _logicalChildren ?? (_logicalChildren = new ReadOnlyCollection<Element>(InternalChildren)); }
}
internal IResourceDictionary SystemResources { get; }
ObservableCollection<Element> InternalChildren { get; } = new ObservableCollection<Element>();
ResourceDictionary _resources;
public bool IsResourcesCreated => _resources != null;
public delegate void resChangeCb(object sender, ResourcesChangedEventArgs e);
static private Dictionary<object, Dictionary<resChangeCb, int>> resourceChangeCallbackDict = new Dictionary<object, Dictionary<resChangeCb, int>>();
static public void AddResourceChangedCallback(object handle, resChangeCb cb)
{
Dictionary<resChangeCb, int> cbDict;
resourceChangeCallbackDict.TryGetValue(handle, out cbDict);
if (null == cbDict)
{
cbDict = new Dictionary<resChangeCb, int>();
resourceChangeCallbackDict.Add(handle, cbDict);
}
if (false == cbDict.ContainsKey(cb))
{
cbDict.Add(cb, 0);
}
}
internal override void OnResourcesChanged(object sender, ResourcesChangedEventArgs e)
{
base.OnResourcesChanged(sender, e);
foreach (KeyValuePair<object, Dictionary<resChangeCb, int>> resourcePair in resourceChangeCallbackDict)
{
foreach (KeyValuePair<resChangeCb, int> cbPair in resourcePair.Value)
{
cbPair.Key(sender, e);
}
}
}
public ResourceDictionary XamlResources
{
get
{
if (_resources != null)
return _resources;
_resources = new ResourceDictionary();
int hashCode = _resources.GetHashCode();
((IResourceDictionary)_resources).ValuesChanged += OnResourcesChanged;
return _resources;
}
set
{
if (_resources == value)
return;
OnPropertyChanging();
if (_resources != null)
((IResourceDictionary)_resources).ValuesChanged -= OnResourcesChanged;
_resources = value;
OnResourcesChanged(value);
if (_resources != null)
((IResourceDictionary)_resources).ValuesChanged += OnResourcesChanged;
OnPropertyChanged();
}
}
protected override void OnParentSet()
{
throw new InvalidOperationException("Setting a Parent on Application is invalid.");
}
[EditorBrowsable(EditorBrowsableState.Never)]
public static bool IsApplicationOrNull(Element element)
{
return element == null || element is Application;
}
internal override void OnParentResourcesChanged(IEnumerable<KeyValuePair<string, object>> values)
{
if (!((IResourcesProvider)this).IsResourcesCreated || XamlResources.Count == 0)
{
base.OnParentResourcesChanged(values);
return;
}
var innerKeys = new HashSet<string>();
var changedResources = new List<KeyValuePair<string, object>>();
foreach (KeyValuePair<string, object> c in XamlResources)
innerKeys.Add(c.Key);
foreach (KeyValuePair<string, object> value in values)
{
if (innerKeys.Add(value.Key))
changedResources.Add(value);
}
OnResourcesChanged(changedResources);
}
internal Application(global::System.IntPtr cPtr, bool cMemoryOwn) : base(NDalicPINVOKE.Application_SWIGUpcast(cPtr), cMemoryOwn)
{
SetCurrentApplication(this);
s_current = this;
}
internal static global::System.Runtime.InteropServices.HandleRef getCPtr(Application obj)
{
return (obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr;
}
protected override void Dispose(DisposeTypes type)
{
if (disposed)
{
return;
}
//Release your own unmanaged resources here.
//You should not access any managed member here except static instance.
//because the execution order of Finalizes is non-deterministic.
if (_applicationInitEventCallbackDelegate != null)
{
this.InitSignal().Disconnect(_applicationInitEventCallbackDelegate);
}
if (_applicationTerminateEventCallbackDelegate != null)
{
this.TerminateSignal().Disconnect(_applicationTerminateEventCallbackDelegate);
}
if (_applicationPauseEventCallbackDelegate != null)
{
this.PauseSignal().Disconnect(_applicationPauseEventCallbackDelegate);
}
if (_applicationResumeEventCallbackDelegate != null)
{
this.ResumeSignal().Disconnect(_applicationResumeEventCallbackDelegate);
}
if (_applicationResetEventCallbackDelegate != null)
{
this.ResetSignal().Disconnect(_applicationResetEventCallbackDelegate);
}
if (_applicationLanguageChangedEventCallbackDelegate != null)
{
this.LanguageChangedSignal().Disconnect(_applicationLanguageChangedEventCallbackDelegate);
}
if (_applicationRegionChangedEventCallbackDelegate != null)
{
this.RegionChangedSignal().Disconnect(_applicationRegionChangedEventCallbackDelegate);
}
if (_applicationBatteryLowEventCallbackDelegate != null)
{
this.BatteryLowSignal().Disconnect(_applicationBatteryLowEventCallbackDelegate);
}
if (_applicationMemoryLowEventCallbackDelegate != null)
{
this.MemoryLowSignal().Disconnect(_applicationMemoryLowEventCallbackDelegate);
}
if (_applicationAppControlEventCallbackDelegate != null)
{
this.AppControlSignal().Disconnect(_applicationAppControlEventCallbackDelegate);
}
base.Dispose(type);
}
protected override void ReleaseSwigCPtr(System.Runtime.InteropServices.HandleRef swigCPtr)
{
Interop.Application.delete_Application(swigCPtr);
}
/// <since_tizen> 4 </since_tizen>
public enum BatteryStatus
{
Normal,
CriticallyLow,
PowerOff
};
/// <since_tizen> 4 </since_tizen>
public enum MemoryStatus
{
Normal,
Low,
CriticallyLow
};
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate void NUIApplicationInitEventCallbackDelegate(IntPtr application);
private DaliEventHandler<object, NUIApplicationInitEventArgs> _applicationInitEventHandler;
private NUIApplicationInitEventCallbackDelegate _applicationInitEventCallbackDelegate;
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate void NUIApplicationTerminateEventCallbackDelegate(IntPtr application);
private DaliEventHandler<object, NUIApplicationTerminatingEventArgs> _applicationTerminateEventHandler;
private NUIApplicationTerminateEventCallbackDelegate _applicationTerminateEventCallbackDelegate;
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate void NUIApplicationPauseEventCallbackDelegate(IntPtr application);
private DaliEventHandler<object, NUIApplicationPausedEventArgs> _applicationPauseEventHandler;
private NUIApplicationPauseEventCallbackDelegate _applicationPauseEventCallbackDelegate;
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate void NUIApplicationResumeEventCallbackDelegate(IntPtr application);
private DaliEventHandler<object, NUIApplicationResumedEventArgs> _applicationResumeEventHandler;
private NUIApplicationResumeEventCallbackDelegate _applicationResumeEventCallbackDelegate;
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate void NUIApplicationResetEventCallbackDelegate(IntPtr application);
private DaliEventHandler<object, NUIApplicationResetEventArgs> _applicationResetEventHandler;
private NUIApplicationResetEventCallbackDelegate _applicationResetEventCallbackDelegate;
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate void NUIApplicationLanguageChangedEventCallbackDelegate(IntPtr application);
private DaliEventHandler<object, NUIApplicationLanguageChangedEventArgs> _applicationLanguageChangedEventHandler;
private NUIApplicationLanguageChangedEventCallbackDelegate _applicationLanguageChangedEventCallbackDelegate;
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate void NUIApplicationRegionChangedEventCallbackDelegate(IntPtr application);
private DaliEventHandler<object, NUIApplicationRegionChangedEventArgs> _applicationRegionChangedEventHandler;
private NUIApplicationRegionChangedEventCallbackDelegate _applicationRegionChangedEventCallbackDelegate;
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate void NUIApplicationBatteryLowEventCallbackDelegate(BatteryStatus status);
private DaliEventHandler<object, NUIApplicationBatteryLowEventArgs> _applicationBatteryLowEventHandler;
private NUIApplicationBatteryLowEventCallbackDelegate _applicationBatteryLowEventCallbackDelegate;
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate void NUIApplicationMemoryLowEventCallbackDelegate(MemoryStatus status);
private DaliEventHandler<object, NUIApplicationMemoryLowEventArgs> _applicationMemoryLowEventHandler;
private NUIApplicationMemoryLowEventCallbackDelegate _applicationMemoryLowEventCallbackDelegate;
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate void NUIApplicationAppControlEventCallbackDelegate(IntPtr application, IntPtr voidp);
private DaliEventHandler<object, NUIApplicationAppControlEventArgs> _applicationAppControlEventHandler;
private NUIApplicationAppControlEventCallbackDelegate _applicationAppControlEventCallbackDelegate;
/**
* @brief Event for Initialized signal which can be used to subscribe/unsubscribe the event handler
* provided by the user. Initialized signal is emitted when application is initialised
*/
public event DaliEventHandler<object, NUIApplicationInitEventArgs> Initialized
{
add
{
lock (this)
{
// Restricted to only one listener
if (_applicationInitEventHandler == null)
{
_applicationInitEventHandler += value;
_applicationInitEventCallbackDelegate = new NUIApplicationInitEventCallbackDelegate(OnApplicationInit);
this.InitSignal().Connect(_applicationInitEventCallbackDelegate);
}
}
}
remove
{
lock (this)
{
if (_applicationInitEventHandler != null)
{
this.InitSignal().Disconnect(_applicationInitEventCallbackDelegate);
}
_applicationInitEventHandler -= value;
}
}
}
// Callback for Application InitSignal
private void OnApplicationInit(IntPtr data)
{
// Initialize DisposeQueue Singleton class. This is also required to create DisposeQueue on main thread.
DisposeQueue.Instance.Initialize();
if (_applicationInitEventHandler != null)
{
NUIApplicationInitEventArgs e = new NUIApplicationInitEventArgs();
e.Application = this;
_applicationInitEventHandler.Invoke(this, e);
}
}
/**
* @brief Event for Terminated signal which can be used to subscribe/unsubscribe the event handler
* provided by the user. Terminated signal is emitted when application is terminating
*/
public event DaliEventHandler<object, NUIApplicationTerminatingEventArgs> Terminating
{
add
{
lock (this)
{
// Restricted to only one listener
if (_applicationTerminateEventHandler == null)
{
_applicationTerminateEventHandler += value;
_applicationTerminateEventCallbackDelegate = new NUIApplicationTerminateEventCallbackDelegate(OnNUIApplicationTerminate);
this.TerminateSignal().Connect(_applicationTerminateEventCallbackDelegate);
}
}
}
remove
{
lock (this)
{
if (_applicationTerminateEventHandler != null)
{
this.TerminateSignal().Disconnect(_applicationTerminateEventCallbackDelegate);
}
_applicationTerminateEventHandler -= value;
}
}
}
// Callback for Application TerminateSignal
private void OnNUIApplicationTerminate(IntPtr data)
{
if (_applicationTerminateEventHandler != null)
{
NUIApplicationTerminatingEventArgs e = new NUIApplicationTerminatingEventArgs();
e.Application = this;
_applicationTerminateEventHandler.Invoke(this, e);
}
List<Window> windows = GetWindowList();
foreach (Window window in windows)
{
window?.DisconnectNativeSignals();
}
}
/**
* @brief Event for Paused signal which can be used to subscribe/unsubscribe the event handler
* provided by the user. Paused signal is emitted when application is paused
*/
public event DaliEventHandler<object, NUIApplicationPausedEventArgs> Paused
{
add
{
lock (this)
{
// Restricted to only one listener
if (_applicationPauseEventHandler == null)
{
_applicationPauseEventHandler += value;
_applicationPauseEventCallbackDelegate = new NUIApplicationPauseEventCallbackDelegate(OnNUIApplicationPause);
this.PauseSignal().Connect(_applicationPauseEventCallbackDelegate);
}
}
}
remove
{
lock (this)
{
if (_applicationPauseEventHandler != null)
{
this.PauseSignal().Disconnect(_applicationPauseEventCallbackDelegate);
}
_applicationPauseEventHandler -= value;
}
}
}
// Callback for Application PauseSignal
private void OnNUIApplicationPause(IntPtr data)
{
if (_applicationPauseEventHandler != null)
{
NUIApplicationPausedEventArgs e = new NUIApplicationPausedEventArgs();
e.Application = this;
_applicationPauseEventHandler.Invoke(this, e);
}
}
/**
* @brief Event for Resumed signal which can be used to subscribe/unsubscribe the event handler
* provided by the user. Resumed signal is emitted when application is resumed
*/
public event DaliEventHandler<object, NUIApplicationResumedEventArgs> Resumed
{
add
{
lock (this)
{
// Restricted to only one listener
if (_applicationResumeEventHandler == null)
{
_applicationResumeEventHandler += value;
_applicationResumeEventCallbackDelegate = new NUIApplicationResumeEventCallbackDelegate(OnNUIApplicationResume);
this.ResumeSignal().Connect(_applicationResumeEventCallbackDelegate);
}
}
}
remove
{
lock (this)
{
if (_applicationResumeEventHandler != null)
{
this.ResumeSignal().Disconnect(_applicationResumeEventCallbackDelegate);
}
_applicationResumeEventHandler -= value;
}
}
}
// Callback for Application ResumeSignal
private void OnNUIApplicationResume(IntPtr data)
{
if (_applicationResumeEventHandler != null)
{
NUIApplicationResumedEventArgs e = new NUIApplicationResumedEventArgs();
e.Application = this;
_applicationResumeEventHandler.Invoke(this, e);
}
}
/**
* @brief Event for Reset signal which can be used to subscribe/unsubscribe the event handler
* provided by the user. Reset signal is emitted when application is reset
*/
public new event DaliEventHandler<object, NUIApplicationResetEventArgs> Reset
{
add
{
lock (this)
{
// Restricted to only one listener
if (_applicationResetEventHandler == null)
{
_applicationResetEventHandler += value;
_applicationResetEventCallbackDelegate = new NUIApplicationResetEventCallbackDelegate(OnNUIApplicationReset);
this.ResetSignal().Connect(_applicationResetEventCallbackDelegate);
}
}
}
remove
{
lock (this)
{
if (_applicationResetEventHandler != null)
{
this.ResetSignal().Disconnect(_applicationResetEventCallbackDelegate);
}
_applicationResetEventHandler -= value;
}
}
}
// Callback for Application ResetSignal
private void OnNUIApplicationReset(IntPtr data)
{
if (_applicationResetEventHandler != null)
{
NUIApplicationResetEventArgs e = new NUIApplicationResetEventArgs();
e.Application = this;
_applicationResetEventHandler.Invoke(this, e);
}
}
/**
* @brief Event for LanguageChanged signal which can be used to subscribe/unsubscribe the event handler
* provided by the user. LanguageChanged signal is emitted when the region of the device is changed.
*/
public event DaliEventHandler<object, NUIApplicationLanguageChangedEventArgs> LanguageChanged
{
add
{
lock (this)
{
// Restricted to only one listener
if (_applicationLanguageChangedEventHandler == null)
{
_applicationLanguageChangedEventHandler += value;
_applicationLanguageChangedEventCallbackDelegate = new NUIApplicationLanguageChangedEventCallbackDelegate(OnNUIApplicationLanguageChanged);
this.LanguageChangedSignal().Connect(_applicationLanguageChangedEventCallbackDelegate);
}
}
}
remove
{
lock (this)
{
if (_applicationLanguageChangedEventHandler != null)
{
this.LanguageChangedSignal().Disconnect(_applicationLanguageChangedEventCallbackDelegate);
}
_applicationLanguageChangedEventHandler -= value;
}
}
}
// Callback for Application LanguageChangedSignal
private void OnNUIApplicationLanguageChanged(IntPtr data)
{
if (_applicationLanguageChangedEventHandler != null)
{
NUIApplicationLanguageChangedEventArgs e = new NUIApplicationLanguageChangedEventArgs();
e.Application = this;
_applicationLanguageChangedEventHandler.Invoke(this, e);
}
}
/**
* @brief Event for RegionChanged signal which can be used to subscribe/unsubscribe the event handler
* provided by the user. RegionChanged signal is emitted when the region of the device is changed.
*/
public event DaliEventHandler<object, NUIApplicationRegionChangedEventArgs> RegionChanged
{
add
{
lock (this)
{
// Restricted to only one listener
if (_applicationRegionChangedEventHandler == null)
{
_applicationRegionChangedEventHandler += value;
_applicationRegionChangedEventCallbackDelegate = new NUIApplicationRegionChangedEventCallbackDelegate(OnNUIApplicationRegionChanged);
this.RegionChangedSignal().Connect(_applicationRegionChangedEventCallbackDelegate);
}
}
}
remove
{
lock (this)
{
if (_applicationRegionChangedEventHandler != null)
{
this.RegionChangedSignal().Disconnect(_applicationRegionChangedEventCallbackDelegate);
}
_applicationRegionChangedEventHandler -= value;
}
}
}
// Callback for Application RegionChangedSignal
private void OnNUIApplicationRegionChanged(IntPtr data)
{
if (_applicationRegionChangedEventHandler != null)
{
NUIApplicationRegionChangedEventArgs e = new NUIApplicationRegionChangedEventArgs();
e.Application = this;
_applicationRegionChangedEventHandler.Invoke(this, e);
}
}
/**
* @brief Event for BatteryLow signal which can be used to subscribe/unsubscribe the event handler
* provided by the user. BatteryLow signal is emitted when the battery level of the device is low.
*/
public event DaliEventHandler<object, NUIApplicationBatteryLowEventArgs> BatteryLow
{
add
{
lock (this)
{
// Restricted to only one listener
if (_applicationBatteryLowEventHandler == null)
{
_applicationBatteryLowEventHandler += value;
_applicationBatteryLowEventCallbackDelegate = new NUIApplicationBatteryLowEventCallbackDelegate(OnNUIApplicationBatteryLow);
this.BatteryLowSignal().Connect(_applicationBatteryLowEventCallbackDelegate);
}
}
}
remove
{
lock (this)
{
if (_applicationBatteryLowEventHandler != null)
{
this.BatteryLowSignal().Disconnect(_applicationBatteryLowEventCallbackDelegate);
}
_applicationBatteryLowEventHandler -= value;
}
}
}
// Callback for Application BatteryLowSignal
private void OnNUIApplicationBatteryLow(BatteryStatus status)
{
lock (this)
{
NUIApplicationBatteryLowEventArgs e = new NUIApplicationBatteryLowEventArgs();
// Populate all members of "e" (NUIApplicationBatteryLowEventArgs) with real data
e.BatteryStatus = status;
_applicationBatteryLowEventHandler?.Invoke(this, e);
}
}
/**
* @brief Event for MemoryLow signal which can be used to subscribe/unsubscribe the event handler
* provided by the user. MemoryLow signal is emitted when the memory level of the device is low.
*/
public event DaliEventHandler<object, NUIApplicationMemoryLowEventArgs> MemoryLow
{
add
{
lock (this)
{
// Restricted to only one listener
if (_applicationMemoryLowEventHandler == null)
{
_applicationMemoryLowEventHandler += value;
_applicationMemoryLowEventCallbackDelegate = new NUIApplicationMemoryLowEventCallbackDelegate(OnNUIApplicationMemoryLow);
this.MemoryLowSignal().Connect(_applicationMemoryLowEventCallbackDelegate);
}
}
}
remove
{
lock (this)
{
if (_applicationMemoryLowEventHandler != null)
{
this.MemoryLowSignal().Disconnect(_applicationMemoryLowEventCallbackDelegate);
}
_applicationMemoryLowEventHandler -= value;
}
}
}
// Callback for Application MemoryLowSignal
private void OnNUIApplicationMemoryLow(MemoryStatus status)
{
lock (this)
{
NUIApplicationMemoryLowEventArgs e = new NUIApplicationMemoryLowEventArgs();
// Populate all members of "e" (NUIApplicationMemoryLowEventArgs) with real data
e.MemoryStatus = status;
_applicationMemoryLowEventHandler?.Invoke(this, e);
}
}
/**
* @brief Event for AppControl signal which can be used to subscribe/unsubscribe the event handler
* provided by the user. AppControl signal is emitted when another application sends a launch request to the application.
*/
public event DaliEventHandler<object, NUIApplicationAppControlEventArgs> AppControl
{
add
{
lock (this)
{
// Restricted to only one listener
if (_applicationAppControlEventHandler == null)
{
_applicationAppControlEventHandler += value;
_applicationAppControlEventCallbackDelegate = new NUIApplicationAppControlEventCallbackDelegate(OnNUIApplicationAppControl);
this.AppControlSignal().Connect(_applicationAppControlEventCallbackDelegate);
}
}
}
remove
{
lock (this)
{
if (_applicationAppControlEventHandler != null)
{
this.AppControlSignal().Disconnect(_applicationAppControlEventCallbackDelegate);
}
_applicationAppControlEventHandler -= value;
}
}
}
// Callback for Application AppControlSignal
private void OnNUIApplicationAppControl(IntPtr application, IntPtr voidp)
{
if (_applicationAppControlEventHandler != null)
{
NUIApplicationAppControlEventArgs e = new NUIApplicationAppControlEventArgs();
e.VoidP = voidp;
e.Application = this;
_applicationAppControlEventHandler.Invoke(this, e);
}
}
protected static Application _instance; // singleton
public static Application Instance
{
get
{
return _instance;
}
}
public static Application GetApplicationFromPtr(global::System.IntPtr cPtr)
{
if (cPtr == global::System.IntPtr.Zero)
{
return null;
}
Application ret = Registry.GetManagedBaseHandleFromNativePtr(cPtr) as Application;
if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve();
return ret;
}
public static Application NewApplication()
{
return NewApplication("", Application.WindowMode.Opaque);
}
public static Application NewApplication(string stylesheet)
{
return NewApplication(stylesheet, Application.WindowMode.Opaque);
}
public static Application NewApplication(string stylesheet, Application.WindowMode windowMode)
{
// register all Views with the type registry, so that can be created / styled via JSON
//ViewRegistryHelper.Initialize(); //moved to Application side.
if (_instance)
{
return _instance;
}
Application ret = New(1, stylesheet, windowMode);
if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve();
// set the singleton
_instance = ret;
return ret;
}
public static Application NewApplication(string stylesheet, Application.WindowMode windowMode, Rectangle positionSize)
{
if (_instance)
{
return _instance;
}
Application ret = New(1, stylesheet, windowMode, positionSize);
if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve();
// set the singleton
_instance = ret;
return ret;
}
public static Application NewApplication(string[] args, string stylesheet, Application.WindowMode windowMode)
{
if (_instance)
{
return _instance;
}
Application ret = New(args, stylesheet, (Application.WindowMode)windowMode);
if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve();
// set the singleton
_instance = ret;
return _instance;
}
public static Application NewApplication(string[] args, string stylesheet, Application.WindowMode windowMode, Rectangle positionSize)
{
if (_instance)
{
return _instance;
}
Application ret = New(args, stylesheet, (Application.WindowMode)windowMode, positionSize);
if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve();
// set the singleton
_instance = ret;
return _instance;
}
/// <summary>
/// Ensures that the function passed in is called from the main loop when it is idle.
/// </summary>
/// <param name="func">The function to call</param>
/// <returns>true if added successfully, false otherwise</returns>
public bool AddIdle(System.Delegate func)
{
System.IntPtr ip = System.Runtime.InteropServices.Marshal.GetFunctionPointerForDelegate<System.Delegate>(func);
System.IntPtr ip2 = Interop.Application.MakeCallback(new System.Runtime.InteropServices.HandleRef(this, ip));
bool ret = Interop.Application.Application_AddIdle(swigCPtr, new System.Runtime.InteropServices.HandleRef(this, ip2));
if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve();
return ret;
}
/**
* Outer::outer_method(int)
*/
public static Application New()
{
Application ret = new Application(Interop.Application.Application_New__SWIG_0(), true);
if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve();
return ret;
}
public static Application New(int argc)
{
Application ret = new Application(Interop.Application.Application_New__SWIG_1(argc), true);
if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve();
return ret;
}
public static Application New(int argc, string stylesheet)
{
Application ret = new Application(Interop.Application.Application_New__SWIG_2(argc, stylesheet), true);
if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve();
return ret;
}
public static Application New(int argc, string stylesheet, Application.WindowMode windowMode)
{
Application ret = new Application(Interop.Application.Application_New__SWIG_3(argc, stylesheet, (int)windowMode), true);
if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve();
s_current = ret;
return ret;
}
public static Application New(string[] args, string stylesheet, Application.WindowMode windowMode)
{
Application ret = null;
int argc = 0;
string argvStr = "";
try
{
argc = args.Length;
argvStr = string.Join(" ", args);
}
catch (Exception exception)
{
Tizen.Log.Fatal("NUI", "[Error] got exception during Application New(), this should not occur, msg : " + exception.Message);
Tizen.Log.Fatal("NUI", "[Error] error line number : " + new StackTrace(exception, true).GetFrame(0).GetFileLineNumber());
Tizen.Log.Fatal("NUI", "[Error] Stack Trace : " + exception.StackTrace);
throw;
}
ret = new Application(NDalicPINVOKE.Application_New__MANUAL_4(argc, argvStr, stylesheet, (int)windowMode), true);
if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve();
return ret;
}
public static Application New(int argc, string stylesheet, Application.WindowMode windowMode, Rectangle positionSize)
{
Application ret = new Application(Interop.Application.Application_New__SWIG_4(argc, stylesheet, (int)windowMode, Rectangle.getCPtr(positionSize)), true);
if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve();
return ret;
}
public static Application New(string[] args, string stylesheet, Application.WindowMode windowMode, Rectangle positionSize)
{
Application ret = null;
int argc = 0;
string argvStr = "";
try
{
argc = args.Length;
argvStr = string.Join(" ", args);
}
catch (Exception exception)
{
Tizen.Log.Fatal("NUI", "[Error] got exception during Application New(), this should not occur, msg : " + exception.Message);
Tizen.Log.Fatal("NUI", "[Error] error line number : " + new StackTrace(exception, true).GetFrame(0).GetFileLineNumber());
Tizen.Log.Fatal("NUI", "[Error] Stack Trace : " + exception.StackTrace);
throw;
}
ret = new Application(NDalicPINVOKE.Application_New_WithWindowSizePosition(argc, argvStr, stylesheet, (int)windowMode, Rectangle.getCPtr(positionSize)), true);
if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve();
return ret;
}
public Application() : this(Interop.Application.new_Application__SWIG_0(), true)
{
if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve();
}
public Application(Application application) : this(Interop.Application.new_Application__SWIG_1(Application.getCPtr(application)), true)
{
if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve();
}
public Application Assign(Application application)
{
Application ret = new Application(Interop.Application.Application_Assign(swigCPtr, Application.getCPtr(application)), false);
if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve();
return ret;
}
public void MainLoop()
{
NDalicPINVOKE.Application_MainLoop__SWIG_0(swigCPtr);
if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve();
}
public void Lower()
{
Interop.Application.Application_Lower(swigCPtr);
if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve();
}
public void Quit()
{
Interop.Application.Application_Quit(swigCPtr);
if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve();
}
internal bool AddIdle(SWIGTYPE_p_Dali__CallbackBase callback)
{
bool ret = Interop.Application.Application_AddIdle(swigCPtr, SWIGTYPE_p_Dali__CallbackBase.getCPtr(callback));
if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve();
return ret;
}
public Window GetWindow()
{
Window ret = Registry.GetManagedBaseHandleFromNativePtr(Interop.Application.Application_GetWindow(swigCPtr)) as Window;
if (ret == null)
{
ret = new Window(Interop.Application.Application_GetWindow(swigCPtr), true);
}
if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve();
return ret;
}
public static string GetResourcePath()
{
string ret = Interop.Application.Application_GetResourcePath();
if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve();
return ret;
}
public string GetLanguage()
{
string ret = Interop.Application.Application_GetLanguage(swigCPtr);
if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve();
return ret;
}
public string GetRegion()
{
string ret = Interop.Application.Application_GetRegion(swigCPtr);
if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve();
return ret;
}
[EditorBrowsable(EditorBrowsableState.Never)]
public static List<Window> GetWindowList()
{
uint ListSize = Interop.Application.Application_GetWindowsListSize();
if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve();
List<Window> WindowList = new List<Window>();
for (uint i = 0; i < ListSize; ++i)
{
Window currWin = Registry.GetManagedBaseHandleFromNativePtr(Interop.Application.Application_GetWindowsFromList(i)) as Window;
if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve();
if (currWin)
{
WindowList.Add(currWin);
}
}
return WindowList;
}
internal ApplicationSignal InitSignal()
{
ApplicationSignal ret = new ApplicationSignal(NDalicPINVOKE.Application_InitSignal(swigCPtr), false);
if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve();
return ret;
}
internal ApplicationSignal TerminateSignal()
{
ApplicationSignal ret = new ApplicationSignal(NDalicPINVOKE.Application_TerminateSignal(swigCPtr), false);
if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve();
return ret;
}
internal ApplicationSignal PauseSignal()
{
ApplicationSignal ret = new ApplicationSignal(NDalicPINVOKE.Application_PauseSignal(swigCPtr), false);
if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve();
return ret;
}
internal ApplicationSignal ResumeSignal()
{
ApplicationSignal ret = new ApplicationSignal(NDalicPINVOKE.Application_ResumeSignal(swigCPtr), false);
if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve();
return ret;
}
internal ApplicationSignal ResetSignal()
{
ApplicationSignal ret = new ApplicationSignal(NDalicPINVOKE.Application_ResetSignal(swigCPtr), false);
if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve();
return ret;
}
internal ApplicationControlSignal AppControlSignal()
{
ApplicationControlSignal ret = new ApplicationControlSignal(NDalicPINVOKE.Application_AppControlSignal(swigCPtr), false);
if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve();
return ret;
}
internal ApplicationSignal LanguageChangedSignal()
{
ApplicationSignal ret = new ApplicationSignal(NDalicPINVOKE.Application_LanguageChangedSignal(swigCPtr), false);
if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve();
return ret;
}
internal ApplicationSignal RegionChangedSignal()
{
ApplicationSignal ret = new ApplicationSignal(NDalicPINVOKE.Application_RegionChangedSignal(swigCPtr), false);
if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve();
return ret;
}
internal LowBatterySignalType BatteryLowSignal()
{
LowBatterySignalType ret = new LowBatterySignalType(NDalicPINVOKE.Application_LowBatterySignal(swigCPtr), false);
if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve();
return ret;
}
internal LowMemorySignalType MemoryLowSignal()
{
LowMemorySignalType ret = new LowMemorySignalType(NDalicPINVOKE.Application_LowMemorySignal(swigCPtr), false);
if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve();
return ret;
}
/// <since_tizen> 3 </since_tizen>
public enum WindowMode
{
Opaque = 0,
Transparent = 1
}
}
}
| 37.055517 | 171 | 0.594728 | [
"Apache-2.0",
"MIT"
] | expertisesolutions/TizenFX | src/Tizen.NUI/src/internal/Application.cs | 52,730 | C# |
using System.Web;
using System.Web.Mvc;
namespace Submitter
{
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
}
}
| 18.714286 | 80 | 0.652672 | [
"MIT"
] | bogdanbrudiu/CupaTimisului | Old.NET/Submitter/App_Start/FilterConfig.cs | 264 | C# |
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
//
//*********************************************************
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
using SDKTemplate;
using System;
namespace SDKTemplate
{
public partial class DirectContentUriScenario : SDKTemplate.Common.LayoutAwarePage
{
// A pointer back to the main page. This is needed if you want to call methods in MainPage such
// as NotifyUser()
MainPage rootPage = MainPage.Current;
public DirectContentUriScenario()
{
this.InitializeComponent();
}
protected async void UpdateIfUriIsInCache(Uri uri, TextBlock cacheStatusTextBlock)
{
var filter = new Windows.Web.Http.Filters.HttpBaseProtocolFilter();
filter.CacheControl.ReadBehavior = Windows.Web.Http.Filters.HttpCacheReadBehavior.OnlyFromCache;
var httpClient = new Windows.Web.Http.HttpClient(filter);
var request = new Windows.Web.Http.HttpRequestMessage(Windows.Web.Http.HttpMethod.Get, uri);
try
{
await httpClient.SendRequestAsync(request);
cacheStatusTextBlock.Text = "Yes";
cacheStatusTextBlock.Foreground = new Windows.UI.Xaml.Media.SolidColorBrush(Windows.UI.Colors.Green);
}
catch
{
cacheStatusTextBlock.Text = "No";
cacheStatusTextBlock.Foreground = new Windows.UI.Xaml.Media.SolidColorBrush(Windows.UI.Colors.Red);
}
}
protected void UpdateUriTable()
{
DirectContentUris.Children.Clear();
UriCacheStatus.Children.Clear();
foreach (Uri uri in Windows.Networking.BackgroundTransfer.ContentPrefetcher.ContentUris)
{
DirectContentUris.Children.Add(new TextBlock() { Text = uri.ToString() });
TextBlock cacheStatusTextBlock = new TextBlock();
UriCacheStatus.Children.Add(cacheStatusTextBlock);
UpdateIfUriIsInCache(uri, cacheStatusTextBlock);
}
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
UpdateUriTable();
}
private void AddDirectUri_Click(object sender, RoutedEventArgs e)
{
Button b = sender as Button;
if (b != null)
{
String uriString = DirectContentUri.Text;
if (uriString != "")
{
Uri uri = null;
// Typically, a developer would add a predetermined URI to the ContentPrefetcher.ContentUris vector, removing the
// need for the following error checking. Because this sample takes URI input from the user, this sample validates
// the input string before passing the URI to the ContentPrefetcher API.
if (Uri.TryCreate(uriString, UriKind.RelativeOrAbsolute, out uri))
{
if (uri.IsAbsoluteUri)
{
Windows.Networking.BackgroundTransfer.ContentPrefetcher.ContentUris.Add(uri);
UpdateUriTable();
this.DirectContentUri.Text = "";
rootPage.NotifyUser("", NotifyType.StatusMessage);
}
else
{
rootPage.NotifyUser("A URI must be an absolute URI", NotifyType.ErrorMessage);
}
}
else
{
rootPage.NotifyUser("A URI must be provided that has the form scheme://address", NotifyType.ErrorMessage);
}
}
}
}
private void ClearDirectUris_Click(object sender, RoutedEventArgs e)
{
Button b = sender as Button;
if (b != null)
{
rootPage.NotifyUser("", NotifyType.StatusMessage);
Windows.Networking.BackgroundTransfer.ContentPrefetcher.ContentUris.Clear();
UpdateUriTable();
}
}
}
}
| 38.26087 | 134 | 0.5425 | [
"MIT"
] | Ranin26/msdn-code-gallery-microsoft | Official Windows Platform Sample/Windows 8.1 Store app samples/99866-Windows 8.1 Store app samples/Content prefetch sample/C#/S1-DirectContentUris.xaml.cs | 4,402 | C# |
using System;
using Newtonsoft.Json;
namespace Salesfly.Tests
{
public class Spew
{
public static void Dump(object obj)
{
Console.WriteLine(JsonConvert.SerializeObject(obj));
}
}
} | 17.615385 | 64 | 0.615721 | [
"MIT"
] | salesfly/salesfly-csharp | Salesfly.Tests/Spew.cs | 229 | C# |
using System;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using FizzWare.NBuilder;
using FluentAssertions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Moq;
using NUnit.Framework;
using VideoWeb.Controllers;
using BookingsApi.Client;
using BookingsApi.Contract.Requests;
using UserApi.Client;
using UserApi.Contract.Responses;
using VideoApi.Client;
using HealthCheckResponse = VideoWeb.Contract.Responses.HealthCheckResponse;
namespace VideoWeb.UnitTests.Controllers.HealthController
{
public class HealthTests
{
private HealthCheckController _controller;
private Mock<IVideoApiClient> _videoApiClientMock;
private Mock<IUserApiClient> _userApiClientMock;
private Mock<IBookingsApiClient> _bookingsApiClientMock;
private Mock<ILogger<HealthCheckController>> _logger;
[SetUp]
public void Setup()
{
_videoApiClientMock = new Mock<IVideoApiClient>();
_userApiClientMock = new Mock<IUserApiClient>();
_bookingsApiClientMock = new Mock<IBookingsApiClient>();
_logger = new Mock<ILogger<HealthCheckController>>();
_controller = new HealthCheckController(_videoApiClientMock.Object, _userApiClientMock.Object, _logger.Object,
_bookingsApiClientMock.Object);
var judges = Builder<UserResponse>.CreateListOfSize(3).Build().ToList();
_userApiClientMock.Setup(x => x.GetJudgesAsync())
.ReturnsAsync(judges);
}
[Test]
public async Task Should_return_internal_server_error_result_when_user_api_not_reachable()
{
var exception = new AggregateException("kinly api error");
_userApiClientMock
.Setup(x => x.GetJudgesAsync())
.ThrowsAsync(exception);
var result = await _controller.HealthAsync();
var typedResult = (ObjectResult) result;
typedResult.StatusCode.Should().Be((int) HttpStatusCode.InternalServerError);
var response = (HealthCheckResponse) typedResult.Value;
response.UserApiHealth.Successful.Should().BeFalse();
response.UserApiHealth.ErrorMessage.Should().NotBeNullOrWhiteSpace();
}
[Test]
public async Task Should_return_internal_server_error_result_when_bookings_api_not_reachable()
{
var exception = new AggregateException("kinly api error");
_bookingsApiClientMock
.Setup(x => x.GetCaseTypesAsync())
.ThrowsAsync(exception);
var result = await _controller.HealthAsync();
var typedResult = (ObjectResult) result;
typedResult.StatusCode.Should().Be((int) HttpStatusCode.InternalServerError);
var response = (HealthCheckResponse) typedResult.Value;
response.BookingsApiHealth.Successful.Should().BeFalse();
response.BookingsApiHealth.ErrorMessage.Should().NotBeNullOrWhiteSpace();
}
[Test]
public async Task Should_return_internal_server_error_result_when_video_api_not_reachable()
{
var exception = new VideoApiException<ProblemDetails>("Bad token", (int) HttpStatusCode.InternalServerError,
"Please provide a valid conference Id", null, default(ProblemDetails), null);
_videoApiClientMock
.Setup(x => x.GetExpiredOpenConferencesAsync())
.ThrowsAsync(exception);
var result = await _controller.HealthAsync();
var typedResult = (ObjectResult) result;
typedResult.StatusCode.Should().Be((int) HttpStatusCode.InternalServerError);
var response = (HealthCheckResponse) typedResult.Value;
response.VideoApiHealth.Successful.Should().BeFalse();
response.VideoApiHealth.ErrorMessage.Should().NotBeNullOrWhiteSpace();
}
[Test]
public async Task Should_return_forbidden_error_result_when_video_api_not_reachable()
{
var exception = new VideoApiException<ProblemDetails>("Unauthorised Token", (int)HttpStatusCode.Unauthorized,
"Invalid Client ID", null, default, null);
_videoApiClientMock
.Setup(x => x.GetExpiredOpenConferencesAsync())
.ThrowsAsync(exception);
var result = await _controller.HealthAsync();
var typedResult = (ObjectResult)result;
typedResult.StatusCode.Should().Be((int)HttpStatusCode.OK);
var response = (HealthCheckResponse)typedResult.Value;
response.VideoApiHealth.Successful.Should().BeTrue();
response.VideoApiHealth.ErrorMessage.Should().BeNullOrWhiteSpace();
}
[Test]
public async Task Should_return_internal_server_error_result_when_non_video_api_exception_thrown()
{
var exception = new UriFormatException("Test format is invalid");
_bookingsApiClientMock
.Setup(x => x.GetCaseTypesAsync())
.ThrowsAsync(exception);
var result = await _controller.HealthAsync();
var typedResult = (ObjectResult) result;
typedResult.StatusCode.Should().Be((int) HttpStatusCode.InternalServerError);
var response = (HealthCheckResponse) typedResult.Value;
response.BookingsApiHealth.Successful.Should().BeFalse();
response.BookingsApiHealth.ErrorMessage.Should().NotBeNullOrWhiteSpace();
}
[Test]
public async Task Should_return_ok_when_exception_is_not_internal_server_error()
{
var exception = new VideoApiException<ProblemDetails>("Bad Request", (int) HttpStatusCode.BadRequest,
"Please provide a valid conference Id", null, default(ProblemDetails), null);
_bookingsApiClientMock
.Setup(x => x.BookNewHearingAsync(It.IsAny<BookNewHearingRequest>()))
.ThrowsAsync(exception);
var result = await _controller.HealthAsync();
var typedResult = (ObjectResult) result;
typedResult.StatusCode.Should().Be((int) HttpStatusCode.OK);
var response = (HealthCheckResponse) typedResult.Value;
response.BookingsApiHealth.Successful.Should().BeTrue();
}
[Test]
public async Task Should_return_ok_when_all_services_are_running()
{
var result = await _controller.HealthAsync();
var typedResult = (ObjectResult) result;
typedResult.StatusCode.Should().Be((int) HttpStatusCode.OK);
var response = (HealthCheckResponse) typedResult.Value;
response.BookingsApiHealth.Successful.Should().BeTrue();
response.UserApiHealth.Successful.Should().BeTrue();
response.VideoApiHealth.Successful.Should().BeTrue();
response.AppVersion.Should().NotBeNull();
response.AppVersion.FileVersion.Should().NotBeNullOrWhiteSpace();
response.AppVersion.InformationVersion.Should().NotBeNullOrWhiteSpace();
}
}
}
| 43.524096 | 122 | 0.663806 | [
"MIT"
] | hmcts/vh-video-web | VideoWeb/VideoWeb.UnitTests/Controllers/HealthController/HealthTests.cs | 7,225 | C# |
using Basement.BLFramework.Core.Common;
using Basement.BLFramework.Core.Context;
using Basement.Common;
namespace Basement.BLFramework.Core.Reference.Description
{
public interface IDescription : IHasContext, IChildren<IDescription>, IParent<IDescription>
{
bool selectable { get; }
string key { get; }
RawNode GetNode();
string GetDescriptionPath();
void Initialization();
}
}
| 27 | 95 | 0.701389 | [
"MIT"
] | planetouched/Unity3d_OEPFramework | Basement/BLFramework/Core/Reference/Description/IDescription.cs | 434 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Drawing;
using System.Threading;
namespace WPrime64
{
public class Gnd
{
private static Gnd _i = null;
public static Gnd I
{
get
{
if (_i == null)
_i = new Gnd();
return _i;
}
}
private Gnd()
{
{
string file = "Prime64.exe";
if (File.Exists(file) == false)
file = @"C:\Factory\Program\Prime64\Prime64.exe";
this.Prime64File = file;
}
}
public void LoadSettingData()
{
this.SettingData = new SettingData("WPrime64.conf");
}
public string Prime64File;
public SettingData SettingData;
public readonly string PRIME_MIN_OVER_UL = "18446744073709551629"; // 2^64 以上で最小の素数 == 2^64 + 13
public readonly string FACTORY_COMMON_MUTEX = "cerulean.charlotte Factory common mutex object"; // @ C:/Factoty/Common/Mutex.c
public MainWin MainWin;
}
}
| 17.792453 | 128 | 0.672322 | [
"MIT"
] | stackprobe/Prime64 | WPrime64/WPrime64/Ground.cs | 961 | C# |
namespace WebScheduler.Server.HealthChecks;
using Microsoft.Extensions.Diagnostics.HealthChecks;
using Orleans;
using WebScheduler.Abstractions.Grains.HealthChecks;
/// <summary>
/// Verifies connectivity to a <see cref="ILocalHealthCheckGrain"/> activation. As this grain is a
/// stateless worker, validation always occurs in the silo where the health check is issued.
/// </summary>
public class GrainHealthCheck : IHealthCheck
{
private const string FailedMessage = "Failed local health check.";
private readonly IClusterClient client;
private readonly ILogger<GrainHealthCheck> logger;
public GrainHealthCheck(IClusterClient client, ILogger<GrainHealthCheck> logger)
{
this.client = client;
this.logger = logger;
}
public async Task<HealthCheckResult> CheckHealthAsync(
HealthCheckContext context,
CancellationToken cancellationToken = default)
{
try
{
await this.client.GetGrain<ILocalHealthCheckGrain>(Guid.Empty).CheckAsync().ConfigureAwait(true);
}
#pragma warning disable CA1031 // Do not catch general exception types
catch (Exception exception)
#pragma warning restore CA1031 // Do not catch general exception types
{
#pragma warning disable CA1303 // Do not pass literals as localized parameters
this.logger.FailedLocalHealthCheck(exception);
#pragma warning restore CA1303 // Do not pass literals as localized parameters
return HealthCheckResult.Unhealthy(FailedMessage, exception);
}
return HealthCheckResult.Healthy();
}
}
| 36.454545 | 109 | 0.73005 | [
"MIT"
] | ElanHasson/web-scheduler | Source/WebScheduler.Server/HealthChecks/GrainHealthCheck.cs | 1,604 | C# |
using System;
using System.Linq;
using BAFactory.Fx.FileTags.Common;
using BAFactory.Fx.FileTags.Exif.IFD;
using BAFactory.Fx.Utilities.ImageProcessing;
namespace BAFactory.Fx.FileTags.Exif.MakerNotes.Canon
{
class CanonMakerInfo : MakerInfo
{
internal override IFDHeader GetMakerNotesHeader(byte[] makerNotesFieldBytes, Endianness e, ImageFile processingFile)
{
IFDHeader result = null;
CanonMakerNotesBytesParser parser = GetMakerNotesBytesParser();
if (parser != null)
{
int offset = 8 + processingFile.TiffHeaderOffset - processingFile.MakerNotesTagOffset;
result = parser.ParseBytes(makerNotesFieldBytes.ToList(), Endianness.BigEndian, offset);
}
return result;
}
internal override IFDHeader GetMakerNotesHeader(byte[] makerNotesFieldBytes, Endianness e)
{
throw new NotImplementedException();
}
private CanonMakerNotesBytesParser GetMakerNotesBytesParser()
{
return new CanonMakerNotesBytesParser();
}
}
}
| 30.763158 | 125 | 0.642429 | [
"Apache-2.0"
] | carlos-takeapps/bafactoryfx | File Tags/Exif/MakerNotes/Canon/CanonMakerInfo.cs | 1,171 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Afonsoft.Libary.Utilities;
using LeComCre.Web.PageBase;
using LeComCre.Web.Negocios;
namespace LeComCre.Web
{
public partial class CadUsuario : pageBase
{
protected void Page_Load(object sender, EventArgs e)
{
try
{
( ( MasterCadastro )this.Master ).setUsuario = getNomeUsuarioLogado;
string op = (!string.IsNullOrEmpty(Request.QueryString["op"]) ? Request.QueryString["op"].ToLower() : "");
if (!IsPostBack)
{
if (!string.IsNullOrEmpty(op) && Utils.isNumeric(op))
{
DivCrianca.Style["display"] = "none";
DivAdulto.Style["display"] = "none";
DivProfissional.Style["display"] = "none";
DivInfoCrianca.Style[ "display" ] = "none";
DivInfoProfissional.Style[ "display" ] = "none";
int i = int.Parse(op);
switch (i)
{
case 1:
DivAdulto.Style["display"] = "block";
DivInfoProfissional.Style[ "display" ] = "block";
break;
case 2:
DivCrianca.Style["display"] = "block";
DivInfoCrianca.Style[ "display" ] = "block";
break;
case 3:
DivAdulto.Style["display"] = "block";
DivInfoProfissional.Style[ "display" ] = "block";
break;
case 4:
DivAdulto.Style["display"] = "block";
DivProfissional.Style["display"] = "block";
DivInfoProfissional.Style[ "display" ] = "block";
break;
default:
Response.Redirect("~/Cadastrar.aspx", true);
break;
}
ViewState["TipoUsuario"] = i;
}
else
{
Response.Redirect("~/Cadastrar.aspx", true);
}
}
}
catch (Exception ex)
{
LogarErro("(CadUsuario.aspx) - Page_Load", ex);
Response.Redirect("~/Cadastrar.aspx", true);
}
}
protected void btnSalvar_Click(object sender, EventArgs e)
{
try
{
if (ValidarDados())
{
Usuario user = PopularUsuario();
new NegUsuario().IncluirUsuario(user);
Alert("Usuario cadastrado com sucesso!", "Default.aspx");
Mail.SendMail( user.EMail, "Portal Educativo Lé Com Cré", "Usuario Cadastrado com sucesso, aguardando a liberação do Administrador<br/>Login: " + user.EMail + " <br/> Senha: " + user.Senha);
}
}
catch (Exception ex)
{
Alert(ex.Message);
LogarErro("(CadUsuario.aspx) - btnSalvar_Click", ex);
}
}
private Usuario PopularUsuario()
{
Usuario u = new Usuario();
u.Usuario_Profissional = new Usuario_Profissional();
u.Usuario_Pai = new Usuario_Pai();
u.Usuario_Filha = new Usuario_Filha();
u.TpUsuario = (tpUsuario)ViewState["TipoUsuario"];
u.Apelido = txtApelido.Text.Trim();
u.DtNascimento = DateTime.Parse(txtDataNascimento.Text);
u.EMail = txtEMail.Text.Trim();
u.Nome = txtNome.Text.Trim();
u.Senha = txtSenha.Text.Trim();
u.SobreNome = txtSobreNome.Text.Trim();
u.Usuario_Pai.CPF = ( u.TpUsuario == tpUsuario.Crianca ? txtCPFResponsavel.Text.Trim() : txtCPF.Text.Trim() );
u.Usuario_Filha.Nome_Escola = txtNomeEscola.Text.Trim();
u.Usuario_Filha.Nome_Mae = txtNomeMae.Text.Trim();
u.Usuario_Filha.Nome_Pai = txtNomePai.Text.Trim();
u.Usuario_Filha.Serie = txtSerieEscola.Text.Trim();
u.Usuario_Profissional.Area = (rdAtuacaoNenhuma.Checked ? "Nenhuma" : (rdAtuacaoPrivada.Checked ? "Privada" : (rdAtuacaoPublica.Checked ? "Publica" : "")));
u.Usuario_Filha.Publica = (rdPublica.Checked ? 1 : 0);
u.Usuario_Profissional.Profissao = (rdPedagogo.Checked ? "Pedagogo" : (rdPisicologo.Checked ? "Pisicologo" : (rdFonoaudiologo.Checked ? "Fonoaudiologo" : (rdOutros.Checked ? txtOutraProfissao.Text.Trim() : ""))));
return u;
}
private bool ValidarDados()
{
string msg = "";
if (String.IsNullOrEmpty(txtNome.Text))
msg += " - Nome é obrigatório.\n";
if (String.IsNullOrEmpty(txtEMail.Text))
msg += " - E-Mail é obrigatório.\n";
if (String.IsNullOrEmpty(txtApelido.Text))
msg += " - Apelido é obrigatório.\n";
if (String.IsNullOrEmpty(txtDataNascimento.Text) || !Utils.IsDate(txtDataNascimento.Text))
msg += " - Data de nascimento não é uma data válida.\n";
if (String.IsNullOrEmpty(txtSobreNome.Text))
msg += " - Sobre nome é obrigatório.\n";
if (String.IsNullOrEmpty(txtSenha.Text))
msg += " - A senha é obrigatório.\n";
if (txtSenha.Text.Length < 6 )
msg += " - A senha tem de ter 6 caracteres no minimo.\n";
if ((tpUsuario)ViewState["TipoUsuario"] == tpUsuario.Crianca)
{
if (String.IsNullOrEmpty(txtCPFResponsavel.Text))
msg += " - CPF do responsável é obrigatório.\n";
if (String.IsNullOrEmpty(txtNomeEscola.Text))
msg += " - Nome da escola é obrigatório.\n";
if (String.IsNullOrEmpty(txtNomeMae.Text))
msg += " - Nome da Mãe é obrigatório.\n";
if (String.IsNullOrEmpty(txtNomePai.Text))
msg += " - Nome do Pai é obrigatório.\n";
if (String.IsNullOrEmpty(txtSerieEscola.Text))
msg += " - Série da escola é obrigatório.\n";
}
if ((tpUsuario)ViewState["TipoUsuario"] == tpUsuario.Profissional)
{
if(rdOutros.Checked && String.IsNullOrEmpty(txtOutraProfissao.Text))
msg += " - O campo profissão é obrigatório.\n";
}
if ((tpUsuario)ViewState["TipoUsuario"] == tpUsuario.Profissional || (tpUsuario)ViewState["TipoUsuario"] == tpUsuario.Adulto || (tpUsuario)ViewState["TipoUsuario"] == tpUsuario.Administrador)
{
if (String.IsNullOrEmpty(txtCPF.Text))
msg += " - O CPF é obrigatório.\n";
}
if (!String.IsNullOrEmpty(msg))
{
Alert(msg);
return false;
}
else
return true;
}
}
}
| 44.918605 | 226 | 0.476961 | [
"MIT"
] | afonsoft/LeComCre | LeComCre.Web/LeComCre.Web/CadUsuario.aspx.cs | 7,763 | C# |
namespace EfDesignDemo.Entities
{
public class Product
{
public int Id { get; set; }
public string ProductName { get; set; }
public decimal UnitPrice { get; set; }
}
} | 22.666667 | 47 | 0.593137 | [
"MIT"
] | hero3616/ef-design-di | EfDesignDemo.Entities/Product.cs | 206 | C# |
using System.Collections.Generic;
using Newtonsoft.Json;
using NJsonSchema;
using NJsonSchema.Annotations;
namespace JsonRpcNet.Docs
{
public class JsonRpcService
{
[JsonProperty("name")]
public string Name { get; set; } = string.Empty;
[JsonProperty("path")]
public string Path { get; set; } = string.Empty;
[JsonProperty("description")]
public string Description { get; set; } = string.Empty;
[JsonProperty("methods")]
public IList<JsonRpcMethod> Methods { get; set; } = new List<JsonRpcMethod>();
[JsonProperty("notifications")]
public IList<JsonRpcNotification> Notifications { get; set; } = new List<JsonRpcNotification>();
}
} | 30.12 | 104 | 0.632138 | [
"MIT"
] | gottscj/JsonRpcNet | src/JsonRpcNet.Docs/JsonRpcService.cs | 753 | C# |
// LeoSingleton.CommonLibs - Common Libraries for TypeScript and .NET Core
// Copyright (c) Leo C. Singleton IV <leo@leosingleton.com>
// See LICENSE in the project root for license information.
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace LeoSingleton.CommonLibs.Coordination.UnitTests
{
public class AsyncEventWaitHandleTest
{
private int _WokenCount = 0;
private void CreateWaitTask(AsyncEventWaitHandle e)
{
var task = Task.Run(async () =>
{
await e.WaitAsync();
Interlocked.Increment(ref _WokenCount);
});
}
/// <summary>
/// Ensures an AsyncManualResetEvent sets and resets
/// </summary>
[Fact]
public async Task ManualResetEventAsync()
{
_WokenCount = 0;
var e = new AsyncManualResetEvent(false);
CreateWaitTask(e);
await Task.Delay(10);
Assert.Equal(0, _WokenCount);
e.Set();
CreateWaitTask(e);
await Task.Delay(10);
Assert.Equal(2, _WokenCount);
e.Reset();
CreateWaitTask(e);
await Task.Delay(10);
Assert.Equal(2, _WokenCount);
}
/// <summary>
/// Ensures an AsyncAutoResetEvent sets and resets
/// </summary>
[Fact]
public async Task AutoResetEventAsync()
{
_WokenCount = 0;
var e = new AsyncAutoResetEvent(false);
CreateWaitTask(e);
await Task.Delay(10);
Assert.Equal(0, _WokenCount);
e.Set();
CreateWaitTask(e);
await Task.Delay(10);
Assert.Equal(1, _WokenCount);
e.Set();
await Task.Delay(10);
Assert.Equal(2, _WokenCount);
}
}
}
| 26.555556 | 75 | 0.540272 | [
"MIT"
] | leosingleton/commonlibs | dotnet/UnitTests/Coordination/AsyncEventWaitHandleTest.cs | 1,914 | C# |
namespace DwellerBot
{
public interface ISaveable
{
void SaveState();
void LoadState();
}
}
| 12.2 | 30 | 0.565574 | [
"MIT"
] | Angelore/dwellerbot | DwellerBot/ISaveable.cs | 124 | C# |
namespace BookShop.Data.EntityConfiguration
{
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Models;
internal class CategoryConfiguration : IEntityTypeConfiguration<Category>
{
public void Configure(EntityTypeBuilder<Category> builder)
{
builder.HasKey(e => e.CategoryId);
builder.Property(e => e.Name)
.IsRequired()
.HasMaxLength(50);
}
}
}
| 26 | 78 | 0.615385 | [
"MIT"
] | AndreyKodzhabashev/CSparpDB | Lec07_Advanced Querying/BookShop.Data/EntityConfiguration/CategoryConfiguration.cs | 522 | 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.Logz.V20201001Preview
{
public static class GetSubAccountTagRule
{
/// <summary>
/// Capture logs and metrics of Azure resources based on ARM tags.
/// </summary>
public static Task<GetSubAccountTagRuleResult> InvokeAsync(GetSubAccountTagRuleArgs args, InvokeOptions? options = null)
=> Pulumi.Deployment.Instance.InvokeAsync<GetSubAccountTagRuleResult>("azure-native:logz/v20201001preview:getSubAccountTagRule", args ?? new GetSubAccountTagRuleArgs(), options.WithVersion());
}
public sealed class GetSubAccountTagRuleArgs : Pulumi.InvokeArgs
{
/// <summary>
/// Monitor resource name
/// </summary>
[Input("monitorName", required: true)]
public string MonitorName { get; set; } = null!;
/// <summary>
/// The name of the resource group. The name is case insensitive.
/// </summary>
[Input("resourceGroupName", required: true)]
public string ResourceGroupName { get; set; } = null!;
[Input("ruleSetName", required: true)]
public string RuleSetName { get; set; } = null!;
/// <summary>
/// Sub Account resource name
/// </summary>
[Input("subAccountName", required: true)]
public string SubAccountName { get; set; } = null!;
public GetSubAccountTagRuleArgs()
{
}
}
[OutputType]
public sealed class GetSubAccountTagRuleResult
{
/// <summary>
/// The id of the rule set.
/// </summary>
public readonly string Id;
/// <summary>
/// Name of the rule set.
/// </summary>
public readonly string Name;
/// <summary>
/// Definition of the properties for a TagRules resource.
/// </summary>
public readonly Outputs.MonitoringTagRulesPropertiesResponse Properties;
/// <summary>
/// The system metadata relating to this resource
/// </summary>
public readonly Outputs.SystemDataResponse SystemData;
/// <summary>
/// The type of the rule set.
/// </summary>
public readonly string Type;
[OutputConstructor]
private GetSubAccountTagRuleResult(
string id,
string name,
Outputs.MonitoringTagRulesPropertiesResponse properties,
Outputs.SystemDataResponse systemData,
string type)
{
Id = id;
Name = name;
Properties = properties;
SystemData = systemData;
Type = type;
}
}
}
| 31.115789 | 204 | 0.605886 | [
"Apache-2.0"
] | polivbr/pulumi-azure-native | sdk/dotnet/Logz/V20201001Preview/GetSubAccountTagRule.cs | 2,956 | C# |
using Microsoft.AspNetCore.Mvc;
using Xms.Web.Framework.Context;
using Xms.Web.Framework.Filters;
namespace Xms.Web.Framework.Controller
{
/// <summary>
/// 登录状态验证控制器基类
/// </summary>
[TypeFilter(typeof(InitializationFilterAttribute), Order = 0)]
[TypeFilter(typeof(IdentityFilterAttribute), Order = 1)]
public class AuthenticatedControllerBase : WebControllerBase
{
protected AuthenticatedControllerBase(IWebAppContext appContext) : base(appContext)
{
}
}
} | 28.666667 | 91 | 0.707364 | [
"MIT"
] | 861191244/xms | Presentation/Xms.Web.FrameWork/Controller/AuthenticatedControllerBase.cs | 540 | C# |
using HydroServerTools.Models;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.Google;
using Owin;
using System;
namespace HydroServerTools
{
public partial class Startup
{
// For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
public void ConfigureAuth(IAppBuilder app)
{
// Configure the db context and user manager to use a single instance per request
app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
//add signalR
//app.MapSignalR();
// Enable the application to use a cookie to store information for the signed in user
// and to use a cookie to temporarily store information about a user logging in with a third party login provider
// Configure the sign in cookie
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
Provider = new CookieAuthenticationProvider
{
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, User>(
validateInterval: TimeSpan.FromMinutes(30),
regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
}
});
// Use a cookie to temporarily store information about a user logging in with a third party login provider
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
// Uncomment the following lines to enable logging in with third party login providers
//app.UseMicrosoftAccountAuthentication(
// clientId: "",
// clientSecret: "");
//app.UseTwitterAuthentication(
// consumerKey: "",
// consumerSecret: "");
//app.UseFacebookAuthentication(
// appId: "",
// appSecret: "");
//app.UseGoogleAuthentication();
var googleOAuth2AuthenticationOptions = new GoogleOAuth2AuthenticationOptions
{
ClientId = "208043537148-ds7a83pm5ssa61kj2jpg7rpojqrqchfj.apps.googleusercontent.com",
ClientSecret = "ah5IH-1uSPb0LAgusAGy5AZM",
CallbackPath = new PathString("/signin-google")
};
app.UseGoogleAuthentication(googleOAuth2AuthenticationOptions);
}
}
} | 39.986111 | 125 | 0.630775 | [
"BSD-3-Clause"
] | CUAHSI/Azure-Hydroservertools | HydroServerTools/App_Start/Startup.Auth.cs | 2,881 | C# |
//===================================================================================
// Microsoft patterns & practices
// Composite Application Guidance for Windows Presentation Foundation and Silverlight
//===================================================================================
// Copyright (c) Microsoft Corporation. All rights reserved.
// 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
// FITNESS FOR A PARTICULAR PURPOSE.
//===================================================================================
// The example companies, organizations, products, domain names,
// e-mail addresses, logos, people, places, and events depicted
// herein are fictitious. No association with any real company,
// organization, product, domain name, email address, logo, person,
// places, or events is intended or should be inferred.
//===================================================================================
using System.Windows.Controls;
using UIComposition.EmployeeModule.ViewModels;
namespace UIComposition.EmployeeModule.Views
{
public partial class EmployeeSummaryView : UserControl
{
// TODO: 06 - The EmployeeSummaryView contains a Tab control which defines a region named TabRegion (EmployeeSummaryView.xaml).
// TODO: 07 - The TabRegion defines a RegionContext which provides a reference to the currently selected employee to all child views (EmployeeSummaryView.xaml).
public EmployeeSummaryView( EmployeeSummaryViewModel viewModel )
{
this.InitializeComponent();
// Set the ViewModel as this View's data context.
this.DataContext = viewModel;
}
}
} | 54.235294 | 169 | 0.594902 | [
"MIT"
] | cointoss1973/Prism4.1-WPF | Quickstarts/UIComposition/EmployeeModule/Views/EmployeeSummaryView.xaml.cs | 1,844 | C# |
using MagusCharacterGenerator.Castes;
using MagusCharacterGenerator.GameSystem.Attributes;
using MagusCharacterGenerator.GameSystem.Valuables;
using MagusCharacterGenerator.GameSystem.Weapons;
using Mtf.Languages;
namespace MagusCharacterGenerator.Things.Weapons.Spears
{
class Javelin : Weapon, IMeleeWeapon
{
public double AttacksPerRound => 1;
public byte InitiatingValue => 8;
public byte AttackingValue => 13;
public byte DefendingValue => 5;
public double Weight => 1.5;
public Money Price => new Money(0, 5);
[DiceThrow(ThrowType._1K6)]
[DiceThrowModifier(1)]
public byte GetDamage() => (byte)(DiceThrow._1K6() + 1);
public override string ToString() => Lng.Elem("Javelin");
}
} | 27.448276 | 66 | 0.680905 | [
"MIT"
] | Mortens4444/MagusCharacterGenerator | MagusCharacterGenerator/Things/Weapons/Spears/Javelin.cs | 798 | C# |
//-----------------------------------------------------------------------------
// Copyright : (c) Chris Moore, 2020
// License : MIT
//-----------------------------------------------------------------------------
namespace Z0.Asm
{
using System;
using System.Runtime.CompilerServices;
using static Root;
using static AsmCodes;
[Record(TableId)]
public struct AsmBranchTarget : IRecord<AsmBranchTarget>
{
public const string TableId = "asm.branch";
/// <summary>
/// The target address
/// </summary>
public MemoryAddress Address;
/// <summary>
/// The target classifier, near or far
/// </summary>
public BranchTargetKind Kind;
/// <summary>
/// The target size
/// </summary>
public BranchTargetWidth Size;
/// <summary>
/// Specifies a branch target selector, if far
/// </summary>
public Address16 Selector;
[MethodImpl(Inline)]
public AsmBranchTarget(MemoryAddress dst, BranchTargetKind kind, BranchTargetWidth size, Address16? selector = null)
{
Kind = kind;
Size = size;
Address = dst;
Selector = selector ?? 0;
}
public static AsmBranchTarget Empty
=> default;
}
} | 27.14 | 125 | 0.492999 | [
"BSD-3-Clause"
] | 0xCM/z0 | src/asm/src/models/AsmBranchTarget.cs | 1,357 | C# |
#region Copyright notice and license
// Copyright 2019 The gRPC Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using Grpc.Core;
using Grpc.Net.Client.Internal;
using Grpc.Net.Compression;
namespace Grpc.Net.Client.Tests.Infrastructure
{
internal static class StreamSerializationHelper
{
public static Task<TResponse?> ReadMessageAsync<TResponse>(
Stream responseStream,
//ILogger logger,
Func<DeserializationContext, TResponse> deserializer,
string grpcEncoding,
int? maximumMessageSize,
Dictionary<string, ICompressionProvider> compressionProviders,
bool singleMessage,
CancellationToken cancellationToken)
where TResponse : class
{
var tempChannel = GrpcChannel.ForAddress("http://localhost", new GrpcChannelOptions
{
MaxReceiveMessageSize = maximumMessageSize,
CompressionProviders = compressionProviders?.Values.ToList(),
HttpHandler = new NullHttpHandler()
});
var tempCall = new TestGrpcCall(new CallOptions(), tempChannel, typeof(TResponse));
var task = responseStream.ReadMessageAsync(tempCall, deserializer, grpcEncoding, singleMessage, cancellationToken);
#if !NET472
return task.AsTask();
#else
return task;
#endif
}
private class TestGrpcCall : GrpcCall
{
private readonly Type _type;
public TestGrpcCall(CallOptions options, GrpcChannel channel, Type type) : base(options, channel)
{
_type = type;
}
public override Type RequestType => _type;
public override Type ResponseType => _type;
public override CancellationToken CancellationToken { get; }
}
}
}
| 33.915493 | 127 | 0.659053 | [
"Apache-2.0"
] | BearerPipelineTest/grpc-dotnet | test/Grpc.Net.Client.Tests/Infrastructure/StreamSerializationHelper.cs | 2,410 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace PdfiumViewer.Properties {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("PdfiumViewer.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Looks up a localized string similar to Page {0}.
/// </summary>
internal static string PageNumber {
get {
return ResourceManager.GetString("PageNumber", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Could not save the PDF file to the specified location..
/// </summary>
internal static string SaveAsFailedText {
get {
return ResourceManager.GetString("SaveAsFailedText", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Could not save file.
/// </summary>
internal static string SaveAsFailedTitle {
get {
return ResourceManager.GetString("SaveAsFailedTitle", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to PDF Files (*.pdf)|*.pdf|All Files (*.*)|*.*.
/// </summary>
internal static string SaveAsFilter {
get {
return ResourceManager.GetString("SaveAsFilter", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Save As.
/// </summary>
internal static string SaveAsTitle {
get {
return ResourceManager.GetString("SaveAsTitle", resourceCulture);
}
}
}
}
| 40.724771 | 179 | 0.564542 | [
"Apache-2.0"
] | thojaw/PdfiumViewer | PdfiumViewer/Properties/Resources.Designer.cs | 4,441 | C# |
namespace Ventas
{
partial class UltimasReservaciones
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.label1 = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// label1
//
this.label1.AutoSize = true;
this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 20.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label1.Location = new System.Drawing.Point(274, 50);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(208, 31);
this.label1.TabIndex = 0;
this.label1.Text = "En construccion";
//
// UltimasReservaciones
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 450);
this.Controls.Add(this.label1);
this.Name = "UltimasReservaciones";
this.Text = "Ultimas Reservaciones";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Label label1;
}
} | 35.016393 | 169 | 0.560861 | [
"MIT"
] | catrachitohn/Ventas | Reservaciones/Ventas/UltimasReservaciones.Designer.cs | 2,138 | C# |
using JetBrains.Annotations;
using NetScript.Runtime.Objects;
namespace NetScript.Runtime.Builtins
{
internal static class IteratorIntrinsics
{
[NotNull]
public static ScriptObject Initialise([NotNull] Agent agent, [NotNull] Realm realm, ScriptObject objectPrototype, ScriptObject functionPrototype)
{
var iteratorPrototype = agent.ObjectCreate(objectPrototype);
Intrinsics.DefineDataProperty(iteratorPrototype, Symbol.Iterator, Intrinsics.CreateBuiltinFunction(realm, Iterator, functionPrototype, 0, "[Symbol.iterator]"));
return iteratorPrototype;
}
private static ScriptValue Iterator([NotNull] ScriptArguments arg)
{
return arg.ThisValue;
}
}
} | 37.47619 | 173 | 0.684879 | [
"MIT"
] | MatthewSmit/.netScript | NetScript/Runtime/Builtins/IteratorIntrinsics.cs | 789 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
using Fritz.TwitchChatArchive.Data;
using Fritz.TwitchChatArchive.Messages;
using Microsoft.Azure.WebJobs;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Microsoft.WindowsAzure.Storage.Blob;
using Microsoft.WindowsAzure.Storage.Queue;
using Newtonsoft.Json;
namespace Fritz.TwitchChatArchive
{
public class Download : BaseFunction
{
private readonly IHttpClientFactory _HttpClientFactory;
private readonly IConfiguration _Configuration;
public Download(IHttpClientFactory httpClientFactory, IConfiguration configuration) : base(httpClientFactory, configuration)
{
}
[FunctionName("DownloadChat")]
public async Task DownloadChat(
[ServiceBusTrigger("EndOfStream", "downloadchat", Connection = "ServiceBusConnectionString")] CompletedStream completedStream,
[Blob("chatlog", FileAccess.ReadWrite, Connection = "TwitchChatStorage")] CloudBlobContainer container,
ILogger log)
{
if (string.IsNullOrEmpty(completedStream.VideoId))
{
log.LogError($"Unable to downloadchat - no VideoId submitted for {completedStream.ChannelName}");
return;
}
log.LogInformation($"Attempting to download chat for {completedStream.ChannelName} - VideoId: {completedStream.VideoId}");
var downloadTask = DownloadChatForVideo(completedStream.VideoId);
var getTitleAndDateTask = GetTitleForVideo(completedStream.VideoId);
Task.WaitAll(downloadTask, getTitleAndDateTask, container.CreateIfNotExistsAsync());
var titleAndDate = getTitleAndDateTask.Result;
var fileName = $"{titleAndDate.publishDate.ToString("yyyyMMdd")}_{titleAndDate.title}.json";
var blob = container.GetBlockBlobReference(fileName);
await blob.UploadTextAsync(JsonConvert.SerializeObject(downloadTask.Result));
var client = GetHttpClient($"https://lemon-bush-027f2e90f.azurestaticapps.net");
_ = client.GetAsync($"/api/youtubechat?twitchid={fileName}");
log.LogInformation($"C# ServiceBus topic trigger function processed message: {completedStream}");
}
[FunctionName("DownloadChatByVideoId")]
public async Task DownloadChatById(
[QueueTrigger("chattodownload-byvideoid", Connection = "TwitchChatStorage")] CloudQueueMessage msg,
[Blob("chatlog", FileAccess.ReadWrite, Connection = "TwitchChatStorage")] CloudBlobContainer container,
ILogger log)
{
var videoId = msg.AsString.Trim();
var downloadTask = DownloadChatForVideo(videoId);
var getTitleAndDateTask = GetTitleForVideo(videoId);
Task.WaitAll(downloadTask, getTitleAndDateTask, container.CreateIfNotExistsAsync());
var titleAndDate = getTitleAndDateTask.Result;
var blob = container.GetBlockBlobReference($"{titleAndDate.publishDate.ToString("yyyyMMdd")}_{titleAndDate.title}.json");
await blob.UploadTextAsync(JsonConvert.SerializeObject(downloadTask.Result));
log.LogInformation($"Downloaded chat for video with id: {msg.AsString}");
}
private async Task<(string title, DateTime publishDate)> GetTitleForVideo(string videoId)
{
using (var client = GetHttpClient($"https://api.twitch.tv/kraken/videos/{videoId}"))
{
string rawString = await client.GetStringAsync($"");
var rootData = JsonConvert.DeserializeObject<VideoDetail>(rawString);
return (rootData.title, rootData.published_at);
}
}
private async Task<IEnumerable<Comment>> DownloadChatForVideo(string videoId)
{
// Cheer 300 codingbandit 29/11/19
// Cheer 100 MattLeibow 29/11/19
var comments = new List<Comment>();
using (var client = GetHttpClient($"https://api.twitch.tv/v5/videos/{videoId}/comments"))
{
string rawString = await client.GetStringAsync($"");
var rootData = JsonConvert.DeserializeObject<CommentsRootData>(rawString);
while (!string.IsNullOrEmpty(rootData._next))
{
comments.AddRange(rootData.comments);
rootData = JsonConvert.DeserializeObject<CommentsRootData>(await client.GetStringAsync($"?cursor={rootData._next}"));
}
comments.AddRange(rootData.comments);
return comments;
}
}
}
}
| 34.347107 | 128 | 0.765159 | [
"MIT"
] | csharpfritz/TwitchChatArchive | src/Fritz.TwitchChatArchive/Download.cs | 4,156 | C# |
using Microsoft.Windows.AppNotifications;
using SettingsUI.Demo.Pages;
using SettingsUI.Helpers;
namespace SettingsUI.Demo.AppNotification;
public class ToastWithAvatar : IScenario
{
private static ToastWithAvatar _Instance;
public static ToastWithAvatar Instance
{
get
{
if (_Instance == null)
{
_Instance = new ToastWithAvatar();
}
return _Instance;
}
set { _Instance = value; }
}
public int ScenarioId { get; set; } = 1;
public string ScenarioName { get; set; } = "Toast with Avatar";
public void NotificationReceived(AppNotificationActivatedEventArgs notificationActivatedEventArgs)
{
var notification = NotificationHelper.GetNotificationForWithAvatar(ScenarioName, notificationActivatedEventArgs);
AppNotificationPage.Instance.NotificationReceived(notification);
}
public bool SendToast()
{
return ScenarioHelper.SendToastWithAvatar(ScenarioId, ScenarioName, "Hi, This is a Toast", "Open App", "OpenApp", "logo.png");
}
}
| 29.756757 | 134 | 0.677566 | [
"MIT"
] | ghost1372/SettingsUI | src/SettingsUI.Demo/AppNotification/ToastWithAvatar.cs | 1,103 | C# |
// Copyright © 2015 Dmitry Sikorsky. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Platformus.Barebone;
using Platformus.Forms.Data.Abstractions;
using Platformus.Forms.Data.Models;
using Platformus.Globalization.Backend.ViewModels;
namespace Platformus.Forms.Backend.ViewModels.Shared
{
public class CompletedFieldViewModelFactory : ViewModelFactoryBase
{
public CompletedFieldViewModelFactory(IRequestHandler requestHandler)
: base(requestHandler)
{
}
public CompletedFieldViewModel Create(CompletedField completedField)
{
return new CompletedFieldViewModel()
{
Id = completedField.Id,
Field = new FieldViewModelFactory(this.RequestHandler).Create(
this.RequestHandler.Storage.GetRepository<IFieldRepository>().WithKey(completedField.FieldId)
),
Value = completedField.Value
};
}
}
} | 32.6 | 111 | 0.745399 | [
"Apache-2.0"
] | uQr/Platformus | src/Platformus.Forms.Backend/Areas/Backend/ViewModels/Shared/CompletedField/CompletedFieldViewModelFactory.cs | 981 | C# |
using System.Diagnostics.CodeAnalysis;
using Xunit;
using Xunit.Sdk;
namespace Funcky;
public static partial class FunctionalAssert
{
/// <summary>Asserts that the given <paramref name="either"/> is <c>Left</c> and contains the given <paramref name="expectedLeft"/>.</summary>
/// <exception cref="AssertActualExpectedException">Thrown when <paramref name="either"/> is <c>Right</c>.</exception>
#if STACK_TRACE_HIDDEN_SUPPORTED
[System.Diagnostics.StackTraceHidden]
#else
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
#endif
public static void IsLeft<TLeft, TRight>(TLeft expectedLeft, Either<TLeft, TRight> either)
{
try
{
Assert.Equal(Either<TLeft, TRight>.Left(expectedLeft), either);
}
catch (EqualException exception)
{
throw new AssertActualExpectedException(
expected: exception.Expected,
actual: exception.Actual,
userMessage: $"{nameof(FunctionalAssert)}.{nameof(IsLeft)}() Failure");
}
}
/// <summary>Asserts that the given <paramref name="either"/> is <c>Left</c>.</summary>
/// <exception cref="AssertActualExpectedException">Thrown when <paramref name="either"/> is <c>Right</c>.</exception>
/// <returns>Returns the value in <paramref name="either"/> if it was <c>Left</c>.</returns>
#if STACK_TRACE_HIDDEN_SUPPORTED
[System.Diagnostics.StackTraceHidden]
#else
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
#endif
[SuppressMessage("Microsoft.Usage", "CA2200", Justification = "Stack trace erasure intentional.")]
[SuppressMessage("ReSharper", "PossibleIntendedRethrow", Justification = "Stack trace erasure intentional.")]
public static TLeft IsLeft<TLeft, TRight>(Either<TLeft, TRight> either)
{
try
{
return either.Match(
left: Identity,
right: static right => throw new AssertActualExpectedException(
expected: "Left(...)",
actual: $"Right({right})",
userMessage: $"{nameof(FunctionalAssert)}.{nameof(IsLeft)}() Failure"));
}
catch (AssertActualExpectedException exception)
{
throw exception;
}
}
}
| 41.965517 | 146 | 0.654478 | [
"Apache-2.0",
"MIT"
] | FreeApophis/Funcky | Funcky.Xunit/FunctionalAssert/IsLeft.cs | 2,434 | C# |
// © Anamnesis.
// Licensed under the MIT license.
namespace Anamnesis.Character.Converters
{
using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;
using Anamnesis.Memory;
[ValueConversion(typeof(Customize.Genders), typeof(Visibility))]
public class MasculineGenderToVisibilityConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
Customize.Genders gender = (Customize.Genders)value;
return gender == Customize.Genders.Masculine ? Visibility.Visible : Visibility.Collapsed;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
| 28.074074 | 97 | 0.774406 | [
"MIT"
] | Caraxi/Anamnesis | Anamnesis/Character/Converters/MasculineGenderToVisibilityConverter.cs | 761 | C# |
/*
Copyright (C) 2020 Jean-Camille Tournier (mail@tournierjc.fr)
This file is part of QLCore Project https://github.com/OpenDerivatives/QLCore
QLCore is free software: you can redistribute it and/or modify it
under the terms of the QLCore and QLNet license. You should have received a
copy of the license along with this program; if not, license is
available at https://github.com/OpenDerivatives/QLCore/LICENSE.
QLCore is a forked of QLNet which is a based on QuantLib, a free-software/open-source
library for financial quantitative analysts and developers - http://quantlib.org/
The QuantLib license is available online at http://quantlib.org/license.shtml and the
QLNet license is available online at https://github.com/amaggiulli/QLNet/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 PARTICAR PURPOSE. See the license for more details.
*/
using System;
namespace QLCore
{
public partial class Utils
{
public static Vector CenteredGrid(double center, double dx, int steps)
{
Vector result = new Vector(steps + 1);
for (int i = 0; i < steps + 1; i++)
result[i] = center + (i - steps / 2.0) * dx;
return result;
}
public static Vector BoundedGrid(double xMin, double xMax, int steps)
{
return new Vector(steps + 1, xMin, (xMax - xMin) / steps);
}
public static Vector BoundedLogGrid(double xMin, double xMax, int steps)
{
Vector result = new Vector(steps + 1);
double gridLogSpacing = (Math.Log(xMax) - Math.Log(xMin)) /
(steps);
double edx = Math.Exp(gridLogSpacing);
result[0] = xMin;
for (int j = 1; j < steps + 1; j++)
{
result[j] = result[j - 1] * edx;
}
return result;
}
}
}
| 34.526316 | 95 | 0.653963 | [
"BSD-3-Clause"
] | OpenDerivatives/QLCore | QLCore/Grid.cs | 1,970 | C# |
using RiveScript.AST;
using System;
using System.Collections.Generic;
namespace RiveScript
{
/// <summary>
/// Topic manager class for RiveScript.
/// </summary>
public class TopicManager
{
Dictionary<string, Topic> topics = new Dictionary<string, Topic>(); // Hash of managed topics
ICollection<string> lTopics = new List<string>(); // A vector of topics
/// <summary>
/// Create a topic manager. Only one per RiveScript interpreter needed.
/// </summary>
public TopicManager() { }
/// <summary>
/// Specify which topic any following operations will operate under.
/// </summary>
/// <param name="topic"></param>
/// <returns></returns>
public Topic topic(string topic)
{
if (!topics.ContainsKey(topic))
{
topics.Add(topic, new Topic(topic));
lTopics.Add(topic);
}
return topics[topic];
}
/// <summary>
/// Test whether a topic exists.
/// </summary>
/// <param name="topic"></param>
/// <returns></returns>
public bool exists(string topic)
{
return topics.ContainsKey(topic);
}
/// <summary>
/// Retrieve a list of the existing topics name.
/// </summary>
public string[] listTopicsName() => lTopics.ToArray();
/// <summary>
/// Retrieve a list of the existing topics name.
/// </summary>
public IDictionary<string, Topic> listTopics() => topics;
public int countTopics() => lTopics.Count;
/// <summary>
/// Sort the replies in all the topics.This will build trigger lists of
/// the topics(taking into account topic inheritence/includes) and sending
/// the final trigger list into each topic's individual sortTriggers() method.
/// </summary>
public void sortReplies()
{
foreach (var topic in listTopicsName())
{
var allTrig = topicTriggers(topic, 0, 0, false);
// Make this topic sort using this trigger list.
this.topic(topic).sortTriggers(allTrig);
// Make the topic update its %Previous buffer.
this.topic(topic).sortPrevious();
//cache de
}
}
/// <summary>
/// Walk the inherit/include trees and return a list of unsorted triggers.
/// </summary>
/// <param name="topic"></param>
/// <param name="depth"></param>
/// <param name="inheritance"></param>
/// <param name="inherited"></param>
/// <returns></returns>
string[] topicTriggers(string topic, int depth, int inheritance, bool inherited)
{
// Break if we're too deep.
if (depth > 50)
{
Console.WriteLine("[ERROR] Deep recursion while scanning topic inheritance (topic " + topic + " was involved)");
return new string[0];
}
/*
Important info about the depth vs inheritance params to this function:
depth increments by 1 every time this function recursively calls itself.
inheritance increments by 1 only when this topic inherits another topic.
This way, '>topic alpha includes beta inherits gamma' will have this effect:
alpha and beta's triggers are combined together into one pool, and then
these triggers have higher matching priority than gamma's.
The inherited option is true if this is a recursive call, from a topic
that inherits other topics. This forces the {inherits} tag to be added to
the triggers, for the topic's sortTriggers() to deal with. This only applies
when the top topic "includes" another topic.
*/
// Collect an array of triggers to return.
var triggers = new List<string>();
// Does this topic include others?
var includes = this.topic(topic).includes();
if (includes.Length > 0)
{
for (int i = 0; i < includes.Length; i++)
{
// Recurse.
var recursive = topicTriggers(includes[i], (depth + 1), inheritance, false);
for (int j = 0; j < recursive.Length; j++)
{
triggers.Add(recursive[j]);
}
}
}
// Does this topic inherit others?
var inherits = this.topic(topic).inherits();
if (inherits.Length > 0)
{
for (int i = 0; i < inherits.Length; i++)
{
// Recurse.
var recursive = topicTriggers(inherits[i], (depth + 1), (inheritance + 1), true);
for (int j = 0; j < recursive.Length; j++)
{
triggers.Add(recursive[j]);
}
}
}
// Collect the triggers for *this* topic. If this topic inherits any other
// topics, it means that this topic's triggers have higher priority than
// those in any inherited topics. Enforce this with an {inherits} tag.
var localTriggers = this.topic(topic).listTriggers(true);
if (inherits.Length > 0 || inherited)
{
// Get the raw unsorted triggers.
for (int i = 0; i < localTriggers.Length; i++)
{
// Skip any trigger with a {previous} tag, these are for %Previous
// and don't go in the general population.
if (localTriggers[i].IndexOf("{previous}") > -1)
{
continue;
}
// Prefix it with an {inherits} tag.
triggers.Add("{inherits=" + inheritance + "}" + localTriggers[i]);
}
}
else
{
// No need for an inherits tag here.
for (int i = 0; i < localTriggers.Length; i++)
{
// Skip any trigger with a {previous} tag, these are for %Previous
// and don't go in the general population.
if (localTriggers[i].IndexOf("{previous}") > -1)
{
continue;
}
triggers.Add(localTriggers[i]);
}
}
// Return it as an array.
return triggers.ToArray();
}
/// <summary>
/// Walk the inherit/include trees starting with one topic and find the trigger
/// object that corresponds to the search trigger.Or rather, if you have a trigger
/// that was part of a topic's sort list, but that topic itself doesn't manage
/// that trigger, this function will search the tree to find the topic that does,
/// and return its Trigger object.
/// </summary>
/// <param name="topic"></param>
/// <param name="pattern"></param>
/// <param name="depth"></param>
/// <returns></returns>
public Trigger findTriggerByInheritance(string topic, string pattern, int depth)
{
// Break if we're too deep.
if (depth > 50)
{
Console.WriteLine("[ERROR] Deep recursion while scanning topic inheritance (topic " + topic + " was involved)");
return null;
}
// Inheritance is more important than inclusion.
var inherits = this.topic(topic).inherits();
for (int i = 0; i < inherits.Length; i++)
{
// Does this topic have our trigger?
if (this.topic(inherits[i]).triggerExists(pattern))
{
// Good! Return it!
return this.topic(inherits[i]).trigger(pattern);
}
else
{
// Recurse.
var match = findTriggerByInheritance(inherits[i], pattern, (depth + 1));
if (match != null)
{
// Found it!
return match;
}
}
}
// Now check for "includes".
var includes = this.topic(topic).includes();
for (int i = 0; i < includes.Length; i++)
{
// Does this topic have our trigger?
if (this.topic(includes[i]).triggerExists(pattern))
{
// Good! Return it!
return this.topic(includes[i]).trigger(pattern);
}
else
{
// Recurse.
var match = findTriggerByInheritance(includes[i], pattern, (depth + 1));
if (match != null)
{
// Found it!
return match;
}
}
}
// Don't know what else we can do.
return null;
}
/// <summary>
/// Walk the inherit/include trees starting with one topic and list every topic we find.
/// </summary>
/// <param name="topic"></param>
/// <param name="depth"></param>
/// <returns></returns>
public string[] getTopicTree(string topic, int depth)
{
// Avoid deep recursion.
if (depth >= 50)
{
Console.WriteLine("[ERROR] Deep recursion while scanning topic inheritance (topic " + topic + " was involved)");
return new String[0];
}
// Collect a vector of topics.
var result = new List<string>();
result.Add(topic);
// Does this topic include others?
var includes = this.topic(topic).includes();
for (int i = 0; i < includes.Length; i++)
{
//Recurse.
var children = getTopicTree(includes[i], (depth + 1));
for (int j = 0; j < children.Length; j++)
{
result.Add(children[j]);
}
}
// Does it inherit?
var inherits = this.topic(topic).inherits();
for (int i = 0; i < inherits.Length; i++)
{
//Recurse
var children = getTopicTree(inherits[i], (depth + 1));
for (int j = 0; j < children.Length; j++)
{
result.Add(children[j]);
}
}
// Return.
return result.ToArray();
}
}
} | 36.20462 | 128 | 0.486053 | [
"MIT"
] | effacestudios/rivescript-csharp | RiveScript/TopicManager.cs | 10,972 | C# |
//
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
//
using UnityEngine;
using UnityEditor;
using HoloToolkit.Unity.Collections;
[CustomEditor(typeof(ObjectCollection))]
public class CollectionEditor : Editor
{
public override void OnInspectorGUI()
{
// Draw the default
base.OnInspectorGUI();
// Place the button at the bottom
ObjectCollection myScript = (ObjectCollection)target;
if(GUILayout.Button("Update Collection"))
{
myScript.UpdateCollection();
}
}
}
| 26.92 | 92 | 0.658247 | [
"MIT"
] | Zeraphil/HoloGaitRehab | Assets/HoloToolkit/UX/Scripts/Collections/Editor/CollectionEditor.cs | 675 | C# |
using System;
using System.Collections.Generic;
using bv.common.Core;
using eidss.model.Core;
using eidss.model.Reports.Common;
namespace eidss.model.Reports.AZ
{
[Serializable]
public class AssignmentLabDiagnosticModel : BaseModel
{
public AssignmentLabDiagnosticModel()
{
}
public AssignmentLabDiagnosticModel(string language, string caseId, long? sentToId, bool useArchive)
: base(language, useArchive)
{
SentTo = sentToId;
CaseId = caseId;
}
[LocalizedDisplayName("strCaseID")]
public string CaseId { get; set; }
[LocalizedDisplayName("strSentTo")]
public long? SentTo { get; set; }
public List<SelectListItemSurrogate> SentToList
{
get
{
if (!string.IsNullOrEmpty(CaseId))
return FilterHelper.GetAssignmentLabDiagnosticAZSendToLookup(CaseId, Localizer.CurrentCultureLanguageID);
return new List<SelectListItemSurrogate>();
}
}
public override string ToString()
{
return string.Format("{0}, sent to ID={1}, case ID={2}", base.ToString(), SentTo, CaseId);
}
}
} | 30.069767 | 126 | 0.58546 | [
"BSD-2-Clause"
] | EIDSS/EIDSS-Legacy | EIDSS v6.1/eidss.model/Reports/AZ/AssignmentLabDiagnosticModel.cs | 1,295 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Composition;
using System.Threading;
using StarkPlatform.Compiler.Stark.Syntax;
using StarkPlatform.Compiler.Organizing.Organizers;
namespace StarkPlatform.Compiler.Stark.Organizing.Organizers
{
[ExportSyntaxNodeOrganizer(LanguageNames.Stark), Shared]
internal class FieldDeclarationOrganizer : AbstractSyntaxNodeOrganizer<FieldDeclarationSyntax>
{
protected override FieldDeclarationSyntax Organize(
FieldDeclarationSyntax syntax,
CancellationToken cancellationToken)
{
return syntax.Update(syntax.AttributeLists,
ModifiersOrganizer.Organize(syntax.Modifiers),
syntax.Declaration,
syntax.EosToken);
}
}
}
| 37.791667 | 161 | 0.726571 | [
"BSD-2-Clause",
"MIT"
] | encrypt0r/stark | src/compiler/StarkPlatform.Compiler.Stark.Features/Organizing/Organizers/FieldDeclarationOrganizer.cs | 909 | C# |
using System.Collections.Generic;
using ModKit;
using UnityModManagerNet;
namespace SolastaUnfinishedBusiness.Viewers
{
public class CreditsAndHelpViewer : IMenuSelectablePage
{
public string Name => "Help & Credits";
public int Priority => 1;
private static void DisplayMulticlassHelp()
{
UI.Label("");
UI.Label("Instructions [Character Inspection Screen]:".yellow());
UI.Label(". press the " + "UP".yellow().bold() + " arrow to toggle the character panel selector [useful if more than 2 spell selection tabs]");
UI.Label(". press the " + "DOWN".yellow().bold() + " arrow to toggle between different class or subclass label styles");
UI.Label(". press the " + "LEFT".yellow().bold() + " and " + "RIGHT".yellow().bold() + " arrows to present other hero classes details");
UI.Label("");
UI.Label("Instructions [Casting]:".yellow());
UI.Label(". " + "default".italic() + " - consumes a short rest slot whenever one is available");
UI.Label(". " + "intermediate".italic() + " - consumes a long rest slot whenever the Warlock spell level is greater than the shared spell level [can be enabled in the settings panel]");
UI.Label(". " + "advanced".italic() + " - " + "SHIFT-click".yellow().bold() + " a spell to consume a long rest slot whenever one is available");
UI.Label("");
UI.Label("Features:".yellow());
UI.Label(". combines up to 4 different classes");
UI.Label(". enforces ability scores minimum in & out pre-requisites");
UI.Label(". enforces the correct subset of starting proficiencies");
UI.Label(". implements the shared slots system combining all casters with an option to also combine Warlock pact magic");
UI.Label(". " + "extra attacks".cyan() + " / " + "unarmored defenses".cyan() + " won't stack whenever combining Barbarian, Fighter, Paladin or Ranger");
UI.Label(". " + "channel divinity".cyan() + " won't stack whenever combining Cleric and Paladin");
UI.Label(". supports official game classes, Tinkerer and all subclass in Community Expansion mod");
UI.Label(". Warlock class in development");
}
private static readonly Dictionary<string, string> creditsTable = new Dictionary<string, string>
{
{ "Zappastuff".bold(), "head developer, UI reverse-engineer, pact magic integration" },
{ "ImpPhil", "code support" },
{ "AceHigh", "shared slot system, pact magic, code support" },
{ "Esker", "ruleset support, quality assurance, tests" },
{ "Lyraele", "ruleset support, quality assurance, tests" },
{ "PraiseThyJeebus", "slot colors idea, quality assurance, tests" },
{ "[MAD] SirMadnessTv", "traduction française" },
{ "Narria", "modKit creator, developer" }
};
private static void DisplayCredits()
{
UI.Label("");
UI.Label("Credits".yellow().bold());
UI.Div();
UI.Label("");
foreach (var kvp in creditsTable)
{
using (UI.HorizontalScope())
{
UI.Label(kvp.Key.orange(), UI.Width(120));
UI.Label(kvp.Value, UI.Width(400));
}
}
UI.Label("");
}
public void OnGUI(UnityModManager.ModEntry modEntry)
{
UI.Label("Welcome to Unfinished Business".yellow().bold());
UI.Div();
DisplayMulticlassHelp();
DisplayCredits();
}
}
}
| 46.148148 | 197 | 0.576244 | [
"MIT"
] | Holic75/SolastaUnfinishedBusiness | SolastaUnfinishedBusiness/Viewers/CreditsAndHelpViewer.cs | 3,741 | C# |
// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using NUnit.Framework;
namespace ICSharpCode.NRefactory.CSharp.Parser.Expression
{
[TestFixture]
public class AnonymousTypeCreateExpressionTests
{
[Test]
public void Simple()
{
ParseUtilCSharp.AssertExpression(
"new { Name = \"Test\", Price, Something.Property }",
new AnonymousTypeCreateExpression {
Initializers = {
new NamedExpression("Name", new PrimitiveExpression("Test")),
new IdentifierExpression("Price"),
new IdentifierExpression("Something").Member("Property")
}});
}
}
}
| 41.268293 | 93 | 0.75 | [
"MIT"
] | Jenkin0603/myvim | bundle/omnisharp-vim/server/NRefactory/ICSharpCode.NRefactory.Tests/CSharp/Parser/Expression/AnonymousTypeCreateExpressionTests.cs | 1,694 | C# |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// <auto-generated/>
// Template Source: MethodRequest.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Threading;
/// <summary>
/// The type ApplicationRemovePasswordRequest.
/// </summary>
public partial class ApplicationRemovePasswordRequest : BaseRequest, IApplicationRemovePasswordRequest
{
/// <summary>
/// Constructs a new ApplicationRemovePasswordRequest.
/// </summary>
public ApplicationRemovePasswordRequest(
string requestUrl,
IBaseClient client,
IEnumerable<Option> options)
: base(requestUrl, client, options)
{
this.ContentType = "application/json";
this.RequestBody = new ApplicationRemovePasswordRequestBody();
}
/// <summary>
/// Gets the request body.
/// </summary>
public ApplicationRemovePasswordRequestBody RequestBody { get; private set; }
/// <summary>
/// Issues the POST request.
/// </summary>
public System.Threading.Tasks.Task PostAsync()
{
return this.PostAsync(CancellationToken.None);
}
/// <summary>
/// Issues the POST request.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The task to await for async call.</returns>
public System.Threading.Tasks.Task PostAsync(
CancellationToken cancellationToken)
{
this.Method = "POST";
return this.SendAsync(this.RequestBody, cancellationToken);
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="value">The expand value.</param>
/// <returns>The request object to send.</returns>
public IApplicationRemovePasswordRequest Expand(string value)
{
this.QueryOptions.Add(new QueryOption("$expand", value));
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="value">The select value.</param>
/// <returns>The request object to send.</returns>
public IApplicationRemovePasswordRequest Select(string value)
{
this.QueryOptions.Add(new QueryOption("$select", value));
return this;
}
}
}
| 34.195402 | 153 | 0.57479 | [
"MIT"
] | DamienTehDemon/msgraph-sdk-dotnet | src/Microsoft.Graph/Generated/requests/ApplicationRemovePasswordRequest.cs | 2,975 | C# |
//------------------------------------------------------------------------------
// <自動產生的>
// 這段程式碼是由工具產生的。
//
// 變更這個檔案可能會導致不正確的行為,而且如果已重新產生
// 程式碼,則會遺失變更。
// </自動產生的>
//------------------------------------------------------------------------------
namespace Questionnaire1029.SystemAdmin
{
public partial class DataConfirmPage
{
/// <summary>
/// form1 控制項。
/// </summary>
/// <remarks>
/// 自動產生的欄位。
/// 若要修改,請將欄位宣告從設計工具檔案移到程式碼後置檔案。
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlForm form1;
/// <summary>
/// txbName 控制項。
/// </summary>
/// <remarks>
/// 自動產生的欄位。
/// 若要修改,請將欄位宣告從設計工具檔案移到程式碼後置檔案。
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txbName;
/// <summary>
/// txbEmail 控制項。
/// </summary>
/// <remarks>
/// 自動產生的欄位。
/// 若要修改,請將欄位宣告從設計工具檔案移到程式碼後置檔案。
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txbEmail;
/// <summary>
/// txbMobilePhone 控制項。
/// </summary>
/// <remarks>
/// 自動產生的欄位。
/// 若要修改,請將欄位宣告從設計工具檔案移到程式碼後置檔案。
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txbMobilePhone;
/// <summary>
/// txbAge 控制項。
/// </summary>
/// <remarks>
/// 自動產生的欄位。
/// 若要修改,請將欄位宣告從設計工具檔案移到程式碼後置檔案。
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txbAge;
/// <summary>
/// ltlTime 控制項。
/// </summary>
/// <remarks>
/// 自動產生的欄位。
/// 若要修改,請將欄位宣告從設計工具檔案移到程式碼後置檔案。
/// </remarks>
protected global::System.Web.UI.WebControls.Literal ltlTime;
/// <summary>
/// txbSurvey 控制項。
/// </summary>
/// <remarks>
/// 自動產生的欄位。
/// 若要修改,請將欄位宣告從設計工具檔案移到程式碼後置檔案。
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txbSurvey;
/// <summary>
/// txbQt 控制項。
/// </summary>
/// <remarks>
/// 自動產生的欄位。
/// 若要修改,請將欄位宣告從設計工具檔案移到程式碼後置檔案。
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txbQt;
/// <summary>
/// txbOptions 控制項。
/// </summary>
/// <remarks>
/// 自動產生的欄位。
/// 若要修改,請將欄位宣告從設計工具檔案移到程式碼後置檔案。
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txbOptions;
/// <summary>
/// txbAnswer 控制項。
/// </summary>
/// <remarks>
/// 自動產生的欄位。
/// 若要修改,請將欄位宣告從設計工具檔案移到程式碼後置檔案。
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txbAnswer;
}
}
| 26.444444 | 81 | 0.479342 | [
"MIT"
] | thousandtw/Questionnaire | Questionnaire1029/Questionnaire1029/SystemAdmin/DataConfirmPage.aspx.designer.cs | 3,780 | C# |
using Microsoft.Azure.Cosmos.Table;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace MailDispatcher.Storage
{
public interface IRepository<T>
where T: TableEntity, new()
{
public IAsyncEnumerable<TableQuerySegment<T>> QueryAsync(Func<TableQuery<T>, IQueryable<T>> query, CancellationToken token);
public Task<T> SaveAsync(T entry);
public Task<T> UpdateAsync(string rowKey, Func<T, T> update);
public Task DeleteAsync(T entity);
public Task<T> GetAsync(string rowKey, bool create = false);
}
}
| 24.769231 | 132 | 0.708075 | [
"MIT"
] | neurospeech/mail-dispatcher-core | MailDispatcher/Storage/IRepository.cs | 646 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
using StartupIdentity.Core.Domain.Entities;
namespace StartupIdentity.Presentations.IdentityWebAPP.Areas.Identity.Pages.Account.Manage
{
public class ResetAuthenticatorModel : PageModel
{
UserManager<User> _userManager;
private readonly SignInManager<User> _signInManager;
ILogger<ResetAuthenticatorModel> _logger;
public ResetAuthenticatorModel(
UserManager<User> userManager,
SignInManager<User> signInManager,
ILogger<ResetAuthenticatorModel> logger)
{
_userManager = userManager;
_signInManager = signInManager;
_logger = logger;
}
[TempData]
public string StatusMessage { get; set; }
public async Task<IActionResult> OnGet()
{
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
}
return Page();
}
public async Task<IActionResult> OnPostAsync()
{
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
}
await _userManager.SetTwoFactorEnabledAsync(user, false);
await _userManager.ResetAuthenticatorKeyAsync(user);
_logger.LogInformation("User with ID '{UserId}' has reset their authentication app key.", user.Id);
await _signInManager.RefreshSignInAsync(user);
StatusMessage = "Your authenticator app key has been reset, you will need to configure your authenticator app using the new key.";
return RedirectToPage("./EnableAuthenticator");
}
}
} | 34.639344 | 142 | 0.645528 | [
"MIT"
] | isilveira/StartUpIdentity | src/StartupIdentity.Presentations.IdentityWebAPP/Areas/Identity/Pages/Account/Manage/ResetAuthenticator.cshtml.cs | 2,115 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.34014
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace GitRepoVisualizer.Properties
{
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
{
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default
{
get
{
return defaultInstance;
}
}
}
}
| 34.580645 | 151 | 0.583955 | [
"MIT"
] | HanseMiner/CloneRepo_gitrepovisualizer | GitRepoVisualizer/Properties/Settings.Designer.cs | 1,074 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace CarDealer.DTO
{
public class SupplierDto
{
public int Id { get; set; }
public string Name { get; set; }
public int PartsCount { get; set; }
}
}
| 18.5 | 43 | 0.625483 | [
"MIT"
] | bobo4aces/07.SoftUni-CSharpDBFundamentals | 02. Databases Advanced - Entity Framework - 10. JSON Processing/Exercises/Car Dealer/CarDealer/DTO/SupplierDto.cs | 261 | 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 Microsoft.AspNetCore.Components.E2ETest.Infrastructure;
using Microsoft.AspNetCore.Components.E2ETest.Infrastructure.ServerFixtures;
using Microsoft.AspNetCore.E2ETesting;
using OpenQA.Selenium;
using TestServer;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.AspNetCore.Components.E2ETests.Tests
{
public class SaveStateTest : ServerTestBase<AspNetSiteServerFixture>
{
public SaveStateTest(
BrowserFixture browserFixture,
AspNetSiteServerFixture serverFixture,
ITestOutputHelper output
) : base(browserFixture, serverFixture, output)
{
serverFixture.BuildWebHostMethod = Program.BuildWebHost<SaveState>;
serverFixture.Environment = AspNetEnvironment.Development;
}
protected override void InitializeAsyncCore()
{
Navigate("/save-state");
}
[Theory]
[InlineData("SingleComponentServer")]
[InlineData("SingleComponentClient")]
public void PreservesStateForSingleServerComponent(string link)
{
Browser.Click(By.Id(link));
var prerenderState = Browser.Exists(By.Id("state-State1")).Text;
var serviceStateAtState1 = Browser.Exists(By.Id("service-State1")).Text;
var serviceState = Browser.Exists(By.Id("service-state")).Text;
var serviceStateAfter = Browser.Exists(By.Id("service-state-after")).Text;
BeginInteractivity();
Browser.Contains("true", () => Browser.FindElement(By.Id("restored-State1")).Text);
var newState = Browser.Exists(By.Id("state-State1")).Text;
var newServiceStateAtState1 = Browser.Exists(By.Id("service-State1")).Text;
var newServiceState = Browser.Exists(By.Id("service-state")).Text;
Assert.Equal(newState, prerenderState);
// The value won't match to the updated value that we created after persisting the state.
Assert.NotEqual(serviceStateAfter, newServiceState);
// The value matches the one that was persisted on to the page.
Assert.Equal(newServiceState, serviceState);
// The state used upon re-render is the updated value that the service persisted (the component catches up)
Assert.Equal(serviceState, newServiceStateAtState1);
}
[Theory]
[InlineData("SingleComponentServer")]
[InlineData("SingleComponentClient")]
public void PreservedStateIsOnlyAvailableDuringFirstRender(string link)
{
Browser.Click(By.Id(link));
var prerenderState = Browser.Exists(By.Id("state-State1")).Text;
var extraPrerenderState = Browser.Exists(By.Id("extra-Extra")).Text;
BeginInteractivity();
Browser.Contains("true", () => Browser.FindElement(By.Id("restored-State1")).Text);
var newState = Browser.Exists(By.Id("state-State1")).Text;
Browser.DoesNotExist(By.Id("extra-Extra"));
Browser.Click(By.Id("button-Extra"));
var extraPrerenderStateAfterClick = Browser.Exists(By.Id("extra-Extra")).Text;
Assert.Equal(newState, prerenderState);
Assert.NotEqual(extraPrerenderState, extraPrerenderStateAfterClick);
}
[Theory]
[InlineData("MultipleComponentServer")]
[InlineData("MultipleComponentClient")]
public void PreservesStateForMultipleServerComponent(string link)
{
Browser.Click(By.Id(link));
var prerenderState1 = Browser.Exists(By.Id("state-State1")).Text;
var prerenderState2 = Browser.Exists(By.Id("state-State2")).Text;
var serviceStateAtState1 = Browser.Exists(By.Id("service-State1")).Text;
var serviceStateAtState2 = Browser.Exists(By.Id("service-State2")).Text;
var serviceState = Browser.Exists(By.Id("service-state")).Text;
var serviceStateAfter = Browser.Exists(By.Id("service-state-after")).Text;
BeginInteractivity();
Browser.Contains("true", () => Browser.FindElement(By.Id("restored-State1")).Text);
var newState1 = Browser.Exists(By.Id("state-State1")).Text;
Assert.Equal(newState1, prerenderState1);
Browser.Contains("true", () => Browser.FindElement(By.Id("restored-State2")).Text);
var newState2 = Browser.Exists(By.Id("state-State2")).Text;
Assert.Equal(newState2, prerenderState2);
var newServiceStateAtState1 = Browser.Exists(By.Id("service-State1")).Text;
var newServiceStateAtState2 = Browser.Exists(By.Id("service-State2")).Text;
var newServiceState = Browser.Exists(By.Id("service-state")).Text;
// These states were not equal because the state changed between the render of the two components.
Assert.NotEqual(serviceStateAtState1, serviceStateAtState2);
// After interactivity starts they catch up an become the same value
Assert.Equal(newServiceStateAtState1, newServiceStateAtState2);
// The value won't match to the updated value that we created after persisting the state.
Assert.NotEqual(serviceStateAfter, newServiceState);
// The value matches the one that was persisted on to the page.
Assert.Equal(newServiceState, serviceState);
// The state used upon re-render is the updated value that the service persisted (the component catches up)
Assert.Equal(serviceState, newServiceStateAtState1);
}
private void BeginInteractivity()
{
Browser.Exists(By.Id("load-boot-script")).Click();
}
}
}
| 44.556391 | 119 | 0.658792 | [
"Apache-2.0"
] | belav/aspnetcore | src/Components/test/E2ETest/Tests/SaveStateTest.cs | 5,926 | 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.Linq;
using Microsoft.Toolkit.Parsers.Markdown.Helpers;
namespace Microsoft.Toolkit.Parsers.Markdown.Inlines
{
/// <summary>
/// Represents a type of hyperlink where the text and the target URL cannot be controlled
/// independently.
/// </summary>
public class HyperlinkInline : MarkdownInline, IInlineLeaf, ILinkElement
{
/// <summary>
/// Initializes a new instance of the <see cref="HyperlinkInline"/> class.
/// </summary>
public HyperlinkInline()
: base(MarkdownInlineType.RawHyperlink)
{
}
/// <summary>
/// Gets or sets the text to display.
/// </summary>
public string Text { get; set; }
/// <summary>
/// Gets or sets the URL to link to.
/// </summary>
public string Url { get; set; }
/// <summary>
/// Gets this type of hyperlink does not have a tooltip.
/// </summary>
string ILinkElement.Tooltip => null;
/// <summary>
/// Gets or sets the type of hyperlink.
/// </summary>
public HyperlinkType LinkType { get; set; }
/// <summary>
/// Returns the chars that if found means we might have a match.
/// </summary>
internal static void AddTripChars(List<InlineTripCharHelper> tripCharHelpers)
{
tripCharHelpers.Add(new InlineTripCharHelper() { FirstChar = '<', Method = InlineParseMethod.AngleBracketLink });
tripCharHelpers.Add(new InlineTripCharHelper() { FirstChar = ':', Method = InlineParseMethod.Url });
tripCharHelpers.Add(new InlineTripCharHelper() { FirstChar = '/', Method = InlineParseMethod.RedditLink });
tripCharHelpers.Add(new InlineTripCharHelper() { FirstChar = '.', Method = InlineParseMethod.PartialLink });
tripCharHelpers.Add(new InlineTripCharHelper() { FirstChar = '@', Method = InlineParseMethod.Email });
}
/// <summary>
/// Attempts to parse a URL within angle brackets e.g. "http://www.reddit.com".
/// </summary>
/// <param name="markdown"> The markdown text. </param>
/// <param name="start"> The location to start parsing. </param>
/// <param name="maxEnd"> The location to stop parsing. </param>
/// <returns> A parsed URL, or <c>null</c> if this is not a URL. </returns>
internal static InlineParseResult ParseAngleBracketLink(string markdown, int start, int maxEnd)
{
int innerStart = start + 1;
// Check for a known scheme e.g. "https://".
int pos = -1;
foreach (var scheme in MarkdownDocument.KnownSchemes)
{
if (maxEnd - innerStart >= scheme.Length && string.Equals(markdown.Substring(innerStart, scheme.Length), scheme, StringComparison.OrdinalIgnoreCase))
{
// URL scheme found.
pos = innerStart + scheme.Length;
break;
}
}
if (pos == -1)
{
return null;
}
// Angle bracket links should not have any whitespace.
int innerEnd = markdown.IndexOfAny(new char[] { ' ', '\t', '\r', '\n', '>' }, pos, maxEnd - pos);
if (innerEnd == -1 || markdown[innerEnd] != '>')
{
return null;
}
// There should be at least one character after the http://.
if (innerEnd == pos)
{
return null;
}
var url = markdown.Substring(innerStart, innerEnd - innerStart);
return new InlineParseResult(new HyperlinkInline { Url = url, Text = url, LinkType = HyperlinkType.BracketedUrl }, start, innerEnd + 1);
}
/// <summary>
/// Attempts to parse a URL e.g. "http://www.reddit.com".
/// </summary>
/// <param name="markdown"> The markdown text. </param>
/// <param name="tripPos"> The location of the colon character. </param>
/// <param name="maxEnd"> The location to stop parsing. </param>
/// <returns> A parsed URL, or <c>null</c> if this is not a URL. </returns>
internal static InlineParseResult ParseUrl(string markdown, int tripPos, int maxEnd)
{
int start = -1;
// Check for a known scheme e.g. "https://".
foreach (var scheme in MarkdownDocument.KnownSchemes)
{
int schemeStart = tripPos - scheme.Length;
if (schemeStart >= 0 && schemeStart <= maxEnd - scheme.Length && string.Equals(markdown.Substring(schemeStart, scheme.Length), scheme, StringComparison.OrdinalIgnoreCase))
{
// URL scheme found.
start = schemeStart;
break;
}
}
if (start == -1)
{
return null;
}
// The previous character must be non-alphanumeric i.e. "ahttp://t.co" is not a valid URL.
if (start > 0 && char.IsLetter(markdown[start - 1]))
{
return null;
}
// The URL must have at least one character after the http:// and at least one dot.
int pos = tripPos + 3;
int dotIndex = markdown.IndexOf('.', pos, maxEnd - pos);
if (dotIndex == -1 || dotIndex == pos)
{
return null;
}
// Find the end of the URL.
int end = FindUrlEnd(markdown, dotIndex + 1, maxEnd);
var url = markdown.Substring(start, end - start);
return new InlineParseResult(new HyperlinkInline { Url = url, Text = url, LinkType = HyperlinkType.FullUrl }, start, end);
}
/// <summary>
/// Attempts to parse a subreddit link e.g. "/r/news" or "r/news".
/// </summary>
/// <param name="markdown"> The markdown text. </param>
/// <param name="start"> The location to start parsing. </param>
/// <param name="maxEnd"> The location to stop parsing. </param>
/// <returns> A parsed subreddit or user link, or <c>null</c> if this is not a subreddit link. </returns>
internal static InlineParseResult ParseRedditLink(string markdown, int start, int maxEnd)
{
var result = ParseDoubleSlashLink(markdown, start, maxEnd);
if (result != null)
{
return result;
}
return ParseSingleSlashLink(markdown, start, maxEnd);
}
/// <summary>
/// Parse a link of the form "/r/news" or "/u/quinbd".
/// </summary>
/// <param name="markdown"> The markdown text. </param>
/// <param name="start"> The location to start parsing. </param>
/// <param name="maxEnd"> The location to stop parsing. </param>
/// <returns> A parsed subreddit or user link, or <c>null</c> if this is not a subreddit link. </returns>
private static InlineParseResult ParseDoubleSlashLink(string markdown, int start, int maxEnd)
{
// The minimum length is 4 characters ("/u/u").
if (start > maxEnd - 4)
{
return null;
}
// Determine the type of link (subreddit or user).
HyperlinkType linkType;
if (markdown[start + 1] == 'r')
{
linkType = HyperlinkType.Subreddit;
}
else if (markdown[start + 1] == 'u')
{
linkType = HyperlinkType.User;
}
else
{
return null;
}
// Check that there is another slash.
if (markdown[start + 2] != '/')
{
return null;
}
// Find the end of the link.
int end = FindEndOfRedditLink(markdown, start + 3, maxEnd);
// Subreddit names must be at least two characters long, users at least one.
if (end - start < (linkType == HyperlinkType.User ? 4 : 5))
{
return null;
}
// We found something!
var text = markdown.Substring(start, end - start);
return new InlineParseResult(new HyperlinkInline { Text = text, Url = text, LinkType = linkType }, start, end);
}
/// <summary>
/// Parse a link of the form "r/news" or "u/quinbd".
/// </summary>
/// <param name="markdown"> The markdown text. </param>
/// <param name="start"> The location to start parsing. </param>
/// <param name="maxEnd"> The location to stop parsing. </param>
/// <returns> A parsed subreddit or user link, or <c>null</c> if this is not a subreddit link. </returns>
private static InlineParseResult ParseSingleSlashLink(string markdown, int start, int maxEnd)
{
// The minimum length is 3 characters ("u/u").
start--;
if (start < 0 || start > maxEnd - 3)
{
return null;
}
// Determine the type of link (subreddit or user).
HyperlinkType linkType;
if (markdown[start] == 'r')
{
linkType = HyperlinkType.Subreddit;
}
else if (markdown[start] == 'u')
{
linkType = HyperlinkType.User;
}
else
{
return null;
}
// If the link doesn't start with '/', then the previous character must be
// non-alphanumeric i.e. "bear/trap" is not a valid subreddit link.
if (start >= 1 && (char.IsLetterOrDigit(markdown[start - 1]) || markdown[start - 1] == '/'))
{
return null;
}
// Find the end of the link.
int end = FindEndOfRedditLink(markdown, start + 2, maxEnd);
// Subreddit names must be at least two characters long, users at least one.
if (end - start < (linkType == HyperlinkType.User ? 3 : 4))
{
return null;
}
// We found something!
var text = markdown.Substring(start, end - start);
return new InlineParseResult(new HyperlinkInline { Text = text, Url = "/" + text, LinkType = linkType }, start, end);
}
/// <summary>
/// Attempts to parse a URL without a scheme e.g. "www.reddit.com".
/// </summary>
/// <param name="markdown"> The markdown text. </param>
/// <param name="tripPos"> The location of the dot character. </param>
/// <param name="maxEnd"> The location to stop parsing. </param>
/// <returns> A parsed URL, or <c>null</c> if this is not a URL. </returns>
internal static InlineParseResult ParsePartialLink(string markdown, int tripPos, int maxEnd)
{
int start = tripPos - 3;
if (start < 0 || markdown[start] != 'w' || markdown[start + 1] != 'w' || markdown[start + 2] != 'w')
{
return null;
}
// The character before the "www" must be non-alphanumeric i.e. "bwww.reddit.com" is not a valid URL.
if (start >= 1 && (char.IsLetterOrDigit(markdown[start - 1]) || markdown[start - 1] == '<'))
{
return null;
}
// The URL must have at least one character after the www.
if (start >= maxEnd - 4)
{
return null;
}
// Find the end of the URL.
int end = FindUrlEnd(markdown, start + 4, maxEnd);
var url = markdown.Substring(start, end - start);
return new InlineParseResult(new HyperlinkInline { Url = "http://" + url, Text = url, LinkType = HyperlinkType.PartialUrl }, start, end);
}
/// <summary>
/// Attempts to parse an email address e.g. "test@reddit.com".
/// </summary>
/// <param name="markdown"> The markdown text. </param>
/// <param name="minStart"> The minimum start position to return. </param>
/// <param name="tripPos"> The location of the at character. </param>
/// <param name="maxEnd"> The location to stop parsing. </param>
/// <returns> A parsed URL, or <c>null</c> if this is not a URL. </returns>
internal static InlineParseResult ParseEmailAddress(string markdown, int minStart, int tripPos, int maxEnd)
{
// Search backwards until we find a character which is not a letter, digit, or one of
// these characters: '+', '-', '_', '.'.
// Note: it is intended that this code match the reddit.com markdown parser; there are
// many characters which are legal in email addresses but which aren't picked up by
// reddit (for example: '$' and '!').
// Special characters as per https://en.wikipedia.org/wiki/Email_address#Local-part allowed
char[] allowedchars = new char[] { '!', '#', '$', '%', '&', '\'', '*', '+', '-', '/', '=', '?', '^', '_', '`', '{', '|', '}', '~' };
int start = tripPos;
while (start > minStart)
{
char c = markdown[start - 1];
if ((c < 'a' || c > 'z') &&
(c < 'A' || c > 'Z') &&
(c < '0' || c > '9') &&
!allowedchars.Contains(c))
{
break;
}
start--;
}
// There must be at least one character before the '@'.
if (start == tripPos)
{
return null;
}
// Search forwards until we find a character which is not a letter, digit, or one of
// these characters: '-', '_'.
// Note: it is intended that this code match the reddit.com markdown parser;
// technically underscores ('_') aren't allowed in a host name.
int dotIndex = tripPos + 1;
while (dotIndex < maxEnd)
{
char c = markdown[dotIndex];
if ((c < 'a' || c > 'z') &&
(c < 'A' || c > 'Z') &&
(c < '0' || c > '9') &&
c != '-' && c != '_')
{
break;
}
dotIndex++;
}
// We are expecting a dot.
if (dotIndex == maxEnd || markdown[dotIndex] != '.')
{
return null;
}
// Search forwards until we find a character which is not a letter, digit, or one of
// these characters: '.', '-', '_'.
// Note: it is intended that this code match the reddit.com markdown parser;
// technically underscores ('_') aren't allowed in a host name.
int end = dotIndex + 1;
while (end < maxEnd)
{
char c = markdown[end];
if ((c < 'a' || c > 'z') &&
(c < 'A' || c > 'Z') &&
(c < '0' || c > '9') &&
c != '.' && c != '-' && c != '_')
{
break;
}
end++;
}
// There must be at least one character after the dot.
if (end == dotIndex + 1)
{
return null;
}
// We found an email address!
var emailAddress = markdown.Substring(start, end - start);
return new InlineParseResult(new HyperlinkInline { Url = "mailto:" + emailAddress, Text = emailAddress, LinkType = HyperlinkType.Email }, start, end);
}
/// <summary>
/// Converts the object into it's textual representation.
/// </summary>
/// <returns> The textual representation of this object. </returns>
public override string ToString()
{
if (Text == null)
{
return base.ToString();
}
return Text;
}
/// <summary>
/// Finds the next character that is not a letter, digit or underscore in a range.
/// </summary>
/// <param name="markdown"> The markdown text. </param>
/// <param name="start"> The location to start searching. </param>
/// <param name="end"> The location to stop searching. </param>
/// <returns> The location of the next character that is not a letter, digit or underscore. </returns>
private static int FindEndOfRedditLink(string markdown, int start, int end)
{
int pos = start;
while (pos < markdown.Length && pos < end)
{
char c = markdown[pos];
if ((c < 'a' || c > 'z') &&
(c < 'A' || c > 'Z') &&
(c < '0' || c > '9') &&
c != '_' && c != '/')
{
return pos;
}
pos++;
}
return end;
}
/// <summary>
/// Finds the end of a URL.
/// </summary>
/// <param name="markdown"> The markdown text. </param>
/// <param name="start"> The location to start searching. </param>
/// <param name="maxEnd"> The location to stop searching. </param>
/// <returns> The location of the end of the URL. </returns>
private static int FindUrlEnd(string markdown, int start, int maxEnd)
{
// For some reason a less than character ends a URL...
int end = markdown.IndexOfAny(new char[] { ' ', '\t', '\r', '\n', '<' }, start, maxEnd - start);
if (end == -1)
{
end = maxEnd;
}
// URLs can't end on a punctuation character.
while (end - 1 > start)
{
if (Array.IndexOf(new char[] { ')', '}', ']', '!', ';', '.', '?', ',' }, markdown[end - 1]) < 0)
{
break;
}
end--;
}
return end;
}
}
} | 39.552966 | 187 | 0.501473 | [
"MIT"
] | DJDGSFTX/WindowsCommunityToolkit | Microsoft.Toolkit.Parsers/Markdown/Inlines/HyperlinkInline.cs | 18,669 | C# |
using System;
using Newtonsoft.Json;
namespace HubSpot.Model.Contacts
{
public static class ContactProperties
{
public static readonly IProperty LastModifiedDate = new Property("lastmodifieddate");
public static readonly IProperty AssociatedCompanyId = new Property("associatedcompanyid");
public static readonly IProperty CreateDate = new Property("createdate");
public static readonly IUpdateableProperty FirstName = new Property("firstname");
public static readonly IUpdateableProperty LastName = new Property("lastname");
public static readonly IUpdateableProperty Email = new Property("email");
}
} | 41.625 | 99 | 0.746246 | [
"MIT"
] | Kralizek/hubspot-dotnet-sdk | src/HubSpot.Client/Model/Contacts/ContactProperties.cs | 668 | C# |
using System;
using System.Diagnostics.CodeAnalysis;
using System.Web;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin;
using Microsoft.Owin.Security;
using Ninject.Modules;
using RememBeer.Models.Identity.Contracts;
namespace RememBeer.MvcClient.Ninject.NinjectModules
{
[ExcludeFromCodeCoverage]
public class AuthNinjectModule : NinjectModule
{
public override void Load()
{
this.Rebind<IApplicationSignInManager>()
.ToMethod(context => GetOwinContext().Get<IApplicationSignInManager>());
this.Rebind<IApplicationUserManager>()
.ToMethod(context => GetOwinContext().Get<IApplicationUserManager>());
this.Rebind<IAuthenticationManager>()
.ToMethod(context => GetOwinContext().Authentication);
}
private static IOwinContext GetOwinContext()
{
var cbase = new HttpContextWrapper(HttpContext.Current);
var owinCtx = cbase.GetOwinContext();
if (owinCtx == null)
{
throw new ArgumentNullException(nameof(owinCtx));
}
return owinCtx;
}
}
}
| 27.090909 | 88 | 0.640101 | [
"MIT"
] | J0hnyBG/RememBeerMeMvc | src/RememBeer.MvcClient/Ninject/NinjectModules/AuthNinjectModule.cs | 1,194 | C# |
using SpreadCommander.Common.PowerShell;
using System;
using System.Collections.Generic;
using System.Linq;
using Automation = System.Management.Automation;
using System.Management.Automation.Runspaces;
using System.Text;
using System.Threading.Tasks;
using System.Collections.ObjectModel;
using System.Management.Automation;
using SpreadCommander.Common.PowerShell.Host;
using SpreadCommander.Common.PowerShell.CmdLets;
using DevExpress.XtraRichEdit.API.Native;
using DevExpress.Spreadsheet;
using System.Drawing;
using System.Data;
using System.Threading;
using SpreadCommander.Common.Code;
using System.ComponentModel;
using DevExpress.XtraRichEdit;
using DevExpress.XtraGauges.Core.Base;
namespace SpreadCommander.Common.ScriptEngines
{
public partial class PowerShellScriptEngine : BaseScriptEngine, ISpreadCommanderHostOwner
{
public const string ScriptEngineName = "PowerShell";
public override string EngineName => ScriptEngineName;
public override string DefaultExt => ".ps1";
public override string FileFilter => "PowerShell files (*.ps1)|*.ps1";
public override string SyntaxFile => "PowerShell";
public readonly static ConsoleColor EchoColor = ConsoleColor.Gray;
public bool ShouldExit { get; set; }
public int ExitCode { get; set; }
IRichEditDocumentServer ISpreadCommanderHostOwner.BookServer => this.BookServer;
IWorkbook ISpreadCommanderHostOwner.Spreadsheet => this.Workbook;
DataSet ISpreadCommanderHostOwner.GridDataSet => this.GridDataSet;
IFileViewer ISpreadCommanderHostOwner.FileViewer => this.FileViewer;
public int DefaultChartDPI { get; set; } = 300;
public bool Silent { get; set; }
private SpreadCommanderHost _Host;
private Runspace _Runspace;
private Pipeline _Pipe;
/// Used to serialize access to instance data.
private readonly object instanceLock = new object();
public static string StartupCommand =>
$@"$global:ErrorActionPreference = 'Break';
$ErrorActionPreference = 'Break';
Set-ExecutionPolicy Bypass -Scope:Process;
cd {Utils.QuoteString(Project.Current.ProjectPath, "\'")};";
public override void Start()
{
lock (instanceLock)
{
_Host = new SpreadCommanderHost(this);
_Runspace = CreateHostedRunspace();
_Runspace.Debugger.DebuggerStop += Debugger_DebuggerStop;
if (ExecutionType == ScriptExecutionType.Interactive)
_Host.UI.WriteLine("SpreadCommander>");
}
}
private void Debugger_DebuggerStop(object sender, DebuggerStopEventArgs e)
{
//if (!(sender is System.Management.Automation.Debugger debugger))
// throw new Exception("Cannot determine script debugger.");
e.ResumeAction = DebuggerResumeAction.Stop;
//Write exception message
using var pipe = _Runspace.CreateNestedPipeline("$error", false);
if (_Runspace.RunspaceAvailability != RunspaceAvailability.Available &&
_Runspace.RunspaceAvailability != RunspaceAvailability.AvailableForNestedCommand)
{
WriteDefaulterrorMessage();
return;
}
var result = pipe.Invoke();
if ((result?.Count ?? 0) > 0 && result[0]?.BaseObject is ErrorRecord error)
{
try
{
//Write error
var cmdlet = error.InvocationInfo?.InvocationName;
var message = GetExceptionMesage(error.Exception);
var positionMessage = error.InvocationInfo?.PositionMessage;
var categoryInfo = error.CategoryInfo?.ToString();
var errorId = error.FullyQualifiedErrorId?.ToString();
var errorMessage =
$@"{cmdlet} : {message}
{positionMessage}
+ CategoryInfo : {categoryInfo}
+ FullyQualifiedErrorId : {errorId}";
_Host.UI.WriteErrorLine(errorMessage);
}
catch (Exception)
{
WriteDefaulterrorMessage();
}
}
else
WriteDefaulterrorMessage();
void WriteDefaulterrorMessage()
{
var errorMessage =
$@"Unknown error : {e.InvocationInfo?.InvocationName}
{e.InvocationInfo?.PositionMessage}";
_Host.UI.WriteErrorLine(errorMessage);
}
static string GetExceptionMesage(Exception ex)
{
var output = new StringBuilder();
while (ex != null)
{
if (output.Length > 0)
output.AppendLine();
output.Append(ex.Message);
ex = ex.InnerException;
}
return output.ToString();
}
}
public override void Stop()
{
lock (instanceLock)
{
// close the runspace to free resources.
_Runspace?.Close();
_Runspace?.Dispose();
_Runspace = null;
}
_Host = null;
}
public void AddVariable(string name, object value)
{
var runspace = _Runspace ?? throw new Exception("Runspace is not initialized.");
runspace.SessionStateProxy.PSVariable.Set(name, value);
}
public override void SendCommand(string command) => SendCommand(command, ExecutionType == ScriptExecutionType.Script);
public void SendCommand(string command, bool silent)
{
if (string.IsNullOrEmpty(command))
{
FireExecutionFinished();
return;
}
if (!command.EndsWith(Environment.NewLine))
command += Environment.NewLine;
ProgressType = ProgressKind.Undetermined;
try
{
if (!(silent || Silent))
Write(EchoColor, ConsoleColor.White, $">> {GetFirstLine(command, 50)}{Environment.NewLine}");
if (_Pipe != null)
{
if (_Pipe.PipelineStateInfo.State == PipelineState.Running)
{
_Pipe.Input.Write(command);
_Pipe.Input.Close();
return;
}
_Pipe = null;
}
_Pipe = _Runspace.CreatePipeline();
_Pipe.StateChanged += ((s, e) =>
{
switch (e.PipelineStateInfo.State)
{
case PipelineState.Running:
//Do nothing
break;
case PipelineState.Stopping:
if (!(silent || Silent))
_Host.UI.WriteErrorLine($"{Environment.NewLine}SpreadCommander> Stopping ...");
break;
case PipelineState.Completed:
case PipelineState.Stopped:
default:
_Pipe?.Dispose();
_Pipe = null;
ProgressType = ProgressKind.None;
if (e.PipelineStateInfo.State == PipelineState.Failed)
_Host.UI.WriteErrorLine($"Failed: {e.PipelineStateInfo.Reason?.Message}");
if (!(silent || Silent))
_Host.UI.Write($"{Environment.NewLine}SpreadCommander>{Environment.NewLine}");
FireExecutionFinished();
break;
}
});
_Pipe.Commands.AddScript(command);
_Pipe.Commands.Add("out-host");
_Pipe.Commands[0].MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output);
if (_Runspace.RunspaceAvailability != RunspaceAvailability.Available)
throw new Exception("Another PowerShell command is already executing.");
_Pipe.InvokeAsync();
}
catch (Exception ex)
{
ReportException(ex);
}
static string GetFirstLine(string value, int maxLength)
{
if (string.IsNullOrEmpty(value))
return string.Empty;
var p = value.IndexOf('\n');
bool addDots = false;
if (p >= 0)
{
value = value.Substring(0, p + 1);
addDots = true;
}
value = value.Trim();
if (value.Length > maxLength)
{
value = value.Substring(0, maxLength);
addDots = true;
}
if (addDots)
value += " ...";
return value;
}
}
//Unlike usual command this one is executed synchronously.
protected static void SendServiceCommand(Runspace runspace, string command)
{
if (string.IsNullOrEmpty(command))
return;
if (!command.EndsWith(Environment.NewLine))
command += Environment.NewLine;
using var pipe = runspace.CreatePipeline();
pipe.Commands.AddScript(command);
pipe.Commands[0].MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output);
if (runspace.RunspaceAvailability != RunspaceAvailability.Available)
throw new Exception("Another PowerShell command is already executing.");
pipe.Invoke();
}
public void Write(ConsoleColor foregroundColor, ConsoleColor backgroundColor, string value)
{
ScriptOutputAvailable(ScriptOutputType.Text, value,
SpreadCommanderHost.ConvertConsoleColor(foregroundColor, false), SpreadCommanderHost.ConvertConsoleColor(backgroundColor, true));
}
public override void ScriptOutputAvailable(ScriptOutputType outputType, string output,
Color foregroundColor, Color backgroundColor)
{
switch (outputType)
{
case ScriptOutputType.Text:
FlushTextBufferSynchronized(Document, SynchronizeInvoke, foregroundColor, backgroundColor, new StringBuilder(output));
break;
case ScriptOutputType.Error:
ReportErrorSynchronized(Document, SynchronizeInvoke, output);
break;
}
}
public void DisplayProgress(long sourceID, ProgressRecord progress)
{
switch (progress.RecordType)
{
case ProgressRecordType.Completed:
ProgressType = ProgressKind.Undetermined; //script continues to run
break;
case ProgressRecordType.Processing:
UpdateProgress(ProgressKind.Value, progress.PercentComplete, 100, progress.StatusDescription);
break;
}
}
public string ReadLine()
{
var result = RequestInputLine();
return Utils.NonNullString(result);
}
private void ReportException(Exception ex)
{
if (ex == null)
return;
object error;
if (ex is Automation.IContainsErrorRecord icer)
error = icer.ErrorRecord;
else
error = (object)new Automation.ErrorRecord(ex, "Host.ReportException", Automation.ErrorCategory.NotSpecified, null);
Automation.PowerShell ps = null;
try
{
lock (instanceLock)
{
ps = Automation.PowerShell.Create();
ps.Runspace = _Runspace;
ps.AddScript("$input").AddCommand("out-string");
// Do not merge errors, this function will swallow errors.
Collection<Automation.PSObject> result;
var inputCollection = new Automation.PSDataCollection<object>
{
error
};
inputCollection.Complete();
result = ps.Invoke(inputCollection);
if (result.Count > 0)
{
string str = result[0].BaseObject as string;
// Remove \r\n that is added by Out-string.
if (!string.IsNullOrEmpty(str) && str.EndsWith("\r\n"))
str = str[0..^2];
_Host.UI.WriteErrorLine(str);
}
}
}
catch (Exception exOutput)
{
_Host.UI.WriteErrorLine(exOutput.Message);
}
finally
{
// Dispose of the pipeline line and set it to null, locked because currentPowerShell
// may be accessed by the ctrl-C handler.
lock (this.instanceLock)
ps?.Dispose();
}
}
public static Runspace CreateRunspace()
{
var sessionState = InitialSessionState.CreateDefault();
InitializeRunspaceConfiguration(sessionState);
var result = RunspaceFactory.CreateRunspace(sessionState);
result.Open();
SendServiceCommand(result, StartupCommand);
return result;
}
public static int DefaultMaxRunspaces => Environment.ProcessorCount;
//PowerShellScriptEngine shall be started
public Runspace CreateHostedRunspace(bool open = true)
{
var sessionState = InitialSessionState.CreateDefault();
InitializeRunspaceConfiguration(sessionState);
var result = RunspaceFactory.CreateRunspace(_Host, sessionState);
if (open)
{
result.Open();
SendServiceCommand(result, StartupCommand);
}
return result;
}
//When using runspace - may need to call SendServiceCommand(runspace, StartupCommand)
public static RunspacePool CreateRunspacePool(int minRunspaces, int maxRunspaces)
{
var sessionState = InitialSessionState.CreateDefault();
InitializeRunspaceConfiguration(sessionState);
var result = RunspaceFactory.CreateRunspacePool(sessionState);
result.SetMinRunspaces(minRunspaces);
result.SetMaxRunspaces(maxRunspaces);
result.Open();
return result;
}
//PowerShellScriptEngine shall be started
//When using runspace - may need to call SendServiceCommand(runspace, StartupCommand)
public RunspacePool CreateHostedRunspacePool(int minRunspaces, int maxRunspaces, bool open = true)
{
var sessionState = InitialSessionState.CreateDefault();
InitializeRunspaceConfiguration(sessionState);
var result = RunspaceFactory.CreateRunspacePool(minRunspaces, maxRunspaces,
sessionState, _Host);
if (open)
result.Open();
return result;
}
}
}
| 35.525727 | 145 | 0.544081 | [
"Apache-2.0"
] | VassilievVV/SpreadCommander | SpreadCommander.Common/ScriptEngines/PowerShellScriptEngine.cs | 15,882 | C# |
#region License
// Copyright 2014 MorseCode Software
// 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
namespace MorseCode.RxMvvm.Observable.Property.Internal
{
using System;
using System.Diagnostics.Contracts;
using System.Reactive.Concurrency;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using System.Runtime.Serialization;
using System.Security.Permissions;
using System.Threading.Tasks;
using MorseCode.RxMvvm.Common;
using MorseCode.RxMvvm.Common.DiscriminatedUnion;
[Serializable]
internal class CancellableAsyncCalculatedPropertyWithContext<TContext, TFirst, TSecond, TThird, T> :
CalculatedPropertyBase<T>,
ISerializable
{
private readonly TContext context;
private readonly IObservable<TFirst> firstProperty;
private readonly IObservable<TSecond> secondProperty;
private readonly IObservable<TThird> thirdProperty;
private readonly TimeSpan throttleTime;
private readonly Func<AsyncCalculationHelper, TContext, TFirst, TSecond, TThird, Task<T>> calculateValue;
private readonly bool isLongRunningCalculation;
private IDisposable scheduledTask;
internal CancellableAsyncCalculatedPropertyWithContext(
TContext context,
IObservable<TFirst> firstProperty,
IObservable<TSecond> secondProperty,
IObservable<TThird> thirdProperty,
TimeSpan throttleTime,
Func<AsyncCalculationHelper, TContext, TFirst, TSecond, TThird, Task<T>> calculateValue,
bool isLongRunningCalculation)
{
Contract.Requires<ArgumentNullException>(firstProperty != null, "firstProperty");
Contract.Requires<ArgumentNullException>(secondProperty != null, "secondProperty");
Contract.Requires<ArgumentNullException>(thirdProperty != null, "thirdProperty");
Contract.Requires<ArgumentNullException>(calculateValue != null, "calculateValue");
Contract.Ensures(this.firstProperty != null);
Contract.Ensures(this.secondProperty != null);
Contract.Ensures(this.thirdProperty != null);
Contract.Ensures(this.calculateValue != null);
RxMvvmConfiguration.EnsureSerializableDelegateIfUsingSerialization(calculateValue);
this.context = context;
this.firstProperty = firstProperty;
this.secondProperty = secondProperty;
this.thirdProperty = thirdProperty;
this.throttleTime = throttleTime;
this.calculateValue = calculateValue;
this.isLongRunningCalculation = isLongRunningCalculation;
Func<AsyncCalculationHelper, TFirst, TSecond, TThird, Task<IDiscriminatedUnion<object, T, Exception>>> calculate = async (helper, first, second, third) =>
{
IDiscriminatedUnion<object, T, Exception> discriminatedUnion;
try
{
discriminatedUnion =
DiscriminatedUnion.First<object, T, Exception>(
await calculateValue(helper, context, first, second, third).ConfigureAwait(true));
}
catch (Exception e)
{
discriminatedUnion = DiscriminatedUnion.Second<object, T, Exception>(e);
}
return discriminatedUnion;
};
this.SetHelper(new CalculatedPropertyHelper(
(resultSubject, isCalculatingSubject) =>
{
CompositeDisposable d = new CompositeDisposable();
IScheduler scheduler = isLongRunningCalculation
? RxMvvmConfiguration.GetLongRunningCalculationScheduler()
: RxMvvmConfiguration.GetCalculationScheduler();
IObservable<Tuple<TFirst, TSecond, TThird>> o = firstProperty.CombineLatest(
secondProperty, thirdProperty, Tuple.Create);
o = throttleTime > TimeSpan.Zero ? o.Throttle(throttleTime, scheduler) : o.ObserveOn(scheduler);
d.Add(
o.Subscribe(
v =>
{
using (this.scheduledTask)
{
}
isCalculatingSubject.OnNext(true);
this.scheduledTask = scheduler.ScheduleAsync(
async (s, t) =>
{
try
{
await s.Yield().ConfigureAwait(true);
IDiscriminatedUnion<object, T, Exception> result =
await
calculate(
new AsyncCalculationHelper(s, t),
v.Item1,
v.Item2,
v.Item3).ConfigureAwait(true);
await s.Yield().ConfigureAwait(true);
resultSubject.OnNext(result);
}
catch (OperationCanceledException)
{
}
catch (Exception e)
{
resultSubject.OnNext(
DiscriminatedUnion.Second<object, T, Exception>(e));
}
isCalculatingSubject.OnNext(false);
});
}));
return d;
}));
}
/// <summary>
/// Initializes a new instance of the <see cref="CancellableAsyncCalculatedPropertyWithContext{TContext,TFirst,TSecond,TThird,T}"/> class from serialized data.
/// </summary>
/// <param name="info">
/// The serialization info.
/// </param>
/// <param name="context">
/// The serialization context.
/// </param>
[ContractVerification(false)]
// ReSharper disable UnusedParameter.Local
protected CancellableAsyncCalculatedPropertyWithContext(SerializationInfo info, StreamingContext context)
// ReSharper restore UnusedParameter.Local
: this(
(TContext)(info.GetValue("c", typeof(TContext)) ?? default(TContext)),
(IObservable<TFirst>)info.GetValue("p1", typeof(IObservable<TFirst>)),
(IObservable<TSecond>)info.GetValue("p2", typeof(IObservable<TSecond>)),
(IObservable<TThird>)info.GetValue("p3", typeof(IObservable<TThird>)),
(TimeSpan)(info.GetValue("t", typeof(TimeSpan)) ?? default(TimeSpan)),
(Func<AsyncCalculationHelper, TContext, TFirst, TSecond, TThird, Task<T>>)info.GetValue("f", typeof(Func<AsyncCalculationHelper, TContext, TFirst, TSecond, TThird, Task<T>>)),
(bool)info.GetValue("l", typeof(bool)))
{
}
/// <summary>
/// Gets the object data to serialize.
/// </summary>
/// <param name="info">
/// The serialization info.
/// </param>
/// <param name="streamingContext">
/// The serialization context.
/// </param>
[SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)]
public virtual void GetObjectData(SerializationInfo info, StreamingContext streamingContext)
{
info.AddValue("c", this.context);
info.AddValue("p1", this.firstProperty);
info.AddValue("p2", this.secondProperty);
info.AddValue("p3", this.thirdProperty);
info.AddValue("t", this.throttleTime);
info.AddValue("f", this.calculateValue);
info.AddValue("l", this.isLongRunningCalculation);
}
/// <summary>
/// Disposes of the property.
/// </summary>
protected override void Dispose()
{
base.Dispose();
using (this.scheduledTask)
{
}
}
[ContractInvariantMethod]
private void CodeContractsInvariants()
{
Contract.Invariant(this.firstProperty != null);
Contract.Invariant(this.secondProperty != null);
Contract.Invariant(this.thirdProperty != null);
Contract.Invariant(this.calculateValue != null);
}
}
} | 47.106977 | 191 | 0.51718 | [
"Apache-2.0"
] | jam40jeff/RxMvvm | Source/MorseCode.RxMvvm/Observable/Property/Internal/CancellableAsyncCalculatedPropertyWithContext{TFirst,TSecond,TThird,T}.cs | 10,128 | C# |
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Routing;
namespace Myproject.Web
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
//ASP.NET Web API Route Config
routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
}
| 27.5 | 99 | 0.52987 | [
"MIT"
] | ahmetkursatesim/ASPNETProject | src/Myproject.Web/App_Start/RouteConfig.cs | 772 | C# |
using System;
class RestaurantDiscount
{
static void Main()
{
int groupSize = int.Parse(Console.ReadLine());
string package = Console.ReadLine().ToLower();
string hallName;
decimal hallPrice = 0;
decimal packagePrice = 0;
decimal discount = 0;
if (groupSize > 120)
{
Console.WriteLine("We do not have an appropriate hall.");
return;
}
else if (groupSize > 100)
{
hallPrice = 7500;
hallName = "Great Hall";
}
else if (groupSize > 50)
{
hallPrice = 5000;
hallName = "Terrace";
}
else
{
hallPrice = 2500;
hallName = "Small Hall";
}
switch (package)
{
case "normal":
packagePrice = 500;
discount = 0.95m;
break;
case "gold":
packagePrice = 750;
discount = 0.9m;
break;
case "platinum":
packagePrice = 1000;
discount = 0.85m;
break;
}
decimal pricePerPerson = Decimal.Multiply((hallPrice + packagePrice), discount) / groupSize;
Console.WriteLine($"We can offer you the {hallName}");
Console.WriteLine($"The price per person is {pricePerPerson:f2}$");
}
}
| 24.775862 | 100 | 0.473208 | [
"MIT"
] | lapd87/SoftUniProgrammingFundamentalsCSharp | ProgrammingFundamentalsCSharp/02ConditionalStatementsAndLoops/03RestaurantDiscount/RestaurantDiscount.cs | 1,439 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.ApplicationModel;
using Windows.ApplicationModel.Activation;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Animation;
using Windows.UI.Xaml.Navigation;
// The Blank Application template is documented at http://go.microsoft.com/fwlink/?LinkId=391641
namespace SpacingButtons.WinPhone
{
/// <summary>
/// Provides application-specific behavior to supplement the default Application class.
/// </summary>
public sealed partial class App : Application
{
private TransitionCollection transitions;
/// <summary>
/// Initializes the singleton application object. This is the first line of authored code
/// executed, and as such is the logical equivalent of main() or WinMain().
/// </summary>
public App()
{
this.InitializeComponent();
this.Suspending += this.OnSuspending;
}
/// <summary>
/// Invoked when the application is launched normally by the end user. Other entry points
/// will be used when the application is launched to open a specific file, to display
/// search results, and so forth.
/// </summary>
/// <param name="e">Details about the launch request and process.</param>
protected override void OnLaunched(LaunchActivatedEventArgs e)
{
#if DEBUG
if (System.Diagnostics.Debugger.IsAttached)
{
this.DebugSettings.EnableFrameRateCounter = true;
}
#endif
Frame rootFrame = Window.Current.Content as Frame;
// Do not repeat app initialization when the Window already has content,
// just ensure that the window is active
if (rootFrame == null)
{
// Create a Frame to act as the navigation context and navigate to the first page
rootFrame = new Frame();
// TODO: change this value to a cache size that is appropriate for your application
rootFrame.CacheSize = 1;
Xamarin.Forms.Forms.Init(e);
if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
{
// TODO: Load state from previously suspended application
}
// Place the frame in the current Window
Window.Current.Content = rootFrame;
}
if (rootFrame.Content == null)
{
// Removes the turnstile navigation for startup.
if (rootFrame.ContentTransitions != null)
{
this.transitions = new TransitionCollection();
foreach (var c in rootFrame.ContentTransitions)
{
this.transitions.Add(c);
}
}
rootFrame.ContentTransitions = null;
rootFrame.Navigated += this.RootFrame_FirstNavigated;
// When the navigation stack isn't restored navigate to the first page,
// configuring the new page by passing required information as a navigation
// parameter
if (!rootFrame.Navigate(typeof(MainPage), e.Arguments))
{
throw new Exception("Failed to create initial page");
}
}
// Ensure the current window is active
Window.Current.Activate();
}
/// <summary>
/// Restores the content transitions after the app has launched.
/// </summary>
/// <param name="sender">The object where the handler is attached.</param>
/// <param name="e">Details about the navigation event.</param>
private void RootFrame_FirstNavigated(object sender, NavigationEventArgs e)
{
var rootFrame = sender as Frame;
rootFrame.ContentTransitions = this.transitions ?? new TransitionCollection() { new NavigationThemeTransition() };
rootFrame.Navigated -= this.RootFrame_FirstNavigated;
}
/// <summary>
/// Invoked when application execution is being suspended. Application state is saved
/// without knowing whether the application will be terminated or resumed with the contents
/// of memory still intact.
/// </summary>
/// <param name="sender">The source of the suspend request.</param>
/// <param name="e">Details about the suspend request.</param>
private void OnSuspending(object sender, SuspendingEventArgs e)
{
var deferral = e.SuspendingOperation.GetDeferral();
// TODO: Save application state and stop any background activity
deferral.Complete();
}
}
} | 38.857143 | 126 | 0.610101 | [
"Apache-2.0"
] | aliozgur/xamarin-forms-book-samples | Chapter17/SpacingButtons/SpacingButtons/SpacingButtons.WinPhone/App.xaml.cs | 5,168 | C# |
using System;
using System.Collections.Generic;
namespace Storagr.Shared
{
public interface IStoragrEnumerable<TItem> :
IStoragrRunner<IEnumerable<TItem>>
{
IStoragrEnumerable<TItem> Take(int count);
IStoragrEnumerable<TItem> Skip(int count);
IStoragrEnumerable<TItem> SkipUntil(string cursor);
}
public interface IStoragrEnumerable<TItem, out TParams> :
IStoragrRunner<IEnumerable<TItem>>
{
IStoragrEnumerable<TItem, TParams> Take(int count);
IStoragrEnumerable<TItem, TParams> Skip(int count);
IStoragrEnumerable<TItem, TParams> SkipUntil(string cursor);
IStoragrEnumerable<TItem, TParams> Where(Action<TParams> whereParams);
}
} | 33.363636 | 78 | 0.702997 | [
"MIT"
] | talaryonlabs/storagr | src/Storagr.Shared/Core/Fluent/IStoragrEnumerable.cs | 736 | 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.Ocr.V20181119.Models
{
using Newtonsoft.Json;
using System.Collections.Generic;
using TencentCloud.Common;
public class SmartStructuralOCRRequest : AbstractModel
{
/// <summary>
/// 图片的 Url 地址。
/// 支持的图片格式:PNG、JPG、JPEG,暂不支持 GIF 格式。
/// 支持的图片大小:所下载图片经 Base64 编码后不超过 7M。图片下载时间不超过 3 秒。
/// 图片存储于腾讯云的 Url 可保障更高的下载速度和稳定性,建议图片存储于腾讯云。
/// 非腾讯云存储的 Url 速度和稳定性可能受一定影响。
/// </summary>
[JsonProperty("ImageUrl")]
public string ImageUrl{ get; set; }
/// <summary>
/// 图片的 Base64 值。
/// 支持的图片格式:PNG、JPG、JPEG,暂不支持 GIF 格式。
/// 支持的图片大小:所下载图片经Base64编码后不超过 7M。图片下载时间不超过 3 秒。
/// 图片的 ImageUrl、ImageBase64 必须提供一个,如果都提供,只使用 ImageUrl。
/// </summary>
[JsonProperty("ImageBase64")]
public string ImageBase64{ get; set; }
/// <summary>
/// 需返回的字段名称,例:
/// 若客户只想返回姓名、性别两个字段的识别结果,则输入
/// ItemNames=["姓名","性别"]
/// </summary>
[JsonProperty("ItemNames")]
public string[] ItemNames{ get; set; }
/// <summary>
/// For internal usage only. DO NOT USE IT.
/// </summary>
public override void ToMap(Dictionary<string, string> map, string prefix)
{
this.SetParamSimple(map, prefix + "ImageUrl", this.ImageUrl);
this.SetParamSimple(map, prefix + "ImageBase64", this.ImageBase64);
this.SetParamArraySimple(map, prefix + "ItemNames.", this.ItemNames);
}
}
}
| 32.925373 | 81 | 0.622847 | [
"Apache-2.0"
] | TencentCloud/tencentcloud-sdk-dotnet | TencentCloud/Ocr/V20181119/Models/SmartStructuralOCRRequest.cs | 2,662 | C# |
using System;
namespace DaRT
{
public class Player
{
public int number;
public String ip;
public String ping;
public String guid;
public String name;
public String status;
public String lastseen;
public String lastseenon;
public String location;
public String comment;
public Player(int number, String ip, String ping, String guid, String name, String status)
{
this.number = number;
this.ip = ip;
this.ping = ping;
this.guid = guid;
this.name = name;
this.status = status;
}
public Player(int number, String ip, String ping, String guid, String name, String status, String lastseenon)
{
this.number = number;
this.ip = ip;
this.ping = ping;
this.guid = guid;
this.name = name;
this.status = status;
this.lastseenon = lastseenon;
}
public Player(int number, String ip, String ping, String guid, String name, String status, String lastseen, String lastseenon, String location)
{
this.number = number;
this.ip = ip;
this.ping = ping;
this.guid = guid;
this.name = name;
this.status = status;
this.lastseen = lastseen;
this.lastseenon = lastseenon;
this.location = location;
}
public Player(int number, String ip, String lastseen, String guid, String name, String lastseenon, String comment, bool doComment)
{
this.number = number;
this.ip = ip;
this.guid = guid;
this.name = name;
this.lastseen = lastseen;
this.lastseenon = lastseenon;
this.comment = comment;
}
}
}
| 29.796875 | 151 | 0.535396 | [
"MIT"
] | bravo10delta/DaRT | DaRT/Classes/Player.cs | 1,909 | C# |
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using FluentAssertions;
using IdentityModel;
using iSHARE.Abstractions;
using iSHARE.IdentityServer.Helpers.Interfaces;
using iSHARE.IdentityServer.Validation;
using iSHARE.IdentityServer.Validation.Interfaces;
using iSHARE.Tests.Common;
using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Tokens;
using Moq;
using Xunit;
namespace iSHARE.IdentityServer.Tests.Validation
{
public class DefaultJwtValidatorTests
{
private const string ClientId = TestData.Warehouse13.ClientId;
private const string PrivateKey = TestData.Warehouse13.PrivateKey;
private const string PublicKey = TestData.Warehouse13.PublicKey;
private readonly Mock<ILogger<DefaultJwtValidator>> _loggerMock;
private readonly Mock<IKeysExtractor> _keysExtractorMock;
private readonly IDefaultJwtValidator _sut;
public DefaultJwtValidatorTests()
{
_loggerMock = new Mock<ILogger<DefaultJwtValidator>>();
_keysExtractorMock = new Mock<IKeysExtractor>();
_keysExtractorMock
.Setup(x => x.ExtractSecurityKeys(It.IsAny<string>()))
.Returns(new List<SecurityKey> { new X509SecurityKey(PublicKey.ConvertToX509Certificate2()) });
_sut = new DefaultJwtValidator(_loggerMock.Object, _keysExtractorMock.Object);
}
[Theory]
[InlineData("PS256")]
[InlineData("RS384")]
[InlineData("RS512")]
public void IsValid_JwtHeaderAlgInvalid_ReturnsFalse(string signingAlgorithm)
{
var jwt = CreateClientAssertionJwt(signingAlgorithm);
var result = _sut.IsValid(jwt, ClientId, TestData.SchemeOwner.ClientId);
result.Should().BeFalse();
}
private static string CreateClientAssertionJwt(string signingAlgorithm)
{
var now = DateTime.UtcNow;
var token = new JwtSecurityToken(
ClientId,
ClientId,
new[]
{
new Claim(JwtClaimTypes.Subject, ClientId),
new Claim(JwtClaimTypes.Audience, TestData.SchemeOwner.ClientId),
new Claim(JwtClaimTypes.JwtId, Guid.NewGuid().ToString()),
new Claim(JwtClaimTypes.IssuedAt, now.ToEpoch()),
new Claim(JwtClaimTypes.Expiration, now.AddSeconds(30).ToEpoch())
},
now,
now.AddSeconds(30),
JwtStringFactory.CreateSigningCredentials(PrivateKey, signingAlgorithm)
).AddPublicKeyHeader(PublicKey);
return JwtStringFactory.CreateToken(token);
}
}
}
| 36 | 111 | 0.657051 | [
"Unlicense"
] | iSHARE-Scheme/Authorization-Registry | tests/iSHARE.IdentityServer.Tests/Validation/DefaultJwtValidatorTests.cs | 2,810 | C# |
using System.Collections.Immutable;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
namespace CodeCracker.CSharp.Usage
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class SimplifyRedundantBooleanComparisonsAnalyzer : DiagnosticAnalyzer
{
internal const string Title = "Simplify expression";
internal const string MessageFormat = "You can remove this comparison.";
internal const string Category = SupportedCategories.Usage;
internal static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor(
DiagnosticId.SimplifyRedundantBooleanComparisons.ToDiagnosticId(),
Title,
MessageFormat,
Category,
SeverityConfigurations.CurrentCS[DiagnosticId.SimplifyRedundantBooleanComparisons],
isEnabledByDefault: true,
customTags: WellKnownDiagnosticTags.Unnecessary,
helpLinkUri: HelpLink.ForDiagnostic(DiagnosticId.SimplifyRedundantBooleanComparisons));
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule);
public override void Initialize(AnalysisContext context) =>
context.RegisterSyntaxNodeAction(AnalyzeNode, SyntaxKind.EqualsExpression, SyntaxKind.NotEqualsExpression);
private static void AnalyzeNode(SyntaxNodeAnalysisContext context)
{
if (context.IsGenerated()) return;
var comparison = (BinaryExpressionSyntax)context.Node;
// Only handle the case where both operands of type bool; other cases involve
// too much complexity to be able to deliver an accurate diagnostic confidently.
var leftType = context.SemanticModel.GetTypeInfo(comparison.Left).Type;
var rightType = context.SemanticModel.GetTypeInfo(comparison.Right).Type;
if (!IsBoolean(leftType) || !IsBoolean(rightType))
return;
var leftConstant = context.SemanticModel.GetConstantValue(comparison.Left);
var rightConstant = context.SemanticModel.GetConstantValue(comparison.Right);
if (!leftConstant.HasValue && !rightConstant.HasValue)
return;
var diagnostic = Diagnostic.Create(Rule, comparison.GetLocation());
context.ReportDiagnostic(diagnostic);
}
private static bool IsBoolean(ITypeSymbol symbol)
{
return symbol != null && symbol.SpecialType == SpecialType.System_Boolean;
}
}
} | 46.157895 | 119 | 0.708856 | [
"Apache-2.0"
] | dotnet-campus/code-cracker | src/CSharp/CodeCracker/Usage/SimplifyRedundantBooleanComparisonsAnalyzer.cs | 2,631 | C# |
// <auto-generated>
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/ads/googleads/v8/services/ad_group_criterion_label_service.proto
// </auto-generated>
// Original file comments:
// Copyright 2021 Google LLC
//
// 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.
//
#pragma warning disable 0414, 1591
#region Designer generated code
using grpc = global::Grpc.Core;
namespace Google.Ads.GoogleAds.V8.Services {
/// <summary>
/// Service to manage labels on ad group criteria.
/// </summary>
public static partial class AdGroupCriterionLabelService
{
static readonly string __ServiceName = "google.ads.googleads.v8.services.AdGroupCriterionLabelService";
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
static void __Helper_SerializeMessage(global::Google.Protobuf.IMessage message, grpc::SerializationContext context)
{
#if !GRPC_DISABLE_PROTOBUF_BUFFER_SERIALIZATION
if (message is global::Google.Protobuf.IBufferMessage)
{
context.SetPayloadLength(message.CalculateSize());
global::Google.Protobuf.MessageExtensions.WriteTo(message, context.GetBufferWriter());
context.Complete();
return;
}
#endif
context.Complete(global::Google.Protobuf.MessageExtensions.ToByteArray(message));
}
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
static class __Helper_MessageCache<T>
{
public static readonly bool IsBufferMessage = global::System.Reflection.IntrospectionExtensions.GetTypeInfo(typeof(global::Google.Protobuf.IBufferMessage)).IsAssignableFrom(typeof(T));
}
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
static T __Helper_DeserializeMessage<T>(grpc::DeserializationContext context, global::Google.Protobuf.MessageParser<T> parser) where T : global::Google.Protobuf.IMessage<T>
{
#if !GRPC_DISABLE_PROTOBUF_BUFFER_SERIALIZATION
if (__Helper_MessageCache<T>.IsBufferMessage)
{
return parser.ParseFrom(context.PayloadAsReadOnlySequence());
}
#endif
return parser.ParseFrom(context.PayloadAsNewBuffer());
}
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
static readonly grpc::Marshaller<global::Google.Ads.GoogleAds.V8.Services.GetAdGroupCriterionLabelRequest> __Marshaller_google_ads_googleads_v8_services_GetAdGroupCriterionLabelRequest = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Google.Ads.GoogleAds.V8.Services.GetAdGroupCriterionLabelRequest.Parser));
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
static readonly grpc::Marshaller<global::Google.Ads.GoogleAds.V8.Resources.AdGroupCriterionLabel> __Marshaller_google_ads_googleads_v8_resources_AdGroupCriterionLabel = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Google.Ads.GoogleAds.V8.Resources.AdGroupCriterionLabel.Parser));
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
static readonly grpc::Marshaller<global::Google.Ads.GoogleAds.V8.Services.MutateAdGroupCriterionLabelsRequest> __Marshaller_google_ads_googleads_v8_services_MutateAdGroupCriterionLabelsRequest = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Google.Ads.GoogleAds.V8.Services.MutateAdGroupCriterionLabelsRequest.Parser));
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
static readonly grpc::Marshaller<global::Google.Ads.GoogleAds.V8.Services.MutateAdGroupCriterionLabelsResponse> __Marshaller_google_ads_googleads_v8_services_MutateAdGroupCriterionLabelsResponse = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Google.Ads.GoogleAds.V8.Services.MutateAdGroupCriterionLabelsResponse.Parser));
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
static readonly grpc::Method<global::Google.Ads.GoogleAds.V8.Services.GetAdGroupCriterionLabelRequest, global::Google.Ads.GoogleAds.V8.Resources.AdGroupCriterionLabel> __Method_GetAdGroupCriterionLabel = new grpc::Method<global::Google.Ads.GoogleAds.V8.Services.GetAdGroupCriterionLabelRequest, global::Google.Ads.GoogleAds.V8.Resources.AdGroupCriterionLabel>(
grpc::MethodType.Unary,
__ServiceName,
"GetAdGroupCriterionLabel",
__Marshaller_google_ads_googleads_v8_services_GetAdGroupCriterionLabelRequest,
__Marshaller_google_ads_googleads_v8_resources_AdGroupCriterionLabel);
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
static readonly grpc::Method<global::Google.Ads.GoogleAds.V8.Services.MutateAdGroupCriterionLabelsRequest, global::Google.Ads.GoogleAds.V8.Services.MutateAdGroupCriterionLabelsResponse> __Method_MutateAdGroupCriterionLabels = new grpc::Method<global::Google.Ads.GoogleAds.V8.Services.MutateAdGroupCriterionLabelsRequest, global::Google.Ads.GoogleAds.V8.Services.MutateAdGroupCriterionLabelsResponse>(
grpc::MethodType.Unary,
__ServiceName,
"MutateAdGroupCriterionLabels",
__Marshaller_google_ads_googleads_v8_services_MutateAdGroupCriterionLabelsRequest,
__Marshaller_google_ads_googleads_v8_services_MutateAdGroupCriterionLabelsResponse);
/// <summary>Service descriptor</summary>
public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor
{
get { return global::Google.Ads.GoogleAds.V8.Services.AdGroupCriterionLabelServiceReflection.Descriptor.Services[0]; }
}
/// <summary>Base class for server-side implementations of AdGroupCriterionLabelService</summary>
[grpc::BindServiceMethod(typeof(AdGroupCriterionLabelService), "BindService")]
public abstract partial class AdGroupCriterionLabelServiceBase
{
/// <summary>
/// Returns the requested ad group criterion label in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request received from the client.</param>
/// <param name="context">The context of the server-side call handler being invoked.</param>
/// <returns>The response to send back to the client (wrapped by a task).</returns>
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
public virtual global::System.Threading.Tasks.Task<global::Google.Ads.GoogleAds.V8.Resources.AdGroupCriterionLabel> GetAdGroupCriterionLabel(global::Google.Ads.GoogleAds.V8.Services.GetAdGroupCriterionLabelRequest request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
/// <summary>
/// Creates and removes ad group criterion labels.
/// Operation statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [FieldError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request received from the client.</param>
/// <param name="context">The context of the server-side call handler being invoked.</param>
/// <returns>The response to send back to the client (wrapped by a task).</returns>
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
public virtual global::System.Threading.Tasks.Task<global::Google.Ads.GoogleAds.V8.Services.MutateAdGroupCriterionLabelsResponse> MutateAdGroupCriterionLabels(global::Google.Ads.GoogleAds.V8.Services.MutateAdGroupCriterionLabelsRequest request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
}
/// <summary>Client for AdGroupCriterionLabelService</summary>
public partial class AdGroupCriterionLabelServiceClient : grpc::ClientBase<AdGroupCriterionLabelServiceClient>
{
/// <summary>Creates a new client for AdGroupCriterionLabelService</summary>
/// <param name="channel">The channel to use to make remote calls.</param>
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
public AdGroupCriterionLabelServiceClient(grpc::ChannelBase channel) : base(channel)
{
}
/// <summary>Creates a new client for AdGroupCriterionLabelService that uses a custom <c>CallInvoker</c>.</summary>
/// <param name="callInvoker">The callInvoker to use to make remote calls.</param>
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
public AdGroupCriterionLabelServiceClient(grpc::CallInvoker callInvoker) : base(callInvoker)
{
}
/// <summary>Protected parameterless constructor to allow creation of test doubles.</summary>
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
protected AdGroupCriterionLabelServiceClient() : base()
{
}
/// <summary>Protected constructor to allow creation of configured clients.</summary>
/// <param name="configuration">The client configuration.</param>
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
protected AdGroupCriterionLabelServiceClient(ClientBaseConfiguration configuration) : base(configuration)
{
}
/// <summary>
/// Returns the requested ad group criterion label in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The response received from the server.</returns>
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
public virtual global::Google.Ads.GoogleAds.V8.Resources.AdGroupCriterionLabel GetAdGroupCriterionLabel(global::Google.Ads.GoogleAds.V8.Services.GetAdGroupCriterionLabelRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken))
{
return GetAdGroupCriterionLabel(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Returns the requested ad group criterion label in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The response received from the server.</returns>
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
public virtual global::Google.Ads.GoogleAds.V8.Resources.AdGroupCriterionLabel GetAdGroupCriterionLabel(global::Google.Ads.GoogleAds.V8.Services.GetAdGroupCriterionLabelRequest request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_GetAdGroupCriterionLabel, null, options, request);
}
/// <summary>
/// Returns the requested ad group criterion label in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The call object.</returns>
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
public virtual grpc::AsyncUnaryCall<global::Google.Ads.GoogleAds.V8.Resources.AdGroupCriterionLabel> GetAdGroupCriterionLabelAsync(global::Google.Ads.GoogleAds.V8.Services.GetAdGroupCriterionLabelRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken))
{
return GetAdGroupCriterionLabelAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Returns the requested ad group criterion label in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The call object.</returns>
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
public virtual grpc::AsyncUnaryCall<global::Google.Ads.GoogleAds.V8.Resources.AdGroupCriterionLabel> GetAdGroupCriterionLabelAsync(global::Google.Ads.GoogleAds.V8.Services.GetAdGroupCriterionLabelRequest request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_GetAdGroupCriterionLabel, null, options, request);
}
/// <summary>
/// Creates and removes ad group criterion labels.
/// Operation statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [FieldError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The response received from the server.</returns>
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
public virtual global::Google.Ads.GoogleAds.V8.Services.MutateAdGroupCriterionLabelsResponse MutateAdGroupCriterionLabels(global::Google.Ads.GoogleAds.V8.Services.MutateAdGroupCriterionLabelsRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken))
{
return MutateAdGroupCriterionLabels(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Creates and removes ad group criterion labels.
/// Operation statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [FieldError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The response received from the server.</returns>
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
public virtual global::Google.Ads.GoogleAds.V8.Services.MutateAdGroupCriterionLabelsResponse MutateAdGroupCriterionLabels(global::Google.Ads.GoogleAds.V8.Services.MutateAdGroupCriterionLabelsRequest request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_MutateAdGroupCriterionLabels, null, options, request);
}
/// <summary>
/// Creates and removes ad group criterion labels.
/// Operation statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [FieldError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The call object.</returns>
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
public virtual grpc::AsyncUnaryCall<global::Google.Ads.GoogleAds.V8.Services.MutateAdGroupCriterionLabelsResponse> MutateAdGroupCriterionLabelsAsync(global::Google.Ads.GoogleAds.V8.Services.MutateAdGroupCriterionLabelsRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken))
{
return MutateAdGroupCriterionLabelsAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Creates and removes ad group criterion labels.
/// Operation statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [FieldError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The call object.</returns>
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
public virtual grpc::AsyncUnaryCall<global::Google.Ads.GoogleAds.V8.Services.MutateAdGroupCriterionLabelsResponse> MutateAdGroupCriterionLabelsAsync(global::Google.Ads.GoogleAds.V8.Services.MutateAdGroupCriterionLabelsRequest request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_MutateAdGroupCriterionLabels, null, options, request);
}
/// <summary>Creates a new instance of client from given <c>ClientBaseConfiguration</c>.</summary>
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
protected override AdGroupCriterionLabelServiceClient NewInstance(ClientBaseConfiguration configuration)
{
return new AdGroupCriterionLabelServiceClient(configuration);
}
}
/// <summary>Creates service definition that can be registered with a server</summary>
/// <param name="serviceImpl">An object implementing the server-side handling logic.</param>
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
public static grpc::ServerServiceDefinition BindService(AdGroupCriterionLabelServiceBase serviceImpl)
{
return grpc::ServerServiceDefinition.CreateBuilder()
.AddMethod(__Method_GetAdGroupCriterionLabel, serviceImpl.GetAdGroupCriterionLabel)
.AddMethod(__Method_MutateAdGroupCriterionLabels, serviceImpl.MutateAdGroupCriterionLabels).Build();
}
/// <summary>Register service method with a service binder with or without implementation. Useful when customizing the service binding logic.
/// Note: this method is part of an experimental API that can change or be removed without any prior notice.</summary>
/// <param name="serviceBinder">Service methods will be bound by calling <c>AddMethod</c> on this object.</param>
/// <param name="serviceImpl">An object implementing the server-side handling logic.</param>
[global::System.CodeDom.Compiler.GeneratedCode("grpc_csharp_plugin", null)]
public static void BindService(grpc::ServiceBinderBase serviceBinder, AdGroupCriterionLabelServiceBase serviceImpl)
{
serviceBinder.AddMethod(__Method_GetAdGroupCriterionLabel, serviceImpl == null ? null : new grpc::UnaryServerMethod<global::Google.Ads.GoogleAds.V8.Services.GetAdGroupCriterionLabelRequest, global::Google.Ads.GoogleAds.V8.Resources.AdGroupCriterionLabel>(serviceImpl.GetAdGroupCriterionLabel));
serviceBinder.AddMethod(__Method_MutateAdGroupCriterionLabels, serviceImpl == null ? null : new grpc::UnaryServerMethod<global::Google.Ads.GoogleAds.V8.Services.MutateAdGroupCriterionLabelsRequest, global::Google.Ads.GoogleAds.V8.Services.MutateAdGroupCriterionLabelsResponse>(serviceImpl.MutateAdGroupCriterionLabels));
}
}
}
#endregion
| 60.204244 | 429 | 0.719699 | [
"Apache-2.0"
] | friedenberg/google-ads-dotnet | src/V8/Services/AdGroupCriterionLabelServiceGrpc.g.cs | 22,697 | C# |
using UnityEngine;
public class Pulse : MonoBehaviour
{
Vector3 startScale;
void Start ()
{
startScale = transform.localScale;
}
void Update()
{
transform.localScale = startScale * (1f + .1f * Mathf.Sin(2 * Time.time));
}
}
| 15.470588 | 82 | 0.608365 | [
"MIT"
] | jaburns/ggj2018 | Assets/Scripts/Pulse.cs | 265 | C# |
namespace _1.Code_First_Student_System.Models
{
using System.ComponentModel.DataAnnotations;
public class License
{
public int Id { get; set; }
[Required]
[StringLength(50)]
public string Name { get; set; }
public int ResourceId { get; set; }
public virtual Resource Resource { get; set; }
}
}
| 20.166667 | 54 | 0.608815 | [
"MIT"
] | RAstardzhiev/SoftUni-C- | Databases Advanced - Entity Framework 6/EF Relations/1. Code First Student System/Models/License.cs | 365 | C# |
using UnityEngine;
using System.Collections;
public class BoostPedalCollider : MonoBehaviour
{
[SerializeField]
private BoostPedal _bp;
void OnTriggerEnter(Collider aCol)
{
CarController target = aCol.gameObject.GetComponent<CarController>();
if (null == target)
{
return;
}
if (target.isLocalPlayer)
{
_bp.CmdBoost(target.netId);
}
else if (target._isAI && target.isServer)
{
_bp.Boost(target);
}
}
} | 21.538462 | 78 | 0.55 | [
"MIT"
] | showstop98/gtb-client | Assets/Script/Play/BoostPedalCollider.cs | 562 | C# |
using Newtonsoft.Json;
using SFA.DAS.EmployerIncentives.Functions.LegalEntities.Services.LegalEntities.Types;
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace SFA.DAS.EmployerIncentives.Functions.LegalEntities.Services.LegalEntities
{
public class EmailService : IEmailService
{
private readonly HttpClient _client;
public EmailService(HttpClient client)
{
_client = client;
}
public async Task SendRepeatReminderEmails(DateTime applicationCutOffDate)
{
var url = "email/bank-details-repeat-reminders";
var request = new BankDetailRepeatReminderEmailsRequest { ApplicationCutOffDate = applicationCutOffDate };
var response = await _client.PostAsync(url, request.GetStringContent());
response.EnsureSuccessStatusCode();
}
}
}
| 32.285714 | 118 | 0.710177 | [
"MIT"
] | SkillsFundingAgency/das-employer-incentives-functions | src/SFA.DAS.EmployerIncentives.Functions.LegalEntities/Services/LegalEntities/EmailService.cs | 906 | C# |
using System.Collections.Generic;
namespace _11_PerlinNoiseMarbled
{
public class Hitable_List : HitTable
{
public List<HitTable> Objects;
public Hitable_List()
{
this.Objects = new List<HitTable>();
}
public Hitable_List(HitTable hitTable)
: this()
{
this.Objects.Add(hitTable);
}
public void Clear() { this.Objects.Clear(); }
public void Add(HitTable o) { this.Objects.Add(o); }
public bool Hit(Ray r, float t_min, float t_max, ref Hit_Record rec)
{
Hit_Record temp_rec = default;
bool hit_anything = false;
float closest_so_far = t_max;
foreach (var o in this.Objects)
{
if (o.Hit(r, t_min, closest_so_far, ref temp_rec))
{
hit_anything = true;
closest_so_far = temp_rec.T;
rec = temp_rec;
}
}
return hit_anything;
}
public bool Bounding_box(float t0, float t1, out AABB output_box)
{
output_box = null;
if (Objects.Count == 0)
{
return false;
}
AABB temp_box;
bool first_box = true;
foreach (var o in Objects)
{
if (!o.Bounding_box(t0, t1, out temp_box))
{
return false;
}
output_box = first_box ? temp_box : Helpers.Surrounding_box(output_box, temp_box);
first_box = false;
}
return true;
}
}
}
| 25.426471 | 98 | 0.470792 | [
"MIT"
] | Jorgemagic/RaytracingTheNextWeek | 11-PerlinNoiseMarbled/HitTables/Hittable_List.cs | 1,731 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Blazor.ECharts.Options
{
/// <summary>
/// 坐标轴在 grid 区域中的分隔线。
/// </summary>
public class SplitLine
{
/// <summary>
/// 是否显示分隔线。默认数值轴显示,类目轴不显示。
/// </summary>
public bool? Show { set; get; }
/// <summary>
/// 坐标轴分隔线的显示间隔,在类目轴中有效。默认同 axisLabel.interval 一样。
/// </summary>
public object Interval { set; get; }
/// <summary>
///
/// </summary>
public LineStyle LineStyle { set; get; }
}
}
| 21.233333 | 58 | 0.55102 | [
"MIT"
] | blazor-cn/Blazor.ECharts | Blazor.ECharts/Options/SplitLine.cs | 761 | C# |
using System.Web;
using System.Web.Optimization;
namespace NuGetVersion
{
public class BundleConfig
{
// For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.validate*"));
// Use the development version of Modernizr to develop with and learn from. Then, when you're
// ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
"~/Scripts/modernizr-*"));
bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
"~/Scripts/bootstrap.js",
"~/Scripts/respond.js"));
bundles.Add(new StyleBundle("~/Content/css").Include(
"~/Content/bootstrap.css",
"~/Content/site.css"));
}
}
}
| 38.78125 | 112 | 0.573731 | [
"MIT"
] | lbearl/NuGetVersionChecker | NuGetVersion/App_Start/BundleConfig.cs | 1,243 | C# |
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Forms;
using PeterPedia.Client.Services;
namespace PeterPedia.Client.Pages.Episodes;
public partial class Add : ComponentBase
{
[Inject]
private TVService TVService { get; set; } = null!;
private ElementReference Input;
private EditContext AddContext = null!;
private bool IsTaskRunning;
private string TVUrl = null!;
protected override void OnInitialized()
{
TVUrl = string.Empty;
IsTaskRunning = false;
AddContext = new EditContext(TVUrl);
}
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (Input.Id is not null)
{
await Input.FocusAsync();
}
}
private async Task AddShow()
{
IsTaskRunning = true;
var result = await TVService.Add(TVUrl);
IsTaskRunning = false;
if (result)
{
TVUrl = string.Empty;
}
}
} | 21.673913 | 70 | 0.62989 | [
"MIT"
] | peter-andersson/peterpedia | src/Client/Pages/Episodes/Add.razor.cs | 999 | C# |
using FlowScriptEngine;
namespace FlowScriptEngineBasic
{
public class ToolTipText : IToolTipText
{
private string toolTipText;
private string summary;
private string remark;
private string key;
public ToolTipText(string summary)
{
this.key = summary;
this.summary = FlowScriptEngineBasic.Properties.Resources.ResourceManager.GetString(summary);
toolTipText = this.summary;
}
public ToolTipText(string summary, string remark)
{
this.key = summary;
this.summary = FlowScriptEngineBasic.Properties.Resources.ResourceManager.GetString(summary);
this.remark = FlowScriptEngineBasic.Properties.Resources.ResourceManager.GetString(remark);
toolTipText = this.summary + "\n" + this.remark;
}
public override string Text
{
get
{
return toolTipText;
}
}
public override string Summary
{
get { return summary; }
}
public override string TextKey
{
get { return key; }
}
}
}
| 25.956522 | 105 | 0.577052 | [
"Apache-2.0"
] | KHCmaster/PPD | Win/FlowScriptEngineBasic/ToolTipText.cs | 1,196 | C# |
namespace EasyAbp.EShop.Stores
{
public static class StoresConsts
{
public const string TransactionOrderCompletedActionName = "OrderCompleted";
public const string TransactionOrderRefundedActionName = "OrderRefunded";
}
} | 28.777778 | 83 | 0.718147 | [
"MIT"
] | Hunter1994/EShop | modules/EasyAbp.EShop.Stores/src/EasyAbp.EShop.Stores.Domain.Shared/EasyAbp/EShop/Stores/StoresConsts.cs | 261 | 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/xaudio2.h in the Windows SDK for Windows 10.0.22000.0
// Original source is Copyright © Microsoft. All rights reserved.
using System.Runtime.InteropServices;
namespace TerraFX.Interop.DirectX;
/// <include file='XAUDIO2_SEND_DESCRIPTOR.xml' path='doc/member[@name="XAUDIO2_SEND_DESCRIPTOR"]/*' />
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public unsafe partial struct XAUDIO2_SEND_DESCRIPTOR
{
/// <include file='XAUDIO2_SEND_DESCRIPTOR.xml' path='doc/member[@name="XAUDIO2_SEND_DESCRIPTOR.Flags"]/*' />
[NativeTypeName("UINT32")]
public uint Flags;
/// <include file='XAUDIO2_SEND_DESCRIPTOR.xml' path='doc/member[@name="XAUDIO2_SEND_DESCRIPTOR.pOutputVoice"]/*' />
public IXAudio2Voice* pOutputVoice;
}
| 42.857143 | 145 | 0.757778 | [
"MIT"
] | reflectronic/terrafx.interop.windows | sources/Interop/Windows/DirectX/um/xaudio2/XAUDIO2_SEND_DESCRIPTOR.cs | 902 | C# |
// 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.
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by google-apis-code-generator 1.5.1
// C# generator version: 1.41.1
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
/**
* \brief
* Stackdriver Trace API Version v2
*
* \section ApiInfo API Version Information
* <table>
* <tr><th>API
* <td><a href='https://cloud.google.com/trace'>Stackdriver Trace API</a>
* <tr><th>API Version<td>v2
* <tr><th>API Rev<td>20190930 (1733)
* <tr><th>API Docs
* <td><a href='https://cloud.google.com/trace'>
* https://cloud.google.com/trace</a>
* <tr><th>Discovery Name<td>cloudtrace
* </table>
*
* \section ForMoreInfo For More Information
*
* The complete API documentation for using Stackdriver Trace API can be found at
* <a href='https://cloud.google.com/trace'>https://cloud.google.com/trace</a>.
*
* For more information about the Google APIs Client Library for .NET, see
* <a href='https://developers.google.com/api-client-library/dotnet/get_started'>
* https://developers.google.com/api-client-library/dotnet/get_started</a>
*/
namespace Google.Apis.CloudTrace.v2
{
/// <summary>The CloudTrace Service.</summary>
public class CloudTraceService : Google.Apis.Services.BaseClientService
{
/// <summary>The API version.</summary>
public const string Version = "v2";
/// <summary>The discovery version used to generate this service.</summary>
public static Google.Apis.Discovery.DiscoveryVersion DiscoveryVersionUsed =
Google.Apis.Discovery.DiscoveryVersion.Version_1_0;
/// <summary>Constructs a new service.</summary>
public CloudTraceService() :
this(new Google.Apis.Services.BaseClientService.Initializer()) {}
/// <summary>Constructs a new service.</summary>
/// <param name="initializer">The service initializer.</param>
public CloudTraceService(Google.Apis.Services.BaseClientService.Initializer initializer)
: base(initializer)
{
projects = new ProjectsResource(this);
}
/// <summary>Gets the service supported features.</summary>
public override System.Collections.Generic.IList<string> Features
{
get { return new string[0]; }
}
/// <summary>Gets the service name.</summary>
public override string Name
{
get { return "cloudtrace"; }
}
/// <summary>Gets the service base URI.</summary>
public override string BaseUri
{
#if NETSTANDARD1_3 || NETSTANDARD2_0 || NET45
get { return BaseUriOverride ?? "https://cloudtrace.googleapis.com/"; }
#else
get { return "https://cloudtrace.googleapis.com/"; }
#endif
}
/// <summary>Gets the service base path.</summary>
public override string BasePath
{
get { return ""; }
}
#if !NET40
/// <summary>Gets the batch base URI; <c>null</c> if unspecified.</summary>
public override string BatchUri
{
get { return "https://cloudtrace.googleapis.com/batch"; }
}
/// <summary>Gets the batch base path; <c>null</c> if unspecified.</summary>
public override string BatchPath
{
get { return "batch"; }
}
#endif
/// <summary>Available OAuth 2.0 scopes for use with the Stackdriver Trace API.</summary>
public class Scope
{
/// <summary>View and manage your data across Google Cloud Platform services</summary>
public static string CloudPlatform = "https://www.googleapis.com/auth/cloud-platform";
/// <summary>Write Trace data for a project or application</summary>
public static string TraceAppend = "https://www.googleapis.com/auth/trace.append";
}
/// <summary>Available OAuth 2.0 scope constants for use with the Stackdriver Trace API.</summary>
public static class ScopeConstants
{
/// <summary>View and manage your data across Google Cloud Platform services</summary>
public const string CloudPlatform = "https://www.googleapis.com/auth/cloud-platform";
/// <summary>Write Trace data for a project or application</summary>
public const string TraceAppend = "https://www.googleapis.com/auth/trace.append";
}
private readonly ProjectsResource projects;
/// <summary>Gets the Projects resource.</summary>
public virtual ProjectsResource Projects
{
get { return projects; }
}
}
///<summary>A base abstract class for CloudTrace requests.</summary>
public abstract class CloudTraceBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse>
{
///<summary>Constructs a new CloudTraceBaseServiceRequest instance.</summary>
protected CloudTraceBaseServiceRequest(Google.Apis.Services.IClientService service)
: base(service)
{
}
/// <summary>V1 error format.</summary>
[Google.Apis.Util.RequestParameterAttribute("$.xgafv", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<XgafvEnum> Xgafv { get; set; }
/// <summary>V1 error format.</summary>
public enum XgafvEnum
{
/// <summary>v1 error format</summary>
[Google.Apis.Util.StringValueAttribute("1")]
Value1,
/// <summary>v2 error format</summary>
[Google.Apis.Util.StringValueAttribute("2")]
Value2,
}
/// <summary>OAuth access token.</summary>
[Google.Apis.Util.RequestParameterAttribute("access_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string AccessToken { get; set; }
/// <summary>Data format for response.</summary>
/// [default: json]
[Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<AltEnum> Alt { get; set; }
/// <summary>Data format for response.</summary>
public enum AltEnum
{
/// <summary>Responses with Content-Type of application/json</summary>
[Google.Apis.Util.StringValueAttribute("json")]
Json,
/// <summary>Media download with context-dependent Content-Type</summary>
[Google.Apis.Util.StringValueAttribute("media")]
Media,
/// <summary>Responses with Content-Type of application/x-protobuf</summary>
[Google.Apis.Util.StringValueAttribute("proto")]
Proto,
}
/// <summary>JSONP</summary>
[Google.Apis.Util.RequestParameterAttribute("callback", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Callback { get; set; }
/// <summary>Selector specifying which fields to include in a partial response.</summary>
[Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Fields { get; set; }
/// <summary>API key. Your API key identifies your project and provides you with API access, quota, and reports.
/// Required unless you provide an OAuth 2.0 token.</summary>
[Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Key { get; set; }
/// <summary>OAuth 2.0 token for the current user.</summary>
[Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string OauthToken { get; set; }
/// <summary>Returns response with indentations and line breaks.</summary>
/// [default: true]
[Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<bool> PrettyPrint { get; set; }
/// <summary>Available to use for quota purposes for server-side applications. Can be any arbitrary string
/// assigned to a user, but should not exceed 40 characters.</summary>
[Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)]
public virtual string QuotaUser { get; set; }
/// <summary>Legacy upload protocol for media (e.g. "media", "multipart").</summary>
[Google.Apis.Util.RequestParameterAttribute("uploadType", Google.Apis.Util.RequestParameterType.Query)]
public virtual string UploadType { get; set; }
/// <summary>Upload protocol for media (e.g. "raw", "multipart").</summary>
[Google.Apis.Util.RequestParameterAttribute("upload_protocol", Google.Apis.Util.RequestParameterType.Query)]
public virtual string UploadProtocol { get; set; }
/// <summary>Initializes CloudTrace parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"$.xgafv", new Google.Apis.Discovery.Parameter
{
Name = "$.xgafv",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"access_token", new Google.Apis.Discovery.Parameter
{
Name = "access_token",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"alt", new Google.Apis.Discovery.Parameter
{
Name = "alt",
IsRequired = false,
ParameterType = "query",
DefaultValue = "json",
Pattern = null,
});
RequestParameters.Add(
"callback", new Google.Apis.Discovery.Parameter
{
Name = "callback",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"fields", new Google.Apis.Discovery.Parameter
{
Name = "fields",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"key", new Google.Apis.Discovery.Parameter
{
Name = "key",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"oauth_token", new Google.Apis.Discovery.Parameter
{
Name = "oauth_token",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"prettyPrint", new Google.Apis.Discovery.Parameter
{
Name = "prettyPrint",
IsRequired = false,
ParameterType = "query",
DefaultValue = "true",
Pattern = null,
});
RequestParameters.Add(
"quotaUser", new Google.Apis.Discovery.Parameter
{
Name = "quotaUser",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"uploadType", new Google.Apis.Discovery.Parameter
{
Name = "uploadType",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"upload_protocol", new Google.Apis.Discovery.Parameter
{
Name = "upload_protocol",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>The "projects" collection of methods.</summary>
public class ProjectsResource
{
private const string Resource = "projects";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public ProjectsResource(Google.Apis.Services.IClientService service)
{
this.service = service;
traces = new TracesResource(service);
}
private readonly TracesResource traces;
/// <summary>Gets the Traces resource.</summary>
public virtual TracesResource Traces
{
get { return traces; }
}
/// <summary>The "traces" collection of methods.</summary>
public class TracesResource
{
private const string Resource = "traces";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public TracesResource(Google.Apis.Services.IClientService service)
{
this.service = service;
spans = new SpansResource(service);
}
private readonly SpansResource spans;
/// <summary>Gets the Spans resource.</summary>
public virtual SpansResource Spans
{
get { return spans; }
}
/// <summary>The "spans" collection of methods.</summary>
public class SpansResource
{
private const string Resource = "spans";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public SpansResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>Creates a new span.</summary>
/// <param name="body">The body of the request.</param>
/// <param name="name">The resource name of the span in the following format:
///
/// projects/[PROJECT_ID]/traces/[TRACE_ID]/spans/SPAN_ID is a unique identifier for a trace within a project; it is
/// a 32-character hexadecimal encoding of a 16-byte array.
///
/// [SPAN_ID] is a unique identifier for a span within a trace; it is a 16-character hexadecimal encoding of an 8-byte
/// array.</param>
public virtual CreateSpanRequest CreateSpan(Google.Apis.CloudTrace.v2.Data.Span body, string name)
{
return new CreateSpanRequest(service, body, name);
}
/// <summary>Creates a new span.</summary>
public class CreateSpanRequest : CloudTraceBaseServiceRequest<Google.Apis.CloudTrace.v2.Data.Span>
{
/// <summary>Constructs a new CreateSpan request.</summary>
public CreateSpanRequest(Google.Apis.Services.IClientService service, Google.Apis.CloudTrace.v2.Data.Span body, string name)
: base(service)
{
Name = name;
Body = body;
InitParameters();
}
/// <summary>The resource name of the span in the following format:
///
/// projects/[PROJECT_ID]/traces/[TRACE_ID]/spans/SPAN_ID is a unique identifier for a trace within
/// a project; it is a 32-character hexadecimal encoding of a 16-byte array.
///
/// [SPAN_ID] is a unique identifier for a span within a trace; it is a 16-character hexadecimal
/// encoding of an 8-byte array.</summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.CloudTrace.v2.Data.Span Body { get; set; }
///<summary>Returns the body of the request.</summary>
protected override object GetBody() { return Body; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "createSpan"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "POST"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v2/{+name}"; }
}
/// <summary>Initializes CreateSpan parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/traces/[^/]+/spans/[^/]+$",
});
}
}
}
/// <summary>Sends new spans to new or existing traces. You cannot update existing spans.</summary>
/// <param name="body">The body of the request.</param>
/// <param name="name">Required. The name of the project where the spans belong. The format is
/// `projects/[PROJECT_ID]`.</param>
public virtual BatchWriteRequest BatchWrite(Google.Apis.CloudTrace.v2.Data.BatchWriteSpansRequest body, string name)
{
return new BatchWriteRequest(service, body, name);
}
/// <summary>Sends new spans to new or existing traces. You cannot update existing spans.</summary>
public class BatchWriteRequest : CloudTraceBaseServiceRequest<Google.Apis.CloudTrace.v2.Data.Empty>
{
/// <summary>Constructs a new BatchWrite request.</summary>
public BatchWriteRequest(Google.Apis.Services.IClientService service, Google.Apis.CloudTrace.v2.Data.BatchWriteSpansRequest body, string name)
: base(service)
{
Name = name;
Body = body;
InitParameters();
}
/// <summary>Required. The name of the project where the spans belong. The format is
/// `projects/[PROJECT_ID]`.</summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.CloudTrace.v2.Data.BatchWriteSpansRequest Body { get; set; }
///<summary>Returns the body of the request.</summary>
protected override object GetBody() { return Body; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "batchWrite"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "POST"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v2/{+name}/traces:batchWrite"; }
}
/// <summary>Initializes BatchWrite parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+$",
});
}
}
}
}
}
namespace Google.Apis.CloudTrace.v2.Data
{
/// <summary>Text annotation with a set of attributes.</summary>
public class Annotation : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>A set of attributes on the annotation. You can have up to 4 attributes per Annotation.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("attributes")]
public virtual Attributes Attributes { get; set; }
/// <summary>A user-supplied message describing the event. The maximum length for the description is 256
/// bytes.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("description")]
public virtual TruncatableString Description { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The allowed types for [VALUE] in a `[KEY]:[VALUE]` attribute.</summary>
public class AttributeValue : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>A Boolean value represented by `true` or `false`.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("boolValue")]
public virtual System.Nullable<bool> BoolValue { get; set; }
/// <summary>A 64-bit signed integer.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("intValue")]
public virtual System.Nullable<long> IntValue { get; set; }
/// <summary>A string up to 256 bytes long.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("stringValue")]
public virtual TruncatableString StringValue { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>A set of attributes, each in the format `[KEY]:[VALUE]`.</summary>
public class Attributes : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The set of attributes. Each attribute's key can be up to 128 bytes long. The value can be a string
/// up to 256 bytes, a signed 64-bit integer, or the Boolean values `true` and `false`. For example:
///
/// "/instance_id": "my-instance" "/http/user_agent": "" "/http/request_bytes": 300 "abc.com/myattribute":
/// true</summary>
[Newtonsoft.Json.JsonPropertyAttribute("attributeMap")]
public virtual System.Collections.Generic.IDictionary<string,AttributeValue> AttributeMap { get; set; }
/// <summary>The number of attributes that were discarded. Attributes can be discarded because their keys are
/// too long or because there are too many attributes. If this value is 0 then all attributes are
/// valid.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("droppedAttributesCount")]
public virtual System.Nullable<int> DroppedAttributesCount { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The request message for the `BatchWriteSpans` method.</summary>
public class BatchWriteSpansRequest : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Required. A list of new spans. The span names must not match existing spans, or the results are
/// undefined.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("spans")]
public virtual System.Collections.Generic.IList<Span> Spans { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>A generic empty message that you can re-use to avoid defining duplicated empty messages in your APIs. A
/// typical example is to use it as the request or the response type of an API method. For instance:
///
/// service Foo { rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty); }
///
/// The JSON representation for `Empty` is empty JSON object `{}`.</summary>
public class Empty : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>A pointer from the current span to another span in the same trace or in a different trace. For example,
/// this can be used in batching operations, where a single batch handler processes multiple requests from different
/// traces or when the handler receives a request from a different project.</summary>
public class Link : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>A set of attributes on the link. You have have up to 32 attributes per link.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("attributes")]
public virtual Attributes Attributes { get; set; }
/// <summary>The [SPAN_ID] for a span within a trace.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("spanId")]
public virtual string SpanId { get; set; }
/// <summary>The [TRACE_ID] for a trace within a project.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("traceId")]
public virtual string TraceId { get; set; }
/// <summary>The relationship of the current span relative to the linked span.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("type")]
public virtual string Type { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>A collection of links, which are references from this span to a span in the same or different
/// trace.</summary>
public class Links : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The number of dropped links after the maximum size was enforced. If this value is 0, then no links
/// were dropped.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("droppedLinksCount")]
public virtual System.Nullable<int> DroppedLinksCount { get; set; }
/// <summary>A collection of links.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("link")]
public virtual System.Collections.Generic.IList<Link> Link { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>An event describing a message sent/received between Spans.</summary>
public class MessageEvent : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The number of compressed bytes sent or received. If missing assumed to be the same size as
/// uncompressed.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("compressedSizeBytes")]
public virtual System.Nullable<long> CompressedSizeBytes { get; set; }
/// <summary>An identifier for the MessageEvent's message that can be used to match SENT and RECEIVED
/// MessageEvents. It is recommended to be unique within a Span.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("id")]
public virtual System.Nullable<long> Id { get; set; }
/// <summary>Type of MessageEvent. Indicates whether the message was sent or received.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("type")]
public virtual string Type { get; set; }
/// <summary>The number of uncompressed bytes sent or received.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("uncompressedSizeBytes")]
public virtual System.Nullable<long> UncompressedSizeBytes { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Binary module.</summary>
public class Module : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>A unique identifier for the module, usually a hash of its contents (up to 128 bytes).</summary>
[Newtonsoft.Json.JsonPropertyAttribute("buildId")]
public virtual TruncatableString BuildId { get; set; }
/// <summary>For example: main binary, kernel modules, and dynamic libraries such as libc.so, sharedlib.so (up
/// to 256 bytes).</summary>
[Newtonsoft.Json.JsonPropertyAttribute("module")]
public virtual TruncatableString ModuleValue { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>A span represents a single operation within a trace. Spans can be nested to form a trace tree. Often, a
/// trace contains a root span that describes the end-to-end latency, and one or more subspans for its sub-
/// operations. A trace can also contain multiple root spans, or none at all. Spans do not need to be
/// contiguousthere may be gaps or overlaps between spans in a trace.</summary>
public class Span : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>A set of attributes on the span. You can have up to 32 attributes per span.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("attributes")]
public virtual Attributes Attributes { get; set; }
/// <summary>Optional. The number of child spans that were generated while this span was active. If set, allows
/// implementation to detect missing child spans.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("childSpanCount")]
public virtual System.Nullable<int> ChildSpanCount { get; set; }
/// <summary>A description of the span's operation (up to 128 bytes). Stackdriver Trace displays the description
/// in the Google Cloud Platform Console. For example, the display name can be a qualified method name or a file
/// name and a line number where the operation is called. A best practice is to use the same display name within
/// an application and at the same call point. This makes it easier to correlate spans in different
/// traces.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("displayName")]
public virtual TruncatableString DisplayName { get; set; }
/// <summary>The end time of the span. On the client side, this is the time kept by the local machine where the
/// span execution ends. On the server side, this is the time when the server application handler stops
/// running.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("endTime")]
public virtual object EndTime { get; set; }
/// <summary>Links associated with the span. You can have up to 128 links per Span.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("links")]
public virtual Links Links { get; set; }
/// <summary>The resource name of the span in the following format:
///
/// projects/[PROJECT_ID]/traces/[TRACE_ID]/spans/SPAN_ID is a unique identifier for a trace within a project;
/// it is a 32-character hexadecimal encoding of a 16-byte array.
///
/// [SPAN_ID] is a unique identifier for a span within a trace; it is a 16-character hexadecimal encoding of an
/// 8-byte array.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("name")]
public virtual string Name { get; set; }
/// <summary>The [SPAN_ID] of this span's parent span. If this is a root span, then this field must be
/// empty.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("parentSpanId")]
public virtual string ParentSpanId { get; set; }
/// <summary>Optional. Set this parameter to indicate whether this span is in the same process as its parent. If
/// you do not set this parameter, Stackdriver Trace is unable to take advantage of this helpful
/// information.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("sameProcessAsParentSpan")]
public virtual System.Nullable<bool> SameProcessAsParentSpan { get; set; }
/// <summary>The [SPAN_ID] portion of the span's resource name.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("spanId")]
public virtual string SpanId { get; set; }
/// <summary>Distinguishes between spans generated in a particular context. For example, two spans with the same
/// name may be distinguished using `CLIENT` (caller) and `SERVER` (callee) to identify an RPC call.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("spanKind")]
public virtual string SpanKind { get; set; }
/// <summary>Stack trace captured at the start of the span.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("stackTrace")]
public virtual StackTrace StackTrace { get; set; }
/// <summary>The start time of the span. On the client side, this is the time kept by the local machine where
/// the span execution starts. On the server side, this is the time when the server's application handler starts
/// running.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("startTime")]
public virtual object StartTime { get; set; }
/// <summary>Optional. The final status for this span.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("status")]
public virtual Status Status { get; set; }
/// <summary>A set of time events. You can have up to 32 annotations and 128 message events per span.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("timeEvents")]
public virtual TimeEvents TimeEvents { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Represents a single stack frame in a stack trace.</summary>
public class StackFrame : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The column number where the function call appears, if available. This is important in JavaScript
/// because of its anonymous functions.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("columnNumber")]
public virtual System.Nullable<long> ColumnNumber { get; set; }
/// <summary>The name of the source file where the function call appears (up to 256 bytes).</summary>
[Newtonsoft.Json.JsonPropertyAttribute("fileName")]
public virtual TruncatableString FileName { get; set; }
/// <summary>The fully-qualified name that uniquely identifies the function or method that is active in this
/// frame (up to 1024 bytes).</summary>
[Newtonsoft.Json.JsonPropertyAttribute("functionName")]
public virtual TruncatableString FunctionName { get; set; }
/// <summary>The line number in `file_name` where the function call appears.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("lineNumber")]
public virtual System.Nullable<long> LineNumber { get; set; }
/// <summary>The binary module from where the code was loaded.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("loadModule")]
public virtual Module LoadModule { get; set; }
/// <summary>An un-mangled function name, if `function_name` is
/// [mangled](http://www.avabodh.com/cxxin/namemangling.html). The name can be fully-qualified (up to 1024
/// bytes).</summary>
[Newtonsoft.Json.JsonPropertyAttribute("originalFunctionName")]
public virtual TruncatableString OriginalFunctionName { get; set; }
/// <summary>The version of the deployed source code (up to 128 bytes).</summary>
[Newtonsoft.Json.JsonPropertyAttribute("sourceVersion")]
public virtual TruncatableString SourceVersion { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>A collection of stack frames, which can be truncated.</summary>
public class StackFrames : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The number of stack frames that were dropped because there were too many stack frames. If this
/// value is 0, then no stack frames were dropped.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("droppedFramesCount")]
public virtual System.Nullable<int> DroppedFramesCount { get; set; }
/// <summary>Stack frames in this call stack.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("frame")]
public virtual System.Collections.Generic.IList<StackFrame> Frame { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>A call stack appearing in a trace.</summary>
public class StackTrace : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Stack frames in this stack trace. A maximum of 128 frames are allowed.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("stackFrames")]
public virtual StackFrames StackFrames { get; set; }
/// <summary>The hash ID is used to conserve network bandwidth for duplicate stack traces within a single trace.
///
/// Often multiple spans will have identical stack traces. The first occurrence of a stack trace should contain
/// both the `stackFrame` content and a value in `stackTraceHashId`.
///
/// Subsequent spans within the same request can refer to that stack trace by only setting
/// `stackTraceHashId`.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("stackTraceHashId")]
public virtual System.Nullable<long> StackTraceHashId { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The `Status` type defines a logical error model that is suitable for different programming
/// environments, including REST APIs and RPC APIs. It is used by [gRPC](https://github.com/grpc). Each `Status`
/// message contains three pieces of data: error code, error message, and error details.
///
/// You can find out more about this error model and how to work with it in the [API Design
/// Guide](https://cloud.google.com/apis/design/errors).</summary>
public class Status : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The status code, which should be an enum value of google.rpc.Code.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("code")]
public virtual System.Nullable<int> Code { get; set; }
/// <summary>A list of messages that carry the error details. There is a common set of message types for APIs
/// to use.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("details")]
public virtual System.Collections.Generic.IList<System.Collections.Generic.IDictionary<string,object>> Details { get; set; }
/// <summary>A developer-facing error message, which should be in English. Any user-facing error message should
/// be localized and sent in the google.rpc.Status.details field, or localized by the client.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("message")]
public virtual string Message { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>A time-stamped annotation or message event in the Span.</summary>
public class TimeEvent : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Text annotation with a set of attributes.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("annotation")]
public virtual Annotation Annotation { get; set; }
/// <summary>An event describing a message sent/received between Spans.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("messageEvent")]
public virtual MessageEvent MessageEvent { get; set; }
/// <summary>The timestamp indicating the time the event occurred.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("time")]
public virtual object Time { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>A collection of `TimeEvent`s. A `TimeEvent` is a time-stamped annotation on the span, consisting of
/// either user-supplied key:value pairs, or details of a message sent/received between Spans.</summary>
public class TimeEvents : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The number of dropped annotations in all the included time events. If the value is 0, then no
/// annotations were dropped.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("droppedAnnotationsCount")]
public virtual System.Nullable<int> DroppedAnnotationsCount { get; set; }
/// <summary>The number of dropped message events in all the included time events. If the value is 0, then no
/// message events were dropped.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("droppedMessageEventsCount")]
public virtual System.Nullable<int> DroppedMessageEventsCount { get; set; }
/// <summary>A collection of `TimeEvent`s.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("timeEvent")]
public virtual System.Collections.Generic.IList<TimeEvent> TimeEvent { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Represents a string that might be shortened to a specified length.</summary>
public class TruncatableString : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The number of bytes removed from the original string. If this value is 0, then the string was not
/// shortened.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("truncatedByteCount")]
public virtual System.Nullable<int> TruncatedByteCount { get; set; }
/// <summary>The shortened string. For example, if the original string is 500 bytes long and the limit of the
/// string is 128 bytes, then `value` contains the first 128 bytes of the 500-byte string.
///
/// Truncation always happens on a UTF8 character boundary. If there are multi-byte characters in the string,
/// then the length of the shortened string might be less than the size limit.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("value")]
public virtual string Value { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
}
| 46.990683 | 158 | 0.609786 | [
"Apache-2.0"
] | ple-utt239/google-api-dotnet-client | Src/Generated/Google.Apis.CloudTrace.v2/Google.Apis.CloudTrace.v2.cs | 45,393 | C# |
namespace WebApi.UseCases.V1.Deposit
{
using System;
using System.ComponentModel.DataAnnotations;
/// <summary>
/// The response for a successfull Deposit.
/// </summary>
public sealed class DepositResponse
{
/// <summary>
/// The Deposit response constructor.
/// </summary>
public DepositResponse(
decimal amount,
string description,
DateTime transactionDate,
decimal updatedBalance)
{
this.Amount = amount;
this.Description = description;
this.TransactionDate = transactionDate;
this.UpdateBalance = updatedBalance;
}
/// <summary>
/// Gets amount Deposited.
/// </summary>
[Required]
public decimal Amount { get; }
/// <summary>
/// Gets description.
/// </summary>
[Required]
public string Description { get; }
/// <summary>
/// Gets transaction Date.
/// </summary>
[Required]
public DateTime TransactionDate { get; }
/// <summary>
/// Gets updated Balance.
/// </summary>
[Required]
public decimal UpdateBalance { get; }
}
}
| 25.431373 | 51 | 0.520432 | [
"Apache-2.0"
] | gfragoso/clean-architecture-manga | src/WebApi/UseCases/V1/Deposit/DepositResponse.cs | 1,297 | C# |
using System.Collections.Generic;
namespace UniDi
{
[NoReflectionBaking]
public class CopyNonLazyBinder : NonLazyBinder
{
List<BindInfo> _secondaryBindInfos;
public CopyNonLazyBinder(BindInfo bindInfo)
: base(bindInfo)
{
}
// This is used in cases where you have multiple bindings that depend on each other so should
// be inherited together (eg. FromIFactory)
internal void AddSecondaryCopyBindInfo(BindInfo bindInfo)
{
if (_secondaryBindInfos == null)
{
_secondaryBindInfos = new List<BindInfo>();
}
_secondaryBindInfos.Add(bindInfo);
}
public NonLazyBinder CopyIntoAllSubContainers()
{
SetInheritanceMethod(BindingInheritanceMethods.CopyIntoAll);
return this;
}
// Only copy the binding into children and not grandchildren
public NonLazyBinder CopyIntoDirectSubContainers()
{
SetInheritanceMethod(BindingInheritanceMethods.CopyDirectOnly);
return this;
}
// Do not apply the binding on the current container
public NonLazyBinder MoveIntoAllSubContainers()
{
SetInheritanceMethod(BindingInheritanceMethods.MoveIntoAll);
return this;
}
// Do not apply the binding on the current container
public NonLazyBinder MoveIntoDirectSubContainers()
{
SetInheritanceMethod(BindingInheritanceMethods.MoveDirectOnly);
return this;
}
void SetInheritanceMethod(BindingInheritanceMethods method)
{
BindInfo.BindingInheritanceMethod = method;
if (_secondaryBindInfos != null)
{
foreach (var secondaryBindInfo in _secondaryBindInfos)
{
secondaryBindInfo.BindingInheritanceMethod = method;
}
}
}
}
}
| 30.029851 | 101 | 0.60835 | [
"Apache-2.0"
] | UniDi/UniDi | Source/Binding/Binders/CopyNonLazyBinder.cs | 2,012 | C# |
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Promociones.API.Entities
{
public class Promocion
{
[BsonId]
public Guid Id { get; private set; }
public IEnumerable<string> MediosDePago { get; private set; }
public IEnumerable<string> Bancos { get; private set; }
public IEnumerable<string> CategoriasProductos { get; private set; }
public int? MaximaCantidadDeCuotas { get; private set; }
public decimal? ValorInteresCuotas { get; private set; }
public decimal? PorcentajeDeDescuento { get; private set; }
public DateTime? FechaInicio { get; private set; }
public DateTime? FechaFin { get; private set; }
public bool Activo { get; private set; }
public DateTime FechaCreacion { get; private set; }
public DateTime? FechaModificacion { get; private set; }
public Promocion(Guid id, IEnumerable<string> mediosDePago, IEnumerable<string> bancos, IEnumerable<string> categoriasProductos, int? maximaCantidadDeCuotas, decimal? valorInteresCuotas, decimal? porcentajeDeDescuento, DateTime? fechaInicio, DateTime? fechaFin, bool activo, DateTime fechaCreacion, DateTime? fechaModificacion)
{
Id = id;
MediosDePago = mediosDePago;
Bancos = bancos;
CategoriasProductos = categoriasProductos;
MaximaCantidadDeCuotas = maximaCantidadDeCuotas;
ValorInteresCuotas = valorInteresCuotas;
PorcentajeDeDescuento = porcentajeDeDescuento;
FechaInicio = fechaInicio;
FechaFin = fechaFin;
Activo = activo;
FechaCreacion = fechaCreacion;
FechaModificacion = fechaModificacion;
}
}
}
| 43.55814 | 335 | 0.67859 | [
"MIT"
] | matiasdotta/Fravega-challenge | src/Services/Promociones/Promociones.API/Entities/Promocion.cs | 1,875 | C# |
using Cybtans.Graphics.Models;
using System.Collections.Generic;
namespace Cybtans.Graphics.Shading
{
public enum Operator
{
IsActive = 1,
Equal = 2,
NotEqual = 3,
LessThan = 4,
GratherThan = 5 ,
LessThanEqual = 6,
GreaterThanEqual = 7
}
public class ParameterPredicate
{
public Operator Op { get; set; }
public string Parameter { get; set; }
public object Value { get; set; }
public static ParameterPredicate FromDto(ParameterPredicateDto dto)
{
if (dto == null)
return null;
return new ParameterPredicate
{
Op = (Operator)dto.Op,
Parameter = dto.Parameter,
Value = dto.Value
};
}
public static ParameterPredicateDto ToDto(ParameterPredicate p)
{
if (p == null) return null;
return new ParameterPredicateDto
{
Op = (int) p.Op,
Parameter = p.Parameter,
Value =p.Value
};
}
}
}
| 21.363636 | 75 | 0.492766 | [
"MIT"
] | ansel86castro/cybtans-sdk | CybtansSDK/Graphics/Cybtans.Graphics/Shading/Conditions/ParameterPredicate.cs | 1,177 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Android.App;
// 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("EFCoreSecurityXamarinDemo.Droid")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("EFCoreSecurityXamarinDemo.Droid")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
// 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")]
// Add some common permissions, these can be removed if not needed
[assembly: UsesPermission(Android.Manifest.Permission.Internet)]
[assembly: UsesPermission(Android.Manifest.Permission.WriteExternalStorage)]
| 37.4 | 84 | 0.76165 | [
"MIT"
] | DevExpress/OBSOLETE_EF-Core-Security | EFCoreSecurityDemos/EFCoreSecurityXamarinDemo/EFCoreSecurityXamarinDemo/EFCoreSecurityXamarinDemo.Droid/Properties/AssemblyInfo.cs | 1,312 | C# |
using System;
using System.Reflection;
namespace Demo.Library.Extensions
{
public static class SecurityExtension
{
public static string GetSecurityContext(this Type type)
{
return type.FullName;
}
public static string GetSecurityContext(this PropertyInfo property)
{
return string.Format("{0}/{2}", property.DeclaringType.FullName, property.Name);
}
public static string GetSecurityContext(this TypeInfo type)
{
return type.FullName;
}
public static string GetSecurityContext(this MethodInfo method)
{
if (method.IsSpecialName && (method.Name.StartsWith("get_") || method.Name.StartsWith("set_")))
{
// Is property
return $"{method.DeclaringType.FullName}/{method.Name.Substring(4)}";
}
return $"{method.DeclaringType.FullName}/{method.Name}";
}
}
} | 29.636364 | 107 | 0.597137 | [
"MIT"
] | ImenRASSAA/DDD.Enterprise.Example | Infrastructure/Library/Security/SecurityExtension.cs | 980 | 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.IO;
namespace DotNetNuke.Services.FileSystem.Internal
{
/// <summary>
/// Internal class to check file security.
/// </summary>
public interface IFileSecurityController
{
/// <summary>
/// Checks if the file has valid content.
/// </summary>
/// <param name="fileName">The File Name.</param>
/// <param name="fileContent">The File Content.</param>
bool Validate(string fileName, Stream fileContent);
}
}
| 31.727273 | 72 | 0.654728 | [
"MIT"
] | MaiklT/Dnn.Platform | DNN Platform/Library/Services/FileSystem/Internal/IFileSecurityController.cs | 700 | C# |
// Copyright (c) Six Labors.
// Licensed under the Apache License, Version 2.0.
namespace SixLabors.Fonts.Tables.General
{
[TableName(TableName)]
internal sealed class HorizontalMetricsTable : Table
{
private const string TableName = "hmtx";
private readonly short[] leftSideBearings;
private readonly ushort[] advancedWidths;
public HorizontalMetricsTable(ushort[] advancedWidths, short[] leftSideBearings)
{
this.advancedWidths = advancedWidths;
this.leftSideBearings = leftSideBearings;
}
public ushort GetAdvancedWidth(int glyphIndex)
{
if (glyphIndex >= this.advancedWidths.Length)
{
return this.advancedWidths[0];
}
return this.advancedWidths[glyphIndex];
}
internal short GetLeftSideBearing(int glyphIndex)
{
if (glyphIndex >= this.leftSideBearings.Length)
{
return this.leftSideBearings[0];
}
return this.leftSideBearings[glyphIndex];
}
public static HorizontalMetricsTable Load(FontReader reader)
{
// you should load all dependent tables prior to manipulating the reader
HorizontalHeadTable headTable = reader.GetTable<HorizontalHeadTable>();
MaximumProfileTable profileTable = reader.GetTable<MaximumProfileTable>();
// move to start of table
using (BigEndianBinaryReader binaryReader = reader.GetReaderAtTablePosition(TableName))
{
return Load(binaryReader, headTable.NumberOfHMetrics, profileTable.GlyphCount);
}
}
public static HorizontalMetricsTable Load(BigEndianBinaryReader reader, int metricCount, int glyphCount)
{
// Type | Name | Description
// longHorMetric | hMetrics[numberOfHMetrics] | Paired advance width and left side bearing values for each glyph. Records are indexed by glyph ID.
// int16 | leftSideBearing[numGlyphs - numberOfHMetrics] | Left side bearings for glyph IDs greater than or equal to numberOfHMetrics.
int bearingCount = glyphCount - metricCount;
ushort[] advancedWidth = new ushort[metricCount];
short[] leftSideBearings = new short[glyphCount];
for (int i = 0; i < metricCount; i++)
{
// longHorMetric Record:
// Type | Name | Description
// uint16 | advanceWidth | Glyph advance width, in font design units.
// int16 | lsb | Glyph left side bearing, in font design units.
advancedWidth[i] = reader.ReadUInt16();
leftSideBearings[i] = reader.ReadInt16();
}
for (int i = 0; i < bearingCount; i++)
{
leftSideBearings[metricCount + i] = reader.ReadInt16();
}
return new HorizontalMetricsTable(advancedWidth, leftSideBearings);
}
}
}
| 39.6 | 178 | 0.590909 | [
"Apache-2.0"
] | BigMach/Fonts | src/SixLabors.Fonts/Tables/General/HorizontalMetricsTable.cs | 3,168 | C# |
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
namespace Afx.Tcp.Host
{
class CmdMethodInfo
{
public int Cmd { get; set; }
public Type Type { get; set; }
public MethodInfo Method { get; set; }
public Type ParameterType { get; set; }
public List<Type> AuthTypeList { get; set; }
public bool NoAuth { get; set; }
}
}
| 18.608696 | 52 | 0.61215 | [
"Apache-2.0"
] | jerrylai/Afx.Tcp.Host | src/Afx.Tcp.Host/CmdMethodInfo.cs | 430 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.ComponentModel.Design.Serialization;
using System.Globalization;
namespace System.ComponentModel
{
/// <summary>
/// Provides a type converter that can be used to populate a list box with available types.
/// </summary>
public abstract class TypeListConverter : TypeConverter
{
private readonly Type[] _types;
private StandardValuesCollection _values;
/// <summary>
/// Initializes a new instance of the <see cref='System.ComponentModel.TypeListConverter'/> class using
/// the type array as the available types.
/// </summary>
protected TypeListConverter(Type[] types)
{
_types = types;
}
/// <summary>
/// Gets a value indicating whether this converter
/// can convert an object in the given source type to an enumeration object using
/// the specified context.
/// </summary>
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
return sourceType == typeof(string) || base.CanConvertFrom(context, sourceType);
}
/// <summary>
/// Gets a value indicating whether this converter can convert an object
/// to the given destination type using the context.
/// </summary>
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
return destinationType == typeof(InstanceDescriptor) || base.CanConvertTo(context, destinationType);
}
/// <summary>
/// Converts the specified value object to an enumeration object.
/// </summary>
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
if (value is string)
{
foreach (Type t in _types)
{
if (value.Equals(t.FullName))
{
return t;
}
}
}
return base.ConvertFrom(context, culture, value);
}
/// <summary>
/// Converts the given value object to the specified destination type.
/// </summary>
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
{
if (destinationType == null)
{
throw new ArgumentNullException(nameof(destinationType));
}
if (destinationType == typeof(string))
{
if (value == null)
{
return SR.none;
}
else
{
return ((Type)value).FullName;
}
}
return base.ConvertTo(context, culture, value, destinationType);
}
/// <summary>
/// Gets a collection of standard values for the data type this validator is designed for.
/// </summary>
public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
{
if (_values == null)
{
object[] objTypes;
if (_types != null)
{
objTypes = new object[_types.Length];
Array.Copy(_types, objTypes, _types.Length);
}
else
{
objTypes = null;
}
_values = new StandardValuesCollection(objTypes);
}
return _values;
}
/// <summary>
/// Gets a value indicating whether the list of standard values returned from
/// <see cref='System.ComponentModel.TypeListConverter.GetStandardValues'/> is an exclusive list.
/// </summary>
public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) => true;
/// <summary>
/// Gets a value indicating whether this object supports a standard set of values that can be
/// picked from a list using the specified context.
/// </summary>
public override bool GetStandardValuesSupported(ITypeDescriptorContext context) => true;
}
}
| 35.436508 | 129 | 0.567973 | [
"MIT"
] | 2m0nd/runtime | src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/TypeListConverter.cs | 4,465 | C# |
using CPFrameWork.Utility.DbOper;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using static CPFrameWork.Utility.DbOper.DbHelper;
namespace CPFrameWork.Global
{
public class CPAppContext
{
#region 依赖注入全局,获取运行时相关信息
public static IHttpContextAccessor HttpContextAccessor{ get; set; }
public static IHostingEnvironment HostingEnvironment { get; set; }
public static IConfigurationRoot Configuration { get; set; }
public static IServiceCollection ServiceCollection { get; set; }
public static T GetService<T>()
{
return HttpContextAccessor.HttpContext.RequestServices.GetService<T>();
}
public static IEnumerable<T> GetServices<T>()
{
return HttpContextAccessor.HttpContext.RequestServices.GetServices<T>();
}
public static object GetService(Type type)
{
return HttpContextAccessor.HttpContext.RequestServices.GetService(type);
}
public static IEnumerable<object> GetServices(Type type)
{
return HttpContextAccessor.HttpContext.RequestServices.GetServices(type);
}
#endregion
public static int RootParentId = -1;
public static int InnerSysId = 1;
public static string CPWebRootPath()
{
if (HostingEnvironment.IsDevelopment())
{
return "";
}
else if (HostingEnvironment.IsProduction())
{
return "/CPSite";
}
else if (HostingEnvironment.IsStaging())
{
return "/CPSite";
}
else
return "";
}
#region 获取ip与MAC地址
/// <summary>
/// 获取客户端IP
/// </summary>
public static string GetClientIP()
{
try
{
object factory = CPAppContext.GetService(typeof(Microsoft.AspNetCore.Http.IHttpContextAccessor));
Microsoft.AspNetCore.Http.HttpContext context = ((Microsoft.AspNetCore.Http.HttpContextAccessor)factory).HttpContext;
var ip = context.Features.Get<IHttpConnectionFeature>()?.RemoteIpAddress?.ToString();
return ip;
}
catch (Exception)
{
return "未获取用户IP";
}
}
#endregion
public static DbTypeEnum CurDbType()
{
return DbTypeEnum.SqlServer;
}
public static HttpContext GetHttpContext()
{
object factory = CPAppContext.GetService(typeof(Microsoft.AspNetCore.Http.IHttpContextAccessor));
Microsoft.AspNetCore.Http.HttpContext context = ((Microsoft.AspNetCore.Http.HttpContextAccessor)factory).HttpContext;
return context;
}
public static bool ConvertIntToBool(object n)
{
if (Convert.ToInt32(n) == 1)
return true;
else
return false;
}
public static int ConvertBoolToInt(bool b)
{
if (b)
return 1;
else
return 0;
}
#region 根据数据库实例,和表名,自动获取表的所有字段名
public static List<CPDbField> GetTableField(string dbInstance,string tableName)
{
List<CPDbField> col = new List<Global.CPDbField>();
if (CurDbType() == DbTypeEnum.SqlServer)
{
#region sql
string strSql = @"SELECT 表名 = d.name ,
字段序号 = a.colorder ,
字段名 = a.name ,
标识 = CASE WHEN COLUMNPROPERTY(a.id, a.name, 'IsIdentity') = 1
THEN '1'
ELSE '0'
END ,
主键 = CASE WHEN EXISTS ( SELECT 1
FROM sysobjects
WHERE xtype = 'PK '
AND name IN (
SELECT name
FROM sysindexes
WHERE indid IN (
SELECT indid
FROM sysindexkeys
WHERE id = a.id
AND colid = a.colid ) ) )
THEN '1'
ELSE '0'
END ,
类型 = b.name ,
占用字节数 = a.length ,
长度 = COLUMNPROPERTY(a.id, a.name, 'PRECISION ') ,
小数位数 = ISNULL(COLUMNPROPERTY(a.id, a.name, 'Scale '), 0) ,
允许空 = CASE WHEN a.isnullable = 1 THEN '1'
ELSE '0'
END ,
默认值 = ISNULL(e.text, ' ')
FROM syscolumns a
LEFT JOIN systypes b ON a.xtype = b.xusertype
INNER JOIN sysobjects d ON a.id = d.id
AND d.xtype = 'U '
AND d.name <> 'dtproperties '
LEFT JOIN syscomments e ON a.cdefault = e.id
WHERE d.name = '" + tableName + @"'
ORDER BY a.id ,
a.colorder";
DbHelper _db = new DbHelper(dbInstance, DbTypeEnum.SqlServer);
DataTable dt = _db.ExecuteDataSet(strSql).Tables[0];
foreach (DataRow dr in dt.Rows)
{
CPDbField f = new CPDbField();
f.TableName = Convert.IsDBNull(dr["表名"]) ? "" : dr["表名"].ToString();
f.FieldName = Convert.IsDBNull(dr["字段名"]) ? "" : dr["字段名"].ToString();
f.IsIdentity = Convert.IsDBNull(dr["标识"]) ? false : ConvertIntToBool(int.Parse(dr["标识"].ToString()));
f.IsPK = Convert.IsDBNull(dr["主键"]) ? false : ConvertIntToBool(int.Parse(dr["主键"].ToString()));
f.IsAllowNull = Convert.IsDBNull(dr["允许空"]) ? true : ConvertIntToBool(int.Parse(dr["允许空"].ToString()));
string sValueType = Convert.IsDBNull(dr["类型"]) ? "" : dr["类型"].ToString();
if (sValueType.Equals("int", StringComparison.CurrentCultureIgnoreCase)
|| sValueType.Equals("bigint", StringComparison.CurrentCultureIgnoreCase)
)
{
f.ValueType = CPEnum.FieldValueTypeEnum.Int;
}
else if (sValueType.Equals("nvarchar", StringComparison.CurrentCultureIgnoreCase)
|| sValueType.Equals("char", StringComparison.CurrentCultureIgnoreCase)
|| sValueType.Equals("nchar", StringComparison.CurrentCultureIgnoreCase)
|| sValueType.Equals("ntext", StringComparison.CurrentCultureIgnoreCase)
|| sValueType.Equals("varchar", StringComparison.CurrentCultureIgnoreCase)
)
{
f.ValueType = CPEnum.FieldValueTypeEnum.String;
}
else if (sValueType.Equals("decimal", StringComparison.CurrentCultureIgnoreCase)
|| sValueType.Equals("float", StringComparison.CurrentCultureIgnoreCase)
|| sValueType.Equals("numeric", StringComparison.CurrentCultureIgnoreCase)
)
{
f.ValueType = CPEnum.FieldValueTypeEnum.Double;
}
else if (sValueType.Equals("date", StringComparison.CurrentCultureIgnoreCase)
|| sValueType.Equals("datetime", StringComparison.CurrentCultureIgnoreCase)
|| sValueType.Equals("datetime2", StringComparison.CurrentCultureIgnoreCase)
)
{
f.ValueType = CPEnum.FieldValueTypeEnum.DateTime;
}
else if (sValueType.Equals("uniqueidentifier", StringComparison.CurrentCultureIgnoreCase)
)
{
f.ValueType = CPEnum.FieldValueTypeEnum.GUID;
}
else
{
f.ValueType = CPEnum.FieldValueTypeEnum.String;
}
f.ValueLength = Convert.IsDBNull(dr["长度"]) ? 0 : int.Parse(dr["长度"].ToString());
col.Add(f);
}
#endregion
}
return col;
}
#endregion
#region 根据数据库实例,获取所有的表名和主键名
public static List<CPDbTable> GetTable(string dbInstance)
{
List<CPDbTable> col = new List<Global.CPDbTable>();
if (CurDbType() == DbTypeEnum.SqlServer)
{
#region sql
string strSql = @"SELECT * FROM (
SELECT 表名 = d.name ,
字段序号 = a.colorder ,
字段名 = a.name ,
标识 = CASE WHEN COLUMNPROPERTY(a.id, a.name, 'IsIdentity') = 1
THEN '1'
ELSE '0'
END ,
主键 = CASE WHEN EXISTS ( SELECT 1
FROM sysobjects
WHERE xtype = 'PK '
AND name IN (
SELECT name
FROM sysindexes
WHERE indid IN (
SELECT indid
FROM sysindexkeys
WHERE id = a.id
AND colid = a.colid ) ) )
THEN '1'
ELSE '0'
END ,
类型 = b.name ,
占用字节数 = a.length ,
长度 = COLUMNPROPERTY(a.id, a.name, 'PRECISION ') ,
小数位数 = ISNULL(COLUMNPROPERTY(a.id, a.name, 'Scale '), 0) ,
允许空 = CASE WHEN a.isnullable = 1 THEN '1'
ELSE '0'
END ,
默认值 = ISNULL(e.text, ' ')
FROM syscolumns a
LEFT JOIN systypes b ON a.xtype = b.xusertype
INNER JOIN sysobjects d ON a.id = d.id
AND d.xtype = 'U '
AND d.name <> 'dtproperties '
LEFT JOIN syscomments e ON a.cdefault = e.id
) AS ccc WHERE ccc.主键=1 ORDER BY ccc.表名
";
DbHelper _db = new DbHelper(dbInstance, DbTypeEnum.SqlServer);
DataTable dt = _db.ExecuteDataSet(strSql).Tables[0];
foreach (DataRow dr in dt.Rows)
{
string TableName = Convert.IsDBNull(dr["表名"]) ? "" : dr["表名"].ToString();
List<CPDbTable> tmpCol = col.Where(t => t.TableName.Equals(TableName)).ToList();
if (tmpCol.Count > 0)
{
tmpCol[0].PKNames += "," + (Convert.IsDBNull(dr["字段名"]) ? "" : dr["字段名"].ToString());
}
else
{
CPDbTable f = new CPDbTable();
f.TableName = TableName;
f.PKNames = Convert.IsDBNull(dr["字段名"]) ? "" : dr["字段名"].ToString();
col.Add(f);
}
}
#endregion
}
return col;
}
#endregion
#region 根据数据库实例,获取所有的视图
public static List<CPDbTable> GetView(string dbInstance)
{
List<CPDbTable> col = new List<Global.CPDbTable>();
if (CurDbType() == DbTypeEnum.SqlServer)
{
#region sql
string strSql = @"select name from sysobjects where xtype='V'
";
DbHelper _db = new DbHelper(dbInstance, DbTypeEnum.SqlServer);
DataTable dt = _db.ExecuteDataSet(strSql).Tables[0];
foreach (DataRow dr in dt.Rows)
{
string TableName = Convert.IsDBNull(dr["name"]) ? "" : dr["name"].ToString();
CPDbTable f = new CPDbTable();
f.TableName = TableName;
f.PKNames = "";
col.Add(f);
}
#endregion
}
return col;
}
#endregion
#region 根据数据库实例,获取数据名
public static string GetDbName(string dbInstance)
{
DbHelper _db = new DbHelper(dbInstance, DbTypeEnum.SqlServer);
string db = _db.GetConnection().Database;
_db = null;
return db;
}
#endregion
/// <summary>
/// 存储文件的真实目录
/// </summary>
/// <returns></returns>
public static string CPFilesPath()
{
string StorePath = Configuration.GetSection("File")["StorePath"];
if (string.IsNullOrEmpty(StorePath))
{
return HostingEnvironment.WebRootPath + System.IO.Path.DirectorySeparatorChar +
"CPFiles" + System.IO.Path.DirectorySeparatorChar;
}
else
{
if (StorePath.EndsWith(System.IO.Path.DirectorySeparatorChar.ToString()) == false)
StorePath += System.IO.Path.DirectorySeparatorChar;
return StorePath;
}
}
public static string GetPara(string key)
{
DbHelper _db = new DbHelper("CPCommonIns",CurDbType());
string strSql = "SELECT ParaValue FROM CP_Para WHERE ParaKey='" + key+ "'";
object obj = _db.ExecuteScalar(strSql);
if (Convert.IsDBNull(obj) || obj == null)
return "";
else
return obj.ToString();
}
public static string FormatSqlPara(string sValue)
{
if (string.IsNullOrEmpty(sValue))
return sValue;
sValue = System.Web.HttpUtility.UrlDecode(sValue);
//增加处理SQL注入的代码
return sValue;
}
public static bool CheckHasQueryStringKeyAndValue(string key)
{
if (string.IsNullOrEmpty(key))
return false;
if (CPAppContext.GetHttpContext().Request.Query.Keys.Contains(key) == false || CPAppContext.GetHttpContext().Request.Query[key] == "")
return false;
else
return true;
}
public static bool CheckHasQueryStringKey(string key)
{
if (string.IsNullOrEmpty(key))
return false;
if (CPAppContext.GetHttpContext().Request.Query.Keys.Contains(key)==false)
return false;
else
return true;
}
public static T QueryString<T>(string key)
{
if (CheckHasQueryStringKey(key) == false)
return default(T);
string s = GetHttpContext().Request.Query[key].ToString();
s = System.Web.HttpUtility.UrlDecode(s);
return ConvertTo<T>(s);
}
/// <summary>
/// 将数据转换为指定类型
/// </summary>
/// <typeparam name="T">转换的目标类型</typeparam>
/// <param name="data">转换的数据</param>
private static T ConvertTo<T>(object data)
{
//如果数据为空,则返回
if (data == null)
{
return default(T);
}
try
{
//如果数据是T类型,则直接转换
if (data is T)
{
return (T)data;
}
//如果目标类型是枚举
if (typeof(T).BaseType == typeof(Enum))
{
return GetInstance<T>(data.ToString());
}
//如果数据实现了IConvertible接口,则转换类型
if (data is IConvertible)
{
return (T)Convert.ChangeType(data, typeof(T));
}
else
{
return default(T);
}
}
catch
{
return default(T);
}
}
private static T GetInstance<T>(string member)
{
return (T)Enum.Parse(typeof(T), member, true);
}
public static string GetInsertSql(string tableName,DataColumnCollection columnCol,DataRow dr)
{
string sql = "insert into " + tableName;
string field = "";
string fieldValue = "";
foreach (DataColumn dc in columnCol)
{
if (dc.AutoIncrement)
{
continue;
}
if (string.IsNullOrEmpty(field))
field = dc.ColumnName;
else
field += " , " + dc.ColumnName;
if (string.IsNullOrEmpty(fieldValue))
fieldValue = "@" + dc.ColumnName;
else
fieldValue += " , @" + dc.ColumnName;
}
sql += " ( " + field + ") VALUES ( " + fieldValue + ")";
//SqlCommand cmd = new SqlCommand(sql, conn);
//foreach (DataColumn dc in columnCol)
//{
// if (dc.AutoIncrement)
// {
// continue;
// }
// cmd.Parameters.AddWithValue("@" + dc.ColumnName, dr[dc.ColumnName]);
//}
// return cmd;
return sql;
}
}
}
| 41.223382 | 147 | 0.43386 | [
"Apache-2.0"
] | VAllens/qMISPlat | Library/Common/CPFrameWork.Global/CPAppContext.cs | 20,356 | C# |
namespace Hash_Table
{
using System;
using System.Collections;
using System.Collections.Generic;
public class MyDictionary<TKey, TValue> : IEnumerable<KeyValue<TKey, TValue>>
{
private HashTable<TKey, TValue> table;
public MyDictionary()
{
this.table = new HashTable<TKey, TValue>();
}
public void Add (TKey key, TValue value)
{
this.table.Add(key, value);
}
public bool ContainsKey(TKey key)
{
return this.table.ContainsKey(key);
}
public TValue this[TKey key]
{
get
{
return this.table.Get(key);
}
set
{
this.table.AddOrReplace(key, value);
}
}
public IEnumerator<KeyValue<TKey, TValue>> GetEnumerator()
{
return this.table.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
}
}
| 22.270833 | 81 | 0.508887 | [
"MIT"
] | NikolaVodenicharov/DataStructures | HasTables/Data-Structures-Hash-Tables-Sets-and-Dictionaries-Lab-CSharp-Skeleton/Dictionaries/MyDictionary.cs | 1,071 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Minesweeper.Properties {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Minesweeper.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap cool {
get {
object obj = ResourceManager.GetObject("cool", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap flag {
get {
object obj = ResourceManager.GetObject("flag", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap happy {
get {
object obj = ResourceManager.GetObject("happy", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap mine {
get {
object obj = ResourceManager.GetObject("mine", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap sad {
get {
object obj = ResourceManager.GetObject("sad", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
}
}
| 40.22807 | 177 | 0.573266 | [
"MIT"
] | UmarNaeem7/Minesweeper | Minesweeper/Properties/Resources.Designer.cs | 4,588 | 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.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
namespace Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210
{
using static Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Extensions;
/// <summary>Mars agent details.</summary>
public partial class MarsAgentDetails
{
/// <summary>
/// <c>AfterFromJson</c> will be called after the json deserialization has finished, allowing customization of the object
/// before it is returned. Implement this method in a partial class to enable this behavior
/// </summary>
/// <param name="json">The JsonNode that should be deserialized into this object.</param>
partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject json);
/// <summary>
/// <c>AfterToJson</c> will be called after the json erialization has finished, allowing customization of the <see cref="Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject"
/// /> before it is returned. Implement this method in a partial class to enable this behavior
/// </summary>
/// <param name="container">The JSON container that the serialization result will be placed in.</param>
partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject container);
/// <summary>
/// <c>BeforeFromJson</c> will be called before the json deserialization has commenced, allowing complete customization of
/// the object before it is deserialized.
/// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter.
/// Implement this method in a partial class to enable this behavior.
/// </summary>
/// <param name="json">The JsonNode that should be deserialized into this object.</param>
/// <param name="returnNow">Determines if the rest of the deserialization should be processed, or if the method should return
/// instantly.</param>
partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject json, ref bool returnNow);
/// <summary>
/// <c>BeforeToJson</c> will be called before the json serialization has commenced, allowing complete customization of the
/// object before it is serialized.
/// If you wish to disable the default serialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter.
/// Implement this method in a partial class to enable this behavior.
/// </summary>
/// <param name="container">The JSON container that the serialization result will be placed in.</param>
/// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return
/// instantly.</param>
partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject container, ref bool returnNow);
/// <summary>
/// Deserializes a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonNode"/> into an instance of Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IMarsAgentDetails.
/// </summary>
/// <param name="node">a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonNode" /> to deserialize from.</param>
/// <returns>
/// an instance of Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IMarsAgentDetails.
/// </returns>
public static Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IMarsAgentDetails FromJson(Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonNode node)
{
return node is Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject json ? new MarsAgentDetails(json) : null;
}
/// <summary>
/// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject into a new instance of <see cref="MarsAgentDetails" />.
/// </summary>
/// <param name="json">A Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject instance to deserialize from.</param>
internal MarsAgentDetails(Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject json)
{
bool returnNow = false;
BeforeFromJson(json, ref returnNow);
if (returnNow)
{
return;
}
{_id = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonString>("id"), out var __jsonId) ? (string)__jsonId : (string)Id;}
{_name = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonString>("name"), out var __jsonName) ? (string)__jsonName : (string)Name;}
{_biosId = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonString>("biosId"), out var __jsonBiosId) ? (string)__jsonBiosId : (string)BiosId;}
{_fabricObjectId = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonString>("fabricObjectId"), out var __jsonFabricObjectId) ? (string)__jsonFabricObjectId : (string)FabricObjectId;}
{_fqdn = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonString>("fqdn"), out var __jsonFqdn) ? (string)__jsonFqdn : (string)Fqdn;}
{_version = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonString>("version"), out var __jsonVersion) ? (string)__jsonVersion : (string)Version;}
{_lastHeartbeatUtc = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonString>("lastHeartbeatUtc"), out var __jsonLastHeartbeatUtc) ? global::System.DateTime.TryParse((string)__jsonLastHeartbeatUtc, global::System.Globalization.CultureInfo.InvariantCulture, global::System.Globalization.DateTimeStyles.AdjustToUniversal, out var __jsonLastHeartbeatUtcValue) ? __jsonLastHeartbeatUtcValue : LastHeartbeatUtc : LastHeartbeatUtc;}
{_health = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonString>("health"), out var __jsonHealth) ? (string)__jsonHealth : (string)Health;}
{_healthError = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonArray>("healthErrors"), out var __jsonHealthErrors) ? If( __jsonHealthErrors as Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonArray, out var __v) ? new global::System.Func<Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IHealthError[]>(()=> global::System.Linq.Enumerable.ToArray(global::System.Linq.Enumerable.Select(__v, (__u)=>(Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IHealthError) (Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.HealthError.FromJson(__u) )) ))() : null : HealthError;}
AfterFromJson(json);
}
/// <summary>
/// Serializes this instance of <see cref="MarsAgentDetails" /> into a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonNode" />.
/// </summary>
/// <param name="container">The <see cref="Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject"/> container to serialize this object into. If the caller
/// passes in <c>null</c>, a new instance will be created and returned to the caller.</param>
/// <param name="serializationMode">Allows the caller to choose the depth of the serialization. See <see cref="Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.SerializationMode"/>.</param>
/// <returns>
/// a serialized instance of <see cref="MarsAgentDetails" /> as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonNode" />.
/// </returns>
public Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.SerializationMode serializationMode)
{
container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject();
bool returnNow = false;
BeforeToJson(ref container, ref returnNow);
if (returnNow)
{
return container;
}
if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.SerializationMode.IncludeReadOnly))
{
AddIf( null != (((object)this._id)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonString(this._id.ToString()) : null, "id" ,container.Add );
}
if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.SerializationMode.IncludeReadOnly))
{
AddIf( null != (((object)this._name)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonString(this._name.ToString()) : null, "name" ,container.Add );
}
if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.SerializationMode.IncludeReadOnly))
{
AddIf( null != (((object)this._biosId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonString(this._biosId.ToString()) : null, "biosId" ,container.Add );
}
if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.SerializationMode.IncludeReadOnly))
{
AddIf( null != (((object)this._fabricObjectId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonString(this._fabricObjectId.ToString()) : null, "fabricObjectId" ,container.Add );
}
if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.SerializationMode.IncludeReadOnly))
{
AddIf( null != (((object)this._fqdn)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonString(this._fqdn.ToString()) : null, "fqdn" ,container.Add );
}
if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.SerializationMode.IncludeReadOnly))
{
AddIf( null != (((object)this._version)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonString(this._version.ToString()) : null, "version" ,container.Add );
}
if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.SerializationMode.IncludeReadOnly))
{
AddIf( null != this._lastHeartbeatUtc ? (Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonString(this._lastHeartbeatUtc?.ToString(@"yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK",global::System.Globalization.CultureInfo.InvariantCulture)) : null, "lastHeartbeatUtc" ,container.Add );
}
if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.SerializationMode.IncludeReadOnly))
{
AddIf( null != (((object)this._health)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonString(this._health.ToString()) : null, "health" ,container.Add );
}
if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.SerializationMode.IncludeReadOnly))
{
if (null != this._healthError)
{
var __w = new Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.XNodeArray();
foreach( var __x in this._healthError )
{
AddIf(__x?.ToJson(null, serializationMode) ,__w.Add);
}
container.Add("healthErrors",__w);
}
}
AfterToJson(ref container);
return container;
}
}
} | 83.133758 | 663 | 0.690929 | [
"MIT"
] | Agazoth/azure-powershell | src/Migrate/generated/api/Models/Api20210210/MarsAgentDetails.json.cs | 12,896 | C# |
using CivLeagueJP.API.Models;
using CivLeagueJP.API.Models.Civ6;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace CivLeagueJP.API.Models
{
public class UserPlayerConnection
{
[Key]
public long Id { get; set; }
public virtual Player Civ6Player { get; set; }
public long ApplicationUserId { get; set; }
[ForeignKey("ApplicationUserId")]
public virtual ApplicationUser ApplicationUser { get; set; }
}
} | 28.833333 | 68 | 0.703276 | [
"MIT"
] | seed-of-apricot/CivLeagueJP.API | Models/UserPlayerConnection.cs | 519 | 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 Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.EntityFrameworkCore.TestModels.UpdatesModel;
using Microsoft.EntityFrameworkCore.TestUtilities;
namespace Microsoft.EntityFrameworkCore
{
public class UpdatesSqlServerFixture : UpdatesRelationalFixture
{
protected override ITestStoreFactory TestStoreFactory => SqlServerTestStoreFactory.Instance;
public override DbContextOptionsBuilder AddOptions(DbContextOptionsBuilder builder)
=> base.AddOptions(builder).ConfigureWarnings(
w =>
{
w.Log(SqlServerEventId.DecimalTypeKeyWarning);
});
protected override void OnModelCreating(ModelBuilder modelBuilder, DbContext context)
{
base.OnModelCreating(modelBuilder, context);
modelBuilder.Entity<ProductBase>()
.Property(p => p.Id).HasDefaultValueSql("NEWID()");
modelBuilder.Entity<Product>()
.Property(p => p.Price).HasColumnType("decimal(18,2)");
modelBuilder.Entity<ProductTableWithView>()
.Property(p => p.Price).HasColumnType("decimal(18,2)");
modelBuilder.Entity<ProductViewTable>()
.Property(p => p.Price).HasColumnType("decimal(18,2)");
modelBuilder.Entity<ProductTableView>()
.Property(p => p.Price).HasColumnType("decimal(18,2)");
modelBuilder
.Entity<
LoginEntityTypeWithAnExtremelyLongAndOverlyConvolutedNameThatIsUsedToVerifyThatTheStoreIdentifierGenerationLengthLimitIsWorkingCorrectly
>()
.Property(l => l.ProfileId3).HasColumnType("decimal(18,2)");
modelBuilder.Entity<Profile>()
.Property(l => l.Id3).HasColumnType("decimal(18,2)");
}
}
}
| 42.333333 | 156 | 0.653051 | [
"Apache-2.0"
] | StevenRasmussen/efcore | test/EFCore.SqlServer.FunctionalTests/UpdatesSqlServerFixture.cs | 2,032 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.