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 |
|---|---|---|---|---|---|---|---|---|
// 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.Diagnostics;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using Microsoft.Win32.SafeHandles;
using Internal.Cryptography.Pal.Native;
namespace Internal.Cryptography.Pal
{
internal sealed partial class CertificatePal : IDisposable, ICertificatePal
{
public bool HasPrivateKey
{
get
{
return _certContext.ContainsPrivateKey;
}
}
public RSA GetRSAPrivateKey()
{
return GetPrivateKey<RSA>(
delegate (CspParameters csp)
{
#if NETNATIVE
// In .NET Native (UWP) we don't have access to CAPI, so it's CNG-or-nothing.
// But we don't expect to get here, so it shouldn't be a problem.
Debug.Fail("A CAPI provider type code was specified");
return null;
#else
return new RSACryptoServiceProvider(csp);
#endif
},
delegate (CngKey cngKey)
{
return new RSACng(cngKey);
}
);
}
public ECDsa GetECDsaPrivateKey()
{
return GetPrivateKey<ECDsa>(
delegate (CspParameters csp)
{
throw new NotSupportedException(SR.NotSupported_ECDsa_Csp);
},
delegate (CngKey cngKey)
{
return new ECDsaCng(cngKey);
}
);
}
private T GetPrivateKey<T>(Func<CspParameters, T> createCsp, Func<CngKey, T> createCng) where T : AsymmetricAlgorithm
{
CngKeyHandleOpenOptions cngHandleOptions;
SafeNCryptKeyHandle ncryptKey = TryAcquireCngPrivateKey(CertContext, out cngHandleOptions);
if (ncryptKey != null)
{
CngKey cngKey = CngKey.Open(ncryptKey, cngHandleOptions);
return createCng(cngKey);
}
CspParameters cspParameters = GetPrivateKey();
if (cspParameters == null)
return null;
if (cspParameters.ProviderType == 0)
{
// ProviderType being 0 signifies that this is actually a CNG key, not a CAPI key. Crypt32.dll stuffs the CNG Key Storage Provider
// name into CRYPT_KEY_PROV_INFO->ProviderName, and the CNG key name into CRYPT_KEY_PROV_INFO->KeyContainerName.
string keyStorageProvider = cspParameters.ProviderName;
string keyName = cspParameters.KeyContainerName;
CngKey cngKey = CngKey.Open(keyName, new CngProvider(keyStorageProvider));
return createCng(cngKey);
}
else
{
// ProviderType being non-zero signifies that this is a CAPI key.
#if NETNATIVE
// In .NET Native (UWP) we don't have access to CAPI, so it's CNG-or-nothing.
// But we don't expect to get here, so it shouldn't be a problem.
Debug.Fail("A CAPI provider type code was specified");
return null;
#else
// We never want to stomp over certificate private keys.
cspParameters.Flags |= CspProviderFlags.UseExistingKey;
return createCsp(cspParameters);
#endif
}
}
private static SafeNCryptKeyHandle TryAcquireCngPrivateKey(
SafeCertContextHandle certificateContext,
out CngKeyHandleOpenOptions handleOptions)
{
Debug.Assert(certificateContext != null, "certificateContext != null");
Debug.Assert(!certificateContext.IsClosed && !certificateContext.IsInvalid,
"!certificateContext.IsClosed && !certificateContext.IsInvalid");
IntPtr privateKeyPtr;
// If the certificate has a key handle instead of a key prov info, return the
// ephemeral key
{
int cbData = IntPtr.Size;
if (Interop.crypt32.CertGetCertificateContextProperty(
certificateContext,
CertContextPropId.CERT_NCRYPT_KEY_HANDLE_PROP_ID,
out privateKeyPtr,
ref cbData))
{
handleOptions = CngKeyHandleOpenOptions.EphemeralKey;
return new SafeNCryptKeyHandle(privateKeyPtr, certificateContext);
}
}
bool freeKey = true;
SafeNCryptKeyHandle privateKey = null;
handleOptions = CngKeyHandleOpenOptions.None;
try
{
int keySpec = 0;
if (!Interop.crypt32.CryptAcquireCertificatePrivateKey(
certificateContext,
CryptAcquireFlags.CRYPT_ACQUIRE_ONLY_NCRYPT_KEY_FLAG,
IntPtr.Zero,
out privateKey,
out keySpec,
out freeKey))
{
int dwErrorCode = Marshal.GetLastWin32Error();
// The documentation for CryptAcquireCertificatePrivateKey says that freeKey
// should already be false if "key acquisition fails", and it can be presumed
// that privateKey was set to 0. But, just in case:
freeKey = false;
privateKey?.SetHandleAsInvalid();
return null;
}
// It is very unlikely that Windows will tell us !freeKey other than when reporting failure,
// because we set neither CRYPT_ACQUIRE_CACHE_FLAG nor CRYPT_ACQUIRE_USE_PROV_INFO_FLAG, which are
// currently the only two success situations documented. However, any !freeKey response means the
// key's lifetime is tied to that of the certificate, so re-register the handle as a child handle
// of the certificate.
if (!freeKey && privateKey != null && !privateKey.IsInvalid)
{
var newKeyHandle = new SafeNCryptKeyHandle(privateKey.DangerousGetHandle(), certificateContext);
privateKey.SetHandleAsInvalid();
privateKey = newKeyHandle;
freeKey = true;
}
return privateKey;
}
catch
{
// If we aren't supposed to free the key, and we're not returning it,
// just tell the SafeHandle to not free itself.
if (privateKey != null && !freeKey)
{
privateKey.SetHandleAsInvalid();
}
throw;
}
}
//
// Returns the private key referenced by a store certificate. Note that despite the return type being declared "CspParameters",
// the key can actually be a CNG key. To distinguish, examine the ProviderType property. If it is 0, this key is a CNG key with
// the various properties of CspParameters being "repurposed" into storing CNG info.
//
// This is a behavior this method inherits directly from the Crypt32 CRYPT_KEY_PROV_INFO semantics.
//
// It would have been nice not to let this ugliness escape out of this helper method. But X509Certificate2.ToString() calls this
// method too so we cannot just change it without breaking its output.
//
private CspParameters GetPrivateKey()
{
int cbData = 0;
if (!Interop.crypt32.CertGetCertificateContextProperty(_certContext, CertContextPropId.CERT_KEY_PROV_INFO_PROP_ID, null, ref cbData))
{
int dwErrorCode = Marshal.GetLastWin32Error();
if (dwErrorCode == ErrorCode.CRYPT_E_NOT_FOUND)
return null;
throw dwErrorCode.ToCryptographicException();
}
unsafe
{
byte[] privateKey = new byte[cbData];
fixed (byte* pPrivateKey = privateKey)
{
if (!Interop.crypt32.CertGetCertificateContextProperty(_certContext, CertContextPropId.CERT_KEY_PROV_INFO_PROP_ID, privateKey, ref cbData))
throw Marshal.GetLastWin32Error().ToCryptographicException();
CRYPT_KEY_PROV_INFO* pKeyProvInfo = (CRYPT_KEY_PROV_INFO*)pPrivateKey;
CspParameters cspParameters = new CspParameters();
cspParameters.ProviderName = Marshal.PtrToStringUni((IntPtr)(pKeyProvInfo->pwszProvName));
cspParameters.KeyContainerName = Marshal.PtrToStringUni((IntPtr)(pKeyProvInfo->pwszContainerName));
cspParameters.ProviderType = pKeyProvInfo->dwProvType;
cspParameters.KeyNumber = pKeyProvInfo->dwKeySpec;
cspParameters.Flags = (CspProviderFlags)((pKeyProvInfo->dwFlags & CryptAcquireContextFlags.CRYPT_MACHINE_KEYSET) == CryptAcquireContextFlags.CRYPT_MACHINE_KEYSET ? CspProviderFlags.UseMachineKeyStore : 0);
return cspParameters;
}
}
}
}
}
| 43.085586 | 225 | 0.576163 | [
"MIT"
] | hgGeorg/corefx | src/System.Security.Cryptography.X509Certificates/src/Internal/Cryptography/Pal.Windows/CertificatePal.PrivateKey.cs | 9,565 | C# |
using System;
using System.Linq;
using System.Threading.Tasks;
using LsifDotnet.Lsif;
using LsifDotnet.Roslyn;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.FileSystemGlobbing;
using Xunit;
namespace LsifDotnet.Tests
{
public class KeywordTest
{
/// <summary>
/// The adhoc workspace.
/// </summary>
private readonly AdhocWorkspace _adhocWorkspace;
private readonly Project _project;
private readonly ServiceProvider _serviceProvider;
public KeywordTest()
{
_adhocWorkspace = new AdhocWorkspace();
_project = AddProject(nameof(KeywordTest));
_serviceProvider = new ServiceCollection()
.AddLogging()
.AddTransient<IdentifierCollectorFactory>()
.AddSingleton<Matcher>()
.AddTransient<LegacyLsifIndexer>()
.AddSingleton(_adhocWorkspace as Workspace)
.BuildServiceProvider();
}
private Project AddProject(string projectName)
{
return _adhocWorkspace.AddProject(ProjectInfo.Create(ProjectId.CreateNewId(),
VersionStamp.Create(),
projectName, projectName, "C#", "F:/dummyProjectPath.csproj", metadataReferences: new[]
{
MetadataReference.CreateFromFile(typeof(object).Assembly.Location)
}));
}
[Fact]
public async Task GlobalKeywordTest()
{
var code1 = SourceText.From(
@"// <autogenerated />
using System;
using System.Reflection;
[assembly: global::System.Runtime.Versioning.TargetFrameworkAttribute("".NETCoreApp,Version=v6.0"", FrameworkDisplayName = """")]");
var code2 = SourceText.From(@"class Test : global::System.object {} // Adding extra global symbol");
var documentId1 = DocumentId.CreateNewId(_project.Id);
var documentId2 = DocumentId.CreateNewId(AddProject("SecondProject").Id);
TextLoader loader1 = TextLoader.From(TextAndVersion.Create(code1, VersionStamp.Create()));
TextLoader loader2 = TextLoader.From(TextAndVersion.Create(code2, VersionStamp.Create()));
_adhocWorkspace.AddDocument(DocumentInfo.Create(documentId1, $"{nameof(GlobalKeywordTest)}.1.cs", null, SourceCodeKind.Regular, loader1, "F:/dummy/dummyDocumentFilePath.cs"));
_adhocWorkspace.AddDocument(DocumentInfo.Create(documentId2, $"{nameof(GlobalKeywordTest)}.2.cs", null, SourceCodeKind.Regular, loader2, "F:/dummy/dummyDocumentFilePath.cs"));
var indexer = _serviceProvider.GetRequiredService<LegacyLsifIndexer>();
await foreach (var item in indexer.EmitLsif())
{
Assert.NotNull(item);
}
}
/// <summary>
/// See https://github.com/dotnet/roslyn/issues/58999
/// </summary>
/// <returns></returns>
[Fact]
[System.Diagnostics.CodeAnalysis.SuppressMessage("MicrosoftCodeAnalysisCorrectness", "RS1024")]
public async Task RoslynAliasEqualBugTest()
{
{
var code1 = SourceText.From(
@"// <autogenerated />
using System;
using System.Reflection;
[assembly: global::System.Runtime.Versioning.TargetFrameworkAttribute("".NETCoreApp,Version=v6.0"", FrameworkDisplayName = """")]");
var code2 = SourceText.From(@"using global::System.IO; // Adding extra global symbol");
var doc1 = _adhocWorkspace.AddDocument(_project.Id, $"{nameof(GlobalKeywordTest)}.1.cs",
code1);
var doc2 = _adhocWorkspace.AddDocument(_project.Id, $"{nameof(GlobalKeywordTest)}.2.cs",
code2);
var globalSymbol1 = (await doc1.GetSemanticModelAsync())!
.GetAliasInfo((await doc1.GetSyntaxRootAsync())!
.DescendantNodes()
.OfType<IdentifierNameSyntax>()
.First(ident => ident.Identifier.Text == "global"));
var globalSymbol2 = (await doc2.GetSemanticModelAsync())!
.GetAliasInfo((await doc2.GetSyntaxRootAsync())!
.DescendantNodes()
.OfType<IdentifierNameSyntax>()
.First(ident => ident.Identifier.Text == "global"));
Assert.NotNull(globalSymbol1);
Assert.NotNull(globalSymbol2);
Assert.Throws<NullReferenceException>(() => globalSymbol1!.Equals(globalSymbol2));
}
}
}
} | 40.991453 | 187 | 0.613636 | [
"Apache-2.0"
] | tcz717/LsifDotnet | LsifDotnet.Tests/KeywordTest.cs | 4,796 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using Model;
namespace QueueClient
{
public class PrintHelper
{
#region
#region TxDoFunction的func参数
UInt32 TX_FONT_SIZE = 1; /*放大系数,0为原始大小,1为增大1倍,如此类推,最大为7;参数1为宽,参数2为高*/
UInt32 TX_FONT_ULINE = 2;/*下划线*/
UInt32 TX_FONT_BOLD = 3;/*粗体*/
UInt32 TX_SEL_FONT = 4;/*选择英文字体*/
UInt32 TX_FONT_ROTATE = 5;/*旋转90度*/
UInt32 TX_ALIGN = 6;/*参数为TX_ALIGN_XXX*/
UInt32 TX_CHINESE_MODE = 7;/*开关中文模式*/
UInt32 TX_FEED = 10;/*执行走纸*/
UInt32 TX_UNIT_TYPE = 11;/*设置动作单位*/
UInt32 TX_CUT = 12;/*执行切纸,第一参数指明类型,第二参数指明切纸前的走纸距离*/
UInt32 TX_HOR_POS = 13;/*绝对水平定位*/
UInt32 TX_LINE_SP = 14;/*设置行间距*/
UInt32 TX_BW_REVERSE = 15;/*设置字体黑白翻转*/
UInt32 TX_UPSIDE_DOWN = 16;/*设置倒置打印*/
UInt32 TX_INET_CHARS = 17;/*选择国际字符集*/
UInt32 TX_CODE_PAGE = 18;/*选择字符代码表*/
UInt32 TX_CH_ROTATE = 19;/*设定汉字旋转*/
UInt32 TX_CHK_BMARK = 20;/*寻找黑标*/
UInt32 TX_SET_BMARK = 21;/*设置黑标相关偏移量*/
UInt32 TX_PRINT_LOGO = 22;/*打印已下载好的LOGO*/
UInt32 TX_BARCODE_HEIGHT = 23;/*设定条码高度*/
UInt32 TX_BARCODE_WIDTH = 24;/*设定条码宽度*/
UInt32 TX_BARCODE_FONT = 25;/*选择HRI字符的打印位置*/
UInt32 TX_FEED_REV = 26;/*执行逆向走纸*/
UInt32 TX_QR_DOTSIZE = 27;/*设置QR码的点大小,2<param1<10*/
UInt32 TX_QR_ERRLEVEL = 28;/*设置QR码的交错等级*/
#endregion
#region TxDoFunction的参数(需对应功能)
UInt32 TX_ON = 1;
UInt32 TX_OFF = 0;
UInt32 TX_CUT_FULL = 0; /*对应TX_CUT*/
UInt32 TX_CUT_PARTIAL = 1;
UInt32 TX_PURECUT_FULL = 2; /*与黑标无关的切纸*/
UInt32 TX_PURECUT_PARTIAL = 3;
UInt32 TX_FONT_A = 0; /*对应TX_SEL_FONT*/
UInt32 TX_FONT_B = 1;
UInt32 TX_ALIGN_LEFT = 0; /*对应TX_ALIGN*/
UInt32 TX_ALIGN_CENTER = 1;
UInt32 TX_ALIGN_RIGHT = 2;
UInt32 TX_SIZE_1X = 0; /*对应TX_FONT_SIZE*/
UInt32 TX_SIZE_2X = 1;
UInt32 TX_SIZE_3X = 2;
UInt32 TX_SIZE_4X = 3;
UInt32 TX_SIZE_5X = 4;
UInt32 TX_SIZE_6X = 5;
UInt32 TX_SIZE_7X = 6;
UInt32 TX_SIZE_8X = 7;
UInt32 TX_UNIT_PIXEL = 0; /*对应TX_UNIT_TYPE*/
UInt32 TX_UNIT_MM = 1;
UInt32 TX_CH_ROTATE_NONE = 0; /*对应TX_CH_ROTATE*/
UInt32 TX_CH_ROTATE_LEFT = 1;
UInt32 TX_CH_ROTATE_RIGHT = 2;
UInt32 TX_BM_START = 1; /*起始打印位置相对于黑标检测位置的偏移量*/
UInt32 TX_BM_TEAR = 2; /*切/撕纸位置相对于黑标检测位置的偏移量*/
UInt32 TX_LOGO_1X1 = 0; /*对应TX_PRINT_LOGO*/
UInt32 TX_LOGO_1X2 = 1; /*203x101*/
UInt32 TX_LOGO_2X1 = 2; /*101x203*/
UInt32 TX_LOGO_2X2 = 3; /*101x101*/
UInt32 TX_BAR_FONT_NONE = 0; /*对应TX_BARCODE_FONT*/
UInt32 TX_BAR_FONT_UP = 1;
UInt32 TX_BAR_FONT_DOWN = 2;
UInt32 TX_BAR_FONT_BOTH = 3;
#endregion
/*
* @brief 连接打印机。需在所有函数前执行。
* @param Type : TX_TYPE_XXX
* @param Idx : 从0开始
* @return 操作是否成功
*/
[DllImport("TxPrnMod.dl")]
public static extern bool TxOpenPrinter(long type, long index);
/// <summary>
/// 获取打印机状态 调用失败则为0。
/// </summary>
[DllImport("TxPrnMod.dl")]
public static extern short TxGetStatus2();
/// <summary>
/// 关闭连接
/// </summary>
[DllImport("TxPrnMod.dl", EntryPoint = "TxClosePrinter")]
public static extern void TxClosePrinter();
/// <summary>
/// 发送初始化
/// </summary>
[DllImport("TxPrnMod.dl", EntryPoint = "TxInit")]
public static extern void TxInit();
/// <summary>
/// 输出字符串(以\0结束)
/// </summary>
[DllImport("TxPrnMod.dl", EntryPoint = "TxOutputString")]
public static extern void TxOutputString(string outString);
/// <summary>
/// 输出回车、换行
/// </summary>
[DllImport("TxPrnMod.dl", EntryPoint = "TxNewline")]
public static extern void TxNewline();
/// <summary>
/// 输出字符串(以\0结束),并自动添加回车、换行
/// </summary>
[DllImport("TxPrnMod.dl", EntryPoint = "TxOutputStringLn")]
public static extern void TxOutputStringLn(string outString);
/// <summary>
/// 恢复字体效果(大小、粗体等)为原始状态。
/// </summary>
[DllImport("TxPrnMod.dl", EntryPoint = "TxResetFont")]
public static extern void TxResetFont();
/// <summary>
/// 执行特殊功能。
/// 有的功能需要传入两个参数,有的功能只需要一个参数(param2=0)
/// </summary>
/// <param name="func">功能类型</param>
/// <param name="param1">参数1</param>
/// <param name="param2"></param>
[DllImport("TxPrnMod.dl", EntryPoint = "TxDoFunction")]
public static extern void TxDoFunction(System.UInt32 func, UInt32 param1, UInt32 param2);
#endregion
public PrintHelper()
{
}
public void Print(BQueueModel model, string area, int wait)
{
var open= TxOpenPrinter(0, 0);
var state = TxGetStatus2();
TxInit();//初始化
TxDoFunction(TX_FEED, 15, 0);//走纸,留空行 15毫米
TxDoFunction(TX_HOR_POS, 15, 0);//距离左边15毫米
TxDoFunction(TX_FONT_SIZE, TX_SIZE_3X, TX_SIZE_2X);//设置标题字体大小
TxOutputStringLn("阳江市票务大厅排队叫号系统");
TxDoFunction(TX_FONT_SIZE, TX_SIZE_1X, TX_SIZE_1X);//设置字体
TxOutputStringLn("排队区域:" + area);
TxOutputStringLn("排队部门:" + model.unitName);
TxOutputStringLn("排队业务:" + model.busTypeName);
TxOutputString("当前号码:");
TxDoFunction(TX_FONT_BOLD, TX_ON, 0);//使用粗体
TxDoFunction(TX_FONT_SIZE, TX_SIZE_3X, TX_SIZE_3X);//设置字体
TxOutputStringLn(model.ticketNumber);
TxDoFunction(TX_FONT_SIZE, TX_SIZE_1X, TX_SIZE_1X);//设置字体
TxDoFunction(TX_FONT_BOLD, TX_OFF, 0);//关闭粗体
TxOutputStringLn(string.Format("你前面还有 {0} 人在等待。", wait.ToString()));
TxOutputStringLn("请在休息区等候,注意呼叫及大屏显示信息。");
TxOutputStringLn("过号无效,请您重新取号。");
TxOutputStringLn(string.Format(" {0} ", DateTime.Now));
TxDoFunction(TX_CUT, TX_CUT_PARTIAL, 5);//切纸,切纸前 走纸5毫米
TxClosePrinter();
}
}
}
| 36.583815 | 97 | 0.584611 | [
"MIT"
] | 1059444127/QueueSystem | QueueClient/QueueClient/PrintHelper.cs | 7,435 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace K3DoNetPlug
{
public interface IToolsButton
{
BaseBiller CurrentBiller { get; }
void AddToolsButton(string name, string parent);
}
}
| 18.461538 | 56 | 0.7 | [
"Apache-2.0"
] | vebin/Kingdee.K3Wise.Plug | K3DoNetPlug/ToolsButton/IToolsButton.cs | 242 | C# |
#if UNITY_EDITOR
using UnityEngine;
using UnityEditor;
using System;
using System.Collections.Generic;
namespace O3DWB
{
[Serializable]
public class ObjectPlacementPathTileConnectionSettingsView : SettingsView
{
#region Private Variables
[NonSerialized]
private ObjectPlacementPathTileConnectionSettings _settings;
[NonSerialized]
private float _setCommonTilePropertyButtonWidth = EditorGUILayoutEx.PreferedActionButtonWidth * 1.23f;
#endregion
#region Constructors
public ObjectPlacementPathTileConnectionSettingsView(ObjectPlacementPathTileConnectionSettings settings)
{
_settings = settings;
}
#endregion
#region Protected Methods
protected override void RenderContent()
{
RenderUseTileConnectionsToggle();
if(_settings.UseTileConnections)
{
Octave3DWorldBuilder.ActiveInstance.ShowGUIHint("When using tile connections, the extension plane will always reside at the bottom of the placement guide in its local space.");
RenderSetCommonPropertiesControls();
RenderRemoveAllPrefabAssociationsButton();
EditorGUILayout.Separator();
PrefabsToPathTileConectionDropEventHandler.Get().DropSettings.View.Render();
RenderViewForEachTileConnectionType();
}
}
#endregion
#region Private Methods
private void RenderUseTileConnectionsToggle()
{
bool newBool = EditorGUILayout.ToggleLeft(GetContentForUseTileConnectionsToggle(), _settings.UseTileConnections);
if(newBool != _settings.UseTileConnections)
{
if (!ObjectPlacementPathTileConnectionSettingsChangeValidation.Validate(true)) return;
UndoEx.RecordForToolAction(_settings);
_settings.UseTileConnections = newBool;
}
}
private GUIContent GetContentForUseTileConnectionsToggle()
{
var content = new GUIContent();
content.text = "Use tile connections";
content.tooltip = "Check this when you would like to construct paths that use tile connections.";
return content;
}
private void RenderSetCommonPropertiesControls()
{
RenderCommonYAxisRotationControls();
RenderCommonYOffsetControls();
RenderSetCommonExtrusionAmountControls();
RenderInheritPrefabControls();
}
private void RenderCommonYAxisRotationControls()
{
EditorGUILayout.BeginHorizontal();
RenderSetCommonYAxisRotationButton();
RenderCommonYAxisRotationSelectionPopup();
EditorGUILayout.EndHorizontal();
}
private void RenderSetCommonYAxisRotationButton()
{
if (GUILayout.Button(GetContentForSetCommonYAxisRotationButton(), GUILayout.Width(_setCommonTilePropertyButtonWidth)))
{
List<ObjectPlacementPathTileConnectionType> allTileConnectionTypes = ObjectPlacementPathTileConnectionTypes.GetAll();
foreach(ObjectPlacementPathTileConnectionType tileConnectionType in allTileConnectionTypes)
{
UndoEx.RecordForToolAction(_settings.GetSettingsForTileConnectionType(tileConnectionType));
_settings.GetSettingsForTileConnectionType(tileConnectionType).YAxisRotation = _settings.CommonYAxisRotation;
}
}
}
private GUIContent GetContentForSetCommonYAxisRotationButton()
{
var content = new GUIContent();
content.text = "Set Y rotation for all tiles";
content.tooltip = "Pressing this button will set the Y axis rotation for all tile connections to the value specified in the adjacent popup.";
return content;
}
private void RenderCommonYAxisRotationSelectionPopup()
{
ObjectPlacementPathTileConnectionYAxisRotation newYAxisRotation = (ObjectPlacementPathTileConnectionYAxisRotation)EditorGUILayout.EnumPopup(GetContentForCommonYAxisRotationSelectionPopup(), _settings.CommonYAxisRotation);
if(newYAxisRotation != _settings.CommonYAxisRotation)
{
UndoEx.RecordForToolAction(_settings);
_settings.CommonYAxisRotation = newYAxisRotation;
}
}
private GUIContent GetContentForCommonYAxisRotationSelectionPopup()
{
var content = new GUIContent();
content.text = "";
content.tooltip = "This is the common Y axis rotation that can be set for all tile connections by pressing the adjacent button.";
return content;
}
private void RenderCommonYOffsetControls()
{
EditorGUILayout.BeginHorizontal();
RenderSetCommonYOffsetButton();
RenderCommonYOffsetField();
EditorGUILayout.EndHorizontal();
}
private void RenderSetCommonYOffsetButton()
{
if (GUILayout.Button(GetContentForSetCommonYOffsetButton(), GUILayout.Width(_setCommonTilePropertyButtonWidth)))
{
List<ObjectPlacementPathTileConnectionType> allTileConnectionTypes = ObjectPlacementPathTileConnectionTypes.GetAll();
foreach (ObjectPlacementPathTileConnectionType tileConnectionType in allTileConnectionTypes)
{
UndoEx.RecordForToolAction(_settings.GetSettingsForTileConnectionType(tileConnectionType));
_settings.GetSettingsForTileConnectionType(tileConnectionType).YOffset = _settings.CommonYOffset;
}
SceneView.RepaintAll();
}
}
private GUIContent GetContentForSetCommonYOffsetButton()
{
var content = new GUIContent();
content.text = "Set Y offset for all tiles";
content.tooltip = "Pressing this button will set the Y offset for all tile connections to the value specified in the adjacent popup.";
return content;
}
private void RenderCommonYOffsetField()
{
float newFloat = EditorGUILayout.FloatField(GetContentForCommonYOffsetField(), _settings.CommonYOffset);
if(newFloat != _settings.CommonYOffset)
{
UndoEx.RecordForToolAction(_settings);
_settings.CommonYOffset = newFloat;
}
}
private GUIContent GetContentForCommonYOffsetField()
{
var content = new GUIContent();
content.text = "";
content.tooltip = "This is the common Y offset that can be set for all tile connections by pressing the adjacent button.";
return content;
}
private void RenderViewForEachTileConnectionType()
{
List<ObjectPlacementPathTileConnectionType> allTileConnectionTypes = ObjectPlacementPathTileConnectionTypes.GetAll();
for(int tileConnectionIndex = 0; tileConnectionIndex < allTileConnectionTypes.Count; ++tileConnectionIndex)
{
_settings.GetSettingsForTileConnectionType(allTileConnectionTypes[tileConnectionIndex]).View.Render();
}
}
private void RenderSetCommonExtrusionAmountControls()
{
RenderSetCommonUpwardsExtrusionAmountControls();
RenderSetCommonDownwardsExtrusionAmountControls();
}
private void RenderSetCommonUpwardsExtrusionAmountControls()
{
EditorGUILayout.BeginHorizontal();
RenderSetCommonUpwardsExtrusionAmountButton();
RenderCommonUpwardsExtrusionAmountField();
EditorGUILayout.EndHorizontal();
}
private void RenderSetCommonUpwardsExtrusionAmountButton()
{
if (GUILayout.Button(GetContentForSetCommonUpwardsExtrusionAmountButton(), GUILayout.Width(_setCommonTilePropertyButtonWidth)))
{
List<ObjectPlacementPathTileConnectionType> allTileConnectionTypes = ObjectPlacementPathTileConnectionTypes.GetAll();
foreach (ObjectPlacementPathTileConnectionType tileConnectionType in allTileConnectionTypes)
{
UndoEx.RecordForToolAction(_settings.GetSettingsForTileConnectionType(tileConnectionType));
_settings.GetSettingsForTileConnectionType(tileConnectionType).UpwardsExtrusionAmount = _settings.CommonUpwardsExtrusionAmount;
}
SceneView.RepaintAll();
}
}
private GUIContent GetContentForSetCommonUpwardsExtrusionAmountButton()
{
var content = new GUIContent();
content.text = "Set upwards extrusion amount for all tiles";
content.tooltip = "Pressing this button will set the upwards extrusion amount for all tile connections to the value specified in the adjacent field.";
return content;
}
private void RenderCommonUpwardsExtrusionAmountField()
{
int newInt = EditorGUILayout.IntField(GetContentForCommonUpwardsExtrusionAmountField(), _settings.CommonUpwardsExtrusionAmount);
if(newInt != _settings.CommonUpwardsExtrusionAmount)
{
UndoEx.RecordForToolAction(_settings);
_settings.CommonUpwardsExtrusionAmount = newInt;
}
}
private GUIContent GetContentForCommonUpwardsExtrusionAmountField()
{
var content = new GUIContent();
content.text = "";
content.tooltip = "This is the common upwards extrusion amount that can be set for all tile connections by pressing the adjacent button.";
return content;
}
private void RenderSetCommonDownwardsExtrusionAmountControls()
{
EditorGUILayout.BeginHorizontal();
RenderSetCommonDownwardsExtrusionAmountButton();
RenderCommonDownwardsExtrusionAmountField();
EditorGUILayout.EndHorizontal();
}
private void RenderSetCommonDownwardsExtrusionAmountButton()
{
if (GUILayout.Button(GetContentForSetCommonDownwardsExtrusionAmountButton(), GUILayout.Width(_setCommonTilePropertyButtonWidth)))
{
List<ObjectPlacementPathTileConnectionType> allTileConnectionTypes = ObjectPlacementPathTileConnectionTypes.GetAll();
foreach (ObjectPlacementPathTileConnectionType tileConnectionType in allTileConnectionTypes)
{
UndoEx.RecordForToolAction(_settings.GetSettingsForTileConnectionType(tileConnectionType));
_settings.GetSettingsForTileConnectionType(tileConnectionType).DownwardsExtrusionAmount = _settings.CommonDownwardsExtrusionAmount;
}
SceneView.RepaintAll();
}
}
private GUIContent GetContentForSetCommonDownwardsExtrusionAmountButton()
{
var content = new GUIContent();
content.text = "Set downwards extrusion amount for all tiles";
content.tooltip = "Pressing this button will set the downwards extrusion amount for all tile connections to the value specified in the adjacent field.";
return content;
}
private void RenderCommonDownwardsExtrusionAmountField()
{
int newInt = EditorGUILayout.IntField(GetContentForCommonDownwardsExtrusionAmountField(), _settings.CommonDownwardsExtrusionAmount);
if (newInt != _settings.CommonDownwardsExtrusionAmount)
{
UndoEx.RecordForToolAction(_settings);
_settings.CommonDownwardsExtrusionAmount = newInt;
}
}
private GUIContent GetContentForCommonDownwardsExtrusionAmountField()
{
var content = new GUIContent();
content.text = "";
content.tooltip = "";
return content;
}
private void RenderInheritPrefabControls()
{
EditorGUILayout.BeginHorizontal();
RenderInheritPrefabButton();
RenderPrefabInheritTileConnectionType();
EditorGUILayout.EndHorizontal();
}
private void RenderInheritPrefabButton()
{
if (GUILayout.Button(GetContentForInheritPrefabButton(), GUILayout.Width(_setCommonTilePropertyButtonWidth)))
{
if (!ObjectPlacementPathTileConnectionSettingsChangeValidation.Validate(true)) return;
Prefab prefabToInherit = _settings.GetSettingsForTileConnectionType(_settings.PrefabInheritTileConnectionType).Prefab;
List<ObjectPlacementPathTileConnectionType> allTileConnectionTypes = ObjectPlacementPathTileConnectionTypes.GetAll();
foreach (ObjectPlacementPathTileConnectionType tileConnectionType in allTileConnectionTypes)
{
UndoEx.RecordForToolAction(_settings.GetSettingsForTileConnectionType(tileConnectionType));
_settings.GetSettingsForTileConnectionType(tileConnectionType).Prefab = prefabToInherit;
}
}
}
private GUIContent GetContentForInheritPrefabButton()
{
var content = new GUIContent();
content.text = "Inherit prefab from tile connection";
content.tooltip = "Pressing this button will adjust the prefab of all tile connections to be the same as the one associated with the tile specified in the adjacent popup.";
return content;
}
private void RenderPrefabInheritTileConnectionType()
{
ObjectPlacementPathTileConnectionType newTileConnectionType = (ObjectPlacementPathTileConnectionType)EditorGUILayout.EnumPopup(GetContentForPrefabInheritTileConnectionTypeSelectionPopup(), _settings.PrefabInheritTileConnectionType);
if(newTileConnectionType != _settings.PrefabInheritTileConnectionType)
{
UndoEx.RecordForToolAction(_settings);
_settings.PrefabInheritTileConnectionType = newTileConnectionType;
}
}
private GUIContent GetContentForPrefabInheritTileConnectionTypeSelectionPopup()
{
var content = new GUIContent();
content.text = "";
content.tooltip = "";
return content;
}
private void RenderRemoveAllPrefabAssociationsButton()
{
if (GUILayout.Button(GetContentForRemoveAllPrefabAssociationsButton(), GUILayout.Width(_setCommonTilePropertyButtonWidth)))
{
if (!ObjectPlacementPathTileConnectionSettingsChangeValidation.Validate(true)) return;
_settings.RecordAllTileConnectionTypeSettingsForUndo();
_settings.RemoveAllPrefabAssociations();
}
}
private GUIContent GetContentForRemoveAllPrefabAssociationsButton()
{
var content = new GUIContent();
content.text = "Remove all prefab associations";
content.tooltip = "Pressing this button will remove the prefab associations for all tile connections.";
return content;
}
#endregion
}
}
#endif | 42.648352 | 244 | 0.663038 | [
"MIT"
] | AestheticalZ/Faithful-SCP-Unity | Assets/Octave3D World Builder/Scripts/Inspector GUI/Views/Settings Views/Objects/Object Placement/Path/Tile Connections/ObjectPlacementPathTileConnectionSettingsView.cs | 15,526 | C# |
using System;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Data.Objects.DataClasses;
namespace Cats.Models.Hubs.MetaModels
{
public sealed class GiftCertificateDetailMetaModel
{
[Required(ErrorMessage="Gift Certificate Detail is required")]
public Int32 GiftCertificateDetailID { get; set; }
//[Required(ErrorMessage="Partition is required")]
//public Int32 PartitionId { get; set; }
[Required(ErrorMessage="Transaction Group is required")]
public Int32 TransactionGroupID { get; set; }
[Required(ErrorMessage="Gift Certificate is required")]
public Int32 GiftCertificateID { get; set; }
[Required(ErrorMessage="Commodity is required")]
public Int32 CommodityID { get; set; }
[Required(ErrorMessage="Weight In M T is required")]
public Decimal WeightInMT { get; set; }
[StringLength(50)]
public String BillOfLoading { get; set; }
[Required(ErrorMessage="Account Number is required")]
public Int32 AccountNumber { get; set; }
[Required(ErrorMessage="Estimated Price is required")]
public Decimal EstimatedPrice { get; set; }
[Required(ErrorMessage="Estimated Tax is required")]
public Decimal EstimatedTax { get; set; }
[Required(ErrorMessage="Year Purchased is required")]
public Int32 YearPurchased { get; set; }
[Required(ErrorMessage="D Fund Source is required")]
public Int32 DFundSourceID { get; set; }
[Required(ErrorMessage="D Currency is required")]
public Int32 DCurrencyID { get; set; }
[Required(ErrorMessage="D Budget Type is required")]
public Int32 DBudgetTypeID { get; set; }
[DataType(DataType.DateTime)]
public DateTime ExpiryDate { get; set; }
public EntityCollection<Commodity> Commodity { get; set; }
public EntityCollection<Detail> Detail { get; set; }
public EntityCollection<Detail> Detail1 { get; set; }
public EntityCollection<Detail> Detail2 { get; set; }
public EntityCollection<GiftCertificate> GiftCertificate { get; set; }
public EntityCollection<ReceiptAllocation> ReceiptAllocations { get; set; }
}
}
| 30.5 | 81 | 0.699454 | [
"Apache-2.0"
] | IYoni/cats | Models/Cats.Models.Hub/MetaModels/GiftCertificateDetailMetaModel.cs | 2,196 | 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.Cdb.V20170320.Models
{
using Newtonsoft.Json;
using System.Collections.Generic;
using TencentCloud.Common;
public class ModifyParamTemplateRequest : AbstractModel
{
/// <summary>
/// 模板 ID。
/// </summary>
[JsonProperty("TemplateId")]
public long? TemplateId{ get; set; }
/// <summary>
/// 模板名称。
/// </summary>
[JsonProperty("Name")]
public string Name{ get; set; }
/// <summary>
/// 模板描述。
/// </summary>
[JsonProperty("Description")]
public string Description{ get; set; }
/// <summary>
/// 参数列表。
/// </summary>
[JsonProperty("ParamList")]
public Parameter[] ParamList{ get; set; }
/// <summary>
/// For internal usage only. DO NOT USE IT.
/// </summary>
internal override void ToMap(Dictionary<string, string> map, string prefix)
{
this.SetParamSimple(map, prefix + "TemplateId", this.TemplateId);
this.SetParamSimple(map, prefix + "Name", this.Name);
this.SetParamSimple(map, prefix + "Description", this.Description);
this.SetParamArrayObj(map, prefix + "ParamList.", this.ParamList);
}
}
}
| 30.184615 | 83 | 0.609582 | [
"Apache-2.0"
] | ImEdisonJiang/tencentcloud-sdk-dotnet | TencentCloud/Cdb/V20170320/Models/ModifyParamTemplateRequest.cs | 1,998 | C# |
using System.Web;
using System.Web.Optimization;
namespace Stardust.Continuum
{
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"));
// 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", "~/Scripts/flot/jquery.flot.min.js"));
bundles.Add(new StyleBundle("~/Content/css").Include(
//"~/Content/bootstrap.css",
"~/Content/bootstrap.cyporg.css",
"~/Content/site.css", "~/Content/vis.min.css", "~/Content/font-awesome.min.css"));
}
}
}
| 42.566667 | 112 | 0.5787 | [
"Apache-2.0"
] | JonasSyrstad/Stardust.Interstellar.Rest | Stardust.Continuum/App_Start/BundleConfig.cs | 1,279 | C# |
using DiscoverValidationTest.Model.Animals.Interface;
namespace DiscoverValidationTest.Model.Animals
{
public class Dog : IAnimal
{
public string Name { get; set; }
public int Age { get; set; }
public bool CanFly { get; set; }
public string Type { get; set; }
public Dog(string name, int age, bool canFly, string type)
{
Name = name;
Age = age;
CanFly = canFly;
Type = type;
}
}
} | 23.761905 | 66 | 0.551102 | [
"Apache-2.0"
] | toni90acg/DiscoverValidation | DiscoverValidationTest/Model/Animals/Dog.cs | 499 | C# |
using System;
using System.IO;
using System.Text;
using Newtonsoft.Json;
namespace Nebula
{
/// <summary>
/// A builder for <see cref="AttachmentTypeMapping{TDocument,TAttachment}"/> classes.
/// </summary>
/// <typeparam name="TDocument">The type of document.</typeparam>
/// <typeparam name="TAttachment">The type of attachment.</typeparam>
public class AttachmentTypeMappingBuilder<TDocument, TAttachment>
{
private readonly string _attachmentName;
private readonly DocumentTypeMapping<TDocument> _documentMapping;
private Func<Stream, TAttachment> _readerFunc;
private Func<TAttachment, Stream> _writerFunc;
/// <summary>
/// Initialises a new instance of the <see cref="AttachmentTypeMappingBuilder{TDocument,TAttachment}"/> class.
/// </summary>
/// <param name="attachmentName">The attachment name.</param>
/// <param name="documentMapping">The document type mapping.</param>
internal AttachmentTypeMappingBuilder(string attachmentName, DocumentTypeMapping<TDocument> documentMapping)
{
if (attachmentName == null)
throw new ArgumentNullException(nameof(attachmentName));
if (documentMapping == null)
throw new ArgumentNullException(nameof(documentMapping));
_attachmentName = attachmentName;
_documentMapping = documentMapping;
}
/// <summary>
/// Sets the attachment reader.
/// </summary>
/// <param name="readerFunc">The attachment reader.</param>
/// <returns>The builder.</returns>
/// <remarks>If no reader is set then a default JSON serialiser is used.</remarks>
public AttachmentTypeMappingBuilder<TDocument, TAttachment> SetReader(Func<Stream, TAttachment> readerFunc)
{
if (readerFunc == null)
throw new ArgumentNullException(nameof(readerFunc));
_readerFunc = readerFunc;
return this;
}
/// <summary>
/// Sets the attachment writer.
/// </summary>
/// <param name="writerFunc">The attachment writer.</param>
/// <returns>The builder.</returns>
/// <remarks>If no writer is set then a default JSON serialiser is used.</remarks>
public AttachmentTypeMappingBuilder<TDocument, TAttachment> SetWriter(Func<TAttachment, Stream> writerFunc)
{
if (writerFunc == null)
throw new ArgumentNullException(nameof(writerFunc));
_writerFunc = writerFunc;
return this;
}
/// <summary>
/// Builds a <see cref="AttachmentTypeMapping{TDocument,TAttachment}"/> class.
/// </summary>
/// <returns>The attachment type mapping.</returns>
public AttachmentTypeMapping<TDocument, TAttachment> Finish()
{
if (_readerFunc == null)
{
_readerFunc = ReadJsonAttachment;
}
if (_writerFunc == null)
{
_writerFunc = WriteJsonAttachment;
}
return new AttachmentTypeMapping<TDocument, TAttachment>(_attachmentName, _documentMapping, _readerFunc, _writerFunc);
}
private static Stream WriteJsonAttachment(TAttachment attachment)
{
var stream = new MemoryStream();
using (var writer = new StreamWriter(stream, Encoding.UTF8, 1024, true))
{
using (var jsonWriter = new JsonTextWriter(writer))
{
var serialiser = new JsonSerializer();
serialiser.Serialize(jsonWriter, attachment);
jsonWriter.Flush();
}
}
stream.Position = 0;
return stream;
}
private static TAttachment ReadJsonAttachment(Stream stream)
{
var serializer = new JsonSerializer();
using (var streamReader = new StreamReader(stream))
{
using (var jsonTextReader = new JsonTextReader(streamReader))
{
return serializer.Deserialize<TAttachment>(jsonTextReader);
}
}
}
}
} | 36.760684 | 130 | 0.595908 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | cloud-maker-ai/Nebula | Nebula/AttachmentTypeMappingBuilder.cs | 4,303 | C# |
#region Copyright
//=======================================================================================
// Author: Paolo Salvatori
// GitHub: https://github.com/paolosalvatori
//=======================================================================================
// Copyright © 2021 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. YOU BEAR THE RISK OF USING IT.
//=======================================================================================
#endregion
#region Using Directives
using System;
using System.Linq;
using System.Data;
using System.Diagnostics;
using System.Threading.Tasks;
using System.Globalization;
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Data.SqlClient;
using Microsoft.Extensions.Logging;
using Microsoft.EntityFrameworkCore;
using Microsoft.ApplicationInsights;
using StackExchange.Redis;
using Products.Models;
using Products.Properties;
using Products.Helpers;
#endregion
namespace Products.Controllers
{
[Route("api/[controller]")]
[Produces("application/json")]
[ApiController]
public class ProductsController : ControllerBase
{
#region Private Instance Fields
private readonly ILogger<ProductsController> logger;
private readonly ProductsContext context;
private readonly IDatabase database;
private readonly TelemetryClient telemetryClient;
#endregion
#region Public Constructors
public ProductsController(ILogger<ProductsController> logger,
ProductsContext context,
TelemetryClient telemetryClient,
IConnectionMultiplexer connectionMultiplexer)
{
this.logger = logger;
this.context = context;
this.telemetryClient = telemetryClient;
database = connectionMultiplexer.GetDatabase();
}
#endregion
#region Public Methods
/// <summary>
/// Gets all the products.
/// </summary>
/// <returns>All the products.</returns>
/// <response code="200">Get all the products, if any.</response>
[HttpGet]
[ProducesResponseType(typeof(Product), 200)]
public async Task<IActionResult> GetAllProductsAsync()
{
var stopwatch = new Stopwatch();
try
{
stopwatch.Start();
logger.LogInformation("Listing all products...");
var startTime = DateTime.UtcNow;
var timer = Stopwatch.StartNew();
IEnumerable<Product> items;
try
{
var values = await database.SetMembersAsync(Resources.RedisKeys);
items = await database.GetAsync<Product>(values.Select(v => (string)v).ToArray());
}
finally
{
timer.Stop();
telemetryClient.TrackDependency("Redis", "RedisCluster", $"GET: All", startTime, timer.Elapsed, true);
}
if (items.Any())
{
var list = items.ToList();
list.Sort((x, y) => x.ProductId - y.ProductId);
return new OkObjectResult(list.ToArray());
}
var products = context.Products.FromSqlRaw(Resources.GetProducts);
foreach (var product in products)
{
var idAsString = product.ProductId.ToString(CultureInfo.InvariantCulture);
await database.SetAsync(idAsString, product);
await database.SetAddAsync(Resources.RedisKeys, idAsString);
}
return new OkObjectResult(products.ToArray());
}
catch (Exception ex)
{
var errorMessage = MessageHelper.FormatException(ex);
logger.LogError(errorMessage);
telemetryClient.TrackException(ex);
return StatusCode(400, new { error = errorMessage });
}
finally
{
stopwatch.Stop();
var message = $"GetAllProductsAsync method completed in {stopwatch.ElapsedMilliseconds} ms.";
logger.LogInformation(message);
telemetryClient.TrackEvent(message);
}
}
/// <summary>
/// Gets a specific product by id.
/// </summary>
/// <param name="id">Id of the product.</param>
/// <returns>Product with the specified id.</returns>
/// <response code="200">Product found</response>
/// <response code="404">Product not found</response>
[HttpGet("{id}", Name = "GetProductByIdAsync")]
[ProducesResponseType(typeof(Product), 200)]
[ProducesResponseType(typeof(Product), 404)]
public async Task<IActionResult> GetProductByIdAsync(int id)
{
var stopwatch = new Stopwatch();
try
{
stopwatch.Start();
logger.LogInformation($"Getting product {id}...");
var startTime = DateTime.UtcNow;
var timer = Stopwatch.StartNew();
Product product;
try
{
product = await database.GetAsync<Product>(id.ToString());
}
finally
{
timer.Stop();
telemetryClient.TrackDependency("Redis", "RedisCluster", $"GET: {id}", startTime, timer.Elapsed, true);
}
if (product != null)
{
return new OkObjectResult(product);
}
var products = context.Products.FromSqlRaw(Resources.GetProduct, new SqlParameter
{
ParameterName = "@ProductID",
Direction = ParameterDirection.Input,
SqlDbType = SqlDbType.Int,
Value = id
});
if (products.Any())
{
product = products.FirstOrDefault();
var idAsString = product.ProductId.ToString(CultureInfo.InvariantCulture);
await database.SetAsync(idAsString, product);
await database.SetAddAsync(Resources.RedisKeys, idAsString);
logger.LogInformation($"Product with id = {product.ProductId} has been successfully retrieved.");
return new OkObjectResult(product);
}
else
{
logger.LogWarning($"No product with id = {id} was found");
return null;
}
}
catch (Exception ex)
{
var errorMessage = MessageHelper.FormatException(ex);
logger.LogError(errorMessage);
telemetryClient.TrackException(ex);
return StatusCode(400, new { error = errorMessage });
}
finally
{
stopwatch.Stop();
var message = $"GetProductByIdAsync method completed in {stopwatch.ElapsedMilliseconds} ms.";
logger.LogInformation(message);
telemetryClient.TrackEvent(message);
}
}
/// <summary>
/// Creates a new product.
/// </summary>
/// <remarks>
/// </remarks>
/// <param name="product">Product to create.</param>
/// <returns>If the operation succeeds, it returns the newly created product.</returns>
/// <response code="201">Product successfully created.</response>
/// <response code="400">Product is null.</response>
[HttpPost]
[ProducesResponseType(typeof(Product), 201)]
[ProducesResponseType(typeof(Product), 400)]
public async Task<IActionResult> CreateProductAsync(Product product)
{
var stopwatch = new Stopwatch();
try
{
stopwatch.Start();
if (product == null)
{
logger.LogWarning("Product cannot be null.");
return BadRequest();
}
var productIdParameter = new SqlParameter
{
ParameterName = "@ProductID",
Direction = ParameterDirection.Output,
SqlDbType = SqlDbType.Int
};
var result = await context.Database.ExecuteSqlRawAsync(Resources.AddProduct, new SqlParameter[] {
productIdParameter,
new SqlParameter
{
ParameterName = "@Name",
Direction = ParameterDirection.Input,
SqlDbType = SqlDbType.NVarChar,
Size = 50,
Value = product.Name
},
new SqlParameter
{
ParameterName = "@Category",
Direction = ParameterDirection.Input,
SqlDbType = SqlDbType.NVarChar,
Size = 50,
Value = product.Category
},
new SqlParameter
{
ParameterName = "@Price",
Direction = ParameterDirection.Input,
SqlDbType = SqlDbType.SmallMoney,
Value = product.Price
}
});
if (result ==1 && productIdParameter.Value != null)
{
product.ProductId = (int)productIdParameter.Value;
var idAsString = product.ProductId.ToString(CultureInfo.InvariantCulture);
var startTime = DateTime.UtcNow;
var timer = Stopwatch.StartNew();
try
{
await database.SetAsync(idAsString, product);
await database.SetAddAsync(Resources.RedisKeys, idAsString);
}
finally
{
timer.Stop();
telemetryClient.TrackDependency("Redis", "RedisCluster", $"POST: {idAsString}", startTime, timer.Elapsed, true);
}
logger.LogInformation($"Product with id = {product.ProductId} has been successfully created.");
return CreatedAtRoute("GetProductByIdAsync", new { id = product.ProductId }, product);
}
return null;
}
catch (Exception ex)
{
var errorMessage = MessageHelper.FormatException(ex);
logger.LogError(errorMessage);
telemetryClient.TrackException(ex);
return StatusCode(400, new { error = errorMessage });
}
finally
{
stopwatch.Stop();
var message = $"CreateProductAsync method completed in {stopwatch.ElapsedMilliseconds} ms.";
logger.LogInformation(message);
telemetryClient.TrackEvent(message);
}
}
/// <summary>
/// Updates a product.
/// </summary>
/// <param name="id">The id of the product.</param>
/// <param name="product">Product to update.</param>
/// <returns>No content.</returns>
/// <response code="204">No content if the product is successfully updated.</response>
/// <response code="404">If the product is not found.</response>
[HttpPut("{id}")]
[ProducesResponseType(typeof(Product), 204)]
[ProducesResponseType(typeof(Product), 404)]
public async Task<IActionResult> Update(int id, [FromBody] Product product)
{
var stopwatch = new Stopwatch();
try
{
stopwatch.Start();
if (product == null || product.ProductId != id)
{
logger.LogWarning("The product is null or its id is different from the id in the payload.");
return BadRequest();
}
var result = await context.Database.ExecuteSqlRawAsync(Resources.UpdateProduct, new SqlParameter[] {
new SqlParameter
{
ParameterName = "@ProductID",
Direction = ParameterDirection.Input,
SqlDbType = SqlDbType.Int,
Value = product.ProductId
},
new SqlParameter
{
ParameterName = "@Name",
Direction = ParameterDirection.Input,
SqlDbType = SqlDbType.NVarChar,
Size = 50,
Value = product.Name
},
new SqlParameter
{
ParameterName = "@Category",
Direction = ParameterDirection.Input,
SqlDbType = SqlDbType.NVarChar,
Size = 50,
Value = product.Category
},
new SqlParameter
{
ParameterName = "@Price",
Direction = ParameterDirection.Input,
SqlDbType = SqlDbType.SmallMoney,
Value = product.Price
}
});
if (result == 1)
{
var idAsString = id.ToString(CultureInfo.InvariantCulture);
var startTime = DateTime.UtcNow;
var timer = Stopwatch.StartNew();
try
{
await database.SetAsync(idAsString, product);
await database.SetAddAsync(Resources.RedisKeys, idAsString);
}
finally
{
timer.Stop();
telemetryClient.TrackDependency("Redis", "RedisCluster", $"PUT: {idAsString}", startTime, timer.Elapsed, true);
}
logger.LogInformation("Product with id = {ID} has been successfully updated.", product.ProductId);
}
return new NoContentResult();
}
catch (Exception ex)
{
var errorMessage = MessageHelper.FormatException(ex);
logger.LogError(errorMessage);
telemetryClient.TrackException(ex);
return StatusCode(400, new { error = errorMessage });
}
finally
{
stopwatch.Stop();
var message = $"Update method completed in {stopwatch.ElapsedMilliseconds} ms.";
logger.LogInformation(message);
telemetryClient.TrackEvent(message);
}
}
/// <summary>
/// Deletes a specific product.
/// </summary>
/// <param name="id">The id of the product.</param>
/// <returns>No content.</returns>
/// <response code="202">No content if the product is successfully deleted.</response>
/// <response code="404">If the product is not found.</response>
[HttpDelete("{id}")]
[ProducesResponseType(typeof(Product), 204)]
[ProducesResponseType(typeof(Product), 404)]
public async Task<IActionResult> Delete(string id)
{
var stopwatch = new Stopwatch();
try
{
stopwatch.Start();
var result = await context.Database.ExecuteSqlRawAsync(Resources.DeleteProduct, new SqlParameter[] {
new SqlParameter
{
ParameterName = "@ProductID",
Direction = ParameterDirection.Input,
SqlDbType = SqlDbType.Int,
Value = id
}
});
if (result == 1)
{
var idAsString = id.ToString(CultureInfo.InvariantCulture);
var startTime = DateTime.UtcNow;
var timer = Stopwatch.StartNew();
try
{
await database.KeyDeleteAsync(idAsString);
await database.SetRemoveAsync(Resources.RedisKeys, idAsString);
}
finally
{
timer.Stop();
telemetryClient.TrackDependency("Redis", "RedisCluster", $"DELETE: {idAsString}", startTime, timer.Elapsed, true);
}
logger.LogInformation("Product with id = {ID} has been successfully deleted.", id);
}
return new NoContentResult();
}
catch (Exception ex)
{
var errorMessage = MessageHelper.FormatException(ex);
logger.LogError(errorMessage);
telemetryClient.TrackException(ex);
return StatusCode(400, new { error = errorMessage });
}
finally
{
stopwatch.Stop();
var message = $"Delete method completed in {stopwatch.ElapsedMilliseconds} ms.";
logger.LogInformation(message);
telemetryClient.TrackEvent(message);
}
}
#endregion
}
}
| 41.937079 | 139 | 0.48221 | [
"MIT"
] | paolosalvatori/web-app-redis-sql-db | src/Controllers/ProductsController.cs | 18,665 | C# |
using System;
using System.Collections.Generic;
using System.Numerics;
using System.Text;
namespace SlipeServer.Packets.Builder;
public static class ElementBuilderExtensions
{
public static void WritePlayerHealth(this PacketBuilder builder, float health)
=> builder.WriteFloatFromBits(health, 8, 0, 255, true, false);
public static void WritePlayerArmor(this PacketBuilder builder, float armor)
=> builder.WriteFloatFromBits(armor, 8, 0, 127.5f, true, false);
}
| 30.625 | 82 | 0.763265 | [
"MIT"
] | correaAlex/Slipe-Server | SlipeServer.Packets/Builder/ElementBuilderExtensions.cs | 492 | C# |
using System;
namespace Avalara.AvaTax.RestClient
{
/// <summary>
///
/// </summary>
public enum LocalNexusTypeId
{
/// <summary>
///
/// </summary>
Selected,
/// <summary>
///
/// </summary>
StateAdministered,
/// <summary>
///
/// </summary>
All,
}
}
| 13.642857 | 35 | 0.400524 | [
"Apache-2.0"
] | CassOnMars/AvaTaxClientLibrary | clients/dotnet/enums/LocalNexusTypeId.cs | 382 | C# |
using System;
using System.Collections.Generic;
namespace EntityHistory.Core.Entities
{
public class EntityChange
{
public EntityChange()
{
PropertyChanges = new HashSet<EntityPropertyChange>();
}
/// <summary>
/// Maximum length of <see cref="EntityId"/> property.
/// Value: 48.
/// </summary>
public const int MaxEntityIdLength = 48;
/// <summary>
/// Maximum length of <see cref="EntityTypeFullName"/> property.
/// Value: 192.
/// </summary>
public const int MaxEntityTypeFullNameLength = 192;
/// <summary>
/// Primary Key
/// </summary>
public Guid Id { get; set; }
/// <summary>
/// ChangeType.
/// </summary>
public EntityChangeType ChangeType { get; set; }
/// <summary>
/// Gets/sets primary key of the entity.
/// </summary>
public string EntityId { get; set; }
/// <summary>
/// FullName of the entity type.
/// </summary>
public string EntityTypeFullName { get; set; }
/// <summary>
/// Gets/sets change set id, used to group entity changes.
/// </summary>
public Guid EntityChangeSetId { get; set; }
/// <summary>
/// PropertyChanges.
/// </summary>
public virtual ICollection<EntityPropertyChange> PropertyChanges { get; set; }
public object EntityEntry { get; set; }
}
}
| 26.327586 | 86 | 0.540275 | [
"MIT"
] | EtwasGE/EntityHistory | src/EntityHistory.Core/Entities/EntityChange.cs | 1,529 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Calculator")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Calculator")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("609f0e37-7e35-4fcd-a176-ad498f2a5a01")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.648649 | 84 | 0.744436 | [
"MIT"
] | Shtereva/Fundamentals-with-CSharp | DataTypesExercises/Calculator/Properties/AssemblyInfo.cs | 1,396 | C# |
using UnityEngine;
using UnityEditor;
using UnityEngine.TestTools;
using NUnit.Framework;
using System.Collections;
using DH.SceneCrawler;
using UnityEditor.SceneManagement;
using UnityEngine.UI;
namespace DH.SceneCrawler
{
public class SceneCrawlerTests
{
[Test]
public void Crawl_Pass()
{
GameObject[] objs = new GameObject[2];
for (int i = 0; i < 2; i++)
{
objs[i] = new GameObject();
objs[i].AddComponent<Text>();
}
SceneCrawler crawler = new SceneCrawler();
CrawlParameters<Text> crawlParameters = new CrawlParameters<Text>();
crawlParameters.SceneList = new [] {EditorSceneManager.GetActiveScene().name};
crawlParameters.OnCrawlingEnd += delegate(CrawlResult<Text> result)
{
Assert.AreEqual(2, result.Components.Length);
};
crawler.Crawl(crawlParameters);
for (int i = 0; i < 2; i++)
{
GameObject.DestroyImmediate(objs[i]);
}
}
[Test]
public void CrawlTestForDeactivatedObjects_Pass()
{
int objectCount = 3;
GameObject[] objs = new GameObject[objectCount];
for (int i = 0; i < objectCount; i++)
{
objs[i] = new GameObject();
objs[i].AddComponent<Text>();
}
objs[objectCount - 1].SetActive(false);
SceneCrawler crawler = new SceneCrawler();
CrawlParameters<Text> crawlParameters = new CrawlParameters<Text>();
crawlParameters.SceneList = new[] {EditorSceneManager.GetActiveScene().name};
crawlParameters.OnCrawlingEnd += delegate(CrawlResult<Text> result)
{
Assert.AreEqual(3, result.Components.Length);
};
crawler.Crawl(crawlParameters);
for (int i = 0; i < objectCount; i++)
{
GameObject.DestroyImmediate(objs[i]);
}
}
}
} | 30.585714 | 90 | 0.538533 | [
"MIT"
] | DreamHarvesters/scene-crawler | test/Editor/SceneCrawlerTests.cs | 2,143 | C# |
namespace QPass.Core.Security.RNG
{
/// <summary>
/// Interface structure for Pseduo Random Number Generator (PRNG).
/// </summary>
public interface IRNG
{
/// <summary>
/// The name of the algorithm this generator implements.
/// </summary>
/// <returns></returns>
string AlgorithmName();
/// <summary>
/// Reset the generator.
/// Autoseed the seed or generator state.
/// </summary>
void Reset();
/// <summary>
/// Generate Boolean value from generator.
/// </summary>
/// <returns></returns>
bool NextBoolean();
/// <summary>
/// Generate Integer value from generator.
/// </summary>
/// <returns></returns>
uint NextInt();
/// <summary>
/// Generate Integer value between
/// lower and upper limit from generator.
/// </summary>
/// <param name="lower">Lower limit.</param>
/// <param name="upper">Upper limit.</param>
/// <returns></returns>
uint NextInt(uint lower, uint upper);
/// <summary>
/// Generate Long value from generator.
/// </summary>
/// <returns></returns>
ulong NextLong();
/// <summary>
/// Generate Long value between
/// lower and upper limit from generator.
/// </summary>
/// <param name="lower">Lower limit.</param>
/// <param name="upper">Upper limit.</param>
/// <returns></returns>
ulong NextLong(ulong lower, ulong upper);
/// <summary>
/// Generate Double value from generator.
/// </summary>
/// <returns></returns>
double NextDouble();
/// <summary>
/// Generate Double value between
/// lower and upper limit from generator.
/// </summary>
/// <param name="lower">Lower limit.</param>
/// <param name="upper">Upper limit.</param>
/// <returns></returns>
double NextDouble(double lower, double upper);
/// <summary>
/// Generate random byte[] value from generator.
/// </summary>
/// <param name="bytes"></param>
void NextBytes(byte[] bytes);
/// <summary>
/// Generate random byte[] value from generator.
/// </summary>
/// <param name="length">Output length.</param>
/// <returns></returns>
byte[] GetBytes(int length);
}
} | 27.083333 | 71 | 0.574505 | [
"MIT"
] | Shiroechi/QPass-Password-Manager | Source/QPass.Core/Security/RNG/IRNG.cs | 2,277 | C# |
using System.Linq;
using Shouldly;
using StructureMap.Testing.Widget;
using Xunit;
namespace Lamar.Testing.IoC.Acceptance
{
public class use_if_none
{
[Fact]
public void add_the_registration_if_there_is_no_prior()
{
var container = new Container(x =>
{
x.For<IWidget>().UseIfNone<AWidget>();
});
container.GetInstance<IWidget>()
.ShouldBeOfType<AWidget>();
}
[Fact]
public void do_nothing_if_a_prior_registration()
{
var container = new Container(x =>
{
x.For<IWidget>().Use<BlueWidget>();
x.For<IWidget>().UseIfNone<AWidget>();
});
container.GetInstance<IWidget>()
.ShouldBeOfType<BlueWidget>();
container.Model.For<IWidget>().Instances.Count()
.ShouldBe(1);
}
[Fact]
public void add_the_registration_if_there_is_no_prior_with_actual_object()
{
var container = new Container(x =>
{
x.For<IWidget>().UseIfNone(new AWidget());
});
container.GetInstance<IWidget>()
.ShouldBeOfType<AWidget>();
}
[Fact]
public void do_nothing_if_a_prior_registration_with_actual_object()
{
var container = new Container(x =>
{
x.For<IWidget>().Use<BlueWidget>();
x.For<IWidget>().UseIfNone(new AWidget());
});
container.GetInstance<IWidget>()
.ShouldBeOfType<BlueWidget>();
container.Model.For<IWidget>().Instances.Count()
.ShouldBe(1);
}
}
} | 27.454545 | 82 | 0.50883 | [
"MIT"
] | Christoph-Wagner/lamar | src/Lamar.Testing/IoC/Acceptance/use_if_none.cs | 1,812 | C# |
using NUnit.Framework;
using System;
namespace Main.Test
{
public class MainTest
{
[Test]
public void Test()
{
Assert.True(true);
}
[TestCase(0)]
[TestCase(1)]
public void DataDrivenTest1(int i)
{
Assert.True(i > 0);
}
[TestCase(0)]
[TestCase(1)]
public void DataDrivenTest2(int i)
{
Assert.True(i >= 0);
}
[TestCaseSource("_items")]
public void SourceDataDrivenTest(int i)
{
Assert.True(i > 0);
}
[Test]
public void FailingTest()
{
Assert.AreEqual(1, 2);
}
[Test]
public void CheckStandardOutput()
{
int a = 1, b = 1;
Console.WriteLine($"a = {a}, b = {b}");
Assert.AreEqual(a,b);
}
public void UtilityFunction()
{
}
private static int[] _items = new int[1] { 1 };
}
}
| 18.321429 | 55 | 0.442495 | [
"MIT"
] | DasCleverle/omnisharp-roslyn | test-assets/test-projects/NUnitTestProject/TestProgram.cs | 1,026 | C# |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
using Microsoft.Azure.Commands.Blueprint.Common;
using Microsoft.WindowsAzure.Commands.Utilities.Common;
using Microsoft.Azure.Commands.Blueprint.Models;
using ParameterSetNames = Microsoft.Azure.Commands.Blueprint.Common.BlueprintConstants.ParameterSetNames;
using ParameterHelpMessages = Microsoft.Azure.Commands.Blueprint.Common.BlueprintConstants.ParameterHelpMessages;
namespace Microsoft.Azure.Commands.Blueprint.Cmdlets
{
[Cmdlet(VerbsCommon.Get, ResourceManager.Common.AzureRMConstants.AzureRMPrefix + "Blueprint", DefaultParameterSetName = ParameterSetNames.SubscriptionScope), OutputType(typeof(PSBlueprint),typeof(PSPublishedBlueprint))]
public class GetAzureRmBlueprint : BlueprintDefinitionCmdletBase
{
#region Parameters
[Parameter(ParameterSetName = ParameterSetNames.ByManagementGroupNameAndVersion, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = ParameterHelpMessages.BlueprintDefinitionName)]
[Parameter(ParameterSetName = ParameterSetNames.BySubscriptionAndName, Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = ParameterHelpMessages.BlueprintDefinitionName)]
[Parameter(ParameterSetName = ParameterSetNames.ByManagementGroupAndName, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = ParameterHelpMessages.BlueprintDefinitionName)]
[Parameter(ParameterSetName = ParameterSetNames.ByManagementGroupNameAndLatestPublished, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = ParameterHelpMessages.BlueprintDefinitionName)]
[Parameter(ParameterSetName = ParameterSetNames.BySubscriptionNameAndLatestPublished, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = ParameterHelpMessages.BlueprintDefinitionName)]
[Parameter(ParameterSetName = ParameterSetNames.BySubscriptionNameAndVersion, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = ParameterHelpMessages.BlueprintDefinitionVersion)]
[ValidateNotNullOrEmpty]
public string Name { get; set; }
[Parameter(ParameterSetName = ParameterSetNames.BySubscriptionAndName, Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = ParameterHelpMessages.DefinitionSubscriptionId)]
[Parameter(ParameterSetName = ParameterSetNames.BySubscriptionNameAndLatestPublished, Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = ParameterHelpMessages.DefinitionSubscriptionId)]
[Parameter(ParameterSetName = ParameterSetNames.BySubscriptionNameAndVersion, Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = ParameterHelpMessages.DefinitionSubscriptionId)]
[Parameter(ParameterSetName = ParameterSetNames.SubscriptionScope, Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = ParameterHelpMessages.DefinitionSubscriptionId)]
[ValidateNotNullOrEmpty]
public string SubscriptionId { get; set; }
[Parameter(ParameterSetName = ParameterSetNames.ByManagementGroupAndName, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = ParameterHelpMessages.DefinitionManagementGroupId)]
[Parameter(ParameterSetName = ParameterSetNames.ManagementGroupScope, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = ParameterHelpMessages.DefinitionManagementGroupId)]
[Parameter(ParameterSetName = ParameterSetNames.ByManagementGroupNameAndVersion, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = ParameterHelpMessages.DefinitionManagementGroupId)]
[Parameter(ParameterSetName = ParameterSetNames.ByManagementGroupNameAndLatestPublished, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = ParameterHelpMessages.DefinitionManagementGroupId)]
[ValidateNotNullOrEmpty]
public string ManagementGroupId { get; set; }
[Parameter(ParameterSetName = ParameterSetNames.BySubscriptionNameAndVersion, Position = 2, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = ParameterHelpMessages.BlueprintDefinitionVersion)]
[Parameter(ParameterSetName = ParameterSetNames.ByManagementGroupNameAndVersion, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = ParameterHelpMessages.BlueprintDefinitionVersion)]
[ValidateNotNullOrEmpty]
public string Version { get; set; }
[Parameter(ParameterSetName = ParameterSetNames.BySubscriptionNameAndLatestPublished, Mandatory = true, HelpMessage = ParameterHelpMessages.LatestPublishedFlag)]
[Parameter(ParameterSetName = ParameterSetNames.ByManagementGroupNameAndLatestPublished, Mandatory = true, HelpMessage = ParameterHelpMessages.LatestPublishedFlag)]
public SwitchParameter LatestPublished { get; set; }
#endregion Parameters
#region Cmdlet Overrides
public override void ExecuteCmdlet()
{
var scope = GetCurrentScope();
try
{
switch (ParameterSetName)
{
case ParameterSetNames.ManagementGroupScope:
foreach (var bp in BlueprintClientWithVersion.ListBlueprints(scope))
WriteObject(bp, true);
break;
case ParameterSetNames.SubscriptionScope:
var queryScopes =
GetManagementGroupAncestorsForSubscription(
SubscriptionId ?? DefaultContext.Subscription.Id)
.Select(mg => FormatManagementGroupAncestorScope(mg))
.ToList();
//add current subscription scope to the list of MG scopes that we'll query
queryScopes.Add(scope);
foreach (var bp in BlueprintClientWithVersion.ListBlueprints(queryScopes))
WriteObject(bp, true);
break;
case ParameterSetNames.BySubscriptionAndName: case ParameterSetNames.ByManagementGroupAndName:
WriteObject(BlueprintClientWithVersion.GetBlueprint(scope, Name));
break;
case ParameterSetNames.BySubscriptionNameAndVersion: case ParameterSetNames.ByManagementGroupNameAndVersion:
WriteObject(BlueprintClient.GetPublishedBlueprint(scope, Name, Version));
break;
case ParameterSetNames.BySubscriptionNameAndLatestPublished: case ParameterSetNames.ByManagementGroupNameAndLatestPublished:
WriteObject(BlueprintClient.GetLatestPublishedBlueprint(scope, Name));
break;
default:
throw new PSInvalidOperationException();
}
}
catch (Exception ex)
{
WriteExceptionError(ex);
}
}
#endregion Cmdlet Overrides
#region Private Methods
private string GetCurrentScope()
{
string scope = null;
if (this.IsParameterBound(c => c.ManagementGroupId))
{
scope = string.Format(BlueprintConstants.ManagementGroupScope, ManagementGroupId);
}
else
{
scope = this.IsParameterBound(c => c.SubscriptionId)
? string.Format(BlueprintConstants.SubscriptionScope, SubscriptionId)
: string.Format(BlueprintConstants.SubscriptionScope, DefaultContext.Subscription.Id);
}
return scope;
}
#endregion Private Methods
}
}
| 65.619403 | 224 | 0.694643 | [
"MIT"
] | 3quanfeng/azure-powershell | src/Blueprint/Blueprint/Cmdlets/BlueprintDefinition/GetAzureRMBlueprint.cs | 8,662 | C# |
using System;
using System.Linq;
using DynamicData.Tests.Domain;
using FluentAssertions;
using Xunit;
namespace DynamicData.Tests.List;
public class DeferAnsdSkipFixture
{
[Fact]
public void DeferUntilLoadedDoesNothingUntilDataHasBeenReceived()
{
bool updateReceived = false;
IChangeSet<Person>? result = null;
var cache = new SourceList<Person>();
var deferStream = cache.Connect().DeferUntilLoaded().Subscribe(
changes =>
{
updateReceived = true;
result = changes;
});
var person = new Person("Test", 1);
updateReceived.Should().BeFalse();
cache.Add(person);
updateReceived.Should().BeTrue();
if (result is null)
{
throw new InvalidOperationException(nameof(result));
}
result.Adds.Should().Be(1);
result.Unified().First().Current.Should().Be(person);
deferStream.Dispose();
}
[Fact]
public void SkipInitialDoesNotReturnTheFirstBatchOfData()
{
bool updateReceived = false;
var cache = new SourceList<Person>();
var deferStream = cache.Connect().SkipInitial().Subscribe(changes => updateReceived = true);
updateReceived.Should().BeFalse();
cache.Add(new Person("P1", 1));
updateReceived.Should().BeFalse();
cache.Add(new Person("P2", 2));
updateReceived.Should().BeTrue();
deferStream.Dispose();
}
}
| 22.969697 | 100 | 0.603562 | [
"MIT"
] | pdegenhardt/DynamicData | src/DynamicData.Tests/List/DeferUntilLoadedFixture.cs | 1,516 | C# |
using System.Data.Entity;
namespace Liyanjie.FakeMQ
{
/// <summary>
///
/// </summary>
public class FakeMQDbContext : DbContext
{
/// <summary>
///
/// </summary>
/// <param name="nameOrConnectionString"></param>
public FakeMQDbContext(string nameOrConnectionString)
: base(nameOrConnectionString) { }
/// <summary>
///
/// </summary>
public IDbSet<FakeMQEvent> FakeMQEvents { get; set; }
/// <summary>
///
/// </summary>
public IDbSet<FakeMQProcess> FakeMQProcesses { get; set; }
/// <summary>
///
/// </summary>
/// <param name="modelBuilder"></param>
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
var fakeMQEventTypeBuilder = modelBuilder.Entity<FakeMQEvent>();
fakeMQEventTypeBuilder.HasKey(_ => _.CreateTime);
fakeMQEventTypeBuilder.Property(_ => _.Type).IsRequired().HasMaxLength(50);
fakeMQEventTypeBuilder.Property(_ => _.Message).IsRequired();
fakeMQEventTypeBuilder.HasIndex(_ => _.Type);
var fakeMQProcessTypeBuilder = modelBuilder.Entity<FakeMQProcess>();
fakeMQProcessTypeBuilder.HasKey(_ => _.HandlerType);
fakeMQProcessTypeBuilder.Property(_ => _.HandlerType).HasMaxLength(200);
}
}
}
| 31.425532 | 87 | 0.586324 | [
"MIT"
] | liyanjie8712/FakeMQ | src/Liyanjie.FakeMQ.EntityFramework/FakeMQDbContext.cs | 1,479 | C# |
using System.Collections.Generic;
using System.IO;
using Serilog.Events;
using Serilog.Formatting;
namespace CodeStream.VisualStudio.Core.Logging.Sanitizer {
public class LogSanitizingFormatter : ITextFormatter {
private readonly IProcessor _processor;
private readonly IEnumerable<ISanitizingFormatRule> _sanitizingFormatRules;
private readonly ITextFormatter _textFormatter;
private readonly bool _sanitizeLogContent;
public LogSanitizingFormatter(IProcessor processor, IEnumerable<ISanitizingFormatRule> sanitizingFormatRules, ITextFormatter jsonFormatter, bool sanitizeLogContent = true) {
_processor = processor;
_sanitizingFormatRules = sanitizingFormatRules;
_textFormatter = jsonFormatter;
_sanitizeLogContent = sanitizeLogContent;
}
public void Format(LogEvent logEvent, TextWriter output) {
if (_sanitizeLogContent) {
var tempTextWriter = new StringWriter();
_textFormatter.Format(logEvent, tempTextWriter);
output.WriteLine(_processor.Process(tempTextWriter.GetStringBuilder().ToString(), _sanitizingFormatRules));
}
else {
_textFormatter.Format(logEvent, output);
}
}
}
}
| 34.909091 | 175 | 0.796007 | [
"Apache-2.0"
] | Craigdigital/codestream | vs/src/CodeStream.VisualStudio.Core/Logging/Sanitizer/LogSanitizingFormatter.cs | 1,154 | C# |
namespace M3U8.Parser.Core
{
internal static class M3UAttributes
{
public const char TagIdentifier = '#';
public const char TagSeparator = ':';
public const char PairSeparator = '=';
public const char AttributeSeparator = ',';
public const string Header = "#EXTM3U";
public const string Key = "#EXT-X-KEY";
public const string Version = "#EXT-X-VERSION";
public const string AllowCache = "#EXT-X-ALLOW-CACHE";
public const string PlaylistType = "#EXT-X-PLAYLIST-TYPE";
public const string MediaSequence = "#EXT-X-MEDIA-SEQUENCE";
public const string TargetDuration = "#EXT-X-TARGETDURATION";
public const string ProgramDateTime = "#EXT-X-PROGRAM-DATE-TIME";
public const string Inf = "#EXTINF";
public const string StreamInf = "#EXT-X-STREAM-INF";
public const string EndList = "#EXT-X-ENDLIST";
public static class Predicates
{
public const string Yes = "YES";
public const string No = "NO";
}
public static class EncryptionMethods
{
public const string None = "NONE";
public const string AES128 = "AES-128";
}
public static class PlaylistTypes
{
public const string Event = "EVENT";
public const string VideoOnDemand = "VOD";
}
public static class KeyAttributes
{
public const string Method = "METHOD";
public const string Uri = "URI";
public const string IV = "IV";
}
public static class StreamInfAttributes
{
public const string Codecs = "CODECS";
public const string Bandwidth = "BANDWIDTH";
public const string ProgramId = "PROGRAM-ID";
public const string Resolution = "RESOLUTION";
}
}
} | 38.074074 | 76 | 0.544261 | [
"MIT"
] | xixixixixiao/m3u8-parser | src/M3U8.Parser/Core/M3UAttributes.cs | 2,058 | C# |
using System;
namespace Bridge.Html5
{
/// <summary>
/// types of Node that must to be presented
/// </summary>
[Flags]
[External]
[Enum(Emit.Value)]
[Name("Number")]
public enum NodeFilter
{
/// <summary>
/// Shows all nodes.
/// </summary>
ShowAll = -1,
/// <summary>
/// Shows attribute Attr nodes. This is meaningful only when creating a NodeIterator with an Attr node as its root; in this case, it means that the attribute node will appear in the first position of the iteration or traversal. Since attributes are never children of other nodes, they do not appear when traversing over the document tree.
/// </summary>
ShowAttribute = 2,
/// <summary>
/// Shows CDATASection nodes.
/// </summary>
ShowCdataSection = 8,
/// <summary>
/// Shows Comment nodes.
/// </summary>
ShowComment = 128,
/// <summary>
/// Shows Document nodes.
/// </summary>
ShowDocument = 256,
/// <summary>
/// Shows DocumentFragment nodes.
/// </summary>
ShowDocumentFragment = 1024,
/// <summary>
/// Shows DocumentType nodes.
/// </summary>
ShowDocumentType = 512,
/// <summary>
/// Shows Element nodes.
/// </summary>
ShowElement = 1,
/// <summary>
/// Shows Entity nodes. This is meaningful only when creating a NodeIterator with an Entity node as its root; in this case, it means that the Entity node will appear in the first position of the traversal. Since entities are not part of the document tree, they do not appear when traversing over the document tree.
/// </summary>
ShowEntity = 32,
/// <summary>
/// Shows EntityReference nodes.
/// </summary>
ShowEntityReference = 16,
/// <summary>
/// Shows Notation nodes. This is meaningful only when creating a NodeIterator with a Notation node as its root; in this case, it means that the Notation node will appear in the first position of the traversal. Since entities are not part of the document tree, they do not appear when traversing over the document tree.
/// </summary>
ShowNotation = 2048,
/// <summary>
/// Shows ProcessingInstruction nodes.
/// </summary>
ShowProcessingInstruction = 64,
/// <summary>
/// Shows Text nodes.
/// </summary>
ShowText = 4
}
} | 32.56962 | 346 | 0.58492 | [
"Apache-2.0"
] | Angolar/Bridge | Html5/NodeFilter.cs | 2,573 | C# |
using System.Globalization;
using System.Linq;
using System.Web.Http;
using System.Web.Http.Description;
using Swashbuckle.Application;
using Swashbuckle.Swagger;
using WebActivatorEx;
using RimshotBackend;
[assembly: PreApplicationStartMethod(typeof(SwaggerConfig), "Register")]
namespace RimshotBackend
{
public class SwaggerConfig
{
public static void Register()
{
var thisAssembly = typeof(SwaggerConfig).Assembly;
GlobalConfiguration.Configuration
.EnableSwagger(c =>
{
// By default, the service root url is inferred from the request used to access the docs.
// However, there may be situations (e.g. proxy and load-balanced environments) where this does not
// resolve correctly. You can workaround this by providing your own code to determine the root URL.
//
//c.RootUrl(req => GetRootUrlFromAppConfig());
// If schemes are not explicitly provided in a Swagger 2.0 document, then the scheme used to access
// the docs is taken as the default. If your API supports multiple schemes and you want to be explicit
// about them, you can use the "Schemes" option as shown below.
//
//c.Schemes(new[] { "http", "https" });
// Use "SingleApiVersion" to describe a single version API. Swagger 2.0 includes an "Info" object to
// hold additional metadata for an API. Version and title are required but you can also provide
// additional fields by chaining methods off SingleApiVersion.
//
c.SingleApiVersion("v1", "RimshotBackend");
// If your API has multiple versions, use "MultipleApiVersions" instead of "SingleApiVersion".
// In this case, you must provide a lambda that tells Swashbuckle which actions should be
// included in the docs for a given API version. Like "SingleApiVersion", each call to "Version"
// returns an "Info" builder so you can provide additional metadata per API version.
//
//c.MultipleApiVersions(
// (apiDesc, targetApiVersion) => ResolveVersionSupportByRouteConstraint(apiDesc, targetApiVersion),
// (vc) =>
// {
// vc.Version("v2", "Swashbuckle Dummy API V2");
// vc.Version("v1", "Swashbuckle Dummy API V1");
// });
// You can use "BasicAuth", "ApiKey" or "OAuth2" options to describe security schemes for the API.
// See https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md for more details.
// NOTE: These only define the schemes and need to be coupled with a corresponding "security" property
// at the document or operation level to indicate which schemes are required for an operation. To do this,
// you'll need to implement a custom IDocumentFilter and/or IOperationFilter to set these properties
// according to your specific authorization implementation
//
//c.BasicAuth("basic")
// .Description("Basic HTTP Authentication");
//
//c.ApiKey("apiKey")
// .Description("API Key Authentication")
// .Name("apiKey")
// .In("header");
//
//c.OAuth2("oauth2")
// .Description("OAuth2 Implicit Grant")
// .Flow("implicit")
// .AuthorizationUrl("http://petstore.swagger.wordnik.com/api/oauth/dialog")
// //.TokenUrl("https://tempuri.org/token")
// .Scopes(scopes =>
// {
// scopes.Add("read", "Read access to protected resources");
// scopes.Add("write", "Write access to protected resources");
// });
// Set this flag to omit descriptions for any actions decorated with the Obsolete attribute
//c.IgnoreObsoleteActions();
// Each operation be assigned one or more tags which are then used by consumers for various reasons.
// For example, the swagger-ui groups operations according to the first tag of each operation.
// By default, this will be controller name but you can use the "GroupActionsBy" option to
// override with any value.
//
//c.GroupActionsBy(apiDesc => apiDesc.HttpMethod.ToString());
// You can also specify a custom sort order for groups (as defined by "GroupActionsBy") to dictate
// the order in which operations are listed. For example, if the default grouping is in place
// (controller name) and you specify a descending alphabetic sort order, then actions from a
// ProductsController will be listed before those from a CustomersController. This is typically
// used to customize the order of groupings in the swagger-ui.
//
//c.OrderActionGroupsBy(new DescendingAlphabeticComparer());
// Swashbuckle makes a best attempt at generating Swagger compliant JSON schemas for the various types
// exposed in your API. However, there may be occasions when more control of the output is needed.
// This is supported through the "MapType" and "SchemaFilter" options:
//
// Use the "MapType" option to override the Schema generation for a specific type.
// It should be noted that the resulting Schema will be placed "inline" for any applicable Operations.
// While Swagger 2.0 supports inline definitions for "all" Schema types, the swagger-ui tool does not.
// It expects "complex" Schemas to be defined separately and referenced. For this reason, you should only
// use the "MapType" option when the resulting Schema is a primitive or array type. If you need to alter a
// complex Schema, use a Schema filter.
//
//c.MapType<ProductType>(() => new Schema { type = "integer", format = "int32" });
//
// If you want to post-modify "complex" Schemas once they've been generated, across the board or for a
// specific type, you can wire up one or more Schema filters.
//
//c.SchemaFilter<ApplySchemaVendorExtensions>();
// Set this flag to omit schema property descriptions for any type properties decorated with the
// Obsolete attribute
//c.IgnoreObsoleteProperties();
// In a Swagger 2.0 document, complex types are typically declared globally and referenced by unique
// Schema Id. By default, Swashbuckle does NOT use the full type name in Schema Ids. In most cases, this
// works well because it prevents the "implementation detail" of type namespaces from leaking into your
// Swagger docs and UI. However, if you have multiple types in your API with the same class name, you'll
// need to opt out of this behavior to avoid Schema Id conflicts.
//
//c.UseFullTypeNameInSchemaIds();
// In accordance with the built in JsonSerializer, Swashbuckle will, by default, describe enums as integers.
// You can change the serializer behavior by configuring the StringToEnumConverter globally or for a given
// enum type. Swashbuckle will honor this change out-of-the-box. However, if you use a different
// approach to serialize enums as strings, you can also force Swashbuckle to describe them as strings.
//
//c.DescribeAllEnumsAsStrings();
// Similar to Schema filters, Swashbuckle also supports Operation and Document filters:
//
// Post-modify Operation descriptions once they've been generated by wiring up one or more
// Operation filters.
//
//c.OperationFilter<AddDefaultResponse>();
//
// If you've defined an OAuth2 flow as described above, you could use a custom filter
// to inspect some attribute on each action and infer which (if any) OAuth2 scopes are required
// to execute the operation
//
//c.OperationFilter<AssignOAuth2SecurityRequirements>();
//
// Set filter to eliminate duplicate operation ids from being generated
// when there are multiple operations with the same verb in the API.
//
c.OperationFilter<IncludeParameterNamesInOperationIdFilter>();
// Post-modify the entire Swagger document by wiring up one or more Document filters.
// This gives full control to modify the final SwaggerDocument. You should have a good understanding of
// the Swagger 2.0 spec. - https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md
// before using this option.
//
//c.DocumentFilter<ApplyDocumentVendorExtensions>();
// If you annonate Controllers and API Types with
// Xml comments (http://msdn.microsoft.com/en-us/library/b2s063f7(v=vs.110).aspx), you can incorporate
// those comments into the generated docs and UI. You can enable this by providing the path to one or
// more Xml comment files.
//
//c.IncludeXmlComments(GetXmlCommentsPath());
// In contrast to WebApi, Swagger 2.0 does not include the query string component when mapping a URL
// to an action. As a result, Swashbuckle will raise an exception if it encounters multiple actions
// with the same path (sans query string) and HTTP method. You can workaround this by providing a
// custom strategy to pick a winner or merge the descriptions for the purposes of the Swagger docs
//
//c.ResolveConflictingActions(apiDescriptions => apiDescriptions.First());
// ***** Uncomment the following to enable the swagger UI *****
})
.EnableSwaggerUi(c =>
{
// Use the "InjectStylesheet" option to enrich the UI with one or more additional CSS stylesheets.
// The file must be included in your project as an "Embedded Resource", and then the resource's
// "Logical Name" is passed to the method as shown below.
//
//c.InjectStylesheet(containingAssembly, "Swashbuckle.Dummy.SwaggerExtensions.testStyles1.css");
// Use the "InjectJavaScript" option to invoke one or more custom JavaScripts after the swagger-ui
// has loaded. The file must be included in your project as an "Embedded Resource", and then the resource's
// "Logical Name" is passed to the method as shown above.
//
//c.InjectJavaScript(thisAssembly, "Swashbuckle.Dummy.SwaggerExtensions.testScript1.js");
// The swagger-ui renders boolean data types as a dropdown. By default, it provides "true" and "false"
// strings as the possible choices. You can use this option to change these to something else,
// for example 0 and 1.
//
//c.BooleanValues(new[] { "0", "1" });
// Use this option to control how the Operation listing is displayed.
// It can be set to "None" (default), "List" (shows operations for each resource),
// or "Full" (fully expanded: shows operations and their details).
//
//c.DocExpansion(DocExpansion.List);
// Use the CustomAsset option to provide your own version of assets used in the swagger-ui.
// It's typically used to instruct Swashbuckle to return your version instead of the default
// when a request is made for "index.html". As with all custom content, the file must be included
// in your project as an "Embedded Resource", and then the resource's "Logical Name" is passed to
// the method as shown below.
//
//c.CustomAsset("index", containingAssembly, "YourWebApiProject.SwaggerExtensions.index.html");
// If your API has multiple versions and you've applied the MultipleApiVersions setting
// as described above, you can also enable a select box in the swagger-ui, that displays
// a discovery URL for each version. This provides a convenient way for users to browse documentation
// for different API versions.
//
//c.EnableDiscoveryUrlSelector();
// If your API supports the OAuth2 Implicit flow, and you've described it correctly, according to
// the Swagger 2.0 specification, you can enable UI support as shown below.
//
//c.EnableOAuth2Support("test-client-id", "test-realm", "Swagger UI");
});
}
}
internal class IncludeParameterNamesInOperationIdFilter : IOperationFilter
{
public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
{
if (operation.parameters != null)
{
// Select the capitalized parameter names
var parameters = operation.parameters.Select(
p => CultureInfo.InvariantCulture.TextInfo.ToTitleCase(p.name));
// Set the operation id to match the format "OperationByParam1AndParam2"
operation.operationId = string.Format(
"{0}By{1}",
operation.operationId,
string.Join("And", parameters));
}
}
}
} | 65.717213 | 132 | 0.53932 | [
"Apache-2.0"
] | dupuyjs/rimshot | Backend/RimshotBackend/App_Start/SwaggerConfig.cs | 16,037 | C# |
using System;
using System.Collections.Generic;
namespace EqualityComparer.Abstractions
{
public class InlineComparer<T> : IEqualityComparer<T>
{
private readonly Func<T, T, bool> getEquals;
private readonly Func<T, int> getHashCode;
public InlineComparer(Func<T, T, bool> equals, Func<T, int> hashCode)
{
getEquals = equals;
getHashCode = hashCode;
}
public bool Equals(T x, T y)
{
return getEquals(x, y);
}
public int GetHashCode(T obj)
{
return getHashCode(obj);
}
}
}
| 22.321429 | 77 | 0.5696 | [
"MIT"
] | Admiraculix/QB.Interview.Task | EqualityComparer.Abstractions/InlineComparer.cs | 627 | C# |
using System.Collections.Generic;
namespace Lpp.Audit.UI
{
public interface IAuditPropertyValueSelector<TProperty>
{
IEnumerable<IAuditProperty<TProperty>> AppliesTo { get; }
ClientControlDisplay RenderSelector( TProperty initialState );
TProperty ParsePostedValue( string value );
}
} | 29.363636 | 70 | 0.73065 | [
"Apache-2.0"
] | Missouri-BMI/popmednet | Lpp.Mvc.Composition/Lpp.Audit.UI/Interfaces/IAuditPropertyValueSelector.cs | 325 | C# |
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.XR.ARSubsystems;
using UnityEngine.XR.ARFoundation;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class PlaceContent : MonoBehaviour {
public ARRaycastManager raycastManager;
public GraphicRaycaster raycaster;
bool wasDoubleTouch;
void Update() {
if (Input.GetMouseButtonDown(0)) {
wasDoubleTouch = false;
}
if (Input.GetMouseButtonDown(1)) {
wasDoubleTouch = true;
}
if (Input.GetMouseButtonUp(0) && !IsClickOverUI() && !wasDoubleTouch) {
List<ARRaycastHit> hitPoints = new List<ARRaycastHit>();
raycastManager.Raycast(Input.mousePosition, hitPoints, TrackableType.Planes);
if (hitPoints.Count > 0) {
Pose pose = hitPoints[0].pose;
transform.rotation = pose.rotation;
transform.position = pose.position;
}
}
}
bool IsClickOverUI() {
//dont place content if pointer is over ui element
PointerEventData data = new PointerEventData(EventSystem.current) {
position = Input.mousePosition
};
List<RaycastResult> results = new List<RaycastResult>();
raycaster.Raycast(data, results);
return results.Count > 0;
}
}
| 28.520833 | 89 | 0.628196 | [
"MIT"
] | HaraldHeide/Nreal-ShaderGraph | TransparentVideoShaderMatthew/Scripts/PlaceContent.cs | 1,371 | C# |
using System;
using System.IO;
using log4net;
using Castle.MicroKernel;
using Castle.Services.Transaction;
namespace Cuyahoga.Core.Service.Files
{
/// <summary>
/// Transactional implementation of the <see cref="IFileService">IFileService</see> interface.
/// </summary>
public class TransactionalFileService : IFileService
{
private static readonly ILog log = LogManager.GetLogger(typeof(TransactionalFileService));
private string _tempDir;
private IKernel _kernel;
/// <summary>
/// Physical path for temporary file storage
/// </summary>
public string TempDir
{
set { this._tempDir = value; }
}
/// <summary>
/// Constructor.
/// </summary>
public TransactionalFileService(IKernel kernel)
{
this._kernel = kernel;
this._kernel.AddComponent("core.fileservice.transactionmanager", typeof(ITransactionManager), typeof(FileTransactionManager));
}
#region IFileService Members
public Stream ReadFile(string filePath)
{
try
{
FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
return fs;
}
catch (FileNotFoundException ex)
{
log.Error("File not found.", ex);
throw;
}
catch (Exception ex)
{
log.Error("An unexpected error occured while reading a file.", ex);
throw;
}
}
public void WriteFile(string filePath, Stream fileContents)
{
ITransaction transaction = ObtainCurrentTransaction();
if (transaction != null)
{
// We're participating in a transaction, use the FileWriter to write the file.
FileWriter fileWriter = new FileWriter(this._tempDir);
transaction.Enlist(fileWriter);
fileWriter.CreateFromStream(filePath, fileContents);
}
else
{
// No transaction, just write the stream to a file.
FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write);
StreamUtil.Copy(fileContents, fs);
fs.Flush();
fs.Close();
}
}
public void DeleteFile(string filePath)
{
ITransaction transaction = ObtainCurrentTransaction();
if (transaction != null)
{
// We're participating in a transaction, use the FileWriter to delete the file.
FileWriter fileWriter = new FileWriter(this._tempDir);
transaction.Enlist(fileWriter);
fileWriter.DeleteFile(filePath);
}
else
{
// No transaction, just delete the file.
File.Delete(filePath);
}
}
public bool CheckIfDirectoryIsWritable(string physicalDirectory)
{
// Check if the given directory is writable by creating a dummy file.
string fileName = Path.Combine(physicalDirectory, "dummy.txt");
try
{
using (StreamWriter sw = new StreamWriter(fileName))
{
// Add some text to the file.
sw.WriteLine("DUMMY");
sw.Flush();
}
File.Delete(fileName);
return true;
}
catch (UnauthorizedAccessException)
{
log.WarnFormat("Checking access to physical directory {0} resulted in no access.", physicalDirectory);
return false;
}
catch (Exception ex)
{
log.Error(String.Format("An unexpected error occured while checking write access for the directory {0}.", physicalDirectory), ex);
throw;
}
}
#endregion
private ITransaction ObtainCurrentTransaction()
{
ITransactionManager transactionManager = this._kernel[typeof(ITransactionManager)] as ITransactionManager;
return transactionManager.CurrentTransaction;
}
}
}
| 26.757576 | 135 | 0.674405 | [
"BSD-3-Clause"
] | dineshkummarc/cuyahoga-1 | Core/Service/Files/TransactionalFileService.cs | 3,532 | C# |
using System;
using Concepts.TodoItem;
using Dolittle.Domain;
using Dolittle.Runtime.Events;
using Events.TodoItem;
namespace Domain.TodoItem
{
public class TodoList : AggregateRoot
{
public TodoList(EventSourceId id) : base(id)
{
}
public void Add(TodoText text)
{
var createdEvent = new ItemCreated(
EventSourceId,
text
);
Apply(createdEvent);
}
public void Remove(TodoText text)
{
var createdEvent = new ItemRemoved(
EventSourceId,
text
);
Apply(createdEvent);
}
public void MarkAsDone(TodoText text)
{
var createdEvent = new ItemDone(
EventSourceId,
text
);
Apply(createdEvent);
}
public void MarkAsNotDone(TodoText text)
{
var createdEvent = new ItemNotDone(
EventSourceId,
text
);
Apply(createdEvent);
}
}
}
| 20.017544 | 52 | 0.486415 | [
"MIT"
] | TomasEkeli/ToDolittle | TodoTracking/Domain/TodoItem/TodoList.cs | 1,141 | 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.Composition;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Remote;
using Microsoft.CodeAnalysis.Telemetry;
using Microsoft.VisualStudio.Telemetry;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Telemetry
{
[ExportWorkspaceService(typeof(IWorkspaceTelemetryService)), Shared]
internal sealed class VisualStudioWorkspaceTelemetryService : AbstractWorkspaceTelemetryService
{
private readonly VisualStudioWorkspace _workspace;
private readonly IGlobalOptionService _globalOptions;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public VisualStudioWorkspaceTelemetryService(
VisualStudioWorkspace workspace,
IGlobalOptionService globalOptions)
{
_workspace = workspace;
_globalOptions = globalOptions;
}
protected override ILogger CreateLogger(TelemetrySession telemetrySession)
=> AggregateLogger.Create(
CodeMarkerLogger.Instance,
new EtwLogger(FunctionIdOptions.CreateFunctionIsEnabledPredicate(_globalOptions)),
TelemetryLogger.Create(telemetrySession, _globalOptions),
new FileLogger(_globalOptions),
Logger.GetLogger());
protected override void TelemetrySessionInitialized()
{
_ = Task.Run(async () =>
{
var client = await RemoteHostClient.TryGetClientAsync(_workspace, CancellationToken.None).ConfigureAwait(false);
if (client == null)
{
return;
}
var settings = SerializeCurrentSessionSettings();
Contract.ThrowIfNull(settings);
// initialize session in the remote service
_ = await client.TryInvokeAsync<IRemoteProcessTelemetryService>(
(service, cancellationToken) => service.InitializeTelemetrySessionAsync(Process.GetCurrentProcess().Id, settings, cancellationToken),
CancellationToken.None).ConfigureAwait(false);
});
}
}
}
| 39.590909 | 153 | 0.687333 | [
"MIT"
] | AlexanderSemenyak/roslyn | src/VisualStudio/Core/Def/Telemetry/VisualStudioWorkspaceTelemetryService.cs | 2,615 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using YamlConfiguration;
namespace demo02
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.ConfigureAppConfiguration((hostingContext, config) =>
{
config.AddYamlFile("configuration/appsettings.yaml");
});
webBuilder.UseUrls("http://*:81");
webBuilder.UseStartup<Startup>();
});
}
}
| 30.30303 | 84 | 0.587 | [
"MIT"
] | axzxs2001/.net-conf-2019-samples | dotnetconfsamples/demo02/Program.cs | 1,000 | C# |
using System;
namespace R5T.Kallithea.Extensions.Construction
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
}
| 16.692308 | 48 | 0.534562 | [
"MIT"
] | MinexAutomation/R5T.Kallithea.Extensions | source/R5T.Kallithea.Extensions.Construction/Code/Program.cs | 219 | C# |
using System;
using System.Security.Claims;
using System.Threading.Tasks;
using ARunner.Auth;
using ARunner.DataLayer.Model;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
namespace ARunner.Auth
{
public class AccessRequired : IAuthorizationRequirement
{
public UserAccess Access { get; }
public AccessRequired(UserAccess access)
{
Access = access;
}
}
}
public class AccessRequiredHandler : AuthorizationHandler<AccessRequired>
{
private readonly UserManager<User> _manager;
public AccessRequiredHandler(UserManager<User> manager)
{
_manager = manager;
}
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, AccessRequired requirement)
{
var user = _manager.GetUserAsync(context.User).Result;
if (requirement.Access <= user.Access)
{
context.Succeed(requirement);
}
return Task.CompletedTask;
}
} | 24.261905 | 115 | 0.692836 | [
"MIT"
] | AbabeiAndrei/ARunner | src/ARunner/Auth/AccessRequired.cs | 1,019 | C# |
using UnityEngine;
namespace PiRhoSoft.UtilityEngine
{
public class SliderAttribute : PropertyAttribute
{
public float MinimumValue { get; private set; }
public float MaximumValue { get; private set; }
public float SnapValue { get; private set; }
public SliderAttribute(float minValue, float maxValue, float snapValue = 0.0f)
{
MinimumValue = minValue;
MaximumValue = maxValue;
SnapValue = snapValue;
}
public SliderAttribute(int minValue, int maxValue, int snapValue = 0)
{
MinimumValue = minValue;
MaximumValue = maxValue;
SnapValue = snapValue;
}
}
}
| 22.961538 | 80 | 0.721943 | [
"MIT"
] | larsolm/Archives | Monster RPG Game Kit/MonsterRPGGameKit/Assets/PiRhoSoft Utilities/Scripts/Engine/Attributes/Slider.cs | 599 | C# |
using Sitrion.Security.KeyVault;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Sitrion.Security.KeyVault.Test
{
public class TestUtil
{
public static readonly IAdalTokenProvider Auth =
new SecretAuthentication(
ConfigurationManager.AppSettings["keyvault-clientid1"],
ConfigurationManager.AppSettings["keyvault-secret1"]);
}
}
| 26.368421 | 71 | 0.720559 | [
"MIT"
] | danlarson/sitrion.security | Sitrion.Security.KeyVault.Test/TestUtil.cs | 503 | C# |
using System;
using System.Collections.Generic;
using UnityEngine;
using Zenject;
namespace Game.Common.Areas
{
public class AreaSystem : MonoBehaviour
{
public event Action OnPlayerEntered;
public event Action OnPlayerLeft;
public event Action<Stat, float> OnStatUpdated;
[Inject]
private EntityState _playerState;
private List<Area> _areas = new List<Area>();
private readonly List<Area> _areasPresent = new List<Area>();
public bool IsPlayerInArea => _areasPresent.Count > 0;
public Area CurrentArea => _areasPresent.Count > 0 ? _areasPresent[0] : null;
private void OnEnable ()
{
_playerState.OnRespawned += OnPlayerRespawn;
foreach (var area in _areas)
area.OnStatUpdated += OnStatUpdated;
}
private void OnDisable ()
{
_playerState.OnRespawned -= OnPlayerRespawn;
foreach (var area in _areas)
area.OnStatUpdated -= OnStatUpdated;
}
public void ResetAllAreas ()
{
List<Area> areas = new List<Area>(_areas.Count);
for (int i = _areas.Count - 1; i >= 0; i--) {
Area area = _areas[i];
if (!area.CanBeDestroyed) {
areas.Add(area);
continue;
}
Destroy(area.gameObject);
}
_areas = areas;
_areasPresent.Clear();
}
public void AddArea(Area area)
{
if (area == null || _areas.Contains(area))
return;
_areas.Add(area);
area.OnStatUpdated += NotifyStatUpdated;
area.OnPlayerEntered += OnPlayerAreaEnter;
area.OnPlayerLeft += OnPlayerAreaExit;
}
public void RemoveArea(Area area)
{
if (area == null || !_areas.Contains(area))
return;
_areas.Remove(area);
area.OnStatUpdated -= NotifyStatUpdated;
area.OnPlayerEntered -= OnPlayerAreaEnter;
area.OnPlayerLeft -= OnPlayerAreaExit;
}
private void OnPlayerRespawn (EntityState state) => ResetAllAreas();
private void OnPlayerAreaEnter (Area area)
{
if (!_areasPresent.Contains(area))
_areasPresent.Add(area);
}
private void OnPlayerAreaExit (Area area)
{
if (_areasPresent.Contains(area))
_areasPresent.Remove(area);
}
private void NotifyStatUpdated(Stat stat, float value) => OnStatUpdated?.Invoke(stat, value);
}
} | 27.272727 | 101 | 0.554444 | [
"MIT"
] | ggj22-redacted/two-health-bars | Assets/Game/Common/Areas/AreaSystem.cs | 2,702 | C# |
// ***********************************************************************
// Copyright (c) 2007 Charlie Poole, Rob Prouse
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
using System;
using System.Collections;
using System.Collections.Generic;
namespace NUnit.TestUtilities.Collections
{
/// <summary>
/// SimpleObjectCollection is used in testing to ensure that only
/// methods of the ICollection interface are accessible.
/// </summary>
class SimpleObjectList : IList
{
private readonly List<object> contents = new List<object>();
public SimpleObjectList(IEnumerable<object> source)
{
this.contents = new List<object>(source);
}
public SimpleObjectList(params object[] source)
{
this.contents = new List<object>(source);
}
#region ICollection Members
public void CopyTo(Array array, int index)
{
((ICollection)contents).CopyTo(array, index);
}
public int Count
{
get { return contents.Count; }
}
public bool IsSynchronized
{
get { return ((ICollection)contents).IsSynchronized; }
}
public object SyncRoot
{
get { return ((ICollection)contents).SyncRoot; }
}
#endregion
#region IEnumerable Members
public IEnumerator GetEnumerator()
{
return contents.GetEnumerator();
}
#endregion
#region IList Members
public int Add(object value)
{
contents.Add(value);
return contents.Count - 1;
}
public void Clear()
{
contents.Clear();
}
public bool Contains(object value)
{
return contents.Contains(value);
}
public int IndexOf(object value)
{
return contents.IndexOf(value);
}
public void Insert(int index, object value)
{
contents.Insert(index, value);
}
public bool IsFixedSize
{
get { return false; }
}
public bool IsReadOnly
{
get { return false; }
}
public void Remove(object value)
{
contents.Remove(value);
}
public void RemoveAt(int index)
{
contents.RemoveAt(index);
}
public object this[int index]
{
get { return contents[index]; }
set { contents[index] = value; }
}
#endregion
}
}
| 27.086957 | 74 | 0.575976 | [
"MIT"
] | Acidburn0zzz/nunit | src/NUnitFramework/tests/TestUtilities/Collections/SimpleObjectList.cs | 3,738 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Cross.DataVault.Helpers")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Cross.DataVault.Helpers")]
[assembly: AssemblyCopyright("Copyright © 2018")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("27475454-5858-4ee3-a821-57d7cdc64312")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.216216 | 84 | 0.748939 | [
"Apache-2.0"
] | TheArchitect123/MiniVault---XamarinForms | Cross.DataVault/Cross.DataVault.Helpers/Properties/AssemblyInfo.cs | 1,417 | C# |
namespace P03_BarraksWars.Core.Commands
{
using System;
public class Fight : Command
{
public Fight(string[] data/*, IRepository repository, IUnitFactory unitFactory*/)
: base(data/*, repository, unitFactory*/)
{
}
public override string Execute()
{
Environment.Exit(0);
return string.Empty;
}
}
} | 21.157895 | 90 | 0.557214 | [
"MIT"
] | pirocorp/C-OOP-Advanced | 04. Reflection and Attributes/04. Reflection and Attributes - Exercise/P03_BarraksWars/Core/Commands/Fight.cs | 404 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace BuldingCustomController.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
}
} | 19.666667 | 67 | 0.572881 | [
"MIT"
] | flaviogf/Cursos | pluralsight/themvcrequestlifecycle/Section4/BuldingCustomController/Controllers/HomeController.cs | 592 | 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.
namespace Microsoft.OneDrive.Sdk
{
using System;
using System.IO;
using System.Net.Http;
using System.Threading;
using Microsoft.Graph;
/// <summary>
/// The interface IThumbnailSetRequest.
/// </summary>
public partial interface IThumbnailSetRequest : IBaseRequest
{
/// <summary>
/// Creates the specified ThumbnailSet using PUT.
/// </summary>
/// <param name="thumbnailSetToCreate">The ThumbnailSet to create.</param>
/// <returns>The created ThumbnailSet.</returns>
System.Threading.Tasks.Task<ThumbnailSet> CreateAsync(ThumbnailSet thumbnailSetToCreate); /// <summary>
/// Creates the specified ThumbnailSet using PUT.
/// </summary>
/// <param name="thumbnailSetToCreate">The ThumbnailSet to create.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The created ThumbnailSet.</returns>
System.Threading.Tasks.Task<ThumbnailSet> CreateAsync(ThumbnailSet thumbnailSetToCreate, CancellationToken cancellationToken);
/// <summary>
/// Deletes the specified ThumbnailSet.
/// </summary>
/// <returns>The task to await.</returns>
System.Threading.Tasks.Task DeleteAsync();
/// <summary>
/// Deletes the specified ThumbnailSet.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The task to await.</returns>
System.Threading.Tasks.Task DeleteAsync(CancellationToken cancellationToken);
/// <summary>
/// Gets the specified ThumbnailSet.
/// </summary>
/// <returns>The ThumbnailSet.</returns>
System.Threading.Tasks.Task<ThumbnailSet> GetAsync();
/// <summary>
/// Gets the specified ThumbnailSet.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The ThumbnailSet.</returns>
System.Threading.Tasks.Task<ThumbnailSet> GetAsync(CancellationToken cancellationToken);
/// <summary>
/// Updates the specified ThumbnailSet using PATCH.
/// </summary>
/// <param name="thumbnailSetToUpdate">The ThumbnailSet to update.</param>
/// <returns>The updated ThumbnailSet.</returns>
System.Threading.Tasks.Task<ThumbnailSet> UpdateAsync(ThumbnailSet thumbnailSetToUpdate);
/// <summary>
/// Updates the specified ThumbnailSet using PATCH.
/// </summary>
/// <param name="thumbnailSetToUpdate">The ThumbnailSet to update.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The updated ThumbnailSet.</returns>
System.Threading.Tasks.Task<ThumbnailSet> UpdateAsync(ThumbnailSet thumbnailSetToUpdate, CancellationToken cancellationToken);
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="value">The expand value.</param>
/// <returns>The request object to send.</returns>
IThumbnailSetRequest Expand(string value);
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="value">The select value.</param>
/// <returns>The request object to send.</returns>
IThumbnailSetRequest Select(string value);
}
}
| 43.923077 | 153 | 0.620215 | [
"MIT"
] | ConnectionMaster/onedrive-sdk-csharp | src/OneDriveSdk/Requests/Generated/IThumbnailSetRequest.cs | 3,997 | C# |
using System.Globalization;
using AutoMapper;
using System.Linq;
using SW.PrimitiveTypes;
using System.Linq.Expressions;
using System;
using Baseline;
namespace SW.Smarten
{
static class IMapperConfigurationExpressionExtensions
{
public static void CreateMultiLingualMap<TMultiLingualEntity, TTranslation, TDestination>(
this IMapperConfigurationExpression configuration)
where TTranslation : class, IEntityTranslation
where TMultiLingualEntity : IMultiLingualEntity<TTranslation>
{
configuration.CreateMap<TTranslation, TDestination>();
configuration.CreateMap<TMultiLingualEntity, TDestination>().AfterMap((source, destination, context) =>
{
//var translation = source.Translations.FirstOrDefault(pt => pt.Language == CultureInfo.CurrentCulture.Name);
//if (translation != null)
//{
// context.Mapper.Map(translation, destination);
// return;
//}
//var defaultLanguage = multiLingualMapContext.SettingManager
// .GetSettingValue(LocalizationSettingNames.DefaultLanguage);
if (!context.Items.TryGetValue("locale", out var locale))
{
locale = CultureInfo.CurrentCulture.Name;
}
var translation = source.Translations.FirstOrDefault(pt => pt.Language.Equals(locale.ToString(), StringComparison.OrdinalIgnoreCase));
if (translation != null)
{
context.Mapper.Map(translation, destination);
return;
}
translation = source.Translations.FirstOrDefault();
if (translation != null)
{
context.Mapper.Map(translation, destination);
}
});
}
}
} | 36.272727 | 150 | 0.576942 | [
"MIT"
] | simplify9/Smarten | SW.Smarten/IMapperConfigurationExpressionExtensions.cs | 1,997 | C# |
// Copyright (c) 2020 DHGMS Solutions and Contributors. All rights reserved.
// DHGMS Solutions and Contributors licenses this file to you under the MIT license.
// See the LICENSE file in the project root for full license information.
using System;
namespace Whipstaff.MediatR.Foundatio.DistributedLocking
{
/// <summary>
/// Exception for when a lock has been lost and the behaviour is to error.
/// </summary>
#pragma warning disable CA1032 // Implement standard exception constructors
public sealed class LockLostException : Exception
#pragma warning restore CA1032 // Implement standard exception constructors
{
/// <summary>
/// Initializes a new instance of the <see cref="LockLostException"/> class.
/// </summary>
/// <param name="lockName">Name of the lock.</param>
/// <param name="innerException">Inner exception.</param>
public LockLostException(
string lockName,
Exception innerException)
: base($"Lock Lost : {lockName}", innerException)
{
}
}
}
| 37.517241 | 84 | 0.672794 | [
"MIT"
] | dpvreony/whipstaff | src/Whipstaff.MediatR.Foundatio/DistributedLocking/LockLostException.cs | 1,090 | C# |
namespace Poker.Tests
{
using System;
using System.Collections.Generic;
using NUnit.Framework;
[TestFixture]
public class HandTests
{
[Test]
public void HandToStringShouldReturnProperValue()
{
IHand hand = new Hand(new List<ICard>() {
new Card(CardFace.Ace, CardSuit.Clubs),
new Card(CardFace.Ace, CardSuit.Diamonds),
new Card(CardFace.King, CardSuit.Hearts),
new Card(CardFace.King, CardSuit.Spades),
new Card(CardFace.Seven, CardSuit.Diamonds),
});
string expectedResult = string.Join(" | ", hand.Cards);
string actualResultResult = hand.ToString();
Assert.AreEqual(expectedResult, actualResultResult);
}
[TestCase(0)]
[TestCase(2)]
[TestCase(4)]
[TestCase(6)]
[ExpectedException(typeof(InvalidOperationException))]
public void HandToStringShouldThrowInvalivOperationExceptionWhenThereAreNotFiveCardsInHand(int cardsCount)
{
IList<ICard> cards = new List<ICard>() {
new Card(CardFace.Ace, CardSuit.Clubs),
new Card(CardFace.Ace, CardSuit.Diamonds),
new Card(CardFace.King, CardSuit.Hearts),
new Card(CardFace.King, CardSuit.Spades),
new Card(CardFace.Queen, CardSuit.Hearts),
new Card(CardFace.Five, CardSuit.Diamonds),
new Card(CardFace.Seven, CardSuit.Diamonds),
};
IList<ICard> listOfCardsForHand = new List<ICard>();
for (int i = 0; i < cardsCount; i++)
{
listOfCardsForHand.Add(cards[i]);
}
IHand hand = new Hand(listOfCardsForHand);
string actualResultResult = hand.ToString();
}
[Test]
[ExpectedException(typeof(NullReferenceException))]
public void HandToStringShouldThrowNullReferenceExceptionWhenHandCardsAreNull()
{
IHand hand = new Hand(null);
hand.ToString();
}
[Test]
[ExpectedException(typeof(NullReferenceException))]
public void HandToStringShouldThrowNullReferenceExceptionWhenHandIsNull()
{
IHand nullHand = null;
nullHand.ToString();
}
}
}
| 31.906667 | 114 | 0.579189 | [
"MIT"
] | TsvetanMilanov/TelerikAcademyHW | 08_HQC/11_TestDrivenDevelopment/TestDrivenDevelopment/Poker.Tests/HandTests.cs | 2,395 | C# |
/*
* Licensed to the Surging.Apm.Skywalking.Abstractions under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The Surging.Apm.Skywalking.Abstractions licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
namespace Surging.Apm.Skywalking.Abstractions.Logging
{
public interface ILogger
{
void Debug(string message);
void Information(string message);
void Warning(string message);
void Error(string message, Exception exception);
void Trace(string message);
}
} | 33.371429 | 106 | 0.734589 | [
"MIT"
] | 914132883/surging | src/Surging.Apm/Surging.Apm.Skywalking/Abstractions/Logging/ILogger.cs | 1,170 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
namespace Kugar.Core.ExtMethod
{
public static class BindingListExt
{
public static BindingList<T> AddRange<T>(this BindingList<T> bd, IEnumerable<T> lst)
{
if (lst == null)
{
return bd;
}
foreach (var l in lst)
{
bd.Add(l);
}
return bd;
}
}
}
| 19.076923 | 92 | 0.506048 | [
"MIT"
] | JTOne123/Kugar.Core | Kugar.Core/ExtMethod/BindingListExt.cs | 498 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DeathPlane : MonoBehaviour
{
// Start is called before the first frame update
void OnCollisionEnter(Collision coll)
{
if (coll.gameObject.tag == "Player")
{
GameObject.FindGameObjectWithTag("Player").GetComponent<Health>().ApplyDamage(100);
}
else
{
Destroy(coll.gameObject);
}
}
}
| 20.478261 | 95 | 0.617834 | [
"MIT"
] | mynk98/Monterball | Assets/0Scripts/Enemy/DeathPlane.cs | 473 | C# |
using Content.Shared.Chemistry.Reagent;
using Content.Shared.FixedPoint;
using Robust.Shared.Serialization.Manager.Attributes;
using Robust.Shared.ViewVariables;
namespace Content.Shared.Chemistry.Components
{
public partial class Solution
{
/// <summary>
/// If reactions will be checked for when adding reagents to the container.
/// </summary>
[ViewVariables(VVAccess.ReadWrite)]
[DataField("canReact")]
public bool CanReact { get; set; } = true;
/// <summary>
/// Volume needed to fill this container.
/// </summary>
[ViewVariables]
public FixedPoint2 AvailableVolume => MaxVolume - CurrentVolume;
public FixedPoint2 DrawAvailable => CurrentVolume;
public FixedPoint2 DrainAvailable => CurrentVolume;
/// <summary>
/// Checks if a solution can fit into the container.
/// </summary>
/// <param name="solution">The solution that is trying to be added.</param>
/// <returns>If the solution can be fully added.</returns>
public bool CanAddSolution(Solution solution)
{
return solution.TotalVolume <= AvailableVolume;
}
[DataField("maxSpillRefill")]
public FixedPoint2 MaxSpillRefill { get; set; }
/// <summary>
/// Initially set <see cref="MaxVolume"/>. If empty will be calculated based
/// on sum of <see cref="Contents"/> fixed units.
/// </summary>
[DataField("maxVol")] public FixedPoint2 InitialMaxVolume;
[ViewVariables(VVAccess.ReadWrite)]
public FixedPoint2 MaxVolume { get; set; } = FixedPoint2.Zero;
[ViewVariables]
public FixedPoint2 CurrentVolume => TotalVolume;
}
}
| 33.641509 | 87 | 0.629837 | [
"MIT"
] | A-Box-12/space-station-14 | Content.Shared/Chemistry/Components/Solution.Managerial.cs | 1,785 | C# |
//-----------------------------------------------------------------------
// <copyright file="AtomicWriteSpec.cs" company="Akka.NET Project">
// Copyright (C) 2009-2021 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2021 .NET Foundation <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections.Immutable;
using Akka.TestKit;
using Xunit;
namespace Akka.Persistence.Tests
{
public class AtomicWriteSpec
{
[Fact]
public void AtomicWrite_must_only_contain_messages_for_the_same_persistence_id()
{
new AtomicWrite(ImmutableList.Create<IPersistentRepresentation>(
new Persistent("", 1, "p1"),
new Persistent("", 2, "p1")
)).PersistenceId.ShouldBe("p1");
Assert.Throws<ArgumentException>(() =>
new AtomicWrite(ImmutableList.Create<IPersistentRepresentation>(
new Persistent("", 1, "p1"),
new Persistent("", 2, "p1"),
new Persistent("", 3, "p2")))
);
}
[Fact]
public void AtomicWrite_must_have_correct_HighestSequenceNr()
{
new AtomicWrite(ImmutableList.Create<IPersistentRepresentation>(
new Persistent("", 1, "p1"),
new Persistent("", 2, "p1"),
new Persistent("", 3, "p1")
)).HighestSequenceNr.ShouldBe(3);
}
[Fact]
public void AtomicWrite_must_have_correct_LowestSequenceNr()
{
new AtomicWrite(ImmutableList.Create<IPersistentRepresentation>(
new Persistent("", 2, "p1"),
new Persistent("", 3, "p1"),
new Persistent("", 4, "p1")
)).LowestSequenceNr.ShouldBe(2);
}
}
}
| 36.592593 | 88 | 0.509109 | [
"Apache-2.0"
] | Aaronontheweb/akka.net | src/core/Akka.Persistence.Tests/AtomicWriteSpec.cs | 1,978 | C# |
// <auto-generated>
// This code was generated by the Hexarc Pact tool. Do not edit.
// </auto-generated>
#nullable enable
namespace Hexarc.Pact.Demo.Api.Controllers
{
public sealed partial class AnimalController : Hexarc.Pact.Client.ControllerBase
{
public AnimalController(Hexarc.Pact.Client.ClientBase client, System.String controllerPath = "/Animals") : base(client, controllerPath)
{
}
public async System.Threading.Tasks.Task<Hexarc.Pact.Demo.Api.Models.Animal?> GetAnimal(System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<System.String, System.String>>? headers = default)
{
return await this.DoGetRequestWithJsonResponse<Hexarc.Pact.Demo.Api.Models.Animal?>("/GetAnimal", System.Array.Empty<Hexarc.Pact.Client.GetMethodParameter>(), headers);
}
}
}
#nullable restore | 40.045455 | 225 | 0.727582 | [
"MIT"
] | hexarc-software/hexarc-pact | Hexarc.Pact.Demo.Client/Api/Controllers/AnimalController.cs | 881 | C# |
// Copyright (c) Six Labors and contributors.
// Licensed under the GNU Affero General Public License, Version 3.
using SixLabors.ImageSharp.PixelFormats;
namespace SixLabors.ImageSharp.Processing.Processors.Quantization
{
/// <summary>
/// Provides methods for allowing quantization of images pixels with configurable dithering.
/// </summary>
public interface IQuantizer
{
/// <summary>
/// Gets the quantizer options defining quantization rules.
/// </summary>
QuantizerOptions Options { get; }
/// <summary>
/// Creates the generic frame quantizer.
/// </summary>
/// <param name="configuration">The <see cref="Configuration"/> to configure internal operations.</param>
/// <typeparam name="TPixel">The pixel format.</typeparam>
/// <returns>The <see cref="IQuantizer{TPixel}"/>.</returns>
IQuantizer<TPixel> CreatePixelSpecificQuantizer<TPixel>(Configuration configuration)
where TPixel : unmanaged, IPixel<TPixel>;
/// <summary>
/// Creates the generic frame quantizer.
/// </summary>
/// <typeparam name="TPixel">The pixel format.</typeparam>
/// <param name="configuration">The <see cref="Configuration"/> to configure internal operations.</param>
/// <param name="options">The options to create the quantizer with.</param>
/// <returns>The <see cref="IQuantizer{TPixel}"/>.</returns>
IQuantizer<TPixel> CreatePixelSpecificQuantizer<TPixel>(Configuration configuration, QuantizerOptions options)
where TPixel : unmanaged, IPixel<TPixel>;
}
}
| 43.526316 | 118 | 0.660822 | [
"Apache-2.0"
] | fahadabdulaziz/ImageSharp | src/ImageSharp/Processing/Processors/Quantization/IQuantizer.cs | 1,654 | C# |
//-----------------------------------------------------------------------
// <copyright file="MailboxesSpec.cs" company="Akka.NET Project">
// Copyright (C) 2009-2015 Typesafe Inc. <http://www.typesafe.com>
// Copyright (C) 2013-2015 Akka.NET project <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Linq;
using Akka.Actor;
using Akka.Dispatch;
using Akka.Dispatch.SysMsg;
using Akka.TestKit;
using Akka.TestKit.TestActors;
using Xunit;
namespace Akka.Tests.Dispatch
{
public class TestPriorityMailbox : UnboundedPriorityMailbox
{
protected override int PriorityGenerator(object message)
{
if (message is string)
return 1;
if (message is bool)
return 2;
if (message is int)
return 3;
if (message is double)
return 4;
return 5;
}
}
public class IntPriorityMailbox : UnboundedPriorityMailbox
{
protected override int PriorityGenerator(object message)
{
return message as int? ?? Int32.MaxValue;
}
}
public class MailboxesSpec : AkkaSpec
{
public MailboxesSpec() : base(GetConfig())
{
}
private static string GetConfig()
{
return @"
akka.actor.default-dispatcher.throughput = 100 #ensure we process 100 messages per mailbox run
string-prio-mailbox {
mailbox-type : """ + typeof(TestPriorityMailbox).AssemblyQualifiedName + @"""
}
int-prio-mailbox {
mailbox-type : """ + typeof(IntPriorityMailbox).AssemblyQualifiedName + @"""
}
";
}
[Fact]
public void CanUseUnboundedPriorityMailbox()
{
var actor = Sys.ActorOf(EchoActor.Props(this).WithMailbox("string-prio-mailbox"), "echo");
//pause mailbox until all messages have been told
actor.Tell(Suspend.Instance);
actor.Tell(true);
for (var i = 0; i < 30; i++)
{
actor.Tell(1);
}
actor.Tell("a");
actor.Tell(2.0);
for (var i = 0; i < 30; i++)
{
actor.Tell(1);
}
actor.Tell(new Resume(null));
//resume mailbox, this prevents the mailbox from running to early
//priority mailbox is best effort only
ExpectMsg("a");
ExpectMsg(true);
for (var i = 0; i < 60; i++)
{
ExpectMsg(1);
}
ExpectMsg(2.0);
ExpectNoMsg(TimeSpan.FromSeconds(0.3));
}
[Fact]
public void PriorityMailboxKeepsOrderingWithManyPriorityValues()
{
var actor = Sys.ActorOf(EchoActor.Props(this).WithMailbox("int-prio-mailbox"), "echo");
//pause mailbox until all messages have been told
actor.Tell(Suspend.Instance);
AwaitCondition(()=> ((LocalActorRef)actor).Cell.Mailbox.IsSuspended);
// creates 50 messages with values spanning from Int32.MinValue to Int32.MaxValue
var values = new int[50];
var increment = (int)(UInt32.MaxValue / values.Length);
for (var i = 0; i < values.Length; i++)
values[i] = Int32.MinValue + increment * i;
// tell the actor in reverse order
foreach (var value in values.Reverse())
{
actor.Tell(value);
actor.Tell(value);
actor.Tell(value);
}
//resume mailbox, this prevents the mailbox from running to early
actor.Tell(new Resume(null));
// expect the messages in the correct order
foreach (var value in values)
{
ExpectMsg(value);
ExpectMsg(value);
ExpectMsg(value);
}
ExpectNoMsg(TimeSpan.FromSeconds(0.3));
}
}
}
| 29.71223 | 102 | 0.522518 | [
"Apache-2.0"
] | Chinchilla-Software-Com/akka.net | src/core/Akka.Tests/Dispatch/MailboxesSpec.cs | 4,132 | C# |
#pragma checksum "C:\c-\Labs_re-api\Pages\Shared\_ValidationScriptsPartial.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "b10ea521c1c01ab2517b11826d64989b590154fa"
// <auto-generated/>
#pragma warning disable 1591
[assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(Labs_re_api.Pages.Shared.Pages_Shared__ValidationScriptsPartial), @"mvc.1.0.view", @"/Pages/Shared/_ValidationScriptsPartial.cshtml")]
[assembly:global::Microsoft.AspNetCore.Mvc.Razor.Compilation.RazorViewAttribute(@"/Pages/Shared/_ValidationScriptsPartial.cshtml", typeof(Labs_re_api.Pages.Shared.Pages_Shared__ValidationScriptsPartial))]
namespace Labs_re_api.Pages.Shared
{
#line hidden
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
#line 1 "C:\c-\Labs_re-api\Pages\_ViewImports.cshtml"
using Labs_re_api;
#line default
#line hidden
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"b10ea521c1c01ab2517b11826d64989b590154fa", @"/Pages/Shared/_ValidationScriptsPartial.cshtml")]
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"c38814d02cff48f3854cbf1ce407e48d4294e1e8", @"/Pages/_ViewImports.cshtml")]
public class Pages_Shared__ValidationScriptsPartial : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<dynamic>
{
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_0 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("src", new global::Microsoft.AspNetCore.Html.HtmlString("~/lib/jquery-validation/dist/jquery.validate.js"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_1 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("src", new global::Microsoft.AspNetCore.Html.HtmlString("~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_2 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("include", "Development", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_3 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("src", "https://ajax.aspnetcdn.com/ajax/jquery.validate/1.17.0/jquery.validate.min.js", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_4 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-fallback-src", "~/lib/jquery-validation/dist/jquery.validate.min.js", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_5 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-fallback-test", "window.jQuery && window.jQuery.validator", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_6 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("crossorigin", new global::Microsoft.AspNetCore.Html.HtmlString("anonymous"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_7 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("integrity", new global::Microsoft.AspNetCore.Html.HtmlString("sha384-rZfj/ogBloos6wzLGpPkkOr/gpkBNLZ6b6yLy4o+ok+t/SAKlL5mvXLr0OXNi1Hp"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_8 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("src", "https://ajax.aspnetcdn.com/ajax/jquery.validation.unobtrusive/3.2.9/jquery.validate.unobtrusive.min.js", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_9 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-fallback-src", "~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_10 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-fallback-test", "window.jQuery && window.jQuery.validator && window.jQuery.validator.unobtrusive", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_11 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("integrity", new global::Microsoft.AspNetCore.Html.HtmlString("sha384-ifv0TYDWxBHzvAk2Z0n8R434FL1Rlv/Av18DXE43N/1rvHyOG4izKst0f2iSLdds"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_12 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("exclude", "Development", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
#line hidden
#pragma warning disable 0169
private string __tagHelperStringValueBuffer;
#pragma warning restore 0169
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext __tagHelperExecutionContext;
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner __tagHelperRunner = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner();
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __backed__tagHelperScopeManager = null;
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __tagHelperScopeManager
{
get
{
if (__backed__tagHelperScopeManager == null)
{
__backed__tagHelperScopeManager = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager(StartTagHelperWritingScope, EndTagHelperWritingScope);
}
return __backed__tagHelperScopeManager;
}
}
private global::Microsoft.AspNetCore.Mvc.TagHelpers.EnvironmentTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_EnvironmentTagHelper;
private global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper;
private global::Microsoft.AspNetCore.Mvc.TagHelpers.ScriptTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper;
#pragma warning disable 1998
public async override global::System.Threading.Tasks.Task ExecuteAsync()
{
BeginContext(0, 224, false);
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("environment", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "e36bf6ad1e7d41a792864a48690099a7", async() => {
BeginContext(35, 6, true);
WriteLiteral("\r\n ");
EndContext();
BeginContext(41, 71, false);
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("script", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "ef909c887bfd4fc29bcd82d9e3e70db9", async() => {
}
);
__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
EndContext();
BeginContext(112, 6, true);
WriteLiteral("\r\n ");
EndContext();
BeginContext(118, 90, false);
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("script", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "bfbe5e4af04c4d6d9f12eecb2019a591", async() => {
}
);
__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_1);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
EndContext();
BeginContext(208, 2, true);
WriteLiteral("\r\n");
EndContext();
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_EnvironmentTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.EnvironmentTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_EnvironmentTagHelper);
__Microsoft_AspNetCore_Mvc_TagHelpers_EnvironmentTagHelper.Include = (string)__tagHelperAttribute_2.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_2);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
EndContext();
BeginContext(224, 2, true);
WriteLiteral("\r\n");
EndContext();
BeginContext(226, 944, false);
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("environment", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "a68b5d527d1a43b6b3fad3dad0266c77", async() => {
BeginContext(261, 6, true);
WriteLiteral("\r\n ");
EndContext();
BeginContext(267, 399, false);
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("script", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "84a97d2829284c8486a98331ff6c74a6", async() => {
BeginContext(651, 6, true);
WriteLiteral("\r\n ");
EndContext();
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.ScriptTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper);
__Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper.Src = (string)__tagHelperAttribute_3.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_3);
__Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper.FallbackSrc = (string)__tagHelperAttribute_4.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_4);
__Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper.FallbackTestExpression = (string)__tagHelperAttribute_5.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_5);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_6);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_7);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
EndContext();
BeginContext(666, 6, true);
WriteLiteral("\r\n ");
EndContext();
BeginContext(672, 482, false);
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("script", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "38159200213c48cfbeb3670a3104ae2f", async() => {
BeginContext(1139, 6, true);
WriteLiteral("\r\n ");
EndContext();
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.ScriptTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper);
__Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper.Src = (string)__tagHelperAttribute_8.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_8);
__Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper.FallbackSrc = (string)__tagHelperAttribute_9.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_9);
__Microsoft_AspNetCore_Mvc_TagHelpers_ScriptTagHelper.FallbackTestExpression = (string)__tagHelperAttribute_10.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_10);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_6);
__tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_11);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
EndContext();
BeginContext(1154, 2, true);
WriteLiteral("\r\n");
EndContext();
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_EnvironmentTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.EnvironmentTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_EnvironmentTagHelper);
__Microsoft_AspNetCore_Mvc_TagHelpers_EnvironmentTagHelper.Exclude = (string)__tagHelperAttribute_12.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_12);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
EndContext();
BeginContext(1170, 2, true);
WriteLiteral("\r\n");
EndContext();
}
#pragma warning restore 1998
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<dynamic> Html { get; private set; }
}
}
#pragma warning restore 1591
| 85.502347 | 414 | 0.737865 | [
"MIT"
] | SebastianTrifa/c- | Labs_re-api/obj/Debug/netcoreapp2.1/Razor/Pages/Shared/_ValidationScriptsPartial.g.cshtml.cs | 18,212 | C# |
/*
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
using System.Collections.Generic;
using Amazon.EC2.Model;
using Amazon.Runtime.Internal.Transform;
namespace Amazon.EC2.Model.Internal.MarshallTransformations
{
/// <summary>
/// InstanceMonitoring Unmarshaller
/// </summary>
internal class InstanceMonitoringUnmarshaller : IUnmarshaller<InstanceMonitoring, XmlUnmarshallerContext>, IUnmarshaller<InstanceMonitoring, JsonUnmarshallerContext>
{
public InstanceMonitoring Unmarshall(XmlUnmarshallerContext context)
{
InstanceMonitoring instanceMonitoring = new InstanceMonitoring();
int originalDepth = context.CurrentDepth;
int targetDepth = originalDepth + 1;
if (context.IsStartOfDocument)
targetDepth += 1;
while (context.Read())
{
if (context.IsStartElement || context.IsAttribute)
{
if (context.TestExpression("instanceId", targetDepth))
{
instanceMonitoring.InstanceId = StringUnmarshaller.GetInstance().Unmarshall(context);
continue;
}
if (context.TestExpression("monitoring", targetDepth))
{
instanceMonitoring.Monitoring = MonitoringUnmarshaller.GetInstance().Unmarshall(context);
continue;
}
}
else if (context.IsEndElement && context.CurrentDepth < originalDepth)
{
return instanceMonitoring;
}
}
return instanceMonitoring;
}
public InstanceMonitoring Unmarshall(JsonUnmarshallerContext context)
{
return null;
}
private static InstanceMonitoringUnmarshaller instance;
public static InstanceMonitoringUnmarshaller GetInstance()
{
if (instance == null)
instance = new InstanceMonitoringUnmarshaller();
return instance;
}
}
}
| 34.604938 | 170 | 0.587228 | [
"Apache-2.0"
] | virajs/aws-sdk-net | AWSSDK_DotNet35/Amazon.EC2/Model/Internal/MarshallTransformations/InstanceMonitoringUnmarshaller.cs | 2,803 | C# |
using NUnit.Framework;
using System.Collections.Generic;
namespace Lucene.Net.Util.Automaton
{
using Util = Lucene.Net.Util.Fst.Util;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
[TestFixture]
public class TestSpecialOperations : LuceneTestCase
{
/// <summary>
/// tests against the original brics implementation.
/// </summary>
[Test]
public virtual void TestIsFinite()
{
int num = AtLeast(200);
for (int i = 0; i < num; i++)
{
Automaton a = AutomatonTestUtil.RandomAutomaton(Random);
Automaton b = (Automaton)a.Clone();
Assert.AreEqual(AutomatonTestUtil.IsFiniteSlow(a), SpecialOperations.IsFinite(b));
}
}
/// <summary>
/// Basic test for getFiniteStrings
/// </summary>
[Test]
public virtual void TestFiniteStrings()
{
Automaton a = BasicOperations.Union(BasicAutomata.MakeString("dog"), BasicAutomata.MakeString("duck"));
MinimizationOperations.Minimize(a);
ISet<Int32sRef> strings = SpecialOperations.GetFiniteStrings(a, -1);
Assert.AreEqual(2, strings.Count);
Int32sRef dog = new Int32sRef();
Util.ToInt32sRef(new BytesRef("dog"), dog);
Assert.IsTrue(strings.Contains(dog));
Int32sRef duck = new Int32sRef();
Util.ToInt32sRef(new BytesRef("duck"), duck);
Assert.IsTrue(strings.Contains(duck));
}
}
} | 39 | 115 | 0.624212 | [
"Apache-2.0"
] | DiogenesPolanco/lucenenet | src/Lucene.Net.Tests/Util/Automaton/TestSpecialOperations.cs | 2,379 | C# |
using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Terraria;
using Terraria.ID;
using Terraria.ModLoader;
namespace tsorcRevamp.NPCs.Bosses.JungleWyvern {
class JungleWyvernLegs : ModNPC {
public override void SetDefaults() {
npc.netAlways = true;
npc.boss = true;
npc.npcSlots = 1;
npc.aiStyle = 6;
npc.width = 45;
npc.height = 45;
npc.knockBackResist = 0f;
npc.timeLeft = 1750;
npc.damage = 38;
npc.defense = 7;
npc.HitSound = SoundID.NPCHit7;
npc.DeathSound = SoundID.NPCDeath8;
npc.lifeMax = 91000000;
npc.noGravity = true;
npc.noTileCollide = true;
npc.value = 70000;
npc.buffImmune[BuffID.Poisoned] = true;
npc.buffImmune[BuffID.OnFire] = true;
npc.buffImmune[BuffID.Confused] = true;
npc.buffImmune[BuffID.CursedInferno] = true;
}
public override void SetStaticDefaults() {
DisplayName.SetDefault("Ancient Jungle Wyvern");
}
public override bool? DrawHealthBar(byte hbPosition, ref float scale, ref Vector2 position)
{
return false;
}
public int PoisonFlamesDamage = 45;
public override void ScaleExpertStats(int numPlayers, float bossLifeScale)
{
}
public override void AI() {
npc.TargetClosest();
if (!Main.npc[(int)npc.ai[1]].active) {
npc.life = 0;
npc.HitEffect(0, 10.0);
NPCLoot();
for (int num36 = 0; num36 < 50; num36++) {
Color color = new Color();
int dust = Dust.NewDust(new Vector2((float)npc.position.X, (float)npc.position.Y), npc.width, npc.height, 62, Main.rand.Next(-20, 20) * 2, Main.rand.Next(-20, 20) * 2, 100, color, 10f);
Main.dust[dust].noGravity = false;
dust = Dust.NewDust(new Vector2((float)npc.position.X, (float)npc.position.Y), npc.width, npc.height, 62, Main.rand.Next(-20, 20) * 2, Main.rand.Next(-20, 20) * 2, 100, color, 6f);
Main.dust[dust].noGravity = false;
dust = Dust.NewDust(new Vector2((float)npc.position.X, (float)npc.position.Y), npc.width, npc.height, 54, Main.rand.Next(-20, 20) * 2, Main.rand.Next(-20, 20) * 2, 100, color, 6f);
Main.dust[dust].noGravity = false;
dust = Dust.NewDust(new Vector2((float)npc.position.X, (float)npc.position.Y), npc.width, npc.height, 62, 0, 0, 100, Color.White, 10.0f);
Main.dust[dust].noGravity = true;
//npc.netUpdate = true; //new
}
npc.active = false;
}
if (npc.position.X > Main.npc[(int)npc.ai[1]].position.X) {
npc.spriteDirection = 1;
}
if (npc.position.X < Main.npc[(int)npc.ai[1]].position.X) {
npc.spriteDirection = -1;
}
int mainDust = Dust.NewDust(new Vector2((float)npc.position.X, (float)npc.position.Y + 10), npc.width, npc.height, 62, 0, 0, 100, default, 1.0f);
Main.dust[mainDust].noGravity = true;
}
public override void OnHitByItem(Player player, Item item, int damage, float knockback, bool crit)
{
damage *= 2;
base.OnHitByItem(player, item, damage, knockback, crit);
}
public override bool PreDraw(SpriteBatch spriteBatch, Color drawColor) {
Vector2 origin = new Vector2(Main.npcTexture[npc.type].Width / 2, Main.npcTexture[npc.type].Height / Main.npcFrameCount[npc.type] / 2);
Color alpha = Color.White;
SpriteEffects effects = SpriteEffects.None;
if (npc.spriteDirection == 1) {
effects = SpriteEffects.FlipHorizontally;
}
spriteBatch.Draw(Main.npcTexture[npc.type], new Vector2(npc.position.X - Main.screenPosition.X + (float)(npc.width / 2) - (float)Main.npcTexture[npc.type].Width * npc.scale / 2f + origin.X * npc.scale, npc.position.Y - Main.screenPosition.Y + (float)npc.height - (float)Main.npcTexture[npc.type].Height * npc.scale / (float)Main.npcFrameCount[npc.type] + 4f + origin.Y * npc.scale + 56f), npc.frame, alpha, npc.rotation, origin, npc.scale, effects, 0f);
npc.alpha = 255;
return true;
}
}
}
| 39.42268 | 456 | 0.677563 | [
"MIT"
] | Zeodexic/tsorcRevamp | NPCs/Bosses/JungleWyvern/JungleWyvernLegs.cs | 3,826 | C# |
using System;
using NDC.Build.Core.ViewModels;
using Xamarin.Forms;
namespace NDC.Build.Forms.Core.Views
{
public partial class BuildsView
{
public BuildsView()
{
InitializeComponent();
}
private void OnQueueBuild(object sender, EventArgs e)
{
((BuildsViewModel)BindingContext).QueueBuild();
}
private void OnItemSelected(object sender, SelectedItemChangedEventArgs e)
{
((ListView) sender).SelectedItem = null;
}
}
}
| 21.68 | 82 | 0.607011 | [
"MIT"
] | derekjwilliams/talks | ndc-sydney-2016/NDC.Build.Forms.Core/Views/BuildsView.xaml.cs | 544 | C# |
using Google.Protobuf.WellKnownTypes;
using Microsoft.Azure.SignalR.Management;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Octolamp.Contracts.Dtos;
using Octolamp.Contracts.Extensions;
using Octolamp.Contracts.Protos;
using System;
using System.Threading;
using System.Threading.Tasks;
using static Octolamp.Contracts.Protos.Covid;
using static Octolamp.Contracts.Protos.Stocks;
namespace Octolamp.DaemonService
{
public class TimedHostedService : IHostedService, IDisposable
{
private async Task DoWork()
{
try
{
var response = await _covidClient.DoHandshakeAsync(new HandshakeRequest { ClientToken = DateTime.Now.ToLongTimeString() });
_logger.LogInformation($"Handshake success. Client Token = {response.ClientToken}; Server Token: {response.ServerToken}");
var report = await _covid19ApiClient.GetSummaryAsync();
if (report != null && report.Global != null && report.Countries != null)
{
await RelayGlobalSummaryAsync(report);
await RelayCountryUpdatesAsync(report);
}
}
catch (Exception e)
{
_logger.LogError(e, e.Message);
}
}
private async Task RelayGlobalSummaryAsync(RawCovidReport report)
{
var sumRespose = await _covidClient.RegisterReportSummaryAsync(new CovidGlobalReport
{
Date = DateTime.UtcNow.ToProtoDateTime(),
NewConfirmed = report.Global.NewConfirmed,
TotalConfirmed = report.Global.TotalConfirmed,
NewDeaths = report.Global.NewDeaths,
TotalDeaths = report.Global.TotalDeaths,
NewRecovered = report.Global.NewRecovered,
TotalRecovered = report.Global.TotalRecovered,
});
if (!string.IsNullOrWhiteSpace(sumRespose.ServerToken))
{
this._logger.LogInformation("Successfully registered the Global summary payload");
}
}
private async Task RelayCountryUpdatesAsync(RawCovidReport report)
{
foreach (var country in report.Countries)
{
var conResponse = await _covidClient.RegisterCountryReportAsync(new CovidCountryReport
{
CountryCode = country.CountryCode,
CountryCountry = country.Country,
Slug = country.Slug,
Date = DateTime.UtcNow.ToProtoDateTime(),
NewConfirmed = country.NewConfirmed,
TotalConfirmed = country.TotalConfirmed,
NewDeaths = country.NewDeaths,
TotalDeaths = country.TotalDeaths,
NewRecovered = country.NewRecovered,
TotalRecovered = country.TotalRecovered,
});
if (!string.IsNullOrWhiteSpace(conResponse.ServerToken))
{
this._logger.LogInformation($"Successfully registered the Country {country.Country} summary payload");
}
}
}
#region Service methods
private readonly CovidClient _covidClient;
private readonly ILogger<TimedHostedService> _logger;
private readonly Covid19ApiClient _covid19ApiClient;
private Timer _timer;
public TimedHostedService(
CovidClient covidClient,
Covid19ApiClient covid19ApiClient,
ILogger<TimedHostedService> logger)
{
_covidClient = covidClient;
_covid19ApiClient = covid19ApiClient;
_logger = logger;
}
public Task StartAsync(CancellationToken stoppingToken)
{
_logger.LogInformation("Timed Hosted Service running.");
_timer = new Timer(new TimerCallback(_ => { DoWork().Wait(); }), null, TimeSpan.Zero,
TimeSpan.FromSeconds(20));
return Task.CompletedTask;
}
public Task StopAsync(CancellationToken stoppingToken)
{
_logger.LogInformation("Timed Hosted Service is stopping.");
_timer?.Change(Timeout.Infinite, 0);
return Task.CompletedTask;
}
public void Dispose()
{
_timer?.Dispose();
}
#endregion
}
}
| 37.297521 | 139 | 0.596277 | [
"MIT"
] | MoimHossain/linkerd-demo | src/Octolamp.DaemonService/TimedHostedService.cs | 4,515 | C# |
using EPiServer;
using EPiServer.Commerce.Catalog.ContentTypes;
using EPiServer.Web.Routing;
using Foundation.Features.CatalogContent.Variation;
using Foundation.Infrastructure.Cms;
using Foundation.Infrastructure.Commerce.Customer.Services;
using Foundation.Infrastructure.Commerce.Extensions;
using Foundation.Infrastructure.Personalization;
using Mediachase.Commerce.Catalog;
using Microsoft.AspNetCore.Mvc;
using System.Linq;
using System.Threading.Tasks;
namespace Foundation.Features.CatalogContent.Package
{
public class PackageController : CatalogContentControllerBase<GenericPackage>
{
private readonly bool _isInEditMode;
private readonly CatalogEntryViewModelFactory _viewModelFactory;
public PackageController(IsInEditModeAccessor isInEditModeAccessor,
CatalogEntryViewModelFactory viewModelFactory,
//IReviewService reviewService,
//IReviewActivityService reviewActivityService,
ICommerceTrackingService recommendationService,
ReferenceConverter referenceConverter,
IContentLoader contentLoader,
UrlResolver urlResolver,
ILoyaltyService loyaltyService) : base(referenceConverter, contentLoader, urlResolver/*, reviewService, reviewActivityService*/, recommendationService, loyaltyService)
{
_isInEditMode = isInEditModeAccessor();
_viewModelFactory = viewModelFactory;
}
[HttpGet]
public async Task<ActionResult> Index(GenericPackage currentContent, bool skipTracking = false)
{
var viewModel = _viewModelFactory.CreatePackage<GenericPackage, GenericVariant, GenericPackageViewModel>(currentContent);
viewModel.BreadCrumb = GetBreadCrumb(currentContent.Code);
if (_isInEditMode && !viewModel.Entries.Any())
{
return View(viewModel);
}
if (viewModel.Entries == null || !viewModel.Entries.Any())
{
return NotFound();
}
await AddInfomationViewModel(viewModel, currentContent.Code, skipTracking);
currentContent.AddBrowseHistory();
return View(viewModel);
}
[HttpGet]
public ActionResult QuickView(string productCode)
{
var currentContentRef = _referenceConverter.GetContentLink(productCode);
var currentContent = _contentLoader.Get<EntryContentBase>(currentContentRef) as GenericPackage;
if (currentContent != null)
{
var viewModel = _viewModelFactory.CreatePackage<GenericPackage, GenericVariant, GenericPackageViewModel>(currentContent);
return PartialView("_QuickView", viewModel);
}
return StatusCode(404, "Product not found.");
}
}
} | 40.871429 | 179 | 0.694862 | [
"Apache-2.0"
] | palle-mertz-merkle/Foundation | src/Foundation/Features/CatalogContent/Package/PackageController.cs | 2,863 | 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.Collections.Generic;
namespace System.ServiceModel
{
internal static class EmptyArray<T>
{
internal static T[] Allocate(int n)
{
if (n == 0)
return Array.Empty<T>();
else
return new T[n];
}
internal static T[] ToArray(IList<T> collection)
{
if (collection.Count == 0)
{
return Array.Empty<T>();
}
else
{
T[] array = new T[collection.Count];
collection.CopyTo(array, 0);
return array;
}
}
internal static T[] ToArray(SynchronizedCollection<T> collection)
{
lock (collection.SyncRoot)
{
return EmptyArray<T>.ToArray((IList<T>)collection);
}
}
}
}
| 26.02381 | 73 | 0.509607 | [
"MIT"
] | Bencargs/wcf | src/dotnet-svcutil/lib/src/FrameworkFork/System.ServiceModel/System/ServiceModel/EmptyArray.cs | 1,093 | C# |
using System;
using System.Runtime.Remoting;
using FluentAssertions;
using ImplicitNullability.Samples.CodeWithIN.NullabilityAnalysis;
using NUnit.Framework;
using static ImplicitNullability.Samples.CodeWithIN.ReSharper;
namespace ImplicitNullability.Samples.Consumer.NullabilityAnalysis
{
[TestFixture]
public class DelegatesSampleTests
{
private string BecauseDelegateMethodIsAnonymous = "because the delegate *method* is an anonymous method";
[Test]
public void SomeAction()
{
Action act = () => DelegatesSample.GetSomeAction()(null);
act.Should().NotThrow(BecauseDelegateMethodIsAnonymous);
}
[Test]
public void SomeActionWithClosedValues()
{
Action act = () => DelegatesSample.GetSomeActionWithClosedValues()(null);
act.Should().NotThrow(BecauseDelegateMethodIsAnonymous + " (implemented using a display class)");
}
[Test]
public void GetSomeActionToAnonymousMethod()
{
Action act = () => DelegatesSample.GetSomeActionToAnonymousMethod()(null);
act.Should().NotThrow(BecauseDelegateMethodIsAnonymous);
}
[Test]
public void GetSomeDelegateToLambda()
{
Action act = () => DelegatesSample.GetSomeDelegate()(null /*Expect:AssignNullToNotNullAttribute[MIn]*/);
act.Should().NotThrow(BecauseDelegateMethodIsAnonymous);
}
[Test]
public void SomeDelegateToNamedMethod()
{
Action act = () => DelegatesSample.GetSomeDelegateToNamedMethod()(null /*Expect:AssignNullToNotNullAttribute[MIn]*/);
act.Should().Throw<ArgumentNullException>("because the delegate *method* parameter is implicitly NotNull")
.And.ParamName.Should().Be("a");
}
[Test]
public void SomeDelegateToNamedMethodWithCanBeNull()
{
Action act = () => DelegatesSample.GetSomeDelegateToNamedMethodWithCanBeNull()(null /*Expect:AssignNullToNotNullAttribute[MIn]*/);
act.Should().NotThrow();
}
[Test]
public void SomeDelegateWithCanBeNullToNamedMethod()
{
Action act = () => DelegatesSample.GetSomeDelegateWithCanBeNullToNamedMethod()(null);
act.Should().Throw<ArgumentNullException>("because the delegate *method* parameter is (implicitly) NotNull")
.And.ParamName.Should().Be("a");
}
[Test]
public void SomeDelegateWithCanBeNullToNamedMethodWithCanBeNull()
{
Action act = () => DelegatesSample.GetSomeDelegateWithCanBeNullToNamedMethodWithCanBeNull()(null);
act.Should().NotThrow();
}
[Test]
public void SomeFunctionDelegateWithNotNull()
{
Action act = () =>
{
DelegatesSample.SomeFunctionDelegateWithNotNull @delegate = DelegatesSample.GetSomeFunctionDelegateWithNotNull();
var result = @delegate();
TestValueAnalysis(result, result == null /* REPORTED false negative https://youtrack.jetbrains.com/issue/RSRP-446852 */);
};
act.Should().NotThrow(BecauseDelegateMethodIsAnonymous);
}
[Test]
public void SomeFunctionDelegate()
{
Action act = () =>
{
DelegatesSample.SomeFunctionDelegate @delegate = DelegatesSample.GetSomeFunctionDelegate();
var result = @delegate();
// This false negative is analog to SomeFunctionDelegateWithNotNull and even requires an exemption for the delegate Invoke() method,
// but it is necessary because the developer can't opt out of the implicit annotation with [CanBeNull]:
TestValueAnalysis(result, result == null);
};
act.Should().NotThrow(BecauseDelegateMethodIsAnonymous);
}
[Test]
public void SomeFunctionDelegateWithCanBeNull()
{
Action act = () =>
{
DelegatesSample.SomeFunctionDelegateWithCanBeNull @delegate = DelegatesSample.GetSomeFunctionDelegateWithCanBeNull();
var result = @delegate();
TestValueAnalysis(result /* REPORTED false negative https://youtrack.jetbrains.com/issue/RSRP-446852 */, result == null);
};
act.Should().NotThrow();
}
[Test]
public void SomeNotNullDelegateOfExternalCode()
{
Action act = () => DelegatesSample.GetSomeNotNullDelegateOfExternalCode()(null /*Expect:AssignNullToNotNullAttribute*/);
act.Should().NotThrow(BecauseDelegateMethodIsAnonymous);
}
[Test]
public void SomeDelegateOfExternalCode()
{
Action act = () => DelegatesSample.GetSomeDelegateOfExternalCode()(null /* no warning because the delegate is external */);
act.Should().NotThrow(BecauseDelegateMethodIsAnonymous);
}
[Test]
public void SomeAsyncFunctionDelegateWithNotNull()
{
Action act = () =>
{
DelegatesSample.SomeAsyncFunctionDelegateWithNotNull @delegate = DelegatesSample.GetSomeAsyncFunctionDelegateWithNotNull();
var result = @delegate();
TestValueAnalysis(result, result == null /* REPORTED false negative https://youtrack.jetbrains.com/issue/RSRP-446852 */);
};
act.Should().NotThrow(BecauseDelegateMethodIsAnonymous);
}
[Test]
public void SomeAsyncFunctionDelegate()
{
Action act = () =>
{
DelegatesSample.SomeAsyncFunctionDelegate @delegate = DelegatesSample.GetSomeAsyncFunctionDelegate();
var result = @delegate();
// This false negative is analog to SomeAsyncFunctionDelegateWithNotNull and even requires an exemption for the delegate Invoke() method,
// but it is necessary because the developer can't opt out of the implicit annotation with [CanBeNull]:
TestValueAnalysis(result, result == null);
};
act.Should().NotThrow(BecauseDelegateMethodIsAnonymous);
}
[Test]
public void SomeAsyncFunctionDelegateWithCanBeNull()
{
Action act = () =>
{
DelegatesSample.SomeAsyncFunctionDelegateWithCanBeNull @delegate = DelegatesSample.GetSomeAsyncFunctionDelegateWithCanBeNull();
var result = @delegate();
TestValueAnalysis(result /* REPORTED false negative https://youtrack.jetbrains.com/issue/RSRP-446852 */, result == null);
};
act.Should().NotThrow();
}
[Test]
public void SomeDelegateWithRefAndOutWithNullValueForRefArgument()
{
Action act = () =>
{
string refParam = null;
DelegatesSample.GetSomeDelegateWithRefAndOut()(ref refParam, out var outParam);
TestValueAnalysis(refParam, refParam == null /*Expect:ConditionIsAlwaysTrueOrFalse[MRef]*/);
TestValueAnalysis(outParam, outParam == null /*Expect:ConditionIsAlwaysTrueOrFalse[MOut]*/);
};
act.Should().NotThrow(BecauseDelegateMethodIsAnonymous);
}
[Test]
public void SomeDelegateWithInvokeAndBeginInvokeCalls()
{
Action act = () =>
{
var someDelegate = DelegatesSample.GetSomeDelegate();
someDelegate.Invoke(null /*Expect:AssignNullToNotNullAttribute[MIn]*/);
var asyncResult = someDelegate.BeginInvoke(null, null, null);
// The BeginInvoke() result is made implicitly NotNull by ReSharper's CodeAnnotationsCache:
TestValueAnalysis(asyncResult, asyncResult == null /*Expect:ConditionIsAlwaysTrueOrFalse*/);
asyncResult.AsyncWaitHandle.WaitOne();
};
act.Should().NotThrow(BecauseDelegateMethodIsAnonymous);
}
[Test]
public void GetSomeDelegateWithCanBeNullWithInvokeAndBeginInvokeCalls()
{
Action act = () =>
{
var someDelegate = DelegatesSample.GetSomeDelegateWithCanBeNull();
someDelegate.Invoke(null);
someDelegate.BeginInvoke(null, null, null).AsyncWaitHandle.WaitOne();
};
act.Should().NotThrow();
}
[Test]
public void SomeFunctionDelegateWithInvokeAndBeginInvokeCalls()
{
Action act = () =>
{
var @delegate = DelegatesSample.GetSomeFunctionDelegate();
var result = @delegate.Invoke();
TestValueAnalysis(result, result == null /* REPORTED false negative https://youtrack.jetbrains.com/issue/RSRP-446852 */);
var asyncResult = @delegate.BeginInvoke(null, null);
var endInvokeResult = @delegate.EndInvoke(asyncResult);
TestValueAnalysis(endInvokeResult, endInvokeResult == null);
};
act.Should().NotThrow(BecauseDelegateMethodIsAnonymous);
}
[Test]
public void SomeFunctionDelegateWithEndInvokeWithNullArgument()
{
var @delegate = DelegatesSample.GetSomeFunctionDelegate();
Action act = () => @delegate.EndInvoke(null /*Expect:AssignNullToNotNullAttribute[MIn]*/);
act.Should().Throw<RemotingException>("because the IAsyncResult argument is null");
}
}
}
| 38.363636 | 153 | 0.616732 | [
"MIT"
] | sheitmann/ImplicitNullability | Src/ImplicitNullability.Samples.Consumer/NullabilityAnalysis/DelegatesSampleTests.cs | 9,706 | C# |
//-----------------------------------------------------------------------------
// FILE: OpenEbsOptions.cs
// CONTRIBUTOR: Jeff Lill
// COPYRIGHT: Copyright (c) 2005-2022 by neonFORGE LLC. 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.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics.Contracts;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
using YamlDotNet.Serialization;
using Neon.Common;
using Neon.IO;
namespace Neon.Kube
{
/// <summary>
/// Specifies cluster OpenEBS options.
/// </summary>
public class OpenEbsOptions
{
private const string minNfsSize = "10 GiB";
/// <summary>
/// <para>
/// Specifies which OpenEBS engine will be deployed within the cluster. This defaults
/// to <see cref="OpenEbsEngine.Default"/>.
/// </para>
/// </summary>
[JsonProperty(PropertyName = "Engine", Required = Required.Default)]
[YamlMember(Alias = "engine", ApplyNamingConventions = false)]
[DefaultValue(OpenEbsEngine.Default)]
public OpenEbsEngine Engine { get; set; } = OpenEbsEngine.Default;
/// <summary>
/// The size of the NFS file system to be created for the cluster. This defaults
/// to <b>10 GiB</b> and cannot be any smaller.
/// </summary>
[JsonProperty(PropertyName = "NfsSize", Required = Required.Default)]
[YamlMember(Alias = "nfsSize", ApplyNamingConventions = false)]
[DefaultValue(minNfsSize)]
public string NfsSize { get; set; } = minNfsSize;
/// <summary>
/// Validates the options.
/// </summary>
/// <param name="clusterDefinition">The cluster definition.</param>
/// <exception cref="ClusterDefinitionException">Thrown if the definition is not valid.</exception>
internal void Validate(ClusterDefinition clusterDefinition)
{
Covenant.Requires<ArgumentNullException>(clusterDefinition != null, nameof(clusterDefinition));
var openEbsOptionsPrefix = $"{nameof(ClusterDefinition.Storage)}.{nameof(ClusterDefinition.Storage.OpenEbs)}";
NfsSize = NfsSize ?? minNfsSize;
ClusterDefinition.ValidateSize(NfsSize, typeof(OpenEbsOptions), nameof(NfsSize), minimum: minNfsSize);
// Clusters require that at least one node has [OpenEbsStorage=true]. We'll set
// this automatically when the user hasn't already done this. All workers will have
// this set to true when there are workers, otherwise we'll set this to true for all
// masters.
if (!clusterDefinition.Nodes.Any(node => node.OpenEbsStorage))
{
if (clusterDefinition.Workers.Count() > 0)
{
foreach (var worker in clusterDefinition.Workers)
{
worker.OpenEbsStorage = true;
}
}
else
{
foreach (var master in clusterDefinition.Masters)
{
master.OpenEbsStorage = true;
}
}
}
switch (Engine)
{
case OpenEbsEngine.Default:
if (clusterDefinition.Nodes.Count() == 1)
{
Engine = OpenEbsEngine.HostPath;
}
else if (clusterDefinition.Nodes.Count(n => n.OpenEbsStorage) > 0)
{
Engine = OpenEbsEngine.Jiva;
}
break;
case OpenEbsEngine.HostPath:
if (clusterDefinition.Nodes.Count() > 1)
{
new ClusterDefinitionException($"[{openEbsOptionsPrefix}.{nameof(Engine)}={Engine}] storage engine is supported only for single-node clusters.");
}
break;
case OpenEbsEngine.cStor:
break; // NOP
case OpenEbsEngine.Jiva:
break; // NOP
default:
case OpenEbsEngine.Mayastor:
throw new ClusterDefinitionException($"[{openEbsOptionsPrefix}.{nameof(Engine)}={Engine}] storage engine is not implemented.");
}
}
}
}
| 36.291667 | 169 | 0.580941 | [
"Apache-2.0"
] | jefflill/neonKUBE | Lib/Neon.Kube/Model/ClusterDefinition/Storage/OpenEbsOptions.cs | 5,228 | C# |
using System.Text.Json.Serialization;
namespace AlexaNetCore.InteractionModel
{
public class SlotDefinitionInteractionModel
{
[JsonPropertyName("name")]
public string Name { get; set; }
[JsonPropertyName("type")]
public string SlotType { get; set; }
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
[JsonPropertyName("multipleValues")]
public MultiValueSlotInteractionModel Enabled { get; set; }
public SlotDefinitionInteractionModel(string name, string typ, bool allowMultipleValues )
{
Name = name;
SlotType = typ;
if (allowMultipleValues) Enabled = new MultiValueSlotInteractionModel();
}
}
} | 26.607143 | 97 | 0.655034 | [
"MIT"
] | bradirby/AlexaNetCore | src/AlexaNetCore/InteractionModel/SlotDefinitionInteractionModel.cs | 747 | C# |
/* Copyright 2010-present MongoDB Inc.
*
* 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;
#if NET452
using System.Runtime.Serialization;
#endif
using MongoDB.Driver.Core.Connections;
namespace MongoDB.Driver
{
/// <summary>
/// Represents a MongoDB duplicate key exception.
/// </summary>
#if NET452
[Serializable]
#endif
public class MongoDuplicateKeyException : MongoWriteConcernException
{
/// <summary>
/// Initializes a new instance of the <see cref="MongoDuplicateKeyException" /> class.
/// </summary>
/// <param name="connectionId">The connection identifier.</param>
/// <param name="message">The error message.</param>
/// <param name="commandResult">The command result.</param>
public MongoDuplicateKeyException(ConnectionId connectionId, string message, WriteConcernResult commandResult)
: base(connectionId, message, commandResult)
{
}
#if NET452
/// <summary>
/// Initializes a new instance of the <see cref="MongoDuplicateKeyException"/> class.
/// </summary>
/// <param name="info">The SerializationInfo.</param>
/// <param name="context">The StreamingContext.</param>
public MongoDuplicateKeyException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
#endif
}
}
| 34 | 118 | 0.684349 | [
"Apache-2.0"
] | Anarh2404/mongo-csharp-driver | src/MongoDB.Driver.Core/MongoDuplicateKeyException.cs | 1,904 | C# |
using System.Text.Json.Serialization;
namespace Essensoft.Paylink.Alipay.Domain
{
/// <summary>
/// RecruitEnrollRuleData Data Structure.
/// </summary>
public class RecruitEnrollRuleData : AlipayObject
{
/// <summary>
/// 素材的要求,json字符串,使用时需要把此字符串解析成json对象
/// </summary>
[JsonPropertyName("schema")]
public string Schema { get; set; }
}
}
| 23.882353 | 53 | 0.62069 | [
"MIT"
] | Frunck8206/payment | src/Essensoft.Paylink.Alipay/Domain/RecruitEnrollRuleData.cs | 458 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using Xunit;
using Xunit.Abstractions;
using System.Linq;
using System.Threading.Tasks;
using System.IO;
namespace Light.Data.Mysql.Test
{
public class Mysql_BaseConfigTest : BaseTest
{
public Mysql_BaseConfigTest(ITestOutputHelper output) : base(output)
{
}
#region base test
List<TeRelateMainConfig> CreateMainTableList(int count)
{
List<TeRelateMainConfig> list = new List<TeRelateMainConfig>();
DateTime now = DateTime.Now;
DateTime d = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute, 0);
for (int i = 1; i <= count; i++) {
int x = i % 5 == 0 ? -1 : 1;
TeRelateMainConfig item = new TeRelateMainConfig();
item.DecimalField = (decimal)((i % 26) * 0.1 * x);
item.DateTimeField = d.AddMinutes(i * 2);
item.VarcharField = "testtest" + item.DecimalField;
list.Add(item);
}
return list;
}
List<TeRelateMainConfig> CreateAndInsertMainTableList(int count)
{
var list = CreateMainTableList(count);
commandOutput.Enable = false;
context.TruncateTable<TeRelateMainConfig>();
context.BatchInsert(list);
commandOutput.Enable = true;
return list;
}
List<TeRelateMainExtendConfig> CreateMainTableListExtend(int count)
{
List<TeRelateMainExtendConfig> list = new List<TeRelateMainExtendConfig>();
DateTime now = DateTime.Now;
DateTime d = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute, 0);
for (int i = 1; i <= count; i++) {
int x = i % 5 == 0 ? -1 : 1;
TeRelateMainExtendConfig item = new TeRelateMainExtendConfig();
item.DecimalField = (decimal)((i % 26) * 0.1 * x);
item.DateTimeField = d.AddMinutes(i * 2);
item.VarcharField = "testtest" + item.DecimalField;
list.Add(item);
}
return list;
}
List<TeRelateMainExtendConfig> CreateAndInsertMainTableListExtend(int count)
{
var list = CreateMainTableListExtend(count);
commandOutput.Enable = false;
context.TruncateTable<TeRelateMainExtendConfig>();
context.BatchInsert(list);
commandOutput.Enable = true;
return list;
}
List<TeRelateSubConfig> CreateSubTableList(int count)
{
List<TeRelateSubConfig> list = new List<TeRelateSubConfig>();
DateTime now = DateTime.Now;
DateTime d = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute, 0);
for (int i = 1; i <= count; i++) {
int x = i % 5 == 0 ? -1 : 1;
TeRelateSubConfig item = new TeRelateSubConfig();
item.MainId = i;
item.DecimalField = (decimal)((i % 26) * 0.1 * x);
item.DateTimeField = d.AddMinutes(i * 2);
item.VarcharField = "testtest" + item.DecimalField;
list.Add(item);
}
return list;
}
List<TeRelateSubConfig> CreateAndInsertSubTableList(int count)
{
var list = CreateSubTableList(count);
commandOutput.Enable = false;
context.TruncateTable<TeRelateSubConfig>();
context.BatchInsert(list);
commandOutput.Enable = true;
return list;
}
[Fact]
public void TestCase_Config()
{
context.TruncateTable<TeBaseFieldConfig>();
var item = context.CreateNew<TeBaseFieldConfig>();
var ret = context.Insert(item);
Assert.Equal(1, ret);
var ac = context.Query<TeBaseFieldConfig>().First();
Assert.Equal(1, ac.Id);
Assert.Equal(0, ac.Int32Field);
Assert.Equal(20, ac.Int32FieldNull);
Assert.Equal(0m, ac.DecimalField);
Assert.Equal(20.5m, ac.DecimalFieldNull);
Assert.Equal(new DateTime(2017, 1, 2, 12, 0, 0), ac.DateTimeField);
Assert.Equal(new DateTime(2017, 1, 2, 12, 0, 0), ac.DateTimeFieldNull);
Assert.Equal("", ac.VarcharField);
Assert.Equal("testtest", ac.VarcharFieldNull);
Assert.True((DateTime.Now - ac.NowField).Seconds <= 5);
Assert.True((DateTime.Now - ac.NowFieldNull.Value).Seconds <= 1);
Assert.Equal(DateTime.Now.Date, ac.TodayField);
Assert.Equal(DateTime.Now.Date, ac.TodayFieldNull);
Assert.Equal(EnumInt32Type.Zero, ac.EnumInt32Field);
Assert.Equal(EnumInt32Type.Positive1, ac.EnumInt32FieldNull);
}
[Fact]
public void TestCase_Config_Replace()
{
context.TruncateTable<TeBaseFieldConfigReplace>();
var item = context.CreateNew<TeBaseFieldConfigReplace>();
var ret = context.Insert(item);
Assert.Equal(1, ret);
var ac = context.Query<TeBaseFieldConfigReplace>().First();
Assert.Equal(1, ac.Id);
Assert.Equal(0, ac.Int32Field);
Assert.Equal(30, ac.Int32FieldNull);
Assert.Equal(0m, ac.DecimalField);
Assert.Equal(30.5m, ac.DecimalFieldNull);
Assert.Equal(new DateTime(2017, 1, 3, 12, 0, 0), ac.DateTimeField);
Assert.Equal(new DateTime(2017, 1, 3, 12, 0, 0), ac.DateTimeFieldNull);
Assert.Equal("", ac.VarcharField);
Assert.Equal("testtest2", ac.VarcharFieldNull);
Assert.True((DateTime.Now - ac.NowField).Seconds <= 5);
Assert.True((DateTime.Now - ac.NowFieldNull.Value).Seconds <= 1);
Assert.Equal(DateTime.Now.Date, ac.TodayField);
Assert.Equal(DateTime.Now.Date, ac.TodayFieldNull);
Assert.Equal(EnumInt32Type.Zero, ac.EnumInt32Field);
Assert.Equal(EnumInt32Type.Positive2, ac.EnumInt32FieldNull);
}
[Fact]
public void TestCase_Config_Relate()
{
var listA = CreateAndInsertMainTableList(10);
var listB = CreateAndInsertSubTableList(5);
{
var listEx = (from x in listA
join y in listB on x.Id equals y.MainId into ps
from p in ps.DefaultIfEmpty()
select new TeRelateMainConfig {
Id = x.Id,
DecimalField = x.DecimalField,
DateTimeField = x.DateTimeField,
VarcharField = x.VarcharField,
SubConfig = p
}).OrderByDescending(x => x.Id).ToList();
var listAc = context.Query<TeRelateMainConfig>().OrderByDescending(x => x.Id).ToList();
AssertExtend.StrictEqual(listEx, listAc);
}
}
[Fact]
public void TestCase_Config_Relate_Extend()
{
var listA = CreateAndInsertMainTableListExtend(10);
var listB = CreateAndInsertSubTableList(5);
{
var listEx = (from x in listA
join y in listB on x.Id equals y.MainId into ps
from p in ps.DefaultIfEmpty()
select new TeRelateMainExtendConfig {
Id = x.Id,
DecimalField = x.DecimalField,
DateTimeField = x.DateTimeField,
VarcharField = x.VarcharField,
SubConfig = p
}).OrderByDescending(x => x.Id).ToList();
var listAc = context.Query<TeRelateMainExtendConfig>().OrderByDescending(x => x.Id).ToList();
AssertExtend.StrictEqual(listEx, listAc);
}
}
#endregion
[Fact]
public void TestCase_Config1()
{
context.TruncateTable<MyConfig1>();
var item = context.CreateNew<MyConfig1>();
item.Int32FieldNull = 1000;
var ret = context.Insert(item);
Assert.Equal(1, ret);
var ac = context.Query<MyConfig1>().First();
Assert.Equal(1, ac.Id);
Assert.Equal(0, ac.Int32Field);
Assert.Null(ac.Int32FieldNull);
Assert.Equal(0m, ac.DecimalField);
Assert.Equal(20.5m, ac.DecimalFieldNull);
Assert.Equal(new DateTime(2017, 1, 2, 12, 0, 0), ac.DateTimeField);
Assert.Equal(new DateTime(2017, 1, 2, 12, 0, 0), ac.DateTimeFieldNull);
Assert.Equal("", ac.VarcharField);
Assert.Equal("testtest", ac.VarcharFieldNull);
Assert.True((DateTime.Now - ac.NowField).Seconds <= 5);
Assert.True((DateTime.Now - ac.NowFieldNull.Value).Seconds <= 1);
Assert.Equal(DateTime.Now.Date, ac.TodayField);
Assert.Equal(DateTime.Now.Date, ac.TodayFieldNull);
Assert.Equal(EnumInt32Type.Zero, ac.EnumInt32Field);
Assert.Equal(EnumInt32Type.Positive1, ac.EnumInt32FieldNull);
ac.Int32FieldNull = 1000;
ac.NowField = DateTime.Now.AddDays(-1).Date;
ret = context.Update(ac);
Assert.Equal(1, ret);
ac = context.Query<MyConfig1>().First();
Assert.Equal(1, ac.Id);
Assert.Equal(0, ac.Int32Field);
Assert.Null(ac.Int32FieldNull);
Assert.Equal(0m, ac.DecimalField);
Assert.Equal(20.5m, ac.DecimalFieldNull);
Assert.Equal(new DateTime(2017, 1, 2, 12, 0, 0), ac.DateTimeField);
Assert.Equal(new DateTime(2017, 1, 2, 12, 0, 0), ac.DateTimeFieldNull);
Assert.Equal("", ac.VarcharField);
Assert.Equal("testtest", ac.VarcharFieldNull);
Assert.True((DateTime.Now - ac.NowField).Seconds <= 5);
Assert.True((DateTime.Now - ac.NowFieldNull.Value).Seconds <= 1);
Assert.Equal(DateTime.Now.Date, ac.TodayField);
Assert.Equal(DateTime.Now.Date, ac.TodayFieldNull);
Assert.Equal(EnumInt32Type.Zero, ac.EnumInt32Field);
Assert.Equal(EnumInt32Type.Positive1, ac.EnumInt32FieldNull);
}
[Fact]
public void TestCase_Config_DbType()
{
context.TruncateTable<MyConfig2>();
var item = context.CreateNew<MyConfig2>();
item.Int32FieldNull = 1000;
item.VarcharField = "11111111111111111111111111";
var ret = context.Insert(item);
Assert.Equal(1, ret);
var ac = context.Query<MyConfig2>().First();
Assert.Equal(1, ac.Id);
Assert.Equal(1000, ac.Int32FieldNull);
Assert.Equal("111111", ac.VarcharField);
}
}
}
| 42.093985 | 109 | 0.551308 | [
"MIT"
] | aquilahkj/Light.Data2 | test/Light.Data.Mysql.Test/Mysql_BaseConfigTest.cs | 11,199 | C# |
using System;
namespace BooleanVariable
{
public class Program
{
public static void Main()
{
Boolean IsFemale = true;
Console.WriteLine(IsFemale);
Console.ReadKey();
}
}
}
| 14.588235 | 40 | 0.524194 | [
"MIT"
] | TheWayBy/TelerikAcademy | C# Part 1/02.PrimitiveDataTypesAndVariables/05.BooleanVariable/Program.cs | 250 | C# |
//-----------------------------------------------------------------------
// <copyright file="SqliteEventsByTagSpec.cs" company="Akka.NET Project">
// Copyright (C) 2009-2021 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2021 .NET Foundation <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using Akka.Configuration;
using Akka.Persistence.Query;
using Akka.Persistence.Query.Sql;
using Akka.Persistence.TCK.Query;
using Akka.Util.Internal;
using Xunit;
using Xunit.Abstractions;
namespace Akka.Persistence.Sqlite.Tests.Query
{
public class SqliteEventsByTagSpec : EventsByTagSpec
{
public static readonly AtomicCounter Counter = new AtomicCounter(0);
public static Config Config(int id) => ConfigurationFactory.ParseString($@"
akka.loglevel = INFO
akka.persistence.query.journal.sql.refresh-interval = 1s
akka.persistence.journal.plugin = ""akka.persistence.journal.sqlite""
akka.persistence.journal.sqlite {{
event-adapters {{
color-tagger = ""Akka.Persistence.TCK.Query.ColorFruitTagger, Akka.Persistence.TCK""
}}
event-adapter-bindings = {{
""System.String"" = color-tagger
}}
class = ""Akka.Persistence.Sqlite.Journal.SqliteJournal, Akka.Persistence.Sqlite""
plugin-dispatcher = ""akka.actor.default-dispatcher""
table-name = event_journal
metadata-table-name = journal_metadata
auto-initialize = on
connection-string = ""Filename=file:memdb-journal-eventsbytag-{id}.db;Mode=Memory;Cache=Shared""
}}
akka.test.single-expect-default = 10s")
.WithFallback(SqlReadJournal.DefaultConfiguration());
public SqliteEventsByTagSpec(ITestOutputHelper output) : base(Config(Counter.GetAndIncrement()), nameof(SqliteEventsByTagSpec), output)
{
ReadJournal = Sys.ReadJournalFor<SqlReadJournal>(SqlReadJournal.Identifier);
}
}
}
| 44.44898 | 143 | 0.60652 | [
"Apache-2.0"
] | BearerPipelineTest/akka.net | src/contrib/persistence/Akka.Persistence.Sqlite.Tests/Query/SqliteEventsByTagSpec.cs | 2,180 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Flightbook.Generator.Models;
using Flightbook.Generator.Models.Flightbook;
using Flightbook.Generator.Models.OurAirports;
using Flightbook.Generator.Models.Registrations;
using Flightbook.Generator.Models.Tracklogs;
using Newtonsoft.Json;
namespace Flightbook.Generator.Export
{
internal class FlightbookJsonExporter : IFlightbookJsonExporter
{
public string CreateFlightbookJson(List<LogEntry> logEntries, List<AirportInfo> worldAirports, List<RunwayInfo> worldRunways, List<CountryInfo> worldCountries, List<RegionInfo> worldRegions, List<RegistrationPrefix> registrationPrefixes,
AircraftInformation[] aircraftInformations, OperatorInformation[] aircraftOperators, List<GpxTrack> trackLogs,
Config configuration)
{
List<Aircraft> aircrafts = ExtractAircrafts(logEntries, registrationPrefixes, aircraftInformations, aircraftOperators);
List<Airport> airports = ExtractAirports(logEntries, worldAirports, worldRunways, worldRegions);
List<Country> countries = ExtractCountries(airports, worldCountries);
List<FlightTimeMonth> flightTimeStatistics = GetFlightTimeStatistics(logEntries);
List<FlightStatistics> flightStatistics = GetFlightStatistics(trackLogs);
Models.Flightbook.Flightbook flightbook = new()
{
ParentPage = configuration.ParentPage?.Length > 0 ? configuration.ParentPage : null,
AirportGallerySearch = configuration.AirportGallerySearch?.Length > 0 ? configuration.AirportGallerySearch : null,
AircraftGallerySearch = configuration.AircraftGallerySearch?.Length > 0 ? configuration.AircraftGallerySearch : null,
FlickrProxyUrl = configuration.FlickrProxyUrl?.Length > 0 ? configuration.FlickrProxyUrl : null,
Aircrafts = aircrafts,
Airports = airports,
Countries = countries,
FlightTimeMonths = flightTimeStatistics,
FlightStatistics = flightStatistics
};
return JsonConvert.SerializeObject(flightbook);
}
private List<Aircraft> ExtractAircrafts(List<LogEntry> logEntries, List<RegistrationPrefix> registrationPrefixes, AircraftInformation[] aircraftInformations, OperatorInformation[] aircraftOperators)
{
List<Aircraft> aircrafts = logEntries.Select(l => l.AircraftRegistration).Distinct().Select(a => new Aircraft {Registration = a}).ToList();
aircrafts.ForEach(aircraft =>
{
LogEntry[] filteredLogEntries = logEntries.Where(l => l.AircraftRegistration == aircraft.Registration).ToArray();
string prefix = aircraft.Registration.Split("-")[0] + "-";
aircraft.IsoCountry = registrationPrefixes.FirstOrDefault(r => r.Prefix == prefix)?.CountryCode ?? "ZZ";
aircraft.FirstFlown = filteredLogEntries.Select(l => l.LogDate).Min();
aircraft.LastFlown = filteredLogEntries.Select(l => l.LogDate).Max();
aircraft.Type = filteredLogEntries.Select(l => l.AircraftType).First();
aircraft.DistinctFlightDates = filteredLogEntries.Select(l => l.LogDate).Distinct().Count();
aircraft.NumberOfFlights = filteredLogEntries.Length;
aircraft.NumberOfAirports = filteredLogEntries.SelectMany(l => new List<string> {l.From, l.To}.Concat(l.Via ?? new string[0])).Distinct().Count();
aircraft.AsDual = filteredLogEntries.Any(l => l.DualMinutes > 0);
aircraft.AsPic = filteredLogEntries.Any(l => l.PicMinutes > 0);
aircraft.Picture = GetAircraftPicture(aircraft.Registration);
AircraftInformation aircraftInformation = aircraftInformations.FirstOrDefault(a => a.Registration == aircraft.Registration);
if (aircraftInformation != default(AircraftInformation))
{
aircraft.Class = aircraftInformation.Class;
aircraft.Manufacturer = aircraftInformation.Manufacturer;
aircraft.Model = aircraftInformation.Model;
aircraft.ManufacturedYear = aircraftInformation.ManufacturedYear;
aircraft.Operator = GetAircraftOperator(aircraftInformation.Operator, aircraftOperators);
}
});
return aircrafts;
}
private string GetAircraftPicture(string registration)
{
return !File.Exists($@"config\aircrafts\{registration.ToLowerInvariant()}.jpg") ? null : $"/aircrafts/{registration.ToLowerInvariant()}.jpg";
}
private Operator GetAircraftOperator(string aircraftOperator, OperatorInformation[] operators)
{
return string.IsNullOrEmpty(aircraftOperator)
? null
: operators
.Where(o => o.Operator == aircraftOperator)
.Select(o => new Operator {Name = o.Operator, Url = o.Url, Picture = GetAircraftOperatorPicture(o.Operator)})
.FirstOrDefault();
}
private string GetAircraftOperatorPicture(string aircraftOperator)
{
string filename = aircraftOperator.Replace(" ", "-").ToLowerInvariant();
filename = string.Join("_", filename.Split(Path.GetInvalidFileNameChars(), StringSplitOptions.RemoveEmptyEntries)).TrimEnd('.');
return !File.Exists($@"config\operators\{filename}.png") ? null : $"/operators/{filename}.png";
}
private List<Airport> ExtractAirports(List<LogEntry> logEntries, List<AirportInfo> worldAirports, List<RunwayInfo> worldRunways, List<RegionInfo> worldRegions)
{
List<Airport> airports = logEntries.Select(l => l.From)
.Concat(logEntries.Select(l => l.To))
.Concat(logEntries.Where(l => l.Via != null).SelectMany(l => l.Via))
.Distinct()
.Select(a => new Airport {Icao = a}).ToList();
airports.ForEach(airport =>
{
LogEntry[] filteredLogEntries = logEntries.Where(l => l.From == airport.Icao || l.To == airport.Icao || l.Via != null && l.Via.Contains(airport.Icao)).ToArray();
airport.FirstVisited = filteredLogEntries.Select(l => l.LogDate).Min();
airport.LastVisited = filteredLogEntries.Select(l => l.LogDate).Max();
airport.DistinctVisitDates = filteredLogEntries.Select(l => l.LogDate).Distinct().Count();
airport.TotalFlights = filteredLogEntries.Length;
airport.Aircrafts = filteredLogEntries.Select(l => l.AircraftRegistration).Distinct().ToArray();
airport.AsDual = filteredLogEntries.Any(l => l.DualMinutes > 0);
airport.AsPic = filteredLogEntries.Any(l => l.PicMinutes > 0);
airport.AsFrom = filteredLogEntries.Any(l => l.From == airport.Icao);
airport.AsTo = filteredLogEntries.Any(l => l.To == airport.Icao);
airport.AsVia = filteredLogEntries.Any(l => l.Via != null && l.Via.Contains(airport.Icao));
airport.Picture = GetAirportPicture(airport.Icao);
AirportInfo airportInfo = worldAirports.Find(ai => string.Equals(ai.IcaoCode, airport.Icao, StringComparison.InvariantCultureIgnoreCase));
if (airportInfo == null)
{
return;
}
airport.Name = airportInfo.Name;
airport.Iata = airportInfo.IataCode;
airport.Type = GetAirportType(airportInfo.Type);
airport.Wikipedia = airportInfo.WikipediaLink;
airport.IsoCountry = airportInfo.IsoCountry;
airport.Region = worldRegions.Where(r => r.Code == airportInfo.IsoRegion).Select(r => r.Name).FirstOrDefault();
airport.FieldElevation = airportInfo.FieldElevation;
if (airportInfo.Latitude.HasValue && airportInfo.Longitude.HasValue)
{
airport.Coordinates = new[] {airportInfo.Latitude.Value, airportInfo.Longitude.Value};
}
});
return airports;
}
private string GetAirportPicture(string icao)
{
return !File.Exists($@"config\airports\{icao.ToLowerInvariant()}.jpg") ? null : $"/airports/{icao.ToLowerInvariant()}.jpg";
}
private string GetAirportType(string airportType)
{
switch (airportType)
{
case "large_airport":
return "Large airport";
case "medium_airport":
return "Medium airport";
case "small_airport":
return "Small airport";
case "seaplane_base":
return "Seaplane base";
case "heliport":
return "Heliport";
case "closed":
return "Closed airport";
default:
return "Unknown";
}
}
private List<Country> ExtractCountries(List<Airport> airports, List<CountryInfo> worldCountries)
{
List<Country> countries = airports.Select(c => c.IsoCountry).Distinct().Select(c => new Country {Iso = c}).ToList();
countries.ForEach(country =>
{
CountryInfo countryInfo = worldCountries.Find(ci => string.Equals(ci.Code, country.Iso, StringComparison.InvariantCultureIgnoreCase));
if (countryInfo == null)
{
return;
}
country.Name = countryInfo.Name;
});
return countries;
}
private List<FlightTimeMonth> GetFlightTimeStatistics(List<LogEntry> logEntries)
{
DateTime startDate = logEntries.Min(l => l.LogDate);
DateTime endDate = logEntries.Max(l => l.LogDate);
startDate = startDate.AddDays(1 - startDate.Day);
List<FlightTimeMonth> months = new();
while (startDate <= endDate)
{
List<LogEntry> filteredLogEntries = logEntries.Where(l => l.LogDate.Year == startDate.Year && l.LogDate.Month == startDate.Month).ToList();
months.Add(new FlightTimeMonth
{
Month = startDate.ToString("yyyy-MM"),
FlightTimeMinutes = filteredLogEntries.Sum(l => l.TotalMinutes),
DualMinutes = filteredLogEntries.Sum(l => l.DualMinutes),
PicMinutes = filteredLogEntries.Sum(l => l.PicMinutes),
NumberOfFlights = filteredLogEntries.Count
});
startDate = startDate.AddMonths(1);
}
return months;
}
private List<FlightStatistics> GetFlightStatistics(List<GpxTrack> trackLogs)
{
int startYear = trackLogs.Select(l => l.DateTime).Min().Year;
int endYear = trackLogs.Select(l => l.DateTime).Max().Year;
List<FlightStatistics> statistics = new()
{
new FlightStatistics
{
AltitudeMax = trackLogs.Max(t => t.AltitudeMax),
AltitudeMaxFlight = trackLogs.OrderByDescending(t => t.AltitudeMax).Select(t => t.Filename).FirstOrDefault(),
AltitudeAverage = (int) trackLogs.Average(t => t.AltitudeMax),
SpeedMax = trackLogs.Max(t => t.SpeedMax),
SpeedMaxFlight = trackLogs.OrderByDescending(t => t.SpeedMax).Select(t => t.Filename).FirstOrDefault(),
SpeedAverage = (int) trackLogs.Average(t => t.SpeedMax),
DistanceTotal = trackLogs.Sum(t => t.TotalDistance),
DistanceMax = trackLogs.Max(t => t.TotalDistance),
DistanceMaxFlight = trackLogs.OrderByDescending(t => t.TotalDistance).Select(t => t.Filename).FirstOrDefault(),
DistanceAverage = trackLogs.Average(t => t.TotalDistance)
}
};
for (int year = startYear; year <= endYear; year++)
{
List<GpxTrack> filteredTracks = trackLogs.Where(l => l.DateTime.Year == year).ToList();
statistics.Add(new FlightStatistics
{
Year = year,
AltitudeMax = filteredTracks.Max(t => t.AltitudeMax),
AltitudeMaxFlight = filteredTracks.OrderByDescending(t => t.AltitudeMax).Select(t => t.Filename).FirstOrDefault(),
AltitudeAverage = (int) filteredTracks.Average(t => t.AltitudeMax),
SpeedMax = filteredTracks.Max(t => t.SpeedMax),
SpeedMaxFlight = filteredTracks.OrderByDescending(t => t.SpeedMax).Select(t => t.Filename).FirstOrDefault(),
SpeedAverage = (int) filteredTracks.Average(t => t.SpeedMax),
DistanceTotal = filteredTracks.Sum(t => t.TotalDistance),
DistanceMax = filteredTracks.Max(t => t.TotalDistance),
DistanceMaxFlight = filteredTracks.OrderByDescending(t => t.TotalDistance).Select(t => t.Filename).FirstOrDefault(),
DistanceAverage = filteredTracks.Average(t => t.TotalDistance)
});
}
return statistics;
}
}
}
| 51.168539 | 245 | 0.603206 | [
"MIT"
] | thomfre/flightbook-generator | Flightbook.Generator/Export/FlightbookJsonExporter.cs | 13,664 | C# |
public class HoneyCake : Food
{
private const int POINTS = 5;
public HoneyCake()
: base(POINTS)
{
}
} | 14.111111 | 33 | 0.559055 | [
"MIT"
] | borisbotev/SoftUni | C# OOP Basics/04.InheritanceExercises/05.MordorsCruelPlan/Food/HoneyCake.cs | 129 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
namespace Prism.Modularity
{
/// <summary>
/// Interface for classes that are responsible for resolving and loading assembly files.
/// </summary>
public interface IAssemblyResolver
{
/// <summary>
/// Load an assembly when it's required by the application.
/// </summary>
/// <param name="assemblyFilePath"></param>
void LoadAssemblyFrom(string assemblyFilePath);
}
}
| 32.823529 | 121 | 0.663082 | [
"Apache-2.0"
] | drcarver/prism | Source/Wpf/Prism.Wpf/Modularity/IAssemblyResolver.Desktop.cs | 558 | C# |
using System;
namespace Evergine.Bindings.OpenXR
{
public partial struct XrInstance : IEquatable<XrInstance>
{
public readonly ulong Handle;
public XrInstance(ulong existingHandle) { Handle = existingHandle; }
public static XrInstance Null => new XrInstance(0);
public static implicit operator XrInstance(ulong handle) => new XrInstance(handle);
public static bool operator ==(XrInstance left, XrInstance right) => left.Handle == right.Handle;
public static bool operator !=(XrInstance left, XrInstance right) => left.Handle != right.Handle;
public static bool operator ==(XrInstance left, ulong right) => left.Handle == right;
public static bool operator !=(XrInstance left, ulong right) => left.Handle != right;
public bool Equals(XrInstance h) => Handle == h.Handle;
public override bool Equals(object o) => o is XrInstance h && Equals(h);
public override int GetHashCode() => Handle.GetHashCode();
}
public partial struct XrSession : IEquatable<XrSession>
{
public readonly ulong Handle;
public XrSession(ulong existingHandle) { Handle = existingHandle; }
public static XrSession Null => new XrSession(0);
public static implicit operator XrSession(ulong handle) => new XrSession(handle);
public static bool operator ==(XrSession left, XrSession right) => left.Handle == right.Handle;
public static bool operator !=(XrSession left, XrSession right) => left.Handle != right.Handle;
public static bool operator ==(XrSession left, ulong right) => left.Handle == right;
public static bool operator !=(XrSession left, ulong right) => left.Handle != right;
public bool Equals(XrSession h) => Handle == h.Handle;
public override bool Equals(object o) => o is XrSession h && Equals(h);
public override int GetHashCode() => Handle.GetHashCode();
}
public partial struct XrActionSet : IEquatable<XrActionSet>
{
public readonly ulong Handle;
public XrActionSet(ulong existingHandle) { Handle = existingHandle; }
public static XrActionSet Null => new XrActionSet(0);
public static implicit operator XrActionSet(ulong handle) => new XrActionSet(handle);
public static bool operator ==(XrActionSet left, XrActionSet right) => left.Handle == right.Handle;
public static bool operator !=(XrActionSet left, XrActionSet right) => left.Handle != right.Handle;
public static bool operator ==(XrActionSet left, ulong right) => left.Handle == right;
public static bool operator !=(XrActionSet left, ulong right) => left.Handle != right;
public bool Equals(XrActionSet h) => Handle == h.Handle;
public override bool Equals(object o) => o is XrActionSet h && Equals(h);
public override int GetHashCode() => Handle.GetHashCode();
}
public partial struct XrAction : IEquatable<XrAction>
{
public readonly ulong Handle;
public XrAction(ulong existingHandle) { Handle = existingHandle; }
public static XrAction Null => new XrAction(0);
public static implicit operator XrAction(ulong handle) => new XrAction(handle);
public static bool operator ==(XrAction left, XrAction right) => left.Handle == right.Handle;
public static bool operator !=(XrAction left, XrAction right) => left.Handle != right.Handle;
public static bool operator ==(XrAction left, ulong right) => left.Handle == right;
public static bool operator !=(XrAction left, ulong right) => left.Handle != right;
public bool Equals(XrAction h) => Handle == h.Handle;
public override bool Equals(object o) => o is XrAction h && Equals(h);
public override int GetHashCode() => Handle.GetHashCode();
}
public partial struct XrSwapchain : IEquatable<XrSwapchain>
{
public readonly ulong Handle;
public XrSwapchain(ulong existingHandle) { Handle = existingHandle; }
public static XrSwapchain Null => new XrSwapchain(0);
public static implicit operator XrSwapchain(ulong handle) => new XrSwapchain(handle);
public static bool operator ==(XrSwapchain left, XrSwapchain right) => left.Handle == right.Handle;
public static bool operator !=(XrSwapchain left, XrSwapchain right) => left.Handle != right.Handle;
public static bool operator ==(XrSwapchain left, ulong right) => left.Handle == right;
public static bool operator !=(XrSwapchain left, ulong right) => left.Handle != right;
public bool Equals(XrSwapchain h) => Handle == h.Handle;
public override bool Equals(object o) => o is XrSwapchain h && Equals(h);
public override int GetHashCode() => Handle.GetHashCode();
}
public partial struct XrSpace : IEquatable<XrSpace>
{
public readonly ulong Handle;
public XrSpace(ulong existingHandle) { Handle = existingHandle; }
public static XrSpace Null => new XrSpace(0);
public static implicit operator XrSpace(ulong handle) => new XrSpace(handle);
public static bool operator ==(XrSpace left, XrSpace right) => left.Handle == right.Handle;
public static bool operator !=(XrSpace left, XrSpace right) => left.Handle != right.Handle;
public static bool operator ==(XrSpace left, ulong right) => left.Handle == right;
public static bool operator !=(XrSpace left, ulong right) => left.Handle != right;
public bool Equals(XrSpace h) => Handle == h.Handle;
public override bool Equals(object o) => o is XrSpace h && Equals(h);
public override int GetHashCode() => Handle.GetHashCode();
}
public partial struct XrDebugUtilsMessengerEXT : IEquatable<XrDebugUtilsMessengerEXT>
{
public readonly ulong Handle;
public XrDebugUtilsMessengerEXT(ulong existingHandle) { Handle = existingHandle; }
public static XrDebugUtilsMessengerEXT Null => new XrDebugUtilsMessengerEXT(0);
public static implicit operator XrDebugUtilsMessengerEXT(ulong handle) => new XrDebugUtilsMessengerEXT(handle);
public static bool operator ==(XrDebugUtilsMessengerEXT left, XrDebugUtilsMessengerEXT right) => left.Handle == right.Handle;
public static bool operator !=(XrDebugUtilsMessengerEXT left, XrDebugUtilsMessengerEXT right) => left.Handle != right.Handle;
public static bool operator ==(XrDebugUtilsMessengerEXT left, ulong right) => left.Handle == right;
public static bool operator !=(XrDebugUtilsMessengerEXT left, ulong right) => left.Handle != right;
public bool Equals(XrDebugUtilsMessengerEXT h) => Handle == h.Handle;
public override bool Equals(object o) => o is XrDebugUtilsMessengerEXT h && Equals(h);
public override int GetHashCode() => Handle.GetHashCode();
}
public partial struct XrSpatialAnchorMSFT : IEquatable<XrSpatialAnchorMSFT>
{
public readonly ulong Handle;
public XrSpatialAnchorMSFT(ulong existingHandle) { Handle = existingHandle; }
public static XrSpatialAnchorMSFT Null => new XrSpatialAnchorMSFT(0);
public static implicit operator XrSpatialAnchorMSFT(ulong handle) => new XrSpatialAnchorMSFT(handle);
public static bool operator ==(XrSpatialAnchorMSFT left, XrSpatialAnchorMSFT right) => left.Handle == right.Handle;
public static bool operator !=(XrSpatialAnchorMSFT left, XrSpatialAnchorMSFT right) => left.Handle != right.Handle;
public static bool operator ==(XrSpatialAnchorMSFT left, ulong right) => left.Handle == right;
public static bool operator !=(XrSpatialAnchorMSFT left, ulong right) => left.Handle != right;
public bool Equals(XrSpatialAnchorMSFT h) => Handle == h.Handle;
public override bool Equals(object o) => o is XrSpatialAnchorMSFT h && Equals(h);
public override int GetHashCode() => Handle.GetHashCode();
}
public partial struct XrHandTrackerEXT : IEquatable<XrHandTrackerEXT>
{
public readonly ulong Handle;
public XrHandTrackerEXT(ulong existingHandle) { Handle = existingHandle; }
public static XrHandTrackerEXT Null => new XrHandTrackerEXT(0);
public static implicit operator XrHandTrackerEXT(ulong handle) => new XrHandTrackerEXT(handle);
public static bool operator ==(XrHandTrackerEXT left, XrHandTrackerEXT right) => left.Handle == right.Handle;
public static bool operator !=(XrHandTrackerEXT left, XrHandTrackerEXT right) => left.Handle != right.Handle;
public static bool operator ==(XrHandTrackerEXT left, ulong right) => left.Handle == right;
public static bool operator !=(XrHandTrackerEXT left, ulong right) => left.Handle != right;
public bool Equals(XrHandTrackerEXT h) => Handle == h.Handle;
public override bool Equals(object o) => o is XrHandTrackerEXT h && Equals(h);
public override int GetHashCode() => Handle.GetHashCode();
}
public partial struct XrFoveationProfileFB : IEquatable<XrFoveationProfileFB>
{
public readonly ulong Handle;
public XrFoveationProfileFB(ulong existingHandle) { Handle = existingHandle; }
public static XrFoveationProfileFB Null => new XrFoveationProfileFB(0);
public static implicit operator XrFoveationProfileFB(ulong handle) => new XrFoveationProfileFB(handle);
public static bool operator ==(XrFoveationProfileFB left, XrFoveationProfileFB right) => left.Handle == right.Handle;
public static bool operator !=(XrFoveationProfileFB left, XrFoveationProfileFB right) => left.Handle != right.Handle;
public static bool operator ==(XrFoveationProfileFB left, ulong right) => left.Handle == right;
public static bool operator !=(XrFoveationProfileFB left, ulong right) => left.Handle != right;
public bool Equals(XrFoveationProfileFB h) => Handle == h.Handle;
public override bool Equals(object o) => o is XrFoveationProfileFB h && Equals(h);
public override int GetHashCode() => Handle.GetHashCode();
}
public partial struct XrTriangleMeshFB : IEquatable<XrTriangleMeshFB>
{
public readonly ulong Handle;
public XrTriangleMeshFB(ulong existingHandle) { Handle = existingHandle; }
public static XrTriangleMeshFB Null => new XrTriangleMeshFB(0);
public static implicit operator XrTriangleMeshFB(ulong handle) => new XrTriangleMeshFB(handle);
public static bool operator ==(XrTriangleMeshFB left, XrTriangleMeshFB right) => left.Handle == right.Handle;
public static bool operator !=(XrTriangleMeshFB left, XrTriangleMeshFB right) => left.Handle != right.Handle;
public static bool operator ==(XrTriangleMeshFB left, ulong right) => left.Handle == right;
public static bool operator !=(XrTriangleMeshFB left, ulong right) => left.Handle != right;
public bool Equals(XrTriangleMeshFB h) => Handle == h.Handle;
public override bool Equals(object o) => o is XrTriangleMeshFB h && Equals(h);
public override int GetHashCode() => Handle.GetHashCode();
}
public partial struct XrPassthroughFB : IEquatable<XrPassthroughFB>
{
public readonly ulong Handle;
public XrPassthroughFB(ulong existingHandle) { Handle = existingHandle; }
public static XrPassthroughFB Null => new XrPassthroughFB(0);
public static implicit operator XrPassthroughFB(ulong handle) => new XrPassthroughFB(handle);
public static bool operator ==(XrPassthroughFB left, XrPassthroughFB right) => left.Handle == right.Handle;
public static bool operator !=(XrPassthroughFB left, XrPassthroughFB right) => left.Handle != right.Handle;
public static bool operator ==(XrPassthroughFB left, ulong right) => left.Handle == right;
public static bool operator !=(XrPassthroughFB left, ulong right) => left.Handle != right;
public bool Equals(XrPassthroughFB h) => Handle == h.Handle;
public override bool Equals(object o) => o is XrPassthroughFB h && Equals(h);
public override int GetHashCode() => Handle.GetHashCode();
}
public partial struct XrPassthroughLayerFB : IEquatable<XrPassthroughLayerFB>
{
public readonly ulong Handle;
public XrPassthroughLayerFB(ulong existingHandle) { Handle = existingHandle; }
public static XrPassthroughLayerFB Null => new XrPassthroughLayerFB(0);
public static implicit operator XrPassthroughLayerFB(ulong handle) => new XrPassthroughLayerFB(handle);
public static bool operator ==(XrPassthroughLayerFB left, XrPassthroughLayerFB right) => left.Handle == right.Handle;
public static bool operator !=(XrPassthroughLayerFB left, XrPassthroughLayerFB right) => left.Handle != right.Handle;
public static bool operator ==(XrPassthroughLayerFB left, ulong right) => left.Handle == right;
public static bool operator !=(XrPassthroughLayerFB left, ulong right) => left.Handle != right;
public bool Equals(XrPassthroughLayerFB h) => Handle == h.Handle;
public override bool Equals(object o) => o is XrPassthroughLayerFB h && Equals(h);
public override int GetHashCode() => Handle.GetHashCode();
}
public partial struct XrGeometryInstanceFB : IEquatable<XrGeometryInstanceFB>
{
public readonly ulong Handle;
public XrGeometryInstanceFB(ulong existingHandle) { Handle = existingHandle; }
public static XrGeometryInstanceFB Null => new XrGeometryInstanceFB(0);
public static implicit operator XrGeometryInstanceFB(ulong handle) => new XrGeometryInstanceFB(handle);
public static bool operator ==(XrGeometryInstanceFB left, XrGeometryInstanceFB right) => left.Handle == right.Handle;
public static bool operator !=(XrGeometryInstanceFB left, XrGeometryInstanceFB right) => left.Handle != right.Handle;
public static bool operator ==(XrGeometryInstanceFB left, ulong right) => left.Handle == right;
public static bool operator !=(XrGeometryInstanceFB left, ulong right) => left.Handle != right;
public bool Equals(XrGeometryInstanceFB h) => Handle == h.Handle;
public override bool Equals(object o) => o is XrGeometryInstanceFB h && Equals(h);
public override int GetHashCode() => Handle.GetHashCode();
}
public partial struct XrSpatialGraphNodeBindingMSFT : IEquatable<XrSpatialGraphNodeBindingMSFT>
{
public readonly ulong Handle;
public XrSpatialGraphNodeBindingMSFT(ulong existingHandle) { Handle = existingHandle; }
public static XrSpatialGraphNodeBindingMSFT Null => new XrSpatialGraphNodeBindingMSFT(0);
public static implicit operator XrSpatialGraphNodeBindingMSFT(ulong handle) => new XrSpatialGraphNodeBindingMSFT(handle);
public static bool operator ==(XrSpatialGraphNodeBindingMSFT left, XrSpatialGraphNodeBindingMSFT right) => left.Handle == right.Handle;
public static bool operator !=(XrSpatialGraphNodeBindingMSFT left, XrSpatialGraphNodeBindingMSFT right) => left.Handle != right.Handle;
public static bool operator ==(XrSpatialGraphNodeBindingMSFT left, ulong right) => left.Handle == right;
public static bool operator !=(XrSpatialGraphNodeBindingMSFT left, ulong right) => left.Handle != right;
public bool Equals(XrSpatialGraphNodeBindingMSFT h) => Handle == h.Handle;
public override bool Equals(object o) => o is XrSpatialGraphNodeBindingMSFT h && Equals(h);
public override int GetHashCode() => Handle.GetHashCode();
}
public partial struct XrSceneObserverMSFT : IEquatable<XrSceneObserverMSFT>
{
public readonly ulong Handle;
public XrSceneObserverMSFT(ulong existingHandle) { Handle = existingHandle; }
public static XrSceneObserverMSFT Null => new XrSceneObserverMSFT(0);
public static implicit operator XrSceneObserverMSFT(ulong handle) => new XrSceneObserverMSFT(handle);
public static bool operator ==(XrSceneObserverMSFT left, XrSceneObserverMSFT right) => left.Handle == right.Handle;
public static bool operator !=(XrSceneObserverMSFT left, XrSceneObserverMSFT right) => left.Handle != right.Handle;
public static bool operator ==(XrSceneObserverMSFT left, ulong right) => left.Handle == right;
public static bool operator !=(XrSceneObserverMSFT left, ulong right) => left.Handle != right;
public bool Equals(XrSceneObserverMSFT h) => Handle == h.Handle;
public override bool Equals(object o) => o is XrSceneObserverMSFT h && Equals(h);
public override int GetHashCode() => Handle.GetHashCode();
}
public partial struct XrSceneMSFT : IEquatable<XrSceneMSFT>
{
public readonly ulong Handle;
public XrSceneMSFT(ulong existingHandle) { Handle = existingHandle; }
public static XrSceneMSFT Null => new XrSceneMSFT(0);
public static implicit operator XrSceneMSFT(ulong handle) => new XrSceneMSFT(handle);
public static bool operator ==(XrSceneMSFT left, XrSceneMSFT right) => left.Handle == right.Handle;
public static bool operator !=(XrSceneMSFT left, XrSceneMSFT right) => left.Handle != right.Handle;
public static bool operator ==(XrSceneMSFT left, ulong right) => left.Handle == right;
public static bool operator !=(XrSceneMSFT left, ulong right) => left.Handle != right;
public bool Equals(XrSceneMSFT h) => Handle == h.Handle;
public override bool Equals(object o) => o is XrSceneMSFT h && Equals(h);
public override int GetHashCode() => Handle.GetHashCode();
}
public partial struct XrSpatialAnchorStoreConnectionMSFT : IEquatable<XrSpatialAnchorStoreConnectionMSFT>
{
public readonly ulong Handle;
public XrSpatialAnchorStoreConnectionMSFT(ulong existingHandle) { Handle = existingHandle; }
public static XrSpatialAnchorStoreConnectionMSFT Null => new XrSpatialAnchorStoreConnectionMSFT(0);
public static implicit operator XrSpatialAnchorStoreConnectionMSFT(ulong handle) => new XrSpatialAnchorStoreConnectionMSFT(handle);
public static bool operator ==(XrSpatialAnchorStoreConnectionMSFT left, XrSpatialAnchorStoreConnectionMSFT right) => left.Handle == right.Handle;
public static bool operator !=(XrSpatialAnchorStoreConnectionMSFT left, XrSpatialAnchorStoreConnectionMSFT right) => left.Handle != right.Handle;
public static bool operator ==(XrSpatialAnchorStoreConnectionMSFT left, ulong right) => left.Handle == right;
public static bool operator !=(XrSpatialAnchorStoreConnectionMSFT left, ulong right) => left.Handle != right;
public bool Equals(XrSpatialAnchorStoreConnectionMSFT h) => Handle == h.Handle;
public override bool Equals(object o) => o is XrSpatialAnchorStoreConnectionMSFT h && Equals(h);
public override int GetHashCode() => Handle.GetHashCode();
}
public partial struct XrFacialTrackerHTC : IEquatable<XrFacialTrackerHTC>
{
public readonly ulong Handle;
public XrFacialTrackerHTC(ulong existingHandle) { Handle = existingHandle; }
public static XrFacialTrackerHTC Null => new XrFacialTrackerHTC(0);
public static implicit operator XrFacialTrackerHTC(ulong handle) => new XrFacialTrackerHTC(handle);
public static bool operator ==(XrFacialTrackerHTC left, XrFacialTrackerHTC right) => left.Handle == right.Handle;
public static bool operator !=(XrFacialTrackerHTC left, XrFacialTrackerHTC right) => left.Handle != right.Handle;
public static bool operator ==(XrFacialTrackerHTC left, ulong right) => left.Handle == right;
public static bool operator !=(XrFacialTrackerHTC left, ulong right) => left.Handle != right;
public bool Equals(XrFacialTrackerHTC h) => Handle == h.Handle;
public override bool Equals(object o) => o is XrFacialTrackerHTC h && Equals(h);
public override int GetHashCode() => Handle.GetHashCode();
}
}
| 63.993127 | 147 | 0.765707 | [
"MIT"
] | EvergineTeam/OpenXR.NET | OpenXRGen/Evergine.Bindings.OpenXR/Generated/Handles.cs | 18,622 | C# |
using CQELight.Abstractions.CQS.Interfaces;
using System;
using System.Collections.Generic;
using System.Text;
namespace CQELight.Abstractions.Dispatcher.Configuration.Commands.Interfaces
{
/// <summary>
/// Contract interface for command dispatching.
/// </summary>
public interface ICommandDispatcherConfiguration
{
/// <summary>
/// Create an error handle to fire if any exception happens on dispatch;
/// </summary>
/// <param name="handler">Handler to fire if exception.</param>
/// <returns>Current configuration.</returns>
ICommandDispatcherConfiguration HandleErrorWith(Action<Exception> handler);
/// <summary>
/// Specify the serializer for command transport.
/// </summary>
/// <typeparam name="T">Type of serializer to use.</typeparam>
/// <returns>Current configuration.</returns>
ICommandDispatcherConfiguration SerializeWith<T>() where T : class, ICommandSerializer;
/// <summary>
/// Set the 'SecurityCritical' flag on this command type to clone it before sending it to
/// dispatcher custom callbacks. It's more secure because instance cannot be modified,
/// but it's slower.
/// </summary>
/// <returns>Current configuration</returns>
ICommandDispatcherConfiguration IsSecurityCritical();
}
}
| 40.911765 | 97 | 0.668584 | [
"MIT"
] | Thanouz/CQELight | src/CQELight/Abstractions/Dispatcher/Configuration/Commands/Interfaces/ICommandDispatcherConfiguration.cs | 1,393 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Master_Page_Example
{
public partial class WebForm1
{
}
}
| 24.5 | 81 | 0.417234 | [
"MIT"
] | Nike98/Master | ASP.NET/Website/Master Page Example/Master Page Example/Home.aspx.designer.cs | 443 | C# |
using Azure.Storage.Blobs;
using Azure.Storage.Blobs.Models;
using Common_Utils;
using Microsoft.Azure.Management.Media;
using Microsoft.Azure.Management.Media.Models;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.IO;
using System.Linq;
using System.Security.Claims;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
using WidevineConfig;
namespace EncryptWithDRM
{
class Program
{
private const string AdaptiveStreamingTransformName = "MyTransformWithAdaptiveStreamingPreset";
// Set this variable to true if you want to authenticate Interactively through the browser using your Azure user account
private const bool UseInteractiveAuth = false;
private const string SourceUri = "https://nimbuscdn-nimbuspm.streaming.mediaservices.windows.net/2b533311-b215-4409-80af-529c3e853622/Ignite-short.mp4";
private static readonly string Issuer = "myIssuer";
private static readonly string Audience = "myAudience";
private static byte[] TokenSigningKey = new byte[40];
private static readonly string ContentKeyPolicyName = "DRMContentKeyPolicy";
public static async Task Main(string[] args)
{
// If Visual Studio is used, let's read the .env file which should be in the root folder (same folder than the solution .sln file).
// Same code will work in VS Code, but VS Code uses also launch.json to get the .env file.
// You can create this ".env" file by saving the "sample.env" file as ".env" file and fill it with the right values.
try
{
DotEnv.Load(".env");
}
catch
{
}
ConfigWrapper config = new(new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables() // parses the values from the optional .env file at the solution root
.Build());
try
{
await RunAsync(config);
}
catch (Exception exception)
{
Console.Error.WriteLine($"{exception.Message}");
if (exception.GetBaseException() is ErrorResponseException apiException)
{
Console.Error.WriteLine(
$"ERROR: API call failed with error code '{apiException.Body.Error.Code}' and message '{apiException.Body.Error.Message}'.");
}
}
Console.WriteLine("Press Enter to continue.");
Console.ReadLine();
}
/// <summary>
/// Run the sample async.
/// </summary>
/// <param name="config">The parm is of type ConfigWrapper. This class reads values from local configuration file.</param>
/// <returns></returns>
// <RunAsync>
private static async Task RunAsync(ConfigWrapper config)
{
IAzureMediaServicesClient client;
try
{
client = await Authentication.CreateMediaServicesClientAsync(config, UseInteractiveAuth);
}
catch (Exception e)
{
Console.Error.WriteLine("TIP: Make sure that you have filled out the appsettings.json file before running this sample.");
Console.Error.WriteLine($"{e.Message}");
return;
}
// Set the polling interval for long running operations to 2 seconds.
// The default value is 30 seconds for the .NET client SDK
client.LongRunningOperationRetryTimeout = 2;
// Creating a unique suffix so that we don't have name collisions if you run the sample
// multiple times without cleaning up.
string uniqueness = Guid.NewGuid().ToString("N");
string jobName = $"job-{uniqueness}";
string locatorName = $"locator-{uniqueness}";
string outputAssetName = $"output-{uniqueness}";
// Ensure that you have the desired encoding Transform. This is really a one time setup operation.
Transform transform = await GetOrCreateTransformAsync(client, config.ResourceGroup, config.AccountName, AdaptiveStreamingTransformName);
// Output from the encoding Job must be written to an Asset, so let's create one
Asset outputAsset = await CreateOutputAssetAsync(client, config.ResourceGroup, config.AccountName, outputAssetName);
Job job = await SubmitJobAsync(client, config.ResourceGroup, config.AccountName, AdaptiveStreamingTransformName, outputAsset.Name, jobName);
// In this demo code, we will poll for Job status
// Polling is not a recommended best practice for production applications because of the latency it introduces.
// Overuse of this API may trigger throttling. Developers should instead use Event Grid.
job = await WaitForJobToFinishAsync(client, config.ResourceGroup, config.AccountName, AdaptiveStreamingTransformName, jobName);
if (job.State == JobState.Finished)
{
// Set a token signing key that you want to use
TokenSigningKey = Convert.FromBase64String(config.SymmetricKey);
// Create the content key policy that configures how the content key is delivered to end clients
// via the Key Delivery component of Azure Media Services.
// We are using the ContentKeyIdentifierClaim in the ContentKeyPolicy which means that the token presented
// to the Key Delivery Component must have the identifier of the content key in it.
ContentKeyPolicy policy = await GetOrCreateContentKeyPolicyAsync(client, config.ResourceGroup, config.AccountName, ContentKeyPolicyName, TokenSigningKey);
StreamingLocator locator = await CreateStreamingLocatorAsync(client, config.ResourceGroup, config.AccountName, outputAsset.Name, locatorName, ContentKeyPolicyName);
// In this example, we want to play the PlayReady (CENC) encrypted stream.
// We need to get the key identifier of the content key where its type is CommonEncryptionCenc.
string keyIdentifier = locator.ContentKeys.Where(k => k.Type == StreamingLocatorContentKeyType.CommonEncryptionCenc).First().Id.ToString();
Console.WriteLine($"KeyIdentifier = {keyIdentifier}");
// In order to generate our test token we must get the ContentKeyId to put in the ContentKeyIdentifierClaim claim.
string token = GetTokenAsync(Issuer, Audience, keyIdentifier, TokenSigningKey);
string dashPath = await GetDASHStreamingUrlAsync(client, config.ResourceGroup, config.AccountName, locator.Name);
Console.WriteLine("Copy and paste the following URL in your browser to play back the file in the Azure Media Player.");
Console.WriteLine("You can use Edge/IE11 for PlayReady and Chrome/Firefox for Widevine.");
Console.WriteLine();
Console.WriteLine($"https://ampdemo.azureedge.net/?url={dashPath}&playready=true&widevine=true&token=Bearer%3D{token}");
Console.WriteLine();
}
Console.WriteLine("When finished testing press enter to cleanup.");
Console.Out.Flush();
Console.ReadLine();
Console.WriteLine("Cleaning up...");
await CleanUpAsync(client, config.ResourceGroup, config.AccountName, AdaptiveStreamingTransformName, job.Name, new List<string> { outputAsset.Name }, ContentKeyPolicyName);
}
// </RunAsync>
/// <summary>
/// Create the content key policy that configures how the content key is delivered to end clients
/// via the Key Delivery component of Azure Media Services.
/// </summary>
/// <param name="client">The Media Services client.</param>
/// <param name="resourceGroupName">The name of the resource group within the Azure subscription.</param>
/// <param name="accountName"> The Media Services account name.</param>
/// <param name="contentKeyPolicyName">The name of the content key policy resource.</param>
/// <returns></returns>
// <GetOrCreateContentKeyPolicy>
private static async Task<ContentKeyPolicy> GetOrCreateContentKeyPolicyAsync(
IAzureMediaServicesClient client,
string resourceGroupName,
string accountName,
string contentKeyPolicyName,
byte[] tokenSigningKey)
{
bool createPolicy = false;
ContentKeyPolicy policy = null;
try
{
policy = await client.ContentKeyPolicies.GetAsync(resourceGroupName, accountName, contentKeyPolicyName);
}
catch (ErrorResponseException ex) when (ex.Response.StatusCode == System.Net.HttpStatusCode.NotFound)
{
createPolicy = true;
}
if (createPolicy)
{
ContentKeyPolicySymmetricTokenKey primaryKey = new ContentKeyPolicySymmetricTokenKey(tokenSigningKey);
List<ContentKeyPolicyTokenClaim> requiredClaims = new List<ContentKeyPolicyTokenClaim>()
{
ContentKeyPolicyTokenClaim.ContentKeyIdentifierClaim
};
List<ContentKeyPolicyRestrictionTokenKey> alternateKeys = null;
ContentKeyPolicyTokenRestriction restriction
= new ContentKeyPolicyTokenRestriction(Issuer, Audience, primaryKey, ContentKeyPolicyRestrictionTokenType.Jwt, alternateKeys, requiredClaims);
ContentKeyPolicyPlayReadyConfiguration playReadyConfig = ConfigurePlayReadyLicenseTemplate();
ContentKeyPolicyWidevineConfiguration widevineConfig = ConfigureWidevineLicenseTemplate();
// ContentKeyPolicyFairPlayConfiguration fairplayConfig = ConfigureFairPlayPolicyOptions();
List<ContentKeyPolicyOption> options = new List<ContentKeyPolicyOption>();
options.Add(
new ContentKeyPolicyOption()
{
Configuration = playReadyConfig,
// If you want to set an open restriction, use
// Restriction = new ContentKeyPolicyOpenRestriction()
Restriction = restriction
});
options.Add(
new ContentKeyPolicyOption()
{
Configuration = widevineConfig,
Restriction = restriction
});
// add CBCS ContentKeyPolicyOption into the list
// options.Add(
// new ContentKeyPolicyOption()
// {
// Configuration = fairplayConfig,
// Restriction = restriction,
// Name = "ContentKeyPolicyOption_CBCS"
// });
policy = await client.ContentKeyPolicies.CreateOrUpdateAsync(resourceGroupName, accountName, contentKeyPolicyName, options);
}
else
{
// Get the signing key from the existing policy.
var policyProperties = await client.ContentKeyPolicies.GetPolicyPropertiesWithSecretsAsync(resourceGroupName, accountName, contentKeyPolicyName);
if (policyProperties.Options[0].Restriction is ContentKeyPolicyTokenRestriction restriction)
{
if (restriction.PrimaryVerificationKey is ContentKeyPolicySymmetricTokenKey signingKey)
{
TokenSigningKey = signingKey.KeyValue;
}
}
}
return policy;
}
// </GetOrCreateContentKeyPolicy>
/// <summary>
/// If the specified transform exists, get that transform.
/// If the it does not exist, creates a new transform with the specified output.
/// In this case, the output is set to encode a video using one of the built-in encoding presets.
/// </summary>
/// <param name="client">The Media Services client.</param>
/// <param name="resourceGroupName">The name of the resource group within the Azure subscription.</param>
/// <param name="accountName"> The Media Services account name.</param>
/// <param name="transformName">The name of the transform.</param>
/// <returns></returns>
// <EnsureTransformExists>
private static async Task<Transform> GetOrCreateTransformAsync(
IAzureMediaServicesClient client,
string resourceGroupName,
string accountName,
string transformName)
{
bool createTransform = false;
Transform transform = null;
try
{
// Does a transform already exist with the desired name? Assume that an existing Transform with the desired name
// also uses the same recipe or Preset for processing content.
transform = client.Transforms.Get(resourceGroupName, accountName, transformName);
}
catch (ErrorResponseException ex) when (ex.Response.StatusCode == System.Net.HttpStatusCode.NotFound)
{
createTransform = true;
}
if (createTransform)
{
// You need to specify what you want it to produce as an output
TransformOutput[] output = new TransformOutput[]
{
new TransformOutput
{
// The preset for the Transform is set to one of Media Services built-in sample presets.
// You can customize the encoding settings by changing this to use "StandardEncoderPreset" class.
Preset = new BuiltInStandardEncoderPreset()
{
// This sample uses the built-in encoding preset for Adaptive Bitrate Streaming.
PresetName = EncoderNamedPreset.AdaptiveStreaming
}
}
};
// Create the Transform with the output defined above
transform = await client.Transforms.CreateOrUpdateAsync(resourceGroupName, accountName, transformName, output);
}
return transform;
}
// </EnsureTransformExists>
/// <summary>
/// Creates an ouput asset. The output from the encoding Job must be written to an Asset.
/// </summary>
/// <param name="client">The Media Services client.</param>
/// <param name="resourceGroupName">The name of the resource group within the Azure subscription.</param>
/// <param name="accountName"> The Media Services account name.</param>
/// <param name="assetName">The output asset name.</param>
/// <returns></returns>
// <CreateOutputAsset>
private static async Task<Asset> CreateOutputAssetAsync(IAzureMediaServicesClient client, string resourceGroupName, string accountName, string assetName)
{
bool existingAsset = true;
Asset outputAsset;
try
{
// Check if an Asset already exists
outputAsset = await client.Assets.GetAsync(resourceGroupName, accountName, assetName);
}
catch (ErrorResponseException ex) when (ex.Response.StatusCode == System.Net.HttpStatusCode.NotFound)
{
existingAsset = false;
}
Asset asset = new Asset();
string outputAssetName = assetName;
if (existingAsset)
{
// Name collision! In order to get the sample to work, let's just go ahead and create a unique asset name
// Note that the returned Asset can have a different name than the one specified as an input parameter.
// You may want to update this part to throw an Exception instead, and handle name collisions differently.
string uniqueness = $"-{Guid.NewGuid():N}";
outputAssetName += uniqueness;
Console.WriteLine("Warning – found an existing Asset with name = " + assetName);
Console.WriteLine("Creating an Asset with this name instead: " + outputAssetName);
}
return await client.Assets.CreateOrUpdateAsync(resourceGroupName, accountName, outputAssetName, asset);
}
// </CreateOutputAsset>
/// <summary>
/// Submits a request to Media Services to apply the specified Transform to a given input video.
/// </summary>
/// <param name="client">The Media Services client.</param>
/// <param name="resourceGroupName">The name of the resource group within the Azure subscription.</param>
/// <param name="accountName"> The Media Services account name.</param>
/// <param name="transformName">The name of the transform.</param>
/// <param name="outputAssetName">The (unique) name of the output asset that will store the result of the encoding job. </param>
/// <param name="jobName">The (unique) name of the job.</param>
/// <returns></returns>
// <SubmitJob>
private static async Task<Job> SubmitJobAsync(IAzureMediaServicesClient client,
string resourceGroup,
string accountName,
string transformName,
string outputAssetName,
string jobName)
{
// This example shows how to encode from any HTTPs source URL - a new feature of the v3 API.
// Change the URL to any accessible HTTPs URL or SAS URL from Azure.
JobInputHttp jobInput =
new JobInputHttp(files: new[] { SourceUri });
JobOutput[] jobOutputs =
{
new JobOutputAsset(outputAssetName),
};
// In this example, we are assuming that the job name is unique.
//
// If you already have a job with the desired name, use the Jobs.Get method
// to get the existing job. In Media Services v3, the Get method on entities returns null
// if the entity doesn't exist (a case-insensitive check on the name).
Job job = await client.Jobs.CreateAsync(
resourceGroup,
accountName,
transformName,
jobName,
new Job
{
Input = jobInput,
Outputs = jobOutputs,
});
return job;
}
// </SubmitJob>
/// <summary>
/// Polls Media Services for the status of the Job.
/// </summary>
/// <param name="client">The Media Services client.</param>
/// <param name="resourceGroupName">The name of the resource group within the Azure subscription.</param>
/// <param name="accountName"> The Media Services account name.</param>
/// <param name="transformName">The name of the transform.</param>
/// <param name="jobName">The name of the job you submitted.</param>
/// <returns></returns>
// <WaitForJobToFinish>
private static async Task<Job> WaitForJobToFinishAsync(IAzureMediaServicesClient client,
string resourceGroupName,
string accountName,
string transformName,
string jobName)
{
const int SleepIntervalMs = 20 * 1000;
Job job;
do
{
job = await client.Jobs.GetAsync(resourceGroupName, accountName, transformName, jobName);
Console.WriteLine($"Job is '{job.State}'.");
for (int i = 0; i < job.Outputs.Count; i++)
{
JobOutput output = job.Outputs[i];
Console.Write($"\tJobOutput[{i}] is '{output.State}'.");
if (output.State == JobState.Processing)
{
Console.Write($" Progress (%): '{output.Progress}'.");
}
Console.WriteLine();
}
if (job.State != JobState.Finished && job.State != JobState.Error && job.State != JobState.Canceled)
{
await Task.Delay(SleepIntervalMs);
}
}
while (job.State != JobState.Finished && job.State != JobState.Error && job.State != JobState.Canceled);
return job;
}
// </WaitForJobToFinish>
/// <summary>
/// Configures PlayReady license template.
/// </summary>
/// <returns></returns>
//<ConfigurePlayReadyLicenseTemplate>
private static ContentKeyPolicyPlayReadyConfiguration ConfigurePlayReadyLicenseTemplate()
{
ContentKeyPolicyPlayReadyLicense objContentKeyPolicyPlayReadyLicense;
objContentKeyPolicyPlayReadyLicense = new ContentKeyPolicyPlayReadyLicense
{
AllowTestDevices = true,
BeginDate = new DateTime(2016, 1, 1),
ContentKeyLocation = new ContentKeyPolicyPlayReadyContentEncryptionKeyFromHeader(),
ContentType = ContentKeyPolicyPlayReadyContentType.UltraVioletStreaming,
LicenseType = ContentKeyPolicyPlayReadyLicenseType.Persistent,
PlayRight = new ContentKeyPolicyPlayReadyPlayRight
{
ImageConstraintForAnalogComponentVideoRestriction = true,
ExplicitAnalogTelevisionOutputRestriction = new ContentKeyPolicyPlayReadyExplicitAnalogTelevisionRestriction(true, 2),
AllowPassingVideoContentToUnknownOutput = ContentKeyPolicyPlayReadyUnknownOutputPassingOption.Allowed
}
};
ContentKeyPolicyPlayReadyConfiguration objContentKeyPolicyPlayReadyConfiguration = new ContentKeyPolicyPlayReadyConfiguration
{
Licenses = new List<ContentKeyPolicyPlayReadyLicense> { objContentKeyPolicyPlayReadyLicense }
};
return objContentKeyPolicyPlayReadyConfiguration;
}
// </ConfigurePlayReadyLicenseTemplate>
/// <summary>
/// Configures Widevine license template.
/// </summary>
/// <returns></returns>
// <ConfigureWidevineLicenseTemplate>
private static ContentKeyPolicyWidevineConfiguration ConfigureWidevineLicenseTemplate()
{
WidevineTemplate template = new WidevineTemplate()
{
AllowedTrackTypes = "SD_HD",
ContentKeySpecs = new ContentKeySpec[]
{
new ContentKeySpec()
{
TrackType = "SD",
SecurityLevel = 1,
RequiredOutputProtection = new OutputProtection()
{
HDCP = "HDCP_NONE"
}
}
},
PolicyOverrides = new PolicyOverrides()
{
CanPlay = true,
CanPersist = true,
CanRenew = false,
RentalDurationSeconds = 2592000,
PlaybackDurationSeconds = 10800,
LicenseDurationSeconds = 604800,
}
};
ContentKeyPolicyWidevineConfiguration objContentKeyPolicyWidevineConfiguration = new ContentKeyPolicyWidevineConfiguration
{
WidevineTemplate = Newtonsoft.Json.JsonConvert.SerializeObject(template)
};
return objContentKeyPolicyWidevineConfiguration;
}
// </ConfigureWidevineLicenseTemplate>
/// <summary>
/// Configures FairPlay policy options.
/// </summary>
/// <returns></returns>
// <ConfigureFairPlayPolicyOptions>
private static ContentKeyPolicyFairPlayConfiguration ConfigureFairPlayPolicyOptions()
{
string askHex = "";
string FairPlayPfxPassword = "";
var appCert = new X509Certificate2("FairPlayPfxPath", FairPlayPfxPassword, X509KeyStorageFlags.Exportable);
byte[] askBytes = Enumerable
.Range(0, askHex.Length)
.Where(x => x % 2 == 0)
.Select(x => Convert.ToByte(askHex.Substring(x, 2), 16))
.ToArray();
ContentKeyPolicyFairPlayConfiguration fairPlayConfiguration =
new ContentKeyPolicyFairPlayConfiguration
{
Ask = askBytes,
FairPlayPfx =
Convert.ToBase64String(appCert.Export(X509ContentType.Pfx, FairPlayPfxPassword)),
FairPlayPfxPassword = FairPlayPfxPassword,
RentalAndLeaseKeyType =
ContentKeyPolicyFairPlayRentalAndLeaseKeyType
.PersistentUnlimited,
RentalDuration = 2249
};
return fairPlayConfiguration;
}
// </ConfigureFairPlayPolicyOptions>
/// <summary>
/// Creates a StreamingLocator for the specified asset and with the specified streaming policy name.
/// Once the StreamingLocator is created the output asset is available to clients for playback.
///
/// This StreamingLocator uses "Predefined_MultiDrmCencStreaming"
/// because this sample encrypts with PlayReady and Widevine (CENC encryption).
///
/// </summary>
/// <param name="client">The Media Services client.</param>
/// <param name="resourceGroupName">The name of the resource group within the Azure subscription.</param>
/// <param name="accountName"> The Media Services account name.</param>
/// <param name="assetName">The name of the output asset.</param>
/// <param name="locatorName">The StreamingLocator name (unique in this case).</param>
/// <returns></returns>
// <CreateStreamingLocator>
private static async Task<StreamingLocator> CreateStreamingLocatorAsync(
IAzureMediaServicesClient client,
string resourceGroup,
string accountName,
string assetName,
string locatorName,
string contentPolicyName)
{
// If you also added FairPlay, use "Predefined_MultiDrmStreaming
StreamingLocator locator = await client.StreamingLocators.CreateAsync(
resourceGroup,
accountName,
locatorName,
new StreamingLocator
{
AssetName = assetName,
// "Predefined_MultiDrmCencStreaming" policy supports envelope and cenc encryption
// And sets two content keys on the StreamingLocator
StreamingPolicyName = "Predefined_MultiDrmCencStreaming",
DefaultContentKeyPolicyName = contentPolicyName
});
return locator;
}
// </CreateStreamingLocator>
/// <summary>
/// Create a token that will be used to protect your stream.
/// Only authorized clients would be able to play the video.
/// </summary>
/// <param name="issuer">The issuer is the secure token service that issues the token. </param>
/// <param name="audience">The audience, sometimes called scope, describes the intent of the token or the resource the token authorizes access to. </param>
/// <param name="keyIdentifier">The content key ID.</param>
/// <param name="tokenVerificationKey">Contains the key that the token was signed with. </param>
/// <returns></returns>
// <GetToken>
private static string GetTokenAsync(string issuer, string audience, string keyIdentifier, byte[] tokenVerificationKey)
{
var tokenSigningKey = new SymmetricSecurityKey(tokenVerificationKey);
SigningCredentials cred = new SigningCredentials(
tokenSigningKey,
// Use the HmacSha256 and not the HmacSha256Signature option, or the token will not work!
SecurityAlgorithms.HmacSha256,
SecurityAlgorithms.Sha256Digest);
Claim[] claims = new Claim[]
{
new Claim(ContentKeyPolicyTokenClaim.ContentKeyIdentifierClaim.ClaimType, keyIdentifier)
};
// To set a limit on how many times the same token can be used to request a key or a license.
// add the "urn:microsoft:azure:mediaservices:maxuses" claim.
// For example, claims.Add(new Claim("urn:microsoft:azure:mediaservices:maxuses", 4));
JwtSecurityToken token = new JwtSecurityToken(
issuer: issuer,
audience: audience,
claims: claims,
notBefore: DateTime.Now.AddMinutes(-5),
expires: DateTime.Now.AddMinutes(60),
signingCredentials: cred);
JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler();
return handler.WriteToken(token);
}
// </GetToken>
/// <summary>
/// Checks if the "default" streaming endpoint is in the running state,
/// if not, starts it.
/// Then, builds the streaming URLs.
/// </summary>
/// <param name="client">The Media Services client.</param>
/// <param name="resourceGroupName">The name of the resource group within the Azure subscription.</param>
/// <param name="accountName"> The Media Services account name.</param>
/// <param name="locatorName">The name of the StreamingLocator that was created.</param>
/// <returns></returns>
// <GetMPEGStreamingUrl>
private static async Task<string> GetDASHStreamingUrlAsync(
IAzureMediaServicesClient client,
string resourceGroupName,
string accountName,
string locatorName)
{
const string DefaultStreamingEndpointName = "default";
string dashPath = "";
StreamingEndpoint streamingEndpoint = await client.StreamingEndpoints.GetAsync(resourceGroupName, accountName, DefaultStreamingEndpointName);
if (streamingEndpoint.ResourceState != StreamingEndpointResourceState.Running)
{
await client.StreamingEndpoints.StartAsync(resourceGroupName, accountName, DefaultStreamingEndpointName);
}
ListPathsResponse paths = await client.StreamingLocators.ListPathsAsync(resourceGroupName, accountName, locatorName);
foreach (StreamingPath path in paths.StreamingPaths)
{
UriBuilder uriBuilder = new UriBuilder
{
Scheme = "https",
Host = streamingEndpoint.HostName
};
// Look for just the DASH path and generate a URL for the Azure Media Player to playback the content with the AES token to decrypt.
// Note that the JWT token is set to expire in 1 hour.
if (path.StreamingProtocol == StreamingPolicyStreamingProtocol.Dash)
{
uriBuilder.Path = path.Paths[0];
dashPath = uriBuilder.ToString();
}
}
return dashPath;
}
// </GetMPEGStreamingUrl>
/// <summary>
/// Downloads the results from the specified output asset, so you can see what you got.
/// </summary>
/// <param name="client">The Media Services client.</param>
/// <param name="resourceGroupName">The name of the resource group within the Azure subscription.</param>
/// <param name="accountName"> The Media Services account name.</param>
/// <param name="assetName">The output asset.</param>
/// <param name="outputFolderName">The name of the folder into which to download the results.</param>
// <DownloadResults>
private static async Task DownloadOutputAssetAsync(
IAzureMediaServicesClient client,
string resourceGroup,
string accountName,
string assetName,
string outputFolderName)
{
if (!Directory.Exists(outputFolderName))
{
Directory.CreateDirectory(outputFolderName);
}
AssetContainerSas assetContainerSas = await client.Assets.ListContainerSasAsync(
resourceGroup,
accountName,
assetName,
permissions: AssetContainerPermission.Read,
expiryTime: DateTime.UtcNow.AddHours(1).ToUniversalTime());
Uri containerSasUrl = new Uri(assetContainerSas.AssetContainerSasUrls.FirstOrDefault());
BlobContainerClient container = new BlobContainerClient(containerSasUrl);
string directory = Path.Combine(outputFolderName, assetName);
Directory.CreateDirectory(directory);
Console.WriteLine($"Downloading output results to '{directory}'...");
string continuationToken = null;
IList<Task> downloadTasks = new List<Task>();
do
{
var resultSegment = container.GetBlobs().AsPages(continuationToken);
foreach (Azure.Page<BlobItem> blobPage in resultSegment)
{
foreach (BlobItem blobItem in blobPage.Values)
{
var blobClient = container.GetBlobClient(blobItem.Name);
string filename = Path.Combine(directory, blobItem.Name);
downloadTasks.Add(blobClient.DownloadToAsync(filename));
}
// Get the continuation token and loop until it is empty.
continuationToken = blobPage.ContinuationToken;
}
} while (continuationToken != "");
await Task.WhenAll(downloadTasks);
Console.WriteLine("Download complete.");
}
// </DownloadResults>
/// <summary>
/// Deletes the jobs, assets and potentially the content key policy that were created.
/// Generally, you should clean up everything except objects
/// that you are planning to reuse (typically, you will reuse Transforms, and you will persist output assets and StreamingLocators).
/// </summary>
/// <param name="client"></param>
/// <param name="resourceGroupName"></param>
/// <param name="accountName"></param>
/// <param name="transformName"></param>
/// <param name="jobName"></param>
/// <param name="assetNames"></param>
/// <param name="contentKeyPolicyName"></param>
/// <returns></returns>
// <CleanUp>
private static async Task CleanUpAsync(
IAzureMediaServicesClient client,
string resourceGroupName,
string accountName,
string transformName,
string jobName,
List<string> assetNames,
string contentKeyPolicyName = null
)
{
await client.Jobs.DeleteAsync(resourceGroupName, accountName, transformName, jobName);
foreach (var assetName in assetNames)
{
await client.Assets.DeleteAsync(resourceGroupName, accountName, assetName);
}
if (contentKeyPolicyName != null)
{
client.ContentKeyPolicies.Delete(resourceGroupName, accountName, contentKeyPolicyName);
}
}
// </CleanUp>
}
}
| 46.318584 | 184 | 0.600688 | [
"MIT"
] | Azure-Samples/media-services-v3-dotnet-tutorials | AMSV3Tutorials/EncryptWithDRM/Program.cs | 36,640 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Text;
namespace UITests.Shared.Helpers
{
[Windows.UI.Xaml.Data.Bindable]
public class BindableBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void RaisePropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
protected void RaiseAllPropertiesChanged()
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(string.Empty));
}
}
}
| 25.48 | 92 | 0.799058 | [
"Apache-2.0"
] | 06needhamt/uno | src/SamplesApp/UITests.Shared/Helpers/BindableBase.cs | 639 | C# |
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.Aws.Iam.Inputs
{
public sealed class GetPolicyDocumentStatementInputArgs : Pulumi.ResourceArgs
{
[Input("actions")]
private InputList<string>? _actions;
/// <summary>
/// List of actions that this statement either allows or denies. For example, `["ec2:RunInstances", "s3:*"]`.
/// </summary>
public InputList<string> Actions
{
get => _actions ?? (_actions = new InputList<string>());
set => _actions = value;
}
[Input("conditions")]
private InputList<Inputs.GetPolicyDocumentStatementConditionInputArgs>? _conditions;
/// <summary>
/// Configuration block for a condition. Detailed below.
/// </summary>
public InputList<Inputs.GetPolicyDocumentStatementConditionInputArgs> Conditions
{
get => _conditions ?? (_conditions = new InputList<Inputs.GetPolicyDocumentStatementConditionInputArgs>());
set => _conditions = value;
}
/// <summary>
/// Whether this statement allows or denies the given actions. Valid values are `Allow` and `Deny`. Defaults to `Allow`.
/// </summary>
[Input("effect")]
public Input<string>? Effect { get; set; }
[Input("notActions")]
private InputList<string>? _notActions;
/// <summary>
/// List of actions that this statement does *not* apply to. Use to apply a policy statement to all actions *except* those listed.
/// </summary>
public InputList<string> NotActions
{
get => _notActions ?? (_notActions = new InputList<string>());
set => _notActions = value;
}
[Input("notPrincipals")]
private InputList<Inputs.GetPolicyDocumentStatementNotPrincipalInputArgs>? _notPrincipals;
/// <summary>
/// Like `principals` except these are principals that the statement does *not* apply to.
/// </summary>
public InputList<Inputs.GetPolicyDocumentStatementNotPrincipalInputArgs> NotPrincipals
{
get => _notPrincipals ?? (_notPrincipals = new InputList<Inputs.GetPolicyDocumentStatementNotPrincipalInputArgs>());
set => _notPrincipals = value;
}
[Input("notResources")]
private InputList<string>? _notResources;
/// <summary>
/// List of resource ARNs that this statement does *not* apply to. Use to apply a policy statement to all resources *except* those listed.
/// </summary>
public InputList<string> NotResources
{
get => _notResources ?? (_notResources = new InputList<string>());
set => _notResources = value;
}
[Input("principals")]
private InputList<Inputs.GetPolicyDocumentStatementPrincipalInputArgs>? _principals;
/// <summary>
/// Configuration block for principals. Detailed below.
/// </summary>
public InputList<Inputs.GetPolicyDocumentStatementPrincipalInputArgs> Principals
{
get => _principals ?? (_principals = new InputList<Inputs.GetPolicyDocumentStatementPrincipalInputArgs>());
set => _principals = value;
}
[Input("resources")]
private InputList<string>? _resources;
/// <summary>
/// List of resource ARNs that this statement applies to. This is required by AWS if used for an IAM policy.
/// </summary>
public InputList<string> Resources
{
get => _resources ?? (_resources = new InputList<string>());
set => _resources = value;
}
/// <summary>
/// Sid (statement ID) is an identifier for a policy statement.
/// </summary>
[Input("sid")]
public Input<string>? Sid { get; set; }
public GetPolicyDocumentStatementInputArgs()
{
}
}
}
| 36.689655 | 146 | 0.618186 | [
"ECL-2.0",
"Apache-2.0"
] | rapzo/pulumi-aws | sdk/dotnet/Iam/Inputs/GetPolicyDocumentStatementArgs.cs | 4,256 | C# |
using GTAVModdingLauncher.Ui;
using GTAVModdingLauncher.Ui.Dialogs;
using GTAVModdingLauncher.Work;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using PursuitLib;
using PursuitLib.Extensions;
using PursuitLib.IO;
using PursuitLib.IO.PPF;
using PursuitLib.Windows;
using PursuitLib.Windows.WPF;
using PursuitLib.Windows.WPF.Dialogs;
using PursuitLib.Windows.WPF.Modern;
using PursuitLib.Work;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Reflection;
using System.Runtime.Serialization.Formatters.Binary;
using System.Security.AccessControl;
using System.Security.Principal;
using System.Text;
using System.Threading;
using System.Windows;
namespace GTAVModdingLauncher
{
/// <summary>
/// Main launcher class
/// </summary>
public class Launcher : ModernApp
{
public static Launcher Instance { get; private set; }
private const int GameInitTime = 60000;
private const int GameCheckInterval = 5000;
private const int GameWaitTimeout = 360000;
public MainWindow Window { get; private set; } = null;
public UserConfig Config { get; private set; }
public UIManager UiManager { get; private set; }
/// <summary>
/// Indicates if the user chose to close the application. <see cref="CloseLauncher"/> <seealso cref="OnWindowClosing"/>
/// </summary>
private bool closeRequested = false;
public Launcher()
{
Instance = this;
if(File.Exists("Resources.ppf"))
ResourceManager.RegisterProvider("appRsrc", new PPFFile("Resources.ppf"));
I18n.Initialize();
this.Config = new UserConfig();
if(this.Config.UseLogFile)
Log.LogFile = Path.Combine(this.UserDirectory, "latest.log");
Log.Info(this.DisplayName);
Log.Info("Using PursuitLib " + typeof(Log).GetVersion());
Log.Info("Loading languages...");
I18n.LoadLanguage(this.Config.Language);
if(!Directory.Exists("Profiles"))
Directory.CreateDirectory("Profiles");
}
/// <summary>
/// Links MainWindow with this class using events
/// </summary>
public void InitUI(MainWindow window)
{
Log.Info("Initializing user interface...");
this.Window = window;
this.Window.EnsureFitsScreen();
this.Window.Closing += OnWindowClosing;
this.Window.Closed += OnWindowClosed;
this.Window.AboutButton.Click += ShowAboutPopup;
this.Window.SettingsButton.Click += (s, a) => this.Window.Settings.Open();
this.Window.CreateButton.Click += (s, a) => new CreateDialog(this.Window).Show();
this.UiManager = new UIManager(this.Window);
this.UiManager.WindowTitle = this.DisplayName;
this.WorkManager.ProgressDisplay = new MultiProgressDisplay((WPFProgressBar)this.Window.Progress, new TaskBarProgress());
this.Theme = this.Config.Theme;
this.InitLauncher();
this.UiManager.RandomizeBackground();
this.UiManager.UpdateProfiles();
this.UiManager.UIEnabled = true;
this.UiManager.LauncherVersion = "Launcher " + this.Version;
I18n.Reload += OnI18nReload;
this.OnI18nReload(null);
if(this.Config.DisplayNews)
this.Window.News.StartCycle();
if(this.Config.CheckUpdates)
this.WorkManager.StartWork(CheckUpdates);
}
private void InitLauncher()
{
Log.Info("Initializing launcher...");
SteamHelper.Initialize();
if(this.Config.SelectedInstall != null && (this.Config.SelectedInstall.Path == null || !Directory.Exists(this.Config.SelectedInstall.Path)))
this.Config.SelectedInstall = null;
if(this.Config.SelectedInstall == null)
{
GTAInstall[] installs = GTAInstall.FindInstalls();
if(installs.Length > 0)
this.Config.SelectedInstall = installs[0];
else
{
LocalizedMessage.Show("GTANotFound", "Info", DialogIcon.Information, DialogButtons.Ok);
HostWindow host = new HostWindow();
host.Content = new ChooseInstallDialog(host);
host.ShowDialog();
if(this.Config.SelectedInstall == null)
{
Environment.Exit(1);
return;
}
}
this.Config.Save();
}
Log.Info("Using GTA V installation at " + this.Config.SelectedInstall.Path);
Log.Info("Installation type: " + this.Config.SelectedInstall.Type);
if(Path.GetFullPath(this.WorkingDirectory).Equals(Path.GetFullPath(this.Config.SelectedInstall.Path)))
{
LocalizedMessage.Show("InstalledInGTA", "Error", DialogIcon.Error, DialogButtons.Ok);
Environment.Exit(1);
}
GameScanner.Init();
Log.Info("Loading profiles...");
string profilesDir = Path.Combine(this.UserDirectory, "Profiles");
if(!Directory.Exists(profilesDir))
Directory.CreateDirectory(profilesDir);
if(this.Config.VanillaProfile == null)
{
Log.Info("Vanilla profile not found. Creating it");
this.Config.Profiles.Add(new Profile("Vanilla", true));
}
foreach(string dir in Directory.EnumerateDirectories(profilesDir))
{
string name = Path.GetFileName(dir);
if(!this.Config.ProfileExists(name))
this.Config.Profiles.Add(new Profile(name));
}
if(this.Config.Profile == null)
{
Log.Info("Current profile is invalid");
if(GameScanner.IsGTAModded())
{
Log.Info("GTA is currently modded: creating new modded profile");
Profile profile = new Profile(this.GetNewProfileName());
this.Config.Profiles.Add(profile);
this.Config.Profile = profile;
}
else
{
Log.Info("GTA is currently not modded: considering the game vanilla");
this.Config.CurrentProfile = this.Config.VanillaProfile.Name;
}
}
}
private void CheckUpdates()
{
JObject obj = this.IsUpToDate();
if(obj != null)
this.Window.Dispatcher.Invoke(() => ShowUpdatePopup(this.Window, obj));
}
/// <summary>
/// Checks whether the software is up to date or not
/// </summary>
/// <returns>A JObject representing the latest update, or null if it's up to date</returns>
public JObject IsUpToDate()
{
try
{
HttpWebRequest request = WebRequest.CreateHttp("https://api.github.com/repos/fr-Pursuit/GTAVModdingLauncher/releases/latest");
request.UserAgent = "GTAVModdingLauncher-" + Version;
using(HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
if(response.StatusCode == HttpStatusCode.OK)
{
using(StreamReader streamReader = new StreamReader(response.GetResponseStream()))
using(JsonReader reader = new JsonTextReader(streamReader))
{
JObject obj = JObject.Load(reader);
if(new Version(obj["tag_name"].ToString()) > Version)
{
Log.Info("New update found (" + obj["name"] + ')');
return obj;
}
}
}
else Log.Warn("Unable to check for updates. Response code was " + response.StatusCode + " (" + response.StatusDescription + ')');
}
}
catch(Exception e)
{
Log.Warn("Unable to check for updates.");
Log.Warn(e.ToString());
}
return null;
}
/// <summary>
/// Shows a popup telling the user a new update is out.
/// </summary>
/// <param name="window">The parent window</param>
/// <param name="obj">A JObject representing the update</param>
public void ShowUpdatePopup(Window window, JObject obj)
{
if(this.Window.CheckAccess())
{
if(MessageDialog.Show(window, I18n.Localize("Dialog", "Update", obj["name"], obj["body"].ToString().Replace("\\", "")), I18n.Localize("Dialog.Caption", "Update"), DialogIcon.Information, DialogButtons.Yes | DialogButtons.No) == DialogStandardResult.Yes)
{
Process.Start(obj["assets"][0]["browser_download_url"].ToString());
this.CloseLauncher();
}
}
else this.Window.Dispatcher.Invoke(() => ShowUpdatePopup(window, obj));
}
/// <summary>
/// Called whenever mods are present in the vanilla profile.
/// Asks the user if they want to delete the mods, or create a new profile with these mods
/// </summary>
/// <returns>true if the user chose a valid outcome, false if the user chose to cancel</returns>
private bool HandleVanillaMods()
{
Log.Warn("GTA V is modded, but the vanilla profile is selected!");
DialogStandardResult result = LocalizedMessage.Show(this.Window, "ModsOnVanilla", "Warn", DialogIcon.Warning, DialogButtons.Yes | DialogButtons.No | DialogButtons.Cancel);
if(result == DialogStandardResult.Yes)
{
string name = this.GetNewProfileName();
Profile profile = new Profile(name);
this.Config.Profiles.Add(profile);
this.Config.Profile = profile;
this.Config.Save();
this.UiManager.AddProfile(profile);
this.UiManager.UpdateActiveProfile();
return true;
}
else if(result == DialogStandardResult.No)
{
new PerformJobDialog(this.WorkManager, new DeleteMods()).Show(this.WorkManager);
return true;
}
else return false;
}
/// <summary>
/// Ensure the vanilla profile is unmodded, and update the current profile's files
/// </summary>
/// <returns>true if the game can be launched, false otherwise</returns>
private bool UpdateCurrentProfile()
{
Profile currentProfile = this.Config.Profile;
if(currentProfile.IsVanilla && GameScanner.IsGTAModded())
{
if(this.HandleVanillaMods())
currentProfile = this.Config.Profile;
else return false;
}
if(!currentProfile.IsVanilla && Directory.Exists(currentProfile.ExtFolder))
{
string path = currentProfile.ExtFolder;
if(Directory.GetFileSystemEntries(path).GetLength(0) != 0)
{
DialogStandardResult result = LocalizedMessage.Show(this.Window, "UpdateProfile", "UpdateProfile", DialogIcon.Information, DialogButtons.Yes | DialogButtons.No);
if(result == DialogStandardResult.Yes)
{
GameScanner.ListRootMods(out List<string> modFiles, out List<string> modDirs);
List<string> dlcMods = GameScanner.ListDlcMods();
foreach(string dir in modDirs)
this.WorkManager.QueueJob(new MoveJob(dir, Path.Combine(path, IOUtil.GetRelativePath(dir, this.Config.SelectedInstall.Path))));
foreach(string file in modFiles)
{
if(this.Config.DeleteLogs && file.EndsWith(".log"))
this.WorkManager.QueueJob(new DeleteJob(file));
else this.WorkManager.QueueJob(new MoveJob(file, Path.Combine(path, IOUtil.GetRelativePath(file, this.Config.SelectedInstall.Path))));
}
foreach(string mod in dlcMods)
this.WorkManager.QueueJob(new MoveJob(mod, Path.Combine(path, IOUtil.GetRelativePath(mod, this.Config.SelectedInstall.Path))));
new PerformJobsDialog(this.WorkManager).Show();
}
}
return true;
}
else return true;
}
public bool CanLaunchGame()
{
if(this.Config.SelectedInstall.Type == InstallType.Retail)
{
if(File.Exists(Path.Combine(this.Config.SelectedInstall.Path, "GTA5.exe")))
return true;
else
{
LocalizedMessage.Show(this.Window, "NoExecutable", "Error", DialogIcon.Error, DialogButtons.Ok);
return false;
}
}
else if(this.Config.SelectedInstall.Type == InstallType.Steam)
{
if(SteamHelper.IsAvailable)
return true;
else
{
LocalizedMessage.Show(this.Window, "NoSteam", "Error", DialogIcon.Error, DialogButtons.Ok);
return false;
}
}
else if(this.Config.SelectedInstall.Type == InstallType.Epic)
return true;
else return false;
}
/// <summary>
/// Used when a profile needs to be created without the user giving it a name
/// </summary>
/// <returns>A generic profile name that doesn't already exist</returns>
public string GetNewProfileName()
{
string baseName = I18n.Localize("Random", "ModdedProfile");
if(this.Config.ProfileExists(baseName))
{
int i = 1;
while(this.Config.ProfileExists(baseName + ' ' + i))
i++;
return baseName + ' ' + i;
}
else return baseName;
}
public void UpdateGameInfo()
{
string exePath = Path.Combine(this.Config.SelectedInstall.Path, "GTA5.exe");
if(File.Exists(exePath))
this.UiManager.GtaVersion = "GTA V " + FileVersionInfo.GetVersionInfo(exePath).FileVersion;
if(this.Config.SelectedInstall.Type == InstallType.Steam)
this.UiManager.GtaType = I18n.Localize("Label", "SteamVersion");
else if(this.Config.SelectedInstall.Type == InstallType.Retail)
this.UiManager.GtaType = I18n.Localize("Label", "RetailVersion");
else if(this.Config.SelectedInstall.Type == InstallType.Epic)
this.UiManager.GtaType = I18n.Localize("Label", "EpicVersion");
else this.UiManager.GtaType = "";
if(Directory.Exists(this.Config.SelectedInstall.Path))
{
DirectoryInfo dir = new DirectoryInfo(this.Config.SelectedInstall.Path);
DirectorySecurity sec = dir.GetAccessControl();
IdentityReference id = new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null);
bool hasPerms = false;
foreach(FileSystemAccessRule rule in sec.GetAccessRules(true, true, typeof(SecurityIdentifier)))
{
if(rule.IdentityReference == id && rule.FileSystemRights == FileSystemRights.FullControl && rule.AccessControlType == AccessControlType.Allow)
{
hasPerms = true;
break;
}
}
if(!hasPerms)
{
Log.Warn("The launcher doesn't have full control over the game's directory!");
if(User.HasElevatedPrivileges)
{
Log.Info("The launcher is running with elevated privileges. Getting full control...");
sec.SetAccessRule(new FileSystemAccessRule(id, FileSystemRights.FullControl, AccessControlType.Allow));
dir.SetAccessControl(sec);
}
else
{
Log.Info("Asking for elevated privileges...");
if(LocalizedCMessage.Show(this.Window, "LauncherNeedsPerms", "Info", DialogIcon.Shield, new DialogButton("Ok", true), "Cancel") == "Ok")
{
ProcessBuilder builder = new ProcessBuilder(Assembly.GetEntryAssembly().Location);
builder.LaunchAsAdmin = true;
builder.StartProcess();
}
Environment.Exit(0);
}
}
}
else
{
HostDialog host = new HostDialog(this.Window);
host.Content = new ChooseInstallDialog(host);
host.Show();
}
}
/// <summary>
/// Change the active profile and move the mods accordingly
/// </summary>
/// <param name="selected"></param>
/// <returns>True if the profile was successfully changed, false otherwise</returns>
public bool SwitchProfileTo(Profile selected)
{
if(this.Config.Profile != selected)
{
Profile oldProfile = this.Config.Profile;
this.UiManager.Working = true;
if(oldProfile.IsVanilla && GameScanner.IsGTAModded())
{
if(this.HandleVanillaMods())
oldProfile = this.Config.Profile;
else return false;
}
Log.Info("Switching from profile '" + oldProfile + "' to '" + selected + "'.");
this.WorkManager.ProgressDisplay.ProgressState = ProgressState.Indeterminate;
try
{
if(!oldProfile.IsVanilla)
{
string profilePath = oldProfile.ExtFolder;
GameScanner.ListRootMods(out List<string> modFiles, out List<string> modDirs);
List<string> dlcMods = GameScanner.ListDlcMods();
foreach(string dir in modDirs)
this.WorkManager.QueueJob(new MoveJob(dir, Path.Combine(profilePath, IOUtil.GetRelativePath(dir, this.Config.SelectedInstall.Path))));
foreach(string file in modFiles)
{
if(this.Config.DeleteLogs && file.EndsWith(".log"))
this.WorkManager.QueueJob(new DeleteJob(file));
else this.WorkManager.QueueJob(new MoveJob(file, Path.Combine(profilePath, IOUtil.GetRelativePath(file, this.Config.SelectedInstall.Path))));
}
foreach(string mod in dlcMods)
this.WorkManager.QueueJob(new MoveJob(mod, Path.Combine(profilePath, IOUtil.GetRelativePath(mod, this.Config.SelectedInstall.Path))));
}
if(!selected.IsVanilla)
{
string profilePath = selected.ExtFolder;
foreach(string entry in Directory.GetFileSystemEntries(profilePath))
this.WorkManager.QueueJob(new MoveJob(entry, Path.Combine(this.Config.SelectedInstall.Path, Path.GetFileName(entry))));
}
this.WorkManager.PerformJobs();
this.Config.Profile = selected;
this.Config.Save();
this.UiManager.UpdateActiveProfile();
}
catch(IOException e)
{
Log.Error(e.ToString());
LocalizedMessage.Show(this.Window, "ProfileSwitchError", "FatalError", DialogIcon.Error, DialogButtons.Ok);
Process.GetCurrentProcess().Kill();
}
this.WorkManager.ProgressDisplay.ProgressState = ProgressState.NoProgress;
this.UiManager.Working = false;
return true;
}
else return true;
}
public void LaunchGame(bool online)
{
Log.Info("Launching game...");
Profile profile = this.Config.Profile;
if(this.CanLaunchGame() && this.UpdateCurrentProfile())
{
if(online && !profile.IsVanilla)
{
LocalizedMessage.Show(this.Window, "CantPlayOnline", "Impossible", DialogIcon.Error, DialogButtons.Ok);
this.UiManager.Working = false;
this.UiManager.UIEnabled = true;
}
else
{
ProcessBuilder builder = new ProcessBuilder();
builder.WorkingDirectory = this.Config.SelectedInstall.Path;
if(this.Config.UseRph && this.Config.SelectedInstall.Type != InstallType.Epic && File.Exists(Path.Combine(this.Config.SelectedInstall.Path, "RAGEPluginHook.exe")))
{
Log.Info("Starting RAGE Plugin Hook process...");
builder.FilePath = Path.Combine(this.Config.SelectedInstall.Path, "RAGEPluginHook.exe");
}
else if(this.Config.SelectedInstall.Type == InstallType.Steam)
{
Log.Info("Starting steam game process...");
builder.FilePath = SteamHelper.ExecutablePath;
builder.AddArgument("-applaunch 271590");
if(!File.Exists(builder.FilePath))
{
builder.FilePath = null;
Log.Error("Error: Steam.exe not found");
LocalizedMessage.Show(this.Window, "SteamNotFound", "Error", DialogIcon.Error, DialogButtons.Ok);
}
}
else if(this.Config.SelectedInstall.Type == InstallType.Retail)
{
Log.Info("Starting retail game process...");
builder.FilePath = Path.Combine(this.Config.SelectedInstall.Path, "PlayGTAV.exe");
if(!File.Exists(builder.FilePath))
{
builder.FilePath = null;
Log.Error("Error: PlayGTAV.exe not found");
LocalizedMessage.Show(this.Window, "PlayGTANotFound", "Error", DialogIcon.Error, DialogButtons.Ok);
}
}
else if(this.Config.SelectedInstall.Type == InstallType.Epic)
{
Log.Info("Starting epic game process...");
builder.FilePath = "com.epicgames.launcher://apps/9d2d0eb64d5c44529cece33fe2a46482?action=launch&silent=true";
}
if(builder.FilePath != null)
{
Log.Info("Setting game language to " + this.Config.GtaLanguage);
builder.AddArgument("-uilanguage " + this.Config.GtaLanguage);
if(online)
builder.AddArgument("-StraightIntoFreemode");
Log.Info("Executing " + builder);
builder.StartProcess();
this.Window.Dispatcher.Invoke(() => this.Window.Visibility = Visibility.Hidden);
if(this.Config.KillLauncher)
{
Log.Info("Waiting for game to launch...");
long start = Environment.TickCount;
while(true)
{
Process[] processes = Process.GetProcessesByName("GTA5");
if(processes.Length > 0)
{
Process process = processes[0];
if(DateTime.Now - process.StartTime > TimeSpan.FromMilliseconds(GameInitTime))
{
Log.Info("Closing Rockstar launcher");
ProcessUtil.Kill("PlayGTAV");
ProcessUtil.Kill("GTAVLauncher");
ProcessUtil.Kill("LauncherPatcher");
ProcessUtil.Kill("Launcher");
break;
}
}
else Thread.Sleep(GameCheckInterval);
if(Environment.TickCount - start > GameWaitTimeout)
{
Log.Warn("The game wasn't launched properly.");
break;
}
}
}
this.CloseLauncher();
}
else
{
this.UiManager.Working = false;
this.UiManager.UIEnabled = true;
}
}
}
else
{
Log.Info("Aborting game launch.");
this.UiManager.Working = false;
this.UiManager.UIEnabled = true;
}
}
public void CloseLauncher()
{
this.closeRequested = true;
if(Application.Current.CheckAccess())
Application.Current.Shutdown();
else Application.Current.Dispatcher.Invoke(Application.Current.Shutdown);
}
private void ShowAboutPopup(object sender, EventArgs e)
{
MessageDialog.Show(this.Window, I18n.Localize("Dialog", "About", this.Version), I18n.Localize("Dialog.Caption", "About"), DialogIcon.Information, DialogButtons.Ok);
}
private void OnI18nReload(string newLanguage)
{
this.UpdateGameInfo();
}
protected override void FillCrashReport(Exception exception, StringBuilder report)
{
base.FillCrashReport(exception, report);
report.Append("-- Launcher state --\n");
try
{
report.Append("Is window initialized: " + (this.Window != null) + '\n');
if(this.Config != null)
{
report.Append("Install: " + this.Config.SelectedInstall + '\n');
report.Append("Current profile: " + this.Config.Profile + '\n');
}
}
catch(Exception)
{
report.Append("~Unexpected error~\n");
}
report.Append('\n');
report.Append("-- UI state --\n");
try
{
if(this.UiManager != null)
{
report.Append("Is working: " + this.UiManager.Working + '\n');
report.Append("Are buttons enabled: " + this.UiManager.UIEnabled + '\n');
}
else report.Append("Unable to get UI state");
}
catch(Exception)
{
report.Append("~Unexpected error~\n");
}
}
private void OnWindowClosing(object sender, CancelEventArgs e)
{
if(!this.closeRequested && this.WorkManager.IsWorking)
{
e.Cancel = true;
LocalizedMessage.Show(this.Window, "LauncherWorking", "Impossible", DialogIcon.Information, DialogButtons.Ok);
}
}
private void OnWindowClosed(object sender, EventArgs e)
{
this.Window.News.Dispose();
if(this.Config.Dirty)
this.Config.Save();
}
}
}
| 31.527817 | 257 | 0.680829 | [
"MIT"
] | A1ex-N/GTAVModdingLauncher | Launcher.cs | 22,103 | C# |
using UnityEditor;
using UnityEngine;
using UnityEngine.UI;
namespace Coffee.UIEffects.Editors
{
/// <summary>
/// UIEffect editor.
/// </summary>
[CustomEditor(typeof(UIGradient))]
[CanEditMultipleObjects]
public class UIGradientEditor : Editor
{
private static readonly GUIContent k_TextVerticalOffset = new GUIContent("Vertical Offset");
private static readonly GUIContent k_TextHorizontalOffset = new GUIContent("Horizontal Offset");
private static readonly GUIContent k_TextOffset = new GUIContent("Offset");
private static readonly GUIContent k_TextLeft = new GUIContent("Left");
private static readonly GUIContent k_TextRight = new GUIContent("Right");
private static readonly GUIContent k_TextTop = new GUIContent("Top");
private static readonly GUIContent k_TextBottom = new GUIContent("Bottom");
private static readonly GUIContent k_TextColor1 = new GUIContent("Color 1");
private static readonly GUIContent k_TextColor2 = new GUIContent("Color 2");
private static readonly GUIContent k_TextDiagonalColor = new GUIContent("Diagonal Color");
SerializedProperty _spDirection;
SerializedProperty _spColor1;
SerializedProperty _spColor2;
SerializedProperty _spColor3;
SerializedProperty _spColor4;
SerializedProperty _spRotation;
SerializedProperty _spOffset1;
SerializedProperty _spOffset2;
SerializedProperty _spIgnoreAspectRatio;
SerializedProperty _spGradientStyle;
SerializedProperty _spColorSpace;
//################################
// Public/Protected Members.
//################################
/// <summary>
/// This function is called when the object becomes enabled and active.
/// </summary>
protected void OnEnable()
{
_spIgnoreAspectRatio = serializedObject.FindProperty("m_IgnoreAspectRatio");
_spDirection = serializedObject.FindProperty("m_Direction");
_spColor1 = serializedObject.FindProperty("m_Color1");
_spColor2 = serializedObject.FindProperty("m_Color2");
_spColor3 = serializedObject.FindProperty("m_Color3");
_spColor4 = serializedObject.FindProperty("m_Color4");
_spRotation = serializedObject.FindProperty("m_Rotation");
_spOffset1 = serializedObject.FindProperty("m_Offset1");
_spOffset2 = serializedObject.FindProperty("m_Offset2");
_spGradientStyle = serializedObject.FindProperty("m_GradientStyle");
_spColorSpace = serializedObject.FindProperty("m_ColorSpace");
}
public override void OnInspectorGUI()
{
serializedObject.Update();
//================
// Direction.
//================
EditorGUILayout.PropertyField(_spDirection);
//================
// Color.
//================
switch ((UIGradient.Direction) _spDirection.intValue)
{
case UIGradient.Direction.Horizontal:
EditorGUILayout.PropertyField(_spColor1, k_TextLeft);
EditorGUILayout.PropertyField(_spColor2, k_TextRight);
break;
case UIGradient.Direction.Vertical:
EditorGUILayout.PropertyField(_spColor1, k_TextTop);
EditorGUILayout.PropertyField(_spColor2, k_TextBottom);
break;
case UIGradient.Direction.Angle:
EditorGUILayout.PropertyField(_spColor1, k_TextColor1);
EditorGUILayout.PropertyField(_spColor2, k_TextColor2);
break;
case UIGradient.Direction.Diagonal:
Rect r = EditorGUILayout.GetControlRect(false, 34);
r = EditorGUI.PrefixLabel(r, k_TextDiagonalColor);
float w = r.width / 2;
EditorGUI.PropertyField(new Rect(r.x, r.y, w, 16), _spColor3, GUIContent.none);
EditorGUI.PropertyField(new Rect(r.x + w, r.y, w, 16), _spColor4, GUIContent.none);
EditorGUI.PropertyField(new Rect(r.x, r.y + 18, w, 16), _spColor1, GUIContent.none);
EditorGUI.PropertyField(new Rect(r.x + w, r.y + 18, w, 16), _spColor2, GUIContent.none);
break;
}
//================
// Angle.
//================
if ((int) UIGradient.Direction.Angle <= _spDirection.intValue)
{
EditorGUILayout.PropertyField(_spRotation);
}
//================
// Offset.
//================
if ((int) UIGradient.Direction.Diagonal == _spDirection.intValue)
{
EditorGUILayout.PropertyField(_spOffset1, k_TextVerticalOffset);
EditorGUILayout.PropertyField(_spOffset2, k_TextHorizontalOffset);
}
else
{
EditorGUILayout.PropertyField(_spOffset1, k_TextOffset);
}
//================
// Advanced options.
//================
EditorGUILayout.Space();
EditorGUILayout.LabelField("Advanced Options", EditorStyles.boldLabel);
EditorGUI.indentLevel++;
{
//if ((target as UIGradient).targetGraphic is Text)
EditorGUILayout.PropertyField(_spGradientStyle);
EditorGUILayout.PropertyField(_spColorSpace);
EditorGUILayout.PropertyField(_spIgnoreAspectRatio);
}
EditorGUI.indentLevel--;
serializedObject.ApplyModifiedProperties();
}
}
} | 42.021429 | 108 | 0.583546 | [
"MIT"
] | Ankh4396/UIEffect | Scripts/Editor/UIGradientEditor.cs | 5,885 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the iot-2015-05-28.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.IoT.Model
{
/// <summary>
/// Describes an action to write data to an Amazon S3 bucket.
/// </summary>
public partial class S3Action
{
private string _bucketName;
private CannedAccessControlList _cannedAcl;
private string _key;
private string _roleArn;
/// <summary>
/// Gets and sets the property BucketName.
/// <para>
/// The Amazon S3 bucket.
/// </para>
/// </summary>
[AWSProperty(Required=true)]
public string BucketName
{
get { return this._bucketName; }
set { this._bucketName = value; }
}
// Check to see if BucketName property is set
internal bool IsSetBucketName()
{
return this._bucketName != null;
}
/// <summary>
/// Gets and sets the property CannedAcl.
/// <para>
/// The Amazon S3 canned ACL that controls access to the object identified by the object
/// key. For more information, see <a href="https://docs.aws.amazon.com/AmazonS3/latest/dev/acl-overview.html#canned-acl">S3
/// canned ACLs</a>.
/// </para>
/// </summary>
public CannedAccessControlList CannedAcl
{
get { return this._cannedAcl; }
set { this._cannedAcl = value; }
}
// Check to see if CannedAcl property is set
internal bool IsSetCannedAcl()
{
return this._cannedAcl != null;
}
/// <summary>
/// Gets and sets the property Key.
/// <para>
/// The object key.
/// </para>
/// </summary>
[AWSProperty(Required=true)]
public string Key
{
get { return this._key; }
set { this._key = value; }
}
// Check to see if Key property is set
internal bool IsSetKey()
{
return this._key != null;
}
/// <summary>
/// Gets and sets the property RoleArn.
/// <para>
/// The ARN of the IAM role that grants access.
/// </para>
/// </summary>
[AWSProperty(Required=true)]
public string RoleArn
{
get { return this._roleArn; }
set { this._roleArn = value; }
}
// Check to see if RoleArn property is set
internal bool IsSetRoleArn()
{
return this._roleArn != null;
}
}
} | 28.563025 | 132 | 0.573404 | [
"Apache-2.0"
] | Singh400/aws-sdk-net | sdk/src/Services/IoT/Generated/Model/S3Action.cs | 3,399 | C# |
using BlazorMovies.Shared;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
namespace BlazorMovies.Server.Controllers
{
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
private readonly ILogger<WeatherForecastController> logger;
public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
this.logger = logger;
}
[HttpGet]
public IEnumerable<WeatherForecast> Get()
{
var rng = new Random();
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = rng.Next(-20, 55),
Summary = Summaries[rng.Next(Summaries.Length)]
})
.ToArray();
}
}
}
| 28.804878 | 110 | 0.607959 | [
"MIT"
] | HaruTzuki/BlazorMovies | BlazorMovies/Server/Controllers/WeatherForecastController.cs | 1,183 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("ReverseAndExclude")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ReverseAndExclude")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("49a078a0-a09e-4a1f-af7b-bd53661d794f")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.027027 | 84 | 0.746979 | [
"MIT"
] | KristiyanVasilev/CSharp-Advanced | FunctionalProgramming/ReverseAndExclude/Properties/AssemblyInfo.cs | 1,410 | C# |
namespace BusTicketsSystem.Client.Core.Dtos.BankAccountDtos
{
public class BankAccountDetailsDto
{
public int Id { get; set; }
public string AccountNumber { get; set; }
public decimal Balance { get; set; }
public int CustomerId { get; set; }
public string CustomerFirstName { get; set; }
public string CustomerLastName { get; set; }
}
} | 23.647059 | 60 | 0.631841 | [
"MIT"
] | pirocorp/Databases-Advanced---Entity-Framework | 09. Best Practices/Exercises/BusTicketsSystem/BusTicketsSystem.Client/Core/Dtos/BankAccountDtos/BankAccountDetailsDto.cs | 404 | C# |
using Bogevang.Booking.Domain.Bookings.CustomEntities;
using Bogevang.Booking.Domain.Documents.Commands;
using Bogevang.Booking.Domain.TenantCategories;
using Bogevang.Common.Utility;
using Bogevang.SequenceGenerator.Domain;
using Bogevang.Templates.Domain;
using Bogevang.Templates.Domain.CustomEntities;
using Cofoundry.Core.Mail;
using Cofoundry.Core.Validation;
using Cofoundry.Domain;
using Cofoundry.Domain.CQS;
using System;
using System.Threading.Tasks;
namespace Bogevang.Booking.Domain.Bookings.Commands
{
public class BookingRequestCommandHandler
: ICommandHandler<BookingRequestCommand>,
IIgnorePermissionCheckHandler // Anyone can add a booking request
{
private readonly IAdvancedContentRepository DomainRepository;
private readonly ISequenceNumberGenerator SequenceNumberGenerator;
private readonly ITemplateProvider TemplateProvider;
private readonly ITenantCategoryProvider TenantCategoryProvider;
private readonly IMailDispatchService MailDispatchService;
private readonly ICommandExecutor CommandExecutor;
private readonly BookingSettings BookingSettings;
private readonly ICurrentUserProvider CurrentUserProvider;
public BookingRequestCommandHandler(
IAdvancedContentRepository domainRepository,
ISequenceNumberGenerator sequenceNumberGenerator,
ITemplateProvider templateProvider,
ITenantCategoryProvider tenantCategoryProvider,
IMailDispatchService mailDispatchService,
ICommandExecutor commandExecutor,
BookingSettings bookingSettings,
ICurrentUserProvider currentUserProvider)
{
DomainRepository = domainRepository;
SequenceNumberGenerator = sequenceNumberGenerator;
TemplateProvider = templateProvider;
TenantCategoryProvider = tenantCategoryProvider;
MailDispatchService = mailDispatchService;
CommandExecutor = commandExecutor;
BookingSettings = bookingSettings;
CurrentUserProvider = currentUserProvider;
}
public async Task ExecuteAsync(BookingRequestCommand command, IExecutionContext executionContext)
{
using (var scope = DomainRepository.Transactions().CreateScope())
{
var tenantCategory = await TenantCategoryProvider.GetTenantCategoryById(command.TenantCategoryId.Value);
DateTime lastAllowedArrivalDate = DateTime.Now.AddMonths(tenantCategory.AllowedBookingFutureMonths);
if (command.ArrivalDate.Value >= lastAllowedArrivalDate || command.DepartureDate.Value >= lastAllowedArrivalDate)
throw new ValidationErrorException(new ValidationError($"Den valgte lejertype kan ikke reservere mere end {tenantCategory.AllowedBookingFutureMonths} måneder ud i fremtiden. Dvs. senest {lastAllowedArrivalDate.ToShortDateString()}.", nameof(command.ArrivalDate)));
int bookingNumber = await SequenceNumberGenerator.NextNumber("BookingNumber");
var booking = new BookingDataModel
{
BookingNumber = bookingNumber,
ArrivalDate = command.ArrivalDate.Value,
DepartureDate = command.DepartureDate.Value,
OnlySelectedWeekdays = command.OnlySelectedWeekdays,
SelectedWeekdays = command.SelectedWeekdays,
TenantCategoryId = command.TenantCategoryId.Value,
TenantName = command.TenantName,
Purpose = command.Purpose,
ContactName = command.ContactName,
ContactPhone = command.ContactPhone,
ContactAddress = command.ContactAddress,
ContactCity = command.ContactCity,
ContactEMail = command.ContactEMail,
Comments = command.Comments,
RentalPrice = null, // To be set later
Deposit = BookingSettings.StandardDeposit,
BookingState = BookingDataModel.BookingStateType.Requested
};
await booking.AddLogEntry(CurrentUserProvider, "Reservationen blev indsendt af lejer.");
await SendConfirmationMail(booking);
await SendNotificationMail(booking);
var addCommand = new AddCustomEntityCommand
{
CustomEntityDefinitionCode = BookingCustomEntityDefinition.DefinitionCode,
Model = booking,
Title = booking.MakeTitle(),
Publish = true,
};
await DomainRepository.WithElevatedPermissions().CustomEntities().AddAsync(addCommand);
await scope.CompleteAsync();
}
}
private async Task SendConfirmationMail(BookingDataModel booking)
{
TemplateDataModel template = await TemplateProvider.GetTemplateByName("reservationskvittering");
string mailText = TemplateProvider.MergeText(template.Text, booking);
MailAddress to = new MailAddress(booking.ContactEMail, booking.ContactName);
MailMessage message = new MailMessage
{
To = to,
Subject = template.Subject,
HtmlBody = mailText
};
await MailDispatchService.DispatchAsync(message);
byte[] mailBody = System.Text.Encoding.UTF8.GetBytes(message.HtmlBody);
var addDcoumentCommand = new AddDocumentCommand
{
Title = message.Subject,
MimeType = "text/html",
Body = mailBody
};
await CommandExecutor.ExecuteAsync(addDcoumentCommand);
booking.AddDocument(message.Subject, addDcoumentCommand.OutputDocumentId);
}
private async Task SendNotificationMail(BookingDataModel booking)
{
TemplateDataModel template = await TemplateProvider.GetTemplateByName("reservationsnotifikation");
string mailText = TemplateProvider.MergeText(template.Text, booking);
MailAddress to = new MailAddress(BookingSettings.AdminEmail);
MailMessage message = new MailMessage
{
To = to,
Subject = template.Subject,
HtmlBody = mailText
};
await MailDispatchService.DispatchAsync(message);
}
}
}
| 39.346405 | 275 | 0.721096 | [
"MIT"
] | Bogevang-spejderhytte/website | Bogevang.Booking.Domain/Bookings/Commands/BookingRequestCommandHandler.cs | 6,023 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace Asp.Net.Core.Controllers
{
[Route("api/[controller]")]
public class ValuesController : Controller
{
// GET api/values
[HttpGet]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/values/5
[HttpGet("{id}")]
public string Get(int id)
{
return "value";
}
// POST api/values
[HttpPost]
public void Post([FromBody]string value)
{
}
// PUT api/values/5
[HttpPut("{id}")]
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/values/5
[HttpDelete("{id}")]
public void Delete(int id)
{
}
}
}
| 20.488889 | 55 | 0.519523 | [
"MIT"
] | pliyosenpai/asp.net.core-api-jumpstart | src/Asp.Net.Core/Controllers/ValuesController.cs | 924 | C# |
//-----------------------------------------------------------------------
// <copyright file="SharedAccessPolicies.cs" company="Microsoft">
// Copyright 2011 Microsoft Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
// <summary>
// Contains code for the SharedAccessPolicies class.
// </summary>
//-----------------------------------------------------------------------
namespace Microsoft.WindowsAzure.StorageClient
{
using System;
using System.Collections.Generic;
/// <summary>
/// Represents the collection of shared access policies defined for a container.
/// </summary>
[Serializable]
[System.Diagnostics.CodeAnalysis.SuppressMessage(
"Microsoft.Naming",
"CA1710:IdentifiersShouldHaveCorrectSuffix",
Justification = "Public APIs should not expose base collection types.")]
public class SharedAccessPolicies : Dictionary<string, SharedAccessPolicy>
{
}
} | 40.351351 | 84 | 0.64367 | [
"Apache-2.0"
] | asirnayeef18/azure-sdk-for-net | microsoft-azure-api/StorageClient/SharedAccessPolicies.cs | 1,495 | C# |
using BlazorErp.Application.Requests.Identity;
using BlazorErp.Client.Extensions;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Forms;
using MudBlazor;
using System;
using System.Threading.Tasks;
namespace BlazorErp.Client.Pages.Identity
{
public partial class Profile
{
[Inject] private Microsoft.Extensions.Localization.IStringLocalizer<Profile> localizer { get; set; }
private char FirstLetterOfName { get; set; }
private readonly UpdateProfileRequest profileModel = new UpdateProfileRequest();
public string UserId { get; set; }
private async Task UpdateProfileAsync()
{
var response = await _accountManager.UpdateProfileAsync(profileModel);
if (response.Succeeded)
{
await _authenticationManager.Logout();
_snackBar.Add("Your Profile has been updated. Please Login to Continue.", Severity.Success);
_navigationManager.NavigateTo("/");
}
else
{
foreach (var message in response.Messages)
{
_snackBar.Add(message, Severity.Error);
}
}
}
protected override async Task OnInitializedAsync()
{
await LoadDataAsync();
}
private async Task LoadDataAsync()
{
var state = await _stateProvider.GetAuthenticationStateAsync();
var user = state.User;
profileModel.Email = user.GetEmail();
profileModel.FirstName = user.GetFirstName();
profileModel.LastName = user.GetLastName();
profileModel.PhoneNumber = user.GetPhoneNumber();
UserId = user.GetUserId();
var data = await _accountManager.GetProfilePictureAsync(UserId);
if (data.Succeeded)
{
ImageDataUrl = data.Data;
}
if (profileModel.FirstName.Length > 0)
{
FirstLetterOfName = profileModel.FirstName[0];
}
}
public IBrowserFile file { get; set; }
[Parameter]
public string ImageDataUrl { get; set; }
private async Task UploadFiles(InputFileChangeEventArgs e)
{
file = e.File;
if (file != null)
{
var format = "image/png";
var imageFile = await e.File.RequestImageFileAsync(format, 250, 250);
var buffer = new byte[imageFile.Size];
await imageFile.OpenReadStream().ReadAsync(buffer);
ImageDataUrl = $"data:{format};base64,{Convert.ToBase64String(buffer)}";
var request = new UpdateProfilePictureRequest() { ProfilePictureDataUrl = ImageDataUrl };
var result = await _accountManager.UpdateProfilePictureAsync(request, UserId);
if (result.Succeeded)
{
_navigationManager.NavigateTo("/account", true);
}
else
{
foreach (var error in result.Messages)
{
_snackBar.Add(error, Severity.Success);
}
}
}
}
private async Task DeleteAsync()
{
var parameters = new DialogParameters();
parameters.Add("ContentText", $"Do you want to delete the profile picture of {profileModel.Email} ?");
var options = new DialogOptions() { CloseButton = true, MaxWidth = MaxWidth.Small, FullWidth = true, DisableBackdropClick = true };
var dialog = _dialogService.Show<Shared.Dialogs.DeleteConfirmation>("Delete", parameters, options);
var result = await dialog.Result;
if (!result.Cancelled)
{
var request = new UpdateProfilePictureRequest() { ProfilePictureDataUrl = string.Empty };
var data = await _accountManager.UpdateProfilePictureAsync(request, UserId);
if (data.Succeeded)
{
ImageDataUrl = string.Empty;
_navigationManager.NavigateTo("/account", true);
}
else
{
foreach (var error in data.Messages)
{
_snackBar.Add(error, Severity.Success);
}
}
}
}
}
} | 38.042017 | 143 | 0.553126 | [
"MIT"
] | BurakIsleyicii/BlazorErp | BlazorErp/Client/Pages/Identity/Profile.razor.cs | 4,529 | C# |
using System;
namespace sqlmapsharp
{
public class SqlmapStatus
{
public SqlmapStatus ()
{
}
public string Status { get; set; }
public int ReturnCode { get; set; }
}
}
| 10.882353 | 37 | 0.654054 | [
"BSD-3-Clause"
] | FingerLeakers/gray_hat_csharp_code | ch9_automating_sqlmap/SqlmapStatus.cs | 185 | C# |
using System;
using System.Collections.Generic;
namespace Rubeus.Commands
{
public class Dump : ICommand
{
public static string CommandName => "dump";
public void Execute(Dictionary<string, string> arguments)
{
if (arguments.ContainsKey("/luid"))
{
string service = "";
if (arguments.ContainsKey("/service"))
{
service = arguments["/service"];
}
UInt32 luid = 0;
try
{
luid = UInt32.Parse(arguments["/luid"]);
}
catch
{
try
{
luid = Convert.ToUInt32(arguments["/luid"], 16);
}
catch
{
Console.WriteLine("[X] Invalid LUID format ({0})\r\n", arguments["/LUID"]);
return;
}
}
LSA.ListKerberosTicketData(luid, service);
}
else if (arguments.ContainsKey("/service"))
{
LSA.ListKerberosTicketData(0, arguments["/service"]);
}
else
{
LSA.ListKerberosTicketData();
}
}
}
} | 28.081633 | 99 | 0.394622 | [
"BSD-3-Clause"
] | BlueSkeye/Rubeus | Rubeus/Commands/Dump.cs | 1,378 | C# |
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
namespace ESIConnectionLibrary.ESIModels
{
internal class EsiV1CorporationRolesHistory
{
[JsonProperty(PropertyName = "changed_at")]
public DateTime ChangedAt { get; set; }
[JsonProperty(PropertyName = "character_id")]
public int CharacterId { get; set; }
[JsonProperty(PropertyName = "issuer_id")]
public int IssuerId { get; set; }
[JsonProperty(PropertyName = "new_roles")]
public IList<EsiCorporationRoles> NewRoles { get; set; }
[JsonProperty(PropertyName = "old_roles")]
public IList<EsiCorporationRoles> OldRoles { get; set; }
[JsonProperty(PropertyName = "role_type")]
public EsiV1CorporationRolesHistoryRoleType RoleType { get; set; }
}
} | 30.814815 | 74 | 0.675481 | [
"MIT"
] | Dusty-Meg/ESIConnectionLibrary | ESIConnectionLibrary/ESIConnectionLibrary/ESIModels/EsiV1CorporationRolesHistory.cs | 834 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using ProjectMann.Web.Models;
namespace ProjectMann.Web.Controllers
{
[Authorize]
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
}
public IActionResult Index()
{
return View();
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}
| 26.685714 | 113 | 0.648822 | [
"MIT"
] | GabrielNunez23/ProjectMann | src/ProjectMann.Web/Controllers/HomeController.cs | 936 | C# |
using System;
using System.Collections.Generic;
namespace PubNubAPI
{
public class PNFetchMessagesResult {
public Dictionary<string, List<PNMessageResult>> Channels { get; set;}
public Dictionary<string, object> More { get; set;}
}
} | 25.8 | 78 | 0.709302 | [
"MIT"
] | JordanSchuetz/Unity-Realtime-Chat-Room-Tutorial | Assets/PubNub/Models/Consumer/History/PNFetchMessagesResult.cs | 258 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.Azure.Devices
{
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.Devices.Common;
using Microsoft.Azure.Devices.Common.Exceptions;
sealed class HttpClientHelper : IHttpClientHelper
{
readonly Uri baseAddress;
readonly IAuthorizationHeaderProvider authenticationHeaderProvider;
readonly IReadOnlyDictionary<HttpStatusCode, Func<HttpResponseMessage, Task<Exception>>> defaultErrorMapping;
HttpClient httpClientObj;
bool isDisposed;
public HttpClientHelper(
Uri baseAddress,
IAuthorizationHeaderProvider authenticationHeaderProvider,
IDictionary<HttpStatusCode, Func<HttpResponseMessage, Task<Exception>>> defaultErrorMapping,
TimeSpan timeout,
Action<HttpClient> preRequestActionForAllRequests)
{
this.baseAddress = baseAddress;
this.authenticationHeaderProvider = authenticationHeaderProvider;
this.defaultErrorMapping =
new ReadOnlyDictionary<HttpStatusCode, Func<HttpResponseMessage, Task<Exception>>>(defaultErrorMapping);
this.httpClientObj = new HttpClient();
this.httpClientObj.BaseAddress = this.baseAddress;
this.httpClientObj.Timeout = timeout;
this.httpClientObj.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(CommonConstants.MediaTypeForDeviceManagementApis));
this.httpClientObj.DefaultRequestHeaders.ExpectContinue = false;
if (preRequestActionForAllRequests != null)
{
preRequestActionForAllRequests(this.httpClientObj);
}
}
public Task<T> GetAsync<T>(
Uri requestUri,
IDictionary<HttpStatusCode, Func<HttpResponseMessage, Task<Exception>>> errorMappingOverrides,
IDictionary<string, string> customHeaders,
CancellationToken cancellationToken)
{
return this.GetAsync<T>(requestUri, errorMappingOverrides, customHeaders, true, cancellationToken);
}
public async Task<T> GetAsync<T>(
Uri requestUri,
IDictionary<HttpStatusCode, Func<HttpResponseMessage, Task<Exception>>> errorMappingOverrides,
IDictionary<string, string> customHeaders,
bool throwIfNotFound,
CancellationToken cancellationToken)
{
T result = default(T);
if (throwIfNotFound)
{
await this.ExecuteAsync(
HttpMethod.Get,
new Uri(this.baseAddress, requestUri),
(requestMsg, token) => AddCustomHeaders(requestMsg, customHeaders),
async (message, token) => result = await ReadResponseMessageAsync<T>(message, token),
errorMappingOverrides,
cancellationToken);
}
else
{
await this.ExecuteAsync(
HttpMethod.Get,
new Uri(this.baseAddress, requestUri),
(requestMsg, token) => AddCustomHeaders(requestMsg, customHeaders),
message => message.IsSuccessStatusCode || message.StatusCode == HttpStatusCode.NotFound,
async (message, token) => result = message.StatusCode == HttpStatusCode.NotFound ? (default(T)) : await ReadResponseMessageAsync<T>(message, token),
errorMappingOverrides,
cancellationToken);
}
return result;
}
public async Task<T> PutAsync<T>(
Uri requestUri,
T entity,
PutOperationType operationType,
IDictionary<HttpStatusCode, Func<HttpResponseMessage, Task<Exception>>> errorMappingOverrides,
CancellationToken cancellationToken) where T: IETagHolder
{
T result = default(T);
await this.ExecuteAsync(
HttpMethod.Put,
new Uri(this.baseAddress, requestUri),
(requestMsg, token) =>
{
InsertEtag(requestMsg, entity, operationType);
requestMsg.Content = new ObjectContent<T>(entity, new JsonMediaTypeFormatter());
return Task.FromResult(0);
},
async (httpClient, token) => result = await ReadResponseMessageAsync<T>(httpClient, token),
errorMappingOverrides,
cancellationToken);
return result;
}
static async Task<T> ReadResponseMessageAsync<T>(HttpResponseMessage message, CancellationToken token)
{
if (typeof(T) == typeof (HttpResponseMessage))
{
return (T) (object)message;
}
T entity = await message.Content.ReadAsAsync<T>(token);
// Etag in the header is considered authoritative
var eTagHolder = entity as IETagHolder;
if (eTagHolder != null)
{
if (message.Headers.ETag != null && !string.IsNullOrWhiteSpace(message.Headers.ETag.Tag))
{
// RDBug 3429280:Make the version field of Device object internal
eTagHolder.ETag = message.Headers.ETag.Tag;
}
}
return entity;
}
static Task AddCustomHeaders(HttpRequestMessage requestMessage, IDictionary<string, string> customHeaders)
{
if (customHeaders != null)
{
foreach (var header in customHeaders)
{
requestMessage.Headers.Add(header.Key, header.Value);
}
}
return Task.FromResult(0);
}
static void InsertEtag(HttpRequestMessage requestMessage, IETagHolder entity, PutOperationType operationType)
{
if (operationType == PutOperationType.CreateEntity)
{
return;
}
if (operationType == PutOperationType.ForceUpdateEntity)
{
const string etag = "\"*\"";
requestMessage.Headers.IfMatch.Add(new EntityTagHeaderValue(etag));
}
else
{
InsertEtag(requestMessage, entity);
}
}
static void InsertEtag(HttpRequestMessage requestMessage, IETagHolder entity)
{
if (string.IsNullOrWhiteSpace(entity.ETag))
{
throw new ArgumentException("The entity does not have its ETag set.");
}
string etag = entity.ETag;
if (!etag.StartsWith("\"", StringComparison.OrdinalIgnoreCase))
{
etag = "\"" + etag;
}
if (!etag.EndsWith("\"", StringComparison.OrdinalIgnoreCase))
{
etag = etag + "\"";
}
requestMessage.Headers.IfMatch.Add(new EntityTagHeaderValue(etag));
}
IDictionary<HttpStatusCode, Func<HttpResponseMessage, Task<Exception>>> MergeErrorMapping(
IDictionary<HttpStatusCode, Func<HttpResponseMessage, Task<Exception>>> errorMappingOverrides)
{
var mergedMapping = this.defaultErrorMapping.ToDictionary(mapping => mapping.Key, mapping => mapping.Value);
if (errorMappingOverrides != null)
{
foreach (var @override in errorMappingOverrides)
{
mergedMapping[@override.Key] = @override.Value;
}
}
return mergedMapping;
}
public Task PostAsync<T>(
Uri requestUri,
T entity,
IDictionary<HttpStatusCode, Func<HttpResponseMessage, Task<Exception>>> errorMappingOverrides,
IDictionary<string, string> customHeaders,
CancellationToken cancellationToken)
{
return this.PostAsyncHelper(
requestUri,
entity,
errorMappingOverrides,
customHeaders,
ReadResponseMessageAsync<HttpResponseMessage>,
cancellationToken);
}
public async Task<T2> PostAsync<T1, T2>(
Uri requestUri,
T1 entity,
IDictionary<HttpStatusCode, Func<HttpResponseMessage, Task<Exception>>> errorMappingOverrides,
IDictionary<string, string> customHeaders,
CancellationToken cancellationToken)
{
T2 result = default(T2);
await this.PostAsyncHelper(
requestUri,
entity,
errorMappingOverrides,
customHeaders,
async (message, token) => result = await ReadResponseMessageAsync<T2>(message, token),
cancellationToken);
return result;
}
Task PostAsyncHelper<T1>(
Uri requestUri,
T1 entity,
IDictionary<HttpStatusCode, Func<HttpResponseMessage, Task<Exception>>> errorMappingOverrides,
IDictionary<string, string> customHeaders,
Func<HttpResponseMessage, CancellationToken, Task> processResponseMessageAsync,
CancellationToken cancellationToken)
{
return this.ExecuteAsync(
HttpMethod.Post,
new Uri(this.baseAddress, requestUri),
(requestMsg, token) =>
{
AddCustomHeaders(requestMsg, customHeaders);
if (entity != null)
{
if (typeof(T1) == typeof(byte[]))
{
requestMsg.Content = new ByteArrayContent((byte[])(object)entity);
}
else if (typeof(T1) == typeof(string))
{
// only used to send batched messages on Http runtime
requestMsg.Content = new StringContent((string)(object)entity);
requestMsg.Content.Headers.ContentType = new MediaTypeHeaderValue(CommonConstants.BatchedMessageContentType);
}
else
{
requestMsg.Content = new ObjectContent<T1>(entity, new JsonMediaTypeFormatter());
}
}
return Task.FromResult(0);
},
processResponseMessageAsync,
errorMappingOverrides,
cancellationToken);
}
public Task DeleteAsync<T>(
Uri requestUri,
T entity,
IDictionary<HttpStatusCode, Func<HttpResponseMessage, Task<Exception>>> errorMappingOverrides,
IDictionary<string, string> customHeaders,
CancellationToken cancellationToken) where T: IETagHolder
{
return this.ExecuteAsync(
HttpMethod.Delete,
new Uri(this.baseAddress, requestUri),
(requestMsg, token) =>
{
InsertEtag(requestMsg, entity);
AddCustomHeaders(requestMsg, customHeaders);
return TaskHelpers.CompletedTask;
},
null,
errorMappingOverrides,
cancellationToken);
}
Task ExecuteAsync(
HttpMethod httpMethod,
Uri requestUri,
Func<HttpRequestMessage, CancellationToken, Task> modifyRequestMessageAsync,
Func<HttpResponseMessage, CancellationToken, Task> processResponseMessageAsync,
IDictionary<HttpStatusCode, Func<HttpResponseMessage, Task<Exception>>> errorMappingOverrides,
CancellationToken cancellationToken)
{
return this.ExecuteAsync(
httpMethod,
requestUri,
modifyRequestMessageAsync,
message => message.IsSuccessStatusCode,
processResponseMessageAsync,
errorMappingOverrides,
cancellationToken);
}
async Task ExecuteAsync(
HttpMethod httpMethod,
Uri requestUri,
Func<HttpRequestMessage, CancellationToken, Task> modifyRequestMessageAsync,
Func<HttpResponseMessage, bool> isSuccessful,
Func<HttpResponseMessage, CancellationToken, Task> processResponseMessageAsync,
IDictionary<HttpStatusCode, Func<HttpResponseMessage, Task<Exception>>> errorMappingOverrides,
CancellationToken cancellationToken)
{
IDictionary<HttpStatusCode, Func<HttpResponseMessage, Task<Exception>>> mergedErrorMapping =
this.MergeErrorMapping(errorMappingOverrides);
using (var msg = new HttpRequestMessage(httpMethod, requestUri))
{
msg.Headers.Add(HttpRequestHeader.Authorization.ToString(), this.authenticationHeaderProvider.GetAuthorizationHeader());
#if !WINDOWS_UWP
msg.Headers.Add(HttpRequestHeader.UserAgent.ToString(), Utils.GetClientVersion());
#endif
if (modifyRequestMessageAsync != null) await modifyRequestMessageAsync(msg, cancellationToken);
// TODO: pradeepc - find out the list of exceptions that HttpClient can throw.
HttpResponseMessage responseMsg;
try
{
responseMsg = await this.httpClientObj.SendAsync(msg, cancellationToken);
if (responseMsg == null)
{
throw new InvalidOperationException("The response message was null when executing operation {0}.".FormatInvariant(httpMethod));
}
if (isSuccessful(responseMsg))
{
if (processResponseMessageAsync != null)
{
await processResponseMessageAsync(responseMsg, cancellationToken);
}
}
}
catch (AggregateException ex)
{
var innerExceptions = ex.Flatten().InnerExceptions;
if (innerExceptions.Any(Fx.IsFatal))
{
throw;
}
// Apparently HttpClient throws AggregateException when a timeout occurs.
// TODO: pradeepc - need to confirm this with ASP.NET team
if (innerExceptions.Any(e => e is TimeoutException))
{
throw new IotHubCommunicationException(ex.Message, ex);
}
throw new IotHubException(ex.Message, ex);
}
catch (TimeoutException ex)
{
throw new IotHubCommunicationException(ex.Message, ex);
}
catch (IOException ex)
{
throw new IotHubCommunicationException(ex.Message, ex);
}
catch (HttpRequestException ex)
{
throw new IotHubCommunicationException(ex.Message, ex);
}
catch (TaskCanceledException ex)
{
// Unfortunately TaskCanceledException is thrown when HttpClient times out.
if (cancellationToken.IsCancellationRequested)
{
throw new IotHubException(ex.Message, ex);
}
throw new IotHubCommunicationException(string.Format(CultureInfo.InvariantCulture, "The {0} operation timed out.", httpMethod), ex);
}
catch (Exception ex)
{
if (Fx.IsFatal(ex)) throw;
throw new IotHubException(ex.Message, ex);
}
if (!isSuccessful(responseMsg))
{
Exception mappedEx = await MapToExceptionAsync(responseMsg, mergedErrorMapping);
throw mappedEx;
}
}
}
static async Task<Exception> MapToExceptionAsync(
HttpResponseMessage response,
IDictionary<HttpStatusCode, Func<HttpResponseMessage, Task<Exception>>> errorMapping)
{
Func<HttpResponseMessage, Task<Exception>> func;
if (!errorMapping.TryGetValue(response.StatusCode, out func))
{
return new IotHubException(
await ExceptionHandlingHelper.GetExceptionMessageAsync(response),
isTransient: true);
}
var mapToExceptionFunc = errorMapping[response.StatusCode];
var exception = mapToExceptionFunc(response);
return await exception;
}
public void Dispose()
{
if (!this.isDisposed && this.httpClientObj != null)
{
this.httpClientObj.Dispose();
this.httpClientObj = null;
}
this.isDisposed = true;
}
}
} | 40.408072 | 167 | 0.557652 | [
"MIT"
] | 5dprinted/azure-iot-sdks | csharp/service/Microsoft.Azure.Devices/HttpClientHelper.cs | 18,024 | C# |
using System;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.Extensions.DependencyInjection;
namespace Cassette.Tests
{
public class CustomWebApplicationFactory<TStartup> : WebApplicationFactory<TStartup> where TStartup : class
{
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
builder.ConfigureServices((builderContext, services) =>
{
// Declare the cache implementation Cassette will rely on
services.AddDistributedMemoryCache();
// Register Cassette in the DI container
services.AddCassette(options =>
{
options.KeyPrefix = "Cassette:Tests";
options.CacheEntryOption.AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(1);
});
});
}
}
}
| 34.037037 | 111 | 0.631121 | [
"MIT"
] | atifaziz/Cassette | test/Cassette.Tests/CustomWebApplicationFactory.cs | 921 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using BasicTestApp;
using Microsoft.AspNetCore.Components.E2ETest.Infrastructure.ServerFixtures;
using Microsoft.AspNetCore.Components.E2ETests.Tests;
using Microsoft.AspNetCore.E2ETesting;
using Microsoft.AspNetCore.Testing;
using OpenQA.Selenium;
using OpenQA.Selenium.Support.UI;
using TestServer;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.AspNetCore.Components.E2ETest.ServerExecutionTests;
// For now this is limited to server-side execution because we don't have the ability to set the
// culture in client-side Blazor.
public class ServerGlobalizationTest : GlobalizationTest<BasicTestAppServerSiteFixture<InternationalizationStartup>>
{
public ServerGlobalizationTest(
BrowserFixture browserFixture,
BasicTestAppServerSiteFixture<InternationalizationStartup> serverFixture,
ITestOutputHelper output)
: base(browserFixture, serverFixture, output)
{
}
protected override void InitializeAsyncCore()
{
Navigate(ServerPathBase);
Browser.MountTestComponent<CulturePicker>();
Browser.Exists(By.Id("culture-selector"));
}
[Theory]
[InlineData("en-US")]
[InlineData("fr-FR")]
public override void CanSetCultureAndParseCultureSensitiveNumbersAndDates(string culture)
{
base.CanSetCultureAndParseCultureSensitiveNumbersAndDates(culture);
}
protected override void SetCulture(string culture)
{
var selector = new SelectElement(Browser.Exists(By.Id("culture-selector")));
selector.SelectByValue(culture);
// Click the link to return back to the test page
Browser.Exists(By.ClassName("return-from-culture-setter")).Click();
// That should have triggered a page load, so wait for the main test selector to come up.
Browser.MountTestComponent<GlobalizationBindCases>();
Browser.Exists(By.Id("globalization-cases"));
var cultureDisplay = Browser.Exists(By.Id("culture-name-display"));
Assert.Equal($"Culture is: {culture}", cultureDisplay.Text);
}
}
| 36.295082 | 116 | 0.742999 | [
"MIT"
] | AndrewTriesToCode/aspnetcore | src/Components/test/E2ETest/ServerExecutionTests/ServerGlobalizationTest.cs | 2,214 | C# |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.PowerFx.Core.Errors;
using Microsoft.PowerFx.Core.Lexer;
using Microsoft.PowerFx.Core.Lexer.Tokens;
using Microsoft.PowerFx.Core.Localization;
using Microsoft.PowerFx.Core.Syntax;
using Microsoft.PowerFx.Core.Syntax.Nodes;
using Microsoft.PowerFx.Core.Syntax.SourceInformation;
using Microsoft.PowerFx.Core.Utils;
namespace Microsoft.PowerFx.Core.Parser
{
internal sealed class TexlParser
{
[Flags]
public enum Flags
{
None = 0,
// When specified, expression chaining is allowed (e.g. in the context of behavior rules).
EnableExpressionChaining = 1 << 0,
// When specified, this is a named formula to be parsed. Mutually exclusive to EnableExpressionChaining.
NamedFormulas = 1 << 1
}
private readonly TokenCursor _curs;
private readonly Flags _flags;
private List<TexlError> _errors;
// Nodes are assigned an integer id that is used to index into arrays later.
private int _idNext;
// Track the parsing depth and enforce a maximum, to avoid excessive recursion.
private int _depth;
private const int MaxAllowedExpressionDepth = 50;
private readonly List<CommentToken> _comments = new List<CommentToken>();
private SourceList _before;
private SourceList _after;
// Represents temporary extra trivia, for when a parsing method
// had to parse tailing trivia to do 1-lookahead. Will be
// collected by the next call to ParseTrivia.
private ITexlSource _extraTrivia;
private TexlParser(Token[] tokens, Flags flags)
{
Contracts.AssertValue(tokens);
_depth = 0;
_curs = new TokenCursor(tokens);
_flags = flags;
}
// Parse the script
// Parsing strips out parens used to establish precedence, but these may be helpful to the
// caller, so precedenceTokens provide a list of stripped tokens.
internal static ParseResult ParseScript(string script, ILanguageSettings loc = null, Flags flags = Flags.None)
{
Contracts.AssertValue(script);
Contracts.AssertValueOrNull(loc);
var tokens = TokenizeScript(script, loc, flags);
var parser = new TexlParser(tokens, flags);
List<TexlError> errors = null;
var parsetree = parser.Parse(ref errors);
return new ParseResult(parsetree, errors, errors?.Any() ?? false, parser._comments, parser._before, parser._after);
}
public static ParseFormulasResult ParseFormulasScript(string script, ILanguageSettings loc = null)
{
Contracts.AssertValue(script);
Contracts.AssertValueOrNull(loc);
var formulaTokens = TokenizeScript(script, loc, Flags.NamedFormulas);
var parser = new TexlParser(formulaTokens, Flags.NamedFormulas);
return parser.ParseFormulas(script);
}
private ParseFormulasResult ParseFormulas(string script)
{
var namedFormulas = new List<KeyValuePair<IdentToken, TexlNode>>();
ParseTrivia();
while (_curs.TokCur.Kind != TokKind.Eof)
{
// Verify identifier
var thisIdentifier = TokEat(TokKind.Ident);
if (thisIdentifier != null)
{
ParseTrivia();
// Verify "="
var thisEq = TokEat(TokKind.Equ);
if (thisEq != null)
{
ParseTrivia();
// Extract expression
while (_curs.TidCur != TokKind.Semicolon)
{
// Check if we're at EOF before a semicolon is found
if (_curs.TidCur == TokKind.Eof)
{
CreateError(_curs.TokCur, TexlStrings.ErrNamedFormula_MissingSemicolon);
return new ParseFormulasResult(namedFormulas, _errors);
}
// Parse expression
var result = ParseExpr(Precedence.None);
namedFormulas.Add(new KeyValuePair<IdentToken, TexlNode>(thisIdentifier.As<IdentToken>(), result));
}
_curs.TokMove();
}
else
{
break;
}
}
else
{
break;
}
ParseTrivia();
}
return new ParseFormulasResult(namedFormulas, _errors);
}
private static Token[] TokenizeScript(string script, ILanguageSettings loc = null, Flags flags = Flags.None)
{
Contracts.AssertValue(script);
Contracts.AssertValueOrNull(loc);
var lexerFlags = TexlLexer.Flags.None;
if (loc == null)
{
return TexlLexer.LocalizedInstance.LexSource(script, lexerFlags);
}
return TexlLexer.NewInstance(loc).LexSource(script, lexerFlags);
}
private TexlNode Parse(ref List<TexlError> errors)
{
Contracts.AssertValueOrNull(errors);
_errors = errors;
TexlNode node;
var firstToken = _curs.TokCur;
_before = new SourceList(ParseTrivia());
if (_curs.TidCur == TokKind.Eof)
{
if (firstToken.Kind == TokKind.Comment && firstToken.As<CommentToken>().IsOpenBlock)
{
// This provides an error message for when a block comment missing a closing '*/' is the only token in the formula bar
PostBlockCommentMissingClosingError();
errors = _errors;
}
node = new BlankNode(ref _idNext, _curs.TokCur);
}
else
{
node = ParseExpr(Precedence.None);
if (_curs.TidCur != TokKind.Eof)
{
PostError(_curs.TokCur, TexlStrings.ErrBadToken);
}
_after = _after == null ? new SourceList(ParseTrivia()) : new SourceList(new SpreadSource(_after.Sources), new SpreadSource(ParseTrivia()));
// This checks for and provides an error message for any block comments missing a closing '*/'
PostBlockCommentMissingClosingError();
errors = _errors;
}
// The top node (of the parse tree) should end up with the biggest id. We use this fact when binding.
Contracts.Assert(node.Id == _idNext - 1);
return node;
}
private void PostBlockCommentMissingClosingError()
{
var openBlockComment = _comments.LastOrDefault(cm => cm.IsOpenBlock == true);
if (openBlockComment != null)
{
PostError(openBlockComment, TexlStrings.ErrMissingEndOfBlockComment);
}
}
private ITexlSource ParseTrivia(TokenCursor cursor = null)
{
cursor = cursor ?? _curs;
var sources = new List<ITexlSource>();
if (_extraTrivia != null)
{
sources.Add(_extraTrivia);
_extraTrivia = null;
}
bool triviaFound;
do
{
triviaFound = false;
var tokens = cursor.SkipWhitespace();
if (tokens.Any())
{
sources.Add(new WhitespaceSource(tokens));
triviaFound = true;
}
if (cursor.TidCur == TokKind.Comment)
{
var comment = cursor.TokMove().As<CommentToken>();
sources.Add(new TokenSource(comment));
if (comment.IsOpenBlock)
{
PostError(comment, TexlStrings.ErrMissingEndOfBlockComment);
}
_comments.Add(comment);
triviaFound = true;
}
}
while (triviaFound);
if (sources.Count() == 1)
{
return sources.Single();
}
else
{
return new SpreadSource(sources);
}
}
private void AddExtraTrivia(ITexlSource trivia)
{
if (_extraTrivia == null)
{
_extraTrivia = trivia;
}
else
{
_extraTrivia = new SpreadSource(_extraTrivia, trivia);
}
}
// Parses the next (maximal) expression with precedence >= precMin.
private TexlNode ParseExpr(Precedence precMin, TexlNode node = null)
{
// ParseOperand may accept PrefixUnary and higher, so ParseExpr should never be called
// with precMin > Precedence.PrefixUnary - it will not correctly handle those cases.
Contracts.Assert(precMin >= Precedence.None && precMin <= Precedence.PrefixUnary);
try
{
// The parser is recursive. Deeply nested invocations (over 200 deep) and other
// intentionally miscrafted rules can throw it off, causing stack overflows.
// Ensure the product doesn't crash in such situations, but instead post
// corresponding parse errors.
if (node == null)
{
if (++_depth > MaxAllowedExpressionDepth)
{
return CreateError(_curs.TokMove(), TexlStrings.ErrRuleNestedTooDeeply);
}
// Get the left operand.
node = ParseOperand();
}
// Process operators and right operands as long as the precedence bound is satisfied.
for (; ;)
{
var leftTrivia = ParseTrivia();
Contracts.AssertValue(node);
Token tok;
TexlNode right;
Identifier identifier;
ITexlSource rightTrivia;
switch (_curs.TidCur)
{
case TokKind.PercentSign:
Contracts.Assert(precMin <= Precedence.PostfixUnary);
tok = _curs.TokMove();
node = new UnaryOpNode(
ref _idNext,
tok,
new SourceList(new NodeSource(node), new TokenSource(tok)),
UnaryOp.Percent,
node);
break;
case TokKind.Dot:
case TokKind.Bang:
Contracts.Assert(precMin <= Precedence.Primary);
if (node is DottedNameNode leftDotted && leftDotted.Token.Kind != _curs.TidCur && leftDotted.Token.Kind != TokKind.BracketOpen)
{
// Can't mix and match separators. E.g. A.B!C is invalid.
goto case TokKind.False;
}
tok = _curs.TokMove();
rightTrivia = ParseTrivia();
identifier = ParseIdentifier();
node = new DottedNameNode(
ref _idNext,
tok,
new SourceList(
new NodeSource(node),
new TokenSource(tok),
new SpreadSource(rightTrivia),
new IdentifierSource(identifier)),
node,
identifier,
null);
if (node.Depth > MaxAllowedExpressionDepth)
{
return CreateError(node.Token, TexlStrings.ErrRuleNestedTooDeeply);
}
break;
case TokKind.Caret:
Contracts.Assert(precMin <= Precedence.Power);
node = ParseBinary(node, leftTrivia, BinaryOp.Power, Precedence.PrefixUnary);
break;
case TokKind.Mul:
if (precMin > Precedence.Mul)
{
goto default;
}
node = ParseBinary(node, leftTrivia, BinaryOp.Mul, Precedence.Mul + 1);
break;
case TokKind.Div:
if (precMin > Precedence.Mul)
{
goto default;
}
tok = _curs.TokMove();
rightTrivia = ParseTrivia();
right = ParseExpr(Precedence.Mul + 1);
node = MakeBinary(BinaryOp.Div, node, leftTrivia, tok, rightTrivia, right);
break;
case TokKind.Sub:
if (precMin > Precedence.Add)
{
goto default;
}
tok = _curs.TokMove();
rightTrivia = ParseTrivia();
right = ParseExpr(Precedence.Add + 1);
right = new UnaryOpNode(ref _idNext, tok, right.SourceList, UnaryOp.Minus, right);
node = MakeBinary(BinaryOp.Add, node, leftTrivia, tok, rightTrivia, right);
break;
case TokKind.Add:
if (precMin > Precedence.Add)
{
goto default;
}
node = ParseBinary(node, leftTrivia, BinaryOp.Add, Precedence.Add + 1);
break;
case TokKind.Ampersand:
if (precMin > Precedence.Concat)
{
goto default;
}
node = ParseBinary(node, leftTrivia, BinaryOp.Concat, Precedence.Concat + 1);
break;
case TokKind.KeyAnd:
case TokKind.And:
if (precMin > Precedence.And)
{
goto default;
}
node = ParseBinary(node, leftTrivia, BinaryOp.And, Precedence.And + 1);
break;
case TokKind.KeyOr:
case TokKind.Or:
if (precMin > Precedence.Or)
{
goto default;
}
node = ParseBinary(node, leftTrivia, BinaryOp.Or, Precedence.Or + 1);
break;
// Comparison operators
// expr = expr
// expr <> expr
case TokKind.Equ:
if (precMin > Precedence.Compare)
{
goto default;
}
node = ParseBinary(node, leftTrivia, BinaryOp.Equal, Precedence.Compare + 1);
break;
case TokKind.LssGrt:
if (precMin > Precedence.Compare)
{
goto default;
}
node = ParseBinary(node, leftTrivia, BinaryOp.NotEqual, Precedence.Compare + 1);
break;
// expr < expr
case TokKind.Lss:
if (precMin > Precedence.Compare)
{
goto default;
}
node = ParseBinary(node, leftTrivia, BinaryOp.Less, Precedence.Compare + 1);
break;
// expr <= expr
case TokKind.LssEqu:
if (precMin > Precedence.Compare)
{
goto default;
}
node = ParseBinary(node, leftTrivia, BinaryOp.LessEqual, Precedence.Compare + 1);
break;
// expr > expr
case TokKind.Grt:
if (precMin > Precedence.Compare)
{
goto default;
}
node = ParseBinary(node, leftTrivia, BinaryOp.Greater, Precedence.Compare + 1);
break;
// expr >= expr
case TokKind.GrtEqu:
if (precMin > Precedence.Compare)
{
goto default;
}
node = ParseBinary(node, leftTrivia, BinaryOp.GreaterEqual, Precedence.Compare + 1);
break;
case TokKind.Ident:
case TokKind.NumLit:
case TokKind.StrLit:
case TokKind.True:
case TokKind.False:
PostError(_curs.TokCur, TexlStrings.ErrOperatorExpected);
tok = _curs.TokMove();
rightTrivia = ParseTrivia();
right = ParseExpr(Precedence.Error);
node = MakeBinary(BinaryOp.Error, node, leftTrivia, tok, rightTrivia, right);
break;
case TokKind.ParenOpen:
if (node is not DottedNameNode dotted ||
!dotted.HasPossibleNamespaceQualifier)
{
goto default;
}
node = ParseInvocationWithNamespace(dotted);
break;
case TokKind.In:
if (precMin > Precedence.In)
{
goto default;
}
node = ParseBinary(node, leftTrivia, BinaryOp.In, Precedence.In + 1);
break;
case TokKind.Exactin:
if (precMin > Precedence.In)
{
goto default;
}
node = ParseBinary(node, leftTrivia, BinaryOp.Exactin, Precedence.In + 1);
break;
case TokKind.As:
if (precMin > Precedence.As)
{
goto default;
}
node = ParseAs(node, leftTrivia);
break;
case TokKind.Semicolon:
if (_flags.HasFlag(Flags.NamedFormulas))
{
goto default;
}
// Only allow this when expression chaining is enabled (e.g. in behavior rules).
if ((_flags & Flags.EnableExpressionChaining) == 0)
{
goto case TokKind.False;
}
if (precMin > Precedence.None)
{
goto default;
}
node = ParseExprChain(node, leftTrivia);
break;
case TokKind.BracketOpen:
// Note we explicitly forbid [@foo][@bar], and also A!B!C[@foo], since these are syntactically nonsensical at the moment.
if (node is not FirstNameNode first || first.Ident.AtToken != null || _curs.TidPeek() != TokKind.At)
{
goto default;
}
node = ParseScopeField(first);
break;
case TokKind.Comment:
Contracts.Assert(false, "A stray comment was found");
_curs.TokMove();
return node;
case TokKind.Eof:
if (_after == null)
{
_after = new SourceList(leftTrivia);
}
else
{
_after = new SourceList(new SpreadSource(_after.Sources), new SpreadSource(leftTrivia));
}
return node;
default:
AddExtraTrivia(leftTrivia);
return node;
}
}
}
finally
{
--_depth;
}
}
private TexlNode ParseBinary(TexlNode left, ITexlSource leftTrivia, BinaryOp op, Precedence precedence)
{
var opToken = _curs.TokMove();
var rightTrivia = ParseTrivia();
var right = ParseExpr(precedence);
return MakeBinary(op, left, leftTrivia, opToken, rightTrivia, right);
}
private TexlNode MakeBinary(BinaryOp op, TexlNode left, ITexlSource leftTrivia, Token opToken, ITexlSource rightTrivia, TexlNode right)
{
return new BinaryOpNode(
ref _idNext,
opToken,
new SourceList(
new NodeSource(left),
new SpreadSource(leftTrivia),
new TokenSource(opToken),
new SpreadSource(rightTrivia),
new NodeSource(right)),
op,
left,
right);
}
private TexlNode ParseAs(TexlNode left, ITexlSource leftTrivia)
{
var opToken = _curs.TokMove();
var rightTrivia = ParseTrivia();
var rhsIdentifier = ParseIdentifier();
return new AsNode(
ref _idNext,
opToken,
new SourceList(
new NodeSource(left),
new SpreadSource(leftTrivia),
new TokenSource(opToken),
new SpreadSource(rightTrivia),
new IdentifierSource(rhsIdentifier)),
left,
rhsIdentifier);
}
private TexlNode ParseOperand()
{
ITexlSource trivia;
switch (_curs.TidCur)
{
// (Expr)
case TokKind.ParenOpen:
return ParseParenExpr();
// {id:Expr*}
case TokKind.CurlyOpen:
return ParseRecordExpr(new SpreadSource());
// [Expr*]
// [@name]
case TokKind.BracketOpen:
if (_curs.TidPeek() == TokKind.At)
{
return ParseBracketIdentifierAsFirstName(accountForAllPrecedenceTokens: true);
}
return ParseTableExpr();
// -Expr
case TokKind.Sub:
return ParseUnary(UnaryOp.Minus);
// not Expr
case TokKind.KeyNot:
case TokKind.Bang:
return ParseUnary(UnaryOp.Not);
// Literals
case TokKind.NumLit:
return new NumLitNode(ref _idNext, _curs.TokMove().As<NumLitToken>());
case TokKind.True:
case TokKind.False:
return new BoolLitNode(ref _idNext, _curs.TokMove());
case TokKind.StrInterpStart:
var res = ParseStringInterpolation();
var tokCur = _curs.TokCur;
if (FeatureFlags.StringInterpolation)
{
return res;
}
return CreateError(tokCur, TexlStrings.ErrBadToken);
case TokKind.StrLit:
return new StrLitNode(ref _idNext, _curs.TokMove().As<StrLitToken>());
// Names
case TokKind.Ident:
var ident = ParseIdentifier();
if (AfterSpaceTokenId() == TokKind.ParenOpen)
{
trivia = ParseTrivia();
return ParseInvocation(ident, trivia, null);
}
if (AfterSpaceTokenId() == TokKind.At)
{
trivia = ParseTrivia();
return ParseRecordExpr(trivia, ident);
}
return new FirstNameNode(ref _idNext, ident.Token, ident);
// Parent
case TokKind.Parent:
return new ParentNode(ref _idNext, _curs.TokMove());
// Self
case TokKind.Self:
return new SelfNode(ref _idNext, _curs.TokMove());
case TokKind.Eof:
return CreateError(_curs.TokCur, TexlStrings.ErrOperandExpected);
case TokKind.Error:
var errorToken = _curs.TokMove().As<ErrorToken>();
var args = errorToken.ResourceKeyFormatStringArgs;
if (args == null || args.Length == 0)
{
return CreateError(errorToken, errorToken.DetailErrorKey ?? TexlStrings.ErrBadToken);
}
return CreateError(errorToken, errorToken.DetailErrorKey ?? TexlStrings.ErrBadToken, args);
case TokKind.Comment:
Contracts.Assert(false, "A stray comment was found");
_curs.TokMove();
return ParseOperand();
// Any other input should cause parsing errors.
default:
return CreateError(_curs.TokMove(), TexlStrings.ErrBadToken);
}
}
private TokKind AfterSpaceTokenId()
{
var split = _curs.Split();
ParseTrivia(split);
return split.TidCur;
}
private TexlNode ParseUnary(UnaryOp op)
{
var tok = _curs.TokMove();
var rightTrivia = ParseTrivia();
var right = ParseExpr(Precedence.PrefixUnary);
return new UnaryOpNode(
ref _idNext,
tok,
new SourceList(
new TokenSource(tok),
rightTrivia,
new NodeSource(right)),
op,
right);
}
// Parses an identifier delimited by brackets, e.g. [@foo]
private FirstNameNode ParseBracketIdentifierAsFirstName(bool accountForAllPrecedenceTokens = false)
{
Contracts.Assert(_curs.TidCur == TokKind.BracketOpen);
Contracts.Assert(_curs.TidPeek() == TokKind.At);
var bracketOpen = _curs.TokMove();
var at = _curs.TokMove();
var ident = ParseIdentifier(at);
var bracketClose = _curs.TokMove();
if (bracketClose.Kind != TokKind.BracketClose)
{
ErrorTid(bracketClose, TokKind.BracketClose);
}
return new FirstNameNode(
ref _idNext,
ident.Token,
new SourceList(
new TokenSource(bracketOpen),
new TokenSource(at),
new IdentifierSource(ident),
new TokenSource(bracketClose)),
ident);
}
// Parses the RHS of a scope field. E.g., [@bar] in "foo[@bar]"
private DottedNameNode ParseScopeField(FirstNameNode lhs)
{
Contracts.AssertValue(lhs);
Contracts.Assert(_curs.TidCur == TokKind.BracketOpen);
Contracts.Assert(_curs.TidPeek() == TokKind.At);
var bracketOpen = _curs.TokCur;
// Parse the rhs of the dotted name
var rhs = ParseBracketIdentifierAsFirstName();
// Form the dotted name
return new DottedNameNode(
ref _idNext,
bracketOpen,
new SourceList(new NodeSource(lhs), new NodeSource(rhs)),
lhs,
rhs.Ident,
rhs);
}
private Identifier ParseIdentifier(Token at = null)
{
Contracts.AssertValueOrNull(at);
IdentToken tok;
if (_curs.TidCur == TokKind.Ident)
{
tok = _curs.TokMove().As<IdentToken>();
if (tok.HasDelimiterStart && !tok.HasDelimiterEnd)
{
PostError(tok, TexlStrings.ErrClosingBracketExpected);
}
else if (tok.IsModified)
{
PostError(tok, TexlStrings.ErrEmptyInvalidIdentifier);
}
}
else
{
ErrorTid(_curs.TokCur, TokKind.Ident);
var ich = _curs.TokCur.Span.Min;
tok = new IdentToken(string.Empty, new Span(ich, ich));
}
return new Identifier(at, tok);
}
private TexlNode ParseStringInterpolation()
{
Contracts.Assert(_curs.TidCur == TokKind.StrInterpStart);
var startToken = _curs.TokMove();
var strInterpStart = startToken;
var strInterpTrivia = ParseTrivia();
var arguments = new List<TexlNode>();
var sourceList = new List<ITexlSource>
{
new TokenSource(strInterpStart),
strInterpTrivia
};
if (_curs.TidCur == TokKind.StrInterpEnd)
{
var tokenEnd = _curs.TokMove();
sourceList.Add(new TokenSource(tokenEnd));
return new StrInterpNode(ref _idNext, strInterpStart, new SourceList(sourceList), new TexlNode[0], tokenEnd);
}
for (var i = 0; ; i++)
{
if (_curs.TidCur == TokKind.IslandStart)
{
var islandStart = _curs.TokMove();
sourceList.Add(new TokenSource(islandStart));
sourceList.Add(ParseTrivia());
if (_curs.TidCur == TokKind.IslandEnd)
{
arguments.Add(CreateError(_curs.TokCur, TexlStrings.ErrEmptyIsland));
}
}
else if (_curs.TidCur == TokKind.IslandEnd)
{
var islandEnd = _curs.TokMove();
sourceList.Add(new TokenSource(islandEnd));
sourceList.Add(ParseTrivia());
}
else if (_curs.TidCur == TokKind.Eof)
{
var error = CreateError(_curs.TokCur, TexlStrings.ErrBadToken);
arguments.Add(error);
sourceList.Add(new NodeSource(error));
sourceList.Add(ParseTrivia());
return new StrInterpNode(
ref _idNext,
strInterpStart,
new SourceList(sourceList),
arguments.ToArray(),
_curs.TokCur);
}
else if (_curs.TidCur == TokKind.StrInterpEnd)
{
break;
}
else
{
var argument = ParseExpr(Precedence.None);
arguments.Add(argument);
sourceList.Add(new NodeSource(argument));
sourceList.Add(ParseTrivia());
}
}
Contracts.Assert(_curs.TidCur == TokKind.StrInterpEnd || _curs.TidCur == TokKind.Eof);
Token strInterpEnd = null;
if (_curs.TidCur == TokKind.StrInterpEnd)
{
strInterpEnd = TokEat(TokKind.StrInterpEnd);
}
if (strInterpEnd != null)
{
sourceList.Add(new TokenSource(strInterpEnd));
}
return new StrInterpNode(
ref _idNext,
strInterpStart,
new SourceList(sourceList),
arguments.ToArray(),
strInterpEnd);
}
// Parse a namespace-qualified invocation, e.g. Facebook.GetFriends()
private CallNode ParseInvocationWithNamespace(DottedNameNode dotted)
{
Contracts.Assert(dotted.HasPossibleNamespaceQualifier);
var path = dotted.ToDPath();
Contracts.Assert(path.IsValid);
Contracts.Assert(!path.IsRoot);
Contracts.Assert(!path.Parent.IsRoot);
var head = new Identifier(path.Parent, null, dotted.Right.Token);
Contracts.Assert(_curs.TidCur == TokKind.ParenOpen);
return ParseInvocation(head, ParseTrivia(), dotted);
}
private CallNode ParseInvocation(Identifier head, ITexlSource headTrivia, TexlNode headNode)
{
Contracts.AssertValue(head);
Contracts.AssertValueOrNull(headNode);
Contracts.Assert(_curs.TidCur == TokKind.ParenOpen);
var leftParen = _curs.TokMove();
var leftTrivia = ParseTrivia();
if (_curs.TidCur == TokKind.ParenClose)
{
var rightParen = _curs.TokMove();
var right = new ListNode(
ref _idNext,
_curs.TokCur,
new TexlNode[0],
null,
new SourceList(
new TokenSource(leftParen),
leftTrivia,
new TokenSource(rightParen)));
var sources = new List<ITexlSource>();
if (headNode != null)
{
sources.Add(new NodeSource(headNode));
}
else
{
sources.Add(new IdentifierSource(head));
}
sources.Add(headTrivia);
sources.Add(new NodeSource(right));
return new CallNode(
ref _idNext,
leftParen,
new SourceList(sources),
head,
headNode,
right,
rightParen);
}
var rgtokCommas = new List<Token>();
var arguments = new List<TexlNode>();
var sourceList = new List<ITexlSource>
{
new TokenSource(leftParen),
leftTrivia
};
for (; ;)
{
while (_curs.TidCur == TokKind.Comma)
{
var commaToken = _curs.TokMove();
arguments.Add(CreateError(commaToken, TexlStrings.ErrBadToken));
sourceList.Add(new TokenSource(commaToken));
sourceList.Add(ParseTrivia());
rgtokCommas.Add(commaToken);
}
var argument = ParseExpr(Precedence.None);
arguments.Add(argument);
sourceList.Add(new NodeSource(argument));
sourceList.Add(ParseTrivia());
if (_curs.TidCur != TokKind.Comma)
{
break;
}
var comma = _curs.TokMove();
rgtokCommas.Add(comma);
sourceList.Add(new TokenSource(comma));
sourceList.Add(ParseTrivia());
}
var parenClose = TokEat(TokKind.ParenClose);
if (parenClose != null)
{
sourceList.Add(new TokenSource(parenClose));
}
var list = new ListNode(
ref _idNext,
leftParen,
arguments.ToArray(),
CollectionUtils.ToArray(rgtokCommas),
new SourceList(sourceList));
ITexlSource headNodeSource = new IdentifierSource(head);
if (headNode != null)
{
headNodeSource = new NodeSource(headNode);
}
return new CallNode(
ref _idNext,
leftParen,
new SourceList(
headNodeSource,
headTrivia,
new NodeSource(list)),
head,
headNode,
list,
parenClose);
}
private TexlNode ParseExprChain(TexlNode node, ITexlSource leftTrivia)
{
Contracts.AssertValue(node);
Contracts.Assert(_curs.TidCur == TokKind.Semicolon);
var delimiters = new List<Token>(1);
var expressions = new List<TexlNode>(2)
{
node
};
var sourceList = new List<ITexlSource>
{
new NodeSource(node),
leftTrivia
};
while (_curs.TidCur == TokKind.Semicolon)
{
var delimiter = _curs.TokMove();
delimiters.Add(delimiter);
sourceList.Add(new TokenSource(delimiter));
sourceList.Add(ParseTrivia());
if (_curs.TidCur == TokKind.Eof || _curs.TidCur == TokKind.Comma || _curs.TidCur == TokKind.ParenClose)
{
break;
}
// SingleExpr here means we don't want chains on the RHS, but individual expressions.
var expression = ParseExpr(Precedence.SingleExpr);
expressions.Add(expression);
sourceList.Add(new NodeSource(expression));
sourceList.Add(ParseTrivia());
}
return new VariadicOpNode(
ref _idNext,
VariadicOp.Chain,
expressions.ToArray(),
delimiters.ToArray(),
new SourceList(sourceList));
}
// Parse a record expression of the form: {id:expr, id:expr, ...}
// or of the form ident@{id:expr, id:expr}
private RecordNode ParseRecordExpr(ITexlSource sourceRestrictionTrivia, Identifier sourceRestriction = null)
{
Contracts.Assert(_curs.TidCur == TokKind.CurlyOpen || _curs.TidCur == TokKind.At);
Contracts.AssertValueOrNull(sourceRestriction);
Token curlyClose;
var commas = new List<Token>();
var colons = new List<Token>();
var ids = new List<Identifier>();
var exprs = new List<TexlNode>();
var sourceList = new List<ITexlSource>();
TexlNode sourceRestrictionNode = null;
var primaryToken = _curs.TokMove();
if (primaryToken.Kind == TokKind.At)
{
Contracts.AssertValue(sourceRestriction);
sourceList.Add(sourceRestrictionTrivia);
sourceList.Add(new TokenSource(primaryToken));
sourceList.Add(ParseTrivia());
primaryToken = sourceRestriction.Token;
sourceRestrictionNode = new FirstNameNode(ref _idNext, sourceRestriction.Token, sourceRestriction);
if (_curs.TidCur != TokKind.CurlyOpen)
{
ErrorTid(_curs.TokCur, TokKind.CurlyOpen);
curlyClose = TokEat(TokKind.CurlyClose);
return new RecordNode(
ref _idNext,
sourceRestriction.Token,
new SourceList(
new SpreadSource(sourceList),
curlyClose != null ? (ITexlSource)new TokenSource(curlyClose) : new SpreadSource()),
ids.ToArray(),
exprs.ToArray(),
null,
null,
curlyClose,
sourceRestrictionNode);
}
sourceList.Add(new TokenSource(_curs.TokMove()));
sourceList.Add(ParseTrivia());
}
else
{
sourceList.Add(new TokenSource(primaryToken));
sourceList.Add(ParseTrivia());
}
while (_curs.TidCur != TokKind.CurlyClose)
{
// id
var ident = ParseIdentifier();
sourceList.Add(new IdentifierSource(ident));
sourceList.Add(ParseTrivia());
// :
if (_curs.TidCur != TokKind.Colon)
{
ErrorTid(_curs.TokCur, TokKind.Colon);
var errorToken = _curs.TokMove();
TexlNode errorExp = CreateError(errorToken, TexlStrings.ErrColonExpected);
sourceList.Add(new TokenSource(errorToken));
sourceList.Add(ParseTrivia());
ids.Add(ident);
exprs.Add(errorExp);
break;
}
var colon = _curs.TokMove();
colons.Add(colon);
sourceList.Add(new TokenSource(colon));
sourceList.Add(ParseTrivia());
// expr
// SingleExpr here means we don't want chains, but individual expressions.
var expr = ParseExpr(Precedence.SingleExpr);
ids.Add(ident);
exprs.Add(expr);
sourceList.Add(new NodeSource(expr));
sourceList.Add(ParseTrivia());
// ,
if (_curs.TidCur != TokKind.Comma)
{
break;
}
var comma = _curs.TokMove();
commas.Add(comma);
sourceList.Add(new TokenSource(comma));
sourceList.Add(ParseTrivia());
if (_curs.TidCur == TokKind.CurlyClose)
{
TexlNode errorExp = CreateError(comma, TexlStrings.ErrColonExpected);
exprs.Add(errorExp);
ids.Add(ParseIdentifier());
}
}
Contracts.Assert(ids.Count == exprs.Count);
var commaArray = commas?.ToArray();
var colonArray = colons?.ToArray();
curlyClose = TokEat(TokKind.CurlyClose);
if (curlyClose != null)
{
sourceList.Add(new TokenSource(curlyClose));
}
return new RecordNode(
ref _idNext,
primaryToken,
new SourceList(sourceList),
ids.ToArray(),
exprs.ToArray(),
commaArray,
colonArray,
curlyClose,
sourceRestrictionNode);
}
// Parse a table expression. The only currently supported form is: [expr, expr, ...]
private TableNode ParseTableExpr()
{
Contracts.Assert(_curs.TidCur == TokKind.BracketOpen);
var sourceList = new List<ITexlSource>();
var tok = _curs.TokMove();
sourceList.Add(new TokenSource(tok));
sourceList.Add(ParseTrivia());
var commas = new List<Token>();
var expressions = new List<TexlNode>();
while (_curs.TidCur != TokKind.BracketClose)
{
// expr
// SingleExpr here means we don't want chains, but individual expressions.
var expression = ParseExpr(Precedence.SingleExpr);
expressions.Add(expression);
sourceList.Add(new NodeSource(expression));
sourceList.Add(ParseTrivia());
// ,
if (_curs.TidCur != TokKind.Comma)
{
break;
}
var comma = _curs.TokMove();
commas.Add(comma);
sourceList.Add(new TokenSource(comma));
sourceList.Add(ParseTrivia());
}
var commaArray = commas?.ToArray();
var bracketClose = TokEat(TokKind.BracketClose);
if (bracketClose != null)
{
sourceList.Add(new TokenSource(bracketClose));
}
return new TableNode(
ref _idNext,
tok,
new SourceList(sourceList),
expressions.ToArray(),
commaArray,
bracketClose);
}
private TexlNode ParseParenExpr()
{
Contracts.Assert(_curs.TidCur == TokKind.ParenOpen);
var open = _curs.TokMove();
var before = ParseTrivia();
// SingleExpr here means we don't want chains, but individual expressions.
var node = ParseExpr(Precedence.SingleExpr);
var after = ParseTrivia();
var close = TokEat(TokKind.ParenClose);
var sources = new List<ITexlSource>
{
new TokenSource(open),
before,
new SpreadSource(node.SourceList.Sources),
after
};
if (close != null)
{
sources.Add(new TokenSource(close));
}
node.Parser_SetSourceList(new SourceList(new SpreadSource(sources)));
return node;
}
private ErrorNode CreateError(Token tok, ErrorResourceKey errKey, object[] args)
{
Contracts.AssertValue(tok);
Contracts.AssertValue(args);
var err = PostError(tok, errKey, args);
return new ErrorNode(ref _idNext, tok, err.ShortMessage, args);
}
private ErrorNode CreateError(Token tok, ErrorResourceKey errKey)
{
Contracts.AssertValue(tok);
var err = PostError(tok, errKey);
return new ErrorNode(ref _idNext, tok, err.ShortMessage);
}
private TexlError PostError(Token tok, ErrorResourceKey errKey)
{
Contracts.AssertValue(tok);
Contracts.AssertValue(errKey.Key);
var err = new TexlError(tok, DocumentErrorSeverity.Critical, errKey);
CollectionUtils.Add(ref _errors, err);
return err;
}
private TexlError PostError(Token tok, ErrorResourceKey errKey, params object[] args)
{
Contracts.AssertValue(tok);
Contracts.AssertValue(errKey.Key);
Contracts.AssertValueOrNull(args);
var err = new TexlError(tok, DocumentErrorSeverity.Critical, errKey, args);
CollectionUtils.Add(ref _errors, err);
return err;
}
// Eats a token of the given kind.
// If the token is not the right kind, reports an error and leaves it.
private bool EatTid(TokKind tid)
{
if (_curs.TidCur == tid)
{
_curs.TokMove();
return true;
}
ErrorTid(_curs.TokCur, tid);
return false;
}
// Returns the current token if it's of the given kind and moves to the next token.
// If the token is not the right kind, reports an error, leaves the token, and returns null.
private Token TokEat(TokKind tid)
{
if (_curs.TidCur == tid)
{
return _curs.TokMove();
}
ErrorTid(_curs.TokCur, tid);
return null;
}
private void ErrorTid(Token tok, TokKind tidWanted)
{
Contracts.Assert(tidWanted != tok.Kind);
PostError(tok, TexlStrings.ErrExpectedFound_Ex_Fnd, tidWanted, tok);
}
// Gets the string corresponding to token kinds used in binary or unary nodes.
internal static string GetTokString(TokKind kind)
{
switch (kind)
{
case TokKind.And:
return TexlLexer.PunctuatorAnd;
case TokKind.Or:
return TexlLexer.PunctuatorOr;
case TokKind.Bang:
return TexlLexer.PunctuatorBang;
case TokKind.Add:
return TexlLexer.PunctuatorAdd;
case TokKind.Sub:
return TexlLexer.PunctuatorSub;
case TokKind.Mul:
return TexlLexer.PunctuatorMul;
case TokKind.Div:
return TexlLexer.PunctuatorDiv;
case TokKind.Caret:
return TexlLexer.PunctuatorCaret;
case TokKind.Ampersand:
return TexlLexer.PunctuatorAmpersand;
case TokKind.PercentSign:
return TexlLexer.PunctuatorPercent;
case TokKind.Equ:
return TexlLexer.PunctuatorEqual;
case TokKind.Lss:
return TexlLexer.PunctuatorLess;
case TokKind.LssEqu:
return TexlLexer.PunctuatorLessOrEqual;
case TokKind.Grt:
return TexlLexer.PunctuatorGreater;
case TokKind.GrtEqu:
return TexlLexer.PunctuatorGreaterOrEqual;
case TokKind.LssGrt:
return TexlLexer.PunctuatorNotEqual;
case TokKind.Dot:
return TexlLexer.PunctuatorDot;
case TokKind.In:
return TexlLexer.KeywordIn;
case TokKind.Exactin:
return TexlLexer.KeywordExactin;
case TokKind.BracketOpen:
return TexlLexer.PunctuatorBracketOpen;
case TokKind.KeyOr:
return TexlLexer.KeywordOr;
case TokKind.KeyAnd:
return TexlLexer.KeywordAnd;
case TokKind.KeyNot:
return TexlLexer.KeywordNot;
case TokKind.As:
return TexlLexer.KeywordAs;
default:
return string.Empty;
}
}
public static string Format(string text)
{
var result = ParseScript(
text,
flags: Flags.EnableExpressionChaining);
// Can't pretty print a script with errors.
if (result.HasError)
{
return text;
}
return PrettyPrintVisitor.Format(result.Root, result.Before, result.After, text);
}
}
}
| 36.608966 | 156 | 0.464593 | [
"MIT"
] | Robulane/Power-Fx | src/libraries/Microsoft.PowerFx.Core/Parser/TexlParser.cs | 53,085 | C# |
namespace LocationView.Client.Config
{
partial class MarkerChangeForm
{
/// <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.labelDevice = new System.Windows.Forms.Label();
this.buttonDevice = new System.Windows.Forms.Button();
this.labelMarker = new System.Windows.Forms.Label();
this.comboBoxMarker = new System.Windows.Forms.ComboBox();
this.buttonOk = new System.Windows.Forms.Button();
this.buttonCancel = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// labelDevice
//
this.labelDevice.AutoSize = true;
this.labelDevice.Location = new System.Drawing.Point(12, 17);
this.labelDevice.Name = "labelDevice";
this.labelDevice.Size = new System.Drawing.Size(43, 13);
this.labelDevice.TabIndex = 0;
this.labelDevice.Text = "Device:";
//
// buttonDevice
//
this.buttonDevice.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.buttonDevice.Location = new System.Drawing.Point(62, 12);
this.buttonDevice.Name = "buttonDevice";
this.buttonDevice.Size = new System.Drawing.Size(155, 23);
this.buttonDevice.TabIndex = 1;
this.buttonDevice.Text = "Select device...";
this.buttonDevice.UseVisualStyleBackColor = true;
this.buttonDevice.Click += new System.EventHandler(this.ButtonDeviceClick);
//
// labelMarker
//
this.labelMarker.AutoSize = true;
this.labelMarker.Location = new System.Drawing.Point(12, 44);
this.labelMarker.Name = "labelMarker";
this.labelMarker.Size = new System.Drawing.Size(44, 13);
this.labelMarker.TabIndex = 2;
this.labelMarker.Text = "Marker:";
//
// comboBoxMarker
//
this.comboBoxMarker.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.comboBoxMarker.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboBoxMarker.FormattingEnabled = true;
this.comboBoxMarker.Location = new System.Drawing.Point(62, 41);
this.comboBoxMarker.Name = "comboBoxMarker";
this.comboBoxMarker.Size = new System.Drawing.Size(155, 21);
this.comboBoxMarker.TabIndex = 3;
this.comboBoxMarker.SelectedIndexChanged += new System.EventHandler(this.ComboBoxMarkerSelectedIndexChanged);
//
// buttonOk
//
this.buttonOk.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.buttonOk.DialogResult = System.Windows.Forms.DialogResult.OK;
this.buttonOk.Location = new System.Drawing.Point(61, 68);
this.buttonOk.Name = "buttonOk";
this.buttonOk.Size = new System.Drawing.Size(75, 23);
this.buttonOk.TabIndex = 4;
this.buttonOk.Text = "OK";
this.buttonOk.UseVisualStyleBackColor = true;
//
// buttonCancel
//
this.buttonCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.buttonCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.buttonCancel.Location = new System.Drawing.Point(142, 68);
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.Size = new System.Drawing.Size(75, 23);
this.buttonCancel.TabIndex = 5;
this.buttonCancel.Text = "Cancel";
this.buttonCancel.UseVisualStyleBackColor = true;
//
// MarkerChangeForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(228, 101);
this.Controls.Add(this.buttonCancel);
this.Controls.Add(this.buttonOk);
this.Controls.Add(this.comboBoxMarker);
this.Controls.Add(this.labelMarker);
this.Controls.Add(this.buttonDevice);
this.Controls.Add(this.labelDevice);
this.MaximizeBox = false;
this.MaximumSize = new System.Drawing.Size(444, 140);
this.MinimizeBox = false;
this.MinimumSize = new System.Drawing.Size(244, 140);
this.Name = "MarkerChangeForm";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "MarkerChangeForm";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Label labelDevice;
private System.Windows.Forms.Button buttonDevice;
private System.Windows.Forms.Label labelMarker;
private System.Windows.Forms.ComboBox comboBoxMarker;
private System.Windows.Forms.Button buttonOk;
private System.Windows.Forms.Button buttonCancel;
}
} | 47.214815 | 160 | 0.607939 | [
"MIT"
] | Silex/mipsdk-samples-plugin | LocationView/Client/Config/MarkerChangeForm.Designer.cs | 6,376 | C# |
using MessagePack.Tests.SharedTypes;
namespace MessagePack.Tests.SharedTestItems.Successes.ImmutableClasses
{
internal sealed class TestClassWithMultipleValidConstructors : SuccessTestItem<ClassWithMultipleValidConstructors>
{
public TestClassWithMultipleValidConstructors() : base(new ClassWithMultipleValidConstructors(123, "ABC", new[] { "DEF", "GHI" })) { }
}
} | 43 | 142 | 0.782946 | [
"BSD-2-Clause"
] | ProductiveRage/MsgPack5.H5 | Tests/SharedTestItems/Successes/ImmutableClasses/TestClassWithMultipleValidConstructors.cs | 389 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.