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
// This code was generated by a kontent-generators-net tool // (see https://github.com/Kentico/kontent-generators-net). // // Changes to this file may cause incorrect behavior and will be lost if the code is regenerated. // For further modifications of the class, create a separate file with the partial class. using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using Kentico.Kontent.Delivery; namespace KenticoKontentModels { public partial class AgendaItem { public const string Codename = "agenda_item"; public const string RoomCodename = "room"; public const string PresentationCodename = "presentation"; public const string EndTimeCodename = "end_time"; public const string RecordingCodename = "recording"; public const string LocationCodename = "location"; public const string SpeakersCodename = "speakers"; public const string UrlSlugCodename = "url_slug"; public const string NameCodename = "name"; public const string StartTimeCodename = "start_time"; public const string TrackCodename = "track"; public IEnumerable<object> Room { get; set; } public IEnumerable<object> Presentation { get; set; } [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:hh:mm tt}")] public DateTime? EndTime { get; set; } public IEnumerable<object> Recording { get; set; } public IEnumerable<TaxonomyTerm> Location { get; set; } public IEnumerable<object> Speakers { get; set; } public string UrlSlug { get; set; } public string Name { get; set; } [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:hh:mm tt}")] public DateTime? StartTime { get; set; } public IEnumerable<TaxonomyTerm> Track { get; set; } public ContentItemSystemAttributes System { get; set; } } }
46.142857
98
0.691434
[ "MIT" ]
kentico-michaelb/kontent-sample-app-conference-net
kontent-sample-app-conference-net/Models/AgendaItem.cs
1,938
C#
namespace Shared.Group_007 { using Xunit; public class Benchmark003Tests { [Fact] public void Test_001() { } [Fact] public void Test_002() { } [Fact] public void Test_003() { } [Fact] public void Test_004() { } [Fact] public void Test_005() { } [Fact] public void Test_006() { } [Fact] public void Test_007() { } [Fact] public void Test_008() { } [Fact] public void Test_009() { } [Fact] public void Test_010() { } [Fact] public void Test_011() { } [Fact] public void Test_012() { } [Fact] public void Test_013() { } [Fact] public void Test_014() { } [Fact] public void Test_015() { } [Fact] public void Test_016() { } [Fact] public void Test_017() { } [Fact] public void Test_018() { } [Fact] public void Test_019() { } [Fact] public void Test_020() { } [Fact] public void Test_021() { } [Fact] public void Test_022() { } [Fact] public void Test_023() { } [Fact] public void Test_024() { } [Fact] public void Test_025() { } [Fact] public void Test_026() { } [Fact] public void Test_027() { } [Fact] public void Test_028() { } [Fact] public void Test_029() { } [Fact] public void Test_030() { } [Fact] public void Test_031() { } [Fact] public void Test_032() { } [Fact] public void Test_033() { } [Fact] public void Test_034() { } [Fact] public void Test_035() { } [Fact] public void Test_036() { } [Fact] public void Test_037() { } [Fact] public void Test_038() { } [Fact] public void Test_039() { } [Fact] public void Test_040() { } [Fact] public void Test_041() { } [Fact] public void Test_042() { } [Fact] public void Test_043() { } [Fact] public void Test_044() { } [Fact] public void Test_045() { } [Fact] public void Test_046() { } [Fact] public void Test_047() { } [Fact] public void Test_048() { } [Fact] public void Test_049() { } [Fact] public void Test_050() { } } }
37.220339
41
0.529144
[ "MIT" ]
chan18/fixie.benchmark
src/Shared/Group_007/Benchmark003Tests.cs
2,196
C#
// <auto-generated> // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Microsoft.Azure.TimeSeriesInsights.Models { using Microsoft.Rest; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; /// <summary> /// Get Series query. Allows to retrieve time series of calculated variable /// values from events for a given Time Series ID and search span. /// </summary> public partial class GetSeries { /// <summary> /// Initializes a new instance of the GetSeries class. /// </summary> public GetSeries() { CustomInit(); } /// <summary> /// Initializes a new instance of the GetSeries class. /// </summary> /// <param name="timeSeriesId">A single Time Series ID value that /// uniquely identifies a single time series instance (e.g. a device). /// Note that a single Time Series ID can be composite if multiple /// properties are specified as Time Series ID at environment creation /// time. The position and type of values must match Time Series ID /// properties specified on the environment and returned by Get Model /// Setting API. Cannot be null.</param> /// <param name="searchSpan">The range of time on which the query is /// executed. Cannot be null.</param> /// <param name="filter">Top-level filter over the events that /// restricts the number of events being considered for computation. /// This filter is AND'ed with filter in each variable. Example: /// "$event.Status.String='Good'". Optional.</param> /// <param name="projectedVariables">Selected variables that needs to /// be projected in the query result. When it is null or not set, all /// the variables from inlineVariables and time series type in the /// model are returned. Can be null.</param> /// <param name="inlineVariables">Optional inline variables apart from /// the ones already defined in the time series type in the model. When /// the inline variable name is the same name as in the model, the /// inline variable definition takes precedence. Can be null.</param> /// <param name="take">Maximum number of property values in the whole /// response set, not the maximum number of property values per page. /// Defaults to 10,000 when not set. Maximum value of take can be /// 250,000.</param> public GetSeries(IList<object> timeSeriesId, DateTimeRange searchSpan, Tsx filter = default(Tsx), IList<string> projectedVariables = default(IList<string>), IDictionary<string, Variable> inlineVariables = default(IDictionary<string, Variable>), int? take = default(int?)) { TimeSeriesId = timeSeriesId; SearchSpan = searchSpan; Filter = filter; ProjectedVariables = projectedVariables; InlineVariables = inlineVariables; Take = take; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// Gets or sets a single Time Series ID value that uniquely identifies /// a single time series instance (e.g. a device). Note that a single /// Time Series ID can be composite if multiple properties are /// specified as Time Series ID at environment creation time. The /// position and type of values must match Time Series ID properties /// specified on the environment and returned by Get Model Setting API. /// Cannot be null. /// </summary> [JsonProperty(PropertyName = "timeSeriesId")] public IList<object> TimeSeriesId { get; set; } /// <summary> /// Gets or sets the range of time on which the query is executed. /// Cannot be null. /// </summary> [JsonProperty(PropertyName = "searchSpan")] public DateTimeRange SearchSpan { get; set; } /// <summary> /// Gets or sets top-level filter over the events that restricts the /// number of events being considered for computation. This filter is /// AND'ed with filter in each variable. Example: /// "$event.Status.String='Good'". Optional. /// </summary> [JsonProperty(PropertyName = "filter")] public Tsx Filter { get; set; } /// <summary> /// Gets or sets selected variables that needs to be projected in the /// query result. When it is null or not set, all the variables from /// inlineVariables and time series type in the model are returned. Can /// be null. /// </summary> [JsonProperty(PropertyName = "projectedVariables")] public IList<string> ProjectedVariables { get; set; } /// <summary> /// Gets or sets optional inline variables apart from the ones already /// defined in the time series type in the model. When the inline /// variable name is the same name as in the model, the inline variable /// definition takes precedence. Can be null. /// </summary> [JsonProperty(PropertyName = "inlineVariables")] public IDictionary<string, Variable> InlineVariables { get; set; } /// <summary> /// Gets or sets maximum number of property values in the whole /// response set, not the maximum number of property values per page. /// Defaults to 10,000 when not set. Maximum value of take can be /// 250,000. /// </summary> [JsonProperty(PropertyName = "take")] public int? Take { get; set; } /// <summary> /// Validate the object. /// </summary> /// <exception cref="ValidationException"> /// Thrown if validation fails /// </exception> public virtual void Validate() { if (TimeSeriesId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "TimeSeriesId"); } if (SearchSpan == null) { throw new ValidationException(ValidationRules.CannotBeNull, "SearchSpan"); } if (SearchSpan != null) { SearchSpan.Validate(); } if (Filter != null) { Filter.Validate(); } if (InlineVariables != null) { foreach (var valueElement in InlineVariables.Values) { if (valueElement != null) { valueElement.Validate(); } } } } } }
42.727811
279
0.601717
[ "MIT" ]
Azure-Samples/Azure-Time-Series-Insights
gen2-sample/csharp-tsi-gen2-sample/DataPlaneClient/Generated/TimeSeriesInsights/DataPlane.TimeSeriesInsights/Generated/Models/GetSeries.cs
7,221
C#
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; using System.Xml; namespace Rami.Wechat.Core.Public.Tencent { /// <summary> /// WXBizMsgCrypt /// </summary> public class WXBizMsgCrypt { /// <summary> /// AppId /// </summary> string m_sAppID; /// <summary> /// Token /// </summary> string m_sToken; /// <summary> /// Aes Key /// </summary> string m_sEncodingAESKey; /// <summary> /// 错误定义 /// </summary> enum WXBizMsgCryptErrorCode { WXBizMsgCrypt_OK = 0, /// <summary> /// 签名验证错误 /// </summary> WXBizMsgCrypt_ValidateSignature_Error = -40001, /// <summary> /// xml解析失败 /// </summary> WXBizMsgCrypt_ParseXml_Error = -40002, /// <summary> /// sha加密生成签名失败 /// </summary> WXBizMsgCrypt_ComputeSignature_Error = -40003, /// <summary> /// AESKey 非法 /// </summary> WXBizMsgCrypt_IllegalAesKey = -40004, /// <summary> /// appid 校验错误 /// </summary> WXBizMsgCrypt_ValidateAppid_Error = -40005, /// <summary> /// AES 加密失败 /// </summary> WXBizMsgCrypt_EncryptAES_Error = -40006, /// <summary> /// AES 解密失败 /// </summary> WXBizMsgCrypt_DecryptAES_Error = -40007, /// <summary> /// 解密后得到的buffer非法 /// </summary> WXBizMsgCrypt_IllegalBuffer = -40008, /// <summary> /// base64加密异常 /// </summary> WXBizMsgCrypt_EncodeBase64_Error = -40009, /// <summary> /// base64解密异常 /// </summary> WXBizMsgCrypt_DecodeBase64_Error = -40010 }; /// <summary> /// 构造函数 /// </summary> /// <param name="sToken">公众平台上,开发者设置的Token</param> /// <param name="sEncodingAESKey">公众平台上,开发者设置的EncodingAESKey</param> /// <param name="sAppID">公众帐号的appid</param> public WXBizMsgCrypt(string sToken, string sEncodingAESKey, string sAppID) { m_sToken = sToken; m_sAppID = sAppID; m_sEncodingAESKey = sEncodingAESKey; } /// <summary> /// 检验消息的真实性,并且获取解密后的明文 /// </summary> /// <param name="sMsgSignature">签名串,对应URL参数的msg_signature</param> /// <param name="sTimeStamp">时间戳,对应URL参数的timestamp</param> /// <param name="sNonce">随机串,对应URL参数的nonce</param> /// <param name="sPostData">密文,对应POST请求的数据</param> /// <param name="sMsg">解密后的原文,当return返回0时有效</param> /// <returns>成功0,失败返回对应的错误码</returns> public int DecryptMsg(string sMsgSignature, string sTimeStamp, string sNonce, string sPostData, ref string sMsg) { if (m_sEncodingAESKey.Length != 43) { return (int)WXBizMsgCryptErrorCode.WXBizMsgCrypt_IllegalAesKey; } XmlDocument doc = new XmlDocument(); XmlNode root; string sEncryptMsg; try { doc.LoadXml(sPostData); root = doc.FirstChild; sEncryptMsg = root["Encrypt"].InnerText; } catch (Exception) { return (int)WXBizMsgCryptErrorCode.WXBizMsgCrypt_ParseXml_Error; } // 验证签名 int ret = 0; ret = VerifySignature(m_sToken, sTimeStamp, sNonce, sEncryptMsg, sMsgSignature); if (ret != 0) { return ret; } // 解密消息 string cpid = ""; try { sMsg = Cryptography.AES_decrypt(sEncryptMsg, m_sEncodingAESKey, ref cpid); } catch (FormatException) { return (int)WXBizMsgCryptErrorCode.WXBizMsgCrypt_DecodeBase64_Error; } catch (Exception) { return (int)WXBizMsgCryptErrorCode.WXBizMsgCrypt_DecryptAES_Error; } if (cpid != m_sAppID) { return (int)WXBizMsgCryptErrorCode.WXBizMsgCrypt_ValidateAppid_Error; } return 0; } /// <summary> /// 将回复用户的消息加密打包 /// </summary> /// <param name="sReplyMsg">企业号待回复用户的消息,xml格式的字符串</param> /// <param name="sTimeStamp">时间戳,可以自己生成,也可以用URL参数的timestamp</param> /// <param name="sNonce">随机串,可以自己生成,也可以用URL参数的nonce</param> /// <param name="sEncryptMsg">加密后的可以直接回复用户的密文,包括msg_signature, timestamp, nonce, encrypt的xml格式的字符串,当return返回0时有效</param> /// <returns>成功0,失败返回对应的错误码</returns> public int EncryptMsg(string sReplyMsg, string sTimeStamp, string sNonce, ref string sEncryptMsg) { if (m_sEncodingAESKey.Length != 43) { return (int)WXBizMsgCryptErrorCode.WXBizMsgCrypt_IllegalAesKey; } string raw = ""; try { raw = Cryptography.AES_encrypt(sReplyMsg, m_sEncodingAESKey, m_sAppID); } catch (Exception) { return (int)WXBizMsgCryptErrorCode.WXBizMsgCrypt_EncryptAES_Error; } string MsgSigature = ""; int ret = 0; ret = GenarateSinature(m_sToken, sTimeStamp, sNonce, raw, ref MsgSigature); if (0 != ret) { return ret; } sEncryptMsg = ""; string EncryptLabelHead = "<Encrypt><![CDATA["; string EncryptLabelTail = "]]></Encrypt>"; string MsgSigLabelHead = "<MsgSignature><![CDATA["; string MsgSigLabelTail = "]]></MsgSignature>"; string TimeStampLabelHead = "<TimeStamp><![CDATA["; string TimeStampLabelTail = "]]></TimeStamp>"; string NonceLabelHead = "<Nonce><![CDATA["; string NonceLabelTail = "]]></Nonce>"; sEncryptMsg = sEncryptMsg + "<xml>" + EncryptLabelHead + raw + EncryptLabelTail; sEncryptMsg = sEncryptMsg + MsgSigLabelHead + MsgSigature + MsgSigLabelTail; sEncryptMsg = sEncryptMsg + TimeStampLabelHead + sTimeStamp + TimeStampLabelTail; sEncryptMsg = sEncryptMsg + NonceLabelHead + sNonce + NonceLabelTail; sEncryptMsg += "</xml>"; return 0; } /// <summary> /// 字典排序 /// </summary> public class DictionarySort : System.Collections.IComparer { /// <summary> /// 字典对比实现 /// </summary> /// <param name="oLeft"></param> /// <param name="oRight"></param> /// <returns></returns> public int Compare(object oLeft, object oRight) { string sLeft = oLeft as string; string sRight = oRight as string; int iLeftLength = sLeft.Length; int iRightLength = sRight.Length; int index = 0; while (index < iLeftLength && index < iRightLength) { if (sLeft[index] < sRight[index]) return -1; else if (sLeft[index] > sRight[index]) return 1; else index++; } return iLeftLength - iRightLength; } } /// <summary> /// 验证签名 /// </summary> /// <param name="sToken"></param> /// <param name="sTimeStamp"></param> /// <param name="sNonce"></param> /// <param name="sMsgEncrypt"></param> /// <param name="sSigture"></param> /// <returns></returns> public static int VerifySignature(string sToken, string sTimeStamp, string sNonce, string sMsgEncrypt, string sSigture) { string hash = ""; int ret = 0; ret = GenarateSinature(sToken, sTimeStamp, sNonce, sMsgEncrypt, ref hash); if (ret != 0) { return ret; } if (hash == sSigture) { return 0; } else { return (int)WXBizMsgCryptErrorCode.WXBizMsgCrypt_ValidateSignature_Error; } } /// <summary> /// 数据签名 /// </summary> /// <param name="sToken"></param> /// <param name="sTimeStamp"></param> /// <param name="sNonce"></param> /// <param name="sMsgEncrypt"></param> /// <param name="sMsgSignature"></param> /// <returns></returns> public static int GenarateSinature(string sToken, string sTimeStamp, string sNonce, string sMsgEncrypt, ref string sMsgSignature) { ArrayList AL = new ArrayList(); AL.Add(sToken); AL.Add(sTimeStamp); AL.Add(sNonce); AL.Add(sMsgEncrypt); AL.Sort(new DictionarySort()); string raw = ""; for (int i = 0; i < AL.Count; ++i) { raw += AL[i]; } SHA1 sha; ASCIIEncoding enc; string hash = ""; try { sha = new SHA1CryptoServiceProvider(); enc = new ASCIIEncoding(); byte[] dataToHash = enc.GetBytes(raw); byte[] dataHashed = sha.ComputeHash(dataToHash); hash = BitConverter.ToString(dataHashed).Replace("-", ""); hash = hash.ToLower(); } catch (Exception) { return (int)WXBizMsgCryptErrorCode.WXBizMsgCrypt_ComputeSignature_Error; } sMsgSignature = hash; return 0; } } }
33.054662
137
0.499222
[ "MIT" ]
tamakiramimy/Rami.Wechat.Core
Rami.Wechat.Core/Public/Tencent/WXBizMsgCrypt.cs
10,888
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System; using System.Collections.Generic; using System.Linq; namespace Azure.Analytics.Synapse.Artifacts.Models { /// <summary> A list of spark job definitions resources. </summary> public partial class SparkJobDefinitionsListResponse { /// <summary> Initializes a new instance of SparkJobDefinitionsListResponse. </summary> /// <param name="value"> List of spark job definitions. </param> /// <exception cref="ArgumentNullException"> <paramref name="value"/> is null. </exception> internal SparkJobDefinitionsListResponse(IEnumerable<SparkJobDefinitionResource> value) { if (value == null) { throw new ArgumentNullException(nameof(value)); } Value = value.ToList(); } /// <summary> Initializes a new instance of SparkJobDefinitionsListResponse. </summary> /// <param name="value"> List of spark job definitions. </param> /// <param name="nextLink"> The link to the next page of results, if any remaining results exist. </param> internal SparkJobDefinitionsListResponse(IReadOnlyList<SparkJobDefinitionResource> value, string nextLink) { Value = value; NextLink = nextLink; } /// <summary> List of spark job definitions. </summary> public IReadOnlyList<SparkJobDefinitionResource> Value { get; } /// <summary> The link to the next page of results, if any remaining results exist. </summary> public string NextLink { get; } } }
37.933333
114
0.659051
[ "MIT" ]
0rland0Wats0n/azure-sdk-for-net
sdk/synapse/Azure.Analytics.Synapse.Artifacts/src/Generated/Models/SparkJobDefinitionsListResponse.cs
1,707
C#
using TMPro; using UnityEngine; using UnityEngine.UI; public class ItemButtonManager : MonoBehaviour { private string itemName; public string ItemName { set => itemName = value; } private string itemDescription; public string ItemDescription { set => itemDescription = value; } private string price; public string Price { set => price = value; } private Sprite itemImage; public Sprite ItemImage { set => itemImage = value; } private GameObject item3DModel; public GameObject Item3DModel { set => item3DModel = value; } private ARInteractionManager interactionManager; private void Start() { transform.GetChild(0).GetComponent<TextMeshProUGUI>().text = itemName; transform.GetChild(1).GetComponent<RawImage>().texture = itemImage.texture; transform.GetChild(2).GetComponent<TextMeshProUGUI>().text = itemDescription; var button = GetComponent<Button>(); button.onClick.AddListener(GameManager.instance.ARPosition); button.onClick.AddListener(Create3DModel); interactionManager = FindObjectOfType<ARInteractionManager>(); } private void Create3DModel() { interactionManager.Item3DModel = Instantiate(item3DModel); } }
30.166667
85
0.703236
[ "MIT" ]
RaimundoGallino/PlaceApp-Clone-ARFoundation
Assets/Scripts/ItemButtonManager.cs
1,267
C#
namespace ABCSharp.Tokens { public class RestToken : Token { public string Symbol { get; set; } public Fraction Length { get; set; } public void Dotify(string dots, string direction) { Length = DurationHelper.Dotify(Length, dots, direction); } } }
24.615385
68
0.575
[ "MIT" ]
ModernMAK/ABCSharp
ABCSharp/src/Tokens/RestToken.cs
320
C#
using System; using System.IO; using System.IO.Compression; namespace Exceptionless.Core.Extensions { public static class ByteArrayExtensions { public static byte[] Decompress(this byte[] data, string encoding) { byte[] decompressedData = null; using (var outputStream = new MemoryStream()) { using (var inputStream = new MemoryStream(data)) { if (encoding == "gzip") using (var zip = new GZipStream(inputStream, CompressionMode.Decompress)) { zip.CopyTo(outputStream); } else if (encoding == "deflate") using (var zip = new DeflateStream(inputStream, CompressionMode.Decompress)) { zip.CopyTo(outputStream); } else throw new ArgumentException(String.Format("Unsupported encoding type \"{0}\".", encoding), "encoding"); } decompressedData = outputStream.ToArray(); } return decompressedData; } public static byte[] Compress(this byte[] data) { byte[] compressesData; using (var outputStream = new MemoryStream()) { using (var zip = new GZipStream(outputStream, CompressionMode.Compress)) { zip.Write(data, 0, data.Length); } compressesData = outputStream.ToArray(); } return compressesData; } } }
37.880952
127
0.522313
[ "Apache-2.0" ]
mahizsas/Exceptionless
Source/Core/Extensions/ByteArrayExtensions.cs
1,593
C#
using System; using NetOffice; using NetOffice.Attributes; namespace NetOffice.ExcelApi.Enums { /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// </summary> ///<remarks> MSDN Online Documentation: <see href="https://docs.microsoft.com/en-us/office/vba/api/Excel.XlCellInsertionMode"/> </remarks> [SupportByVersion("Excel", 9,10,11,12,14,15,16)] [EntityType(EntityType.IsEnum)] public enum XlCellInsertionMode { /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// </summary> /// <remarks>0</remarks> [SupportByVersion("Excel", 9,10,11,12,14,15,16)] xlOverwriteCells = 0, /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// </summary> /// <remarks>1</remarks> [SupportByVersion("Excel", 9,10,11,12,14,15,16)] xlInsertDeleteCells = 1, /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// </summary> /// <remarks>2</remarks> [SupportByVersion("Excel", 9,10,11,12,14,15,16)] xlInsertEntireRows = 2 } }
29.8
140
0.641419
[ "MIT" ]
NetOfficeFw/NetOffice
Source/Excel/Enums/XlCellInsertionMode.cs
1,045
C#
/******************************************************************************* * Copyright 2012-2019 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. * ***************************************************************************** * * AWS Tools for Windows (TM) PowerShell (TM) * */ using System; using System.Collections.Generic; using System.Linq; using System.Management.Automation; using System.Text; using Amazon.PowerShell.Common; using Amazon.Runtime; using Amazon.GroundStation; using Amazon.GroundStation.Model; namespace Amazon.PowerShell.Cmdlets.GS { /// <summary> /// Deletes a dataflow endpoint group. /// </summary> [Cmdlet("Remove", "GSDataflowEndpointGroup", SupportsShouldProcess = true, ConfirmImpact = ConfirmImpact.High)] [OutputType("System.String")] [AWSCmdlet("Calls the AWS Ground Station DeleteDataflowEndpointGroup API operation.", Operation = new[] {"DeleteDataflowEndpointGroup"}, SelectReturnType = typeof(Amazon.GroundStation.Model.DeleteDataflowEndpointGroupResponse))] [AWSCmdletOutput("System.String or Amazon.GroundStation.Model.DeleteDataflowEndpointGroupResponse", "This cmdlet returns a System.String object.", "The service call response (type Amazon.GroundStation.Model.DeleteDataflowEndpointGroupResponse) can also be referenced from properties attached to the cmdlet entry in the $AWSHistory stack." )] public partial class RemoveGSDataflowEndpointGroupCmdlet : AmazonGroundStationClientCmdlet, IExecutor { #region Parameter DataflowEndpointGroupId /// <summary> /// <para> /// <para>ID of a dataflow endpoint group.</para> /// </para> /// </summary> #if !MODULAR [System.Management.Automation.Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true)] #else [System.Management.Automation.Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true, Mandatory = true)] [System.Management.Automation.AllowEmptyString] [System.Management.Automation.AllowNull] #endif [Amazon.PowerShell.Common.AWSRequiredParameter] public System.String DataflowEndpointGroupId { get; set; } #endregion #region Parameter Select /// <summary> /// Use the -Select parameter to control the cmdlet output. The default value is 'DataflowEndpointGroupId'. /// Specifying -Select '*' will result in the cmdlet returning the whole service response (Amazon.GroundStation.Model.DeleteDataflowEndpointGroupResponse). /// Specifying the name of a property of type Amazon.GroundStation.Model.DeleteDataflowEndpointGroupResponse will result in that property being returned. /// Specifying -Select '^ParameterName' will result in the cmdlet returning the selected cmdlet parameter value. /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public string Select { get; set; } = "DataflowEndpointGroupId"; #endregion #region Parameter PassThru /// <summary> /// Changes the cmdlet behavior to return the value passed to the DataflowEndpointGroupId parameter. /// The -PassThru parameter is deprecated, use -Select '^DataflowEndpointGroupId' instead. This parameter will be removed in a future version. /// </summary> [System.Obsolete("The -PassThru parameter is deprecated, use -Select '^DataflowEndpointGroupId' instead. This parameter will be removed in a future version.")] [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public SwitchParameter PassThru { get; set; } #endregion #region Parameter Force /// <summary> /// This parameter overrides confirmation prompts to force /// the cmdlet to continue its operation. This parameter should always /// be used with caution. /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public SwitchParameter Force { get; set; } #endregion protected override void ProcessRecord() { base.ProcessRecord(); var resourceIdentifiersText = FormatParameterValuesForConfirmationMsg(nameof(this.DataflowEndpointGroupId), MyInvocation.BoundParameters); if (!ConfirmShouldProceed(this.Force.IsPresent, resourceIdentifiersText, "Remove-GSDataflowEndpointGroup (DeleteDataflowEndpointGroup)")) { return; } var context = new CmdletContext(); // allow for manipulation of parameters prior to loading into context PreExecutionContextLoad(context); #pragma warning disable CS0618, CS0612 //A class member was marked with the Obsolete attribute if (ParameterWasBound(nameof(this.Select))) { context.Select = CreateSelectDelegate<Amazon.GroundStation.Model.DeleteDataflowEndpointGroupResponse, RemoveGSDataflowEndpointGroupCmdlet>(Select) ?? throw new System.ArgumentException("Invalid value for -Select parameter.", nameof(this.Select)); if (this.PassThru.IsPresent) { throw new System.ArgumentException("-PassThru cannot be used when -Select is specified.", nameof(this.Select)); } } else if (this.PassThru.IsPresent) { context.Select = (response, cmdlet) => this.DataflowEndpointGroupId; } #pragma warning restore CS0618, CS0612 //A class member was marked with the Obsolete attribute context.DataflowEndpointGroupId = this.DataflowEndpointGroupId; #if MODULAR if (this.DataflowEndpointGroupId == null && ParameterWasBound(nameof(this.DataflowEndpointGroupId))) { WriteWarning("You are passing $null as a value for parameter DataflowEndpointGroupId which is marked as required. In case you believe this parameter was incorrectly marked as required, report this by opening an issue at https://github.com/aws/aws-tools-for-powershell/issues."); } #endif // allow further manipulation of loaded context prior to processing PostExecutionContextLoad(context); var output = Execute(context) as CmdletOutput; ProcessOutput(output); } #region IExecutor Members public object Execute(ExecutorContext context) { var cmdletContext = context as CmdletContext; // create request var request = new Amazon.GroundStation.Model.DeleteDataflowEndpointGroupRequest(); if (cmdletContext.DataflowEndpointGroupId != null) { request.DataflowEndpointGroupId = cmdletContext.DataflowEndpointGroupId; } CmdletOutput output; // issue call var client = Client ?? CreateClient(_CurrentCredentials, _RegionEndpoint); try { var response = CallAWSServiceOperation(client, request); object pipelineOutput = null; pipelineOutput = cmdletContext.Select(response, this); output = new CmdletOutput { PipelineOutput = pipelineOutput, ServiceResponse = response }; } catch (Exception e) { output = new CmdletOutput { ErrorResponse = e }; } return output; } public ExecutorContext CreateContext() { return new CmdletContext(); } #endregion #region AWS Service Operation Call private Amazon.GroundStation.Model.DeleteDataflowEndpointGroupResponse CallAWSServiceOperation(IAmazonGroundStation client, Amazon.GroundStation.Model.DeleteDataflowEndpointGroupRequest request) { Utils.Common.WriteVerboseEndpointMessage(this, client.Config, "AWS Ground Station", "DeleteDataflowEndpointGroup"); try { #if DESKTOP return client.DeleteDataflowEndpointGroup(request); #elif CORECLR return client.DeleteDataflowEndpointGroupAsync(request).GetAwaiter().GetResult(); #else #error "Unknown build edition" #endif } catch (AmazonServiceException exc) { var webException = exc.InnerException as System.Net.WebException; if (webException != null) { throw new Exception(Utils.Common.FormatNameResolutionFailureMessage(client.Config, webException.Message), webException); } throw; } } #endregion internal partial class CmdletContext : ExecutorContext { public System.String DataflowEndpointGroupId { get; set; } public System.Func<Amazon.GroundStation.Model.DeleteDataflowEndpointGroupResponse, RemoveGSDataflowEndpointGroupCmdlet, object> Select { get; set; } = (response, cmdlet) => response.DataflowEndpointGroupId; } } }
47.194444
294
0.632627
[ "Apache-2.0" ]
5u5hma/aws-tools-for-powershell
modules/AWSPowerShell/Cmdlets/GroundStation/Basic/Remove-GSDataflowEndpointGroup-Cmdlet.cs
10,194
C#
using Benday.EasyAuthDemo.Api.Adapters; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Collections.Generic; using System.Text; using Benday.EasyAuthDemo.UnitTests.Utilities; using Benday.EasyAuthDemo.WebUi.Models; using Benday.EasyAuthDemo.WebUi.Models.Adapters; namespace Benday.EasyAuthDemo.UnitTests.ViewModels.Adapters { [TestClass] public class ConfigurationItemAdapterFixture { [TestInitialize] public void OnTestInitialize() { _SystemUnderTest = null; } private ConfigurationItemEditorViewModelAdapter _SystemUnderTest; public ConfigurationItemEditorViewModelAdapter SystemUnderTest { get { if (_SystemUnderTest == null) { _SystemUnderTest = new ConfigurationItemEditorViewModelAdapter(); } return _SystemUnderTest; } } [TestMethod] public void AdaptConfigurationItemFromViewModelsToModels() { // arrange var fromValues = ConfigurationItemViewModelTestUtility.CreateEditorViewModels(); var allValuesCount = fromValues.Count; var toValues = new List<Benday.EasyAuthDemo.Api.DomainModels.ConfigurationItem>(); // act SystemUnderTest.Adapt(fromValues, toValues); // assert Assert.AreEqual<int>(allValuesCount, toValues.Count, "Count was wrong."); } [TestMethod] public void AdaptConfigurationItemFromViewModelToModel() { // arrange var fromValue = ConfigurationItemViewModelTestUtility.CreateEditorViewModel(); var toValue = new Benday.EasyAuthDemo.Api.DomainModels.ConfigurationItem(); // act SystemUnderTest.Adapt(fromValue, toValue); // assert ConfigurationItemViewModelTestUtility.AssertAreEqual(fromValue, toValue); } [TestMethod] public void AdaptConfigurationItemFromModelToViewModel() { // arrange var fromValue = ConfigurationItemTestUtility.CreateModel(); var toValue = new Benday.EasyAuthDemo.WebUi.Models.ConfigurationItemEditorViewModel(); // act SystemUnderTest.Adapt(fromValue, toValue); // assert ConfigurationItemViewModelTestUtility.AssertAreEqual(fromValue, toValue); } } }
32.82716
98
0.605867
[ "MIT" ]
benday-inc/azure-app-service-security
dotnet5.0/Benday.EasyAuthDemo/test/Benday.EasyAuthDemo.UnitTests/ViewModels/Adapters/ConfigurationItemEditorViewModelAdapterFixture.generated.cs
2,659
C#
 using System; using System.Collections.Generic; using TES3.Util; namespace TES3.Records { public class NameEnumerable<TSub, TParent> : AbstractEnumeratorEnumerable<TSub> where TSub : INamed where TParent : IRecord<TSub> { readonly TParent parent; readonly IEnumerator<TSub> backing; readonly string[] names; internal NameEnumerable(TParent parent, string[] names) { this.parent = parent; backing = parent.GetEnumerator(); this.names = names; } public int Index { get; private set; } = -1; public override bool MoveNext() { while (backing.MoveNext()) { ++Index; var current = backing.Current; if (Array.IndexOf(names, current.Name) == -1) { continue; } Current = current; return true; } return false; } public override void Reset() { backing.Reset(); Index = -1; } public bool HasNext() { return Index + 1 < parent.Count; } public TSub PeekNext() { var next = Index + 1; if (next >= parent.Count) { throw new InvalidOperationException("No next element."); } return parent[next]; } } }
22.575758
133
0.48255
[ "BSD-3-Clause" ]
mschlege1838/tes3-net
TES3.Records/NameEnumerable.cs
1,492
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using System.Text; public class LeetCode_22 : MonoBehaviour { // Use this for initialization void Start () { GenerateParenthesis(3); } // Update is called once per frame void Update () { } // Medium https://leetcode.com/problems/generate-parentheses/description/ // Discuss solution public IList<string> GenerateParenthesis(int n) { IList<string> result = new List<string>(); BackTrack(result, "", n , 0); return result; } public void BackTrack(IList<string> result, string sb, int m, int n){ if(m ==0 && n == 0){ result.Add(sb); return ; } if(n > 0) BackTrack(result, sb + ")", m, n - 1); if(m > 0) BackTrack(result, sb + "(", m - 1, n + 1); } }
21.666667
74
0.646154
[ "MIT" ]
dftty/LeetCode
Assets/Scripts/LeetCode/LeetCode_22.cs
782
C#
namespace WinControl { /// <summary> /// Provides efficient way to control child form by a WinControl control. /// <para>Обеспечивает эффективное управление дочерней формой с помощью элемента управления WinControl.</para> /// </summary> /// <remarks> /// Author: Mikhail Shiryaev, 2010, 2018 /// </remarks> public interface IChildForm { /// <summary> /// Получить или установить информацию о контролируемом окне /// </summary> ChildFormTag ChildFormTag { get; set; } /// <summary> /// Saves the changes of the child form data. /// </summary> void Save(); } }
28.913043
114
0.6
[ "MIT" ]
2mik/wincontrol
Source/WinControl/IChildForm.cs
790
C#
/* * Copyright 2015-2018 Mohawk College of Applied Arts and Technology * * * 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. * * User: fyfej * Date: 2017-9-1 */ using Newtonsoft.Json; using OpenIZ.Core.Model.Attributes; using OpenIZ.Core.Model.Constants; using OpenIZ.Core.Model.DataTypes; using System; using System.ComponentModel; using System.Xml.Serialization; namespace OpenIZ.Core.Model.Entities { /// <summary> /// Organization entity /// </summary> [XmlType("Organization", Namespace = "http://openiz.org/model"), JsonObject("Organization")] [XmlRoot(Namespace = "http://openiz.org/model", ElementName = "Organization")] public class Organization : Entity { private Concept m_industryConcept; // Industry concept private Guid? m_industryConceptKey; // Industry Concept /// <summary> /// Organization ctor /// </summary> public Organization() { this.DeterminerConceptKey = DeterminerKeys.Specific; this.ClassConceptKey = EntityClassKeys.Organization; } /// <summary> /// Initializes a new instance of the <see cref="Organization"/> class. /// </summary> /// <param name="key">The key.</param> public Organization(Guid key) { this.Key = key; } /// <summary> /// Gets or sets the industry concept key /// </summary> /// <summary> /// Gets or sets the industry in which the organization operates /// </summary> /// <remarks> /// The industry concept is used to classify the industrial sector to which an organization belongs. For example, /// an organization may be of type NGO, but the industry in which that organization operates is Healthcare /// </remarks> /// <see cref="IndustryConceptKey"/> [SerializationReference(nameof(IndustryConceptKey))] [XmlIgnore, JsonIgnore] public Concept IndustryConcept { get { this.m_industryConcept = base.DelayLoad(this.m_industryConceptKey, this.m_industryConcept); return this.m_industryConcept; } set { this.m_industryConcept = value; this.m_industryConceptKey = value?.Key; } } /// <summary> /// Gets or sets the concept key which classifies the industry in which the organization operates /// </summary> /// <remarks> /// The industry concept is used to classify the industrial sector to which an organization belongs. For example, /// an organization may be of type NGO, but the industry in which that organization operates is Healthcare /// </remarks> /// <see cref="IndustryConcept"/> [EditorBrowsable(EditorBrowsableState.Never)] [XmlElement("industryConcept"), JsonProperty("industryConcept")] public Guid? IndustryConceptKey { get { return this.m_industryConceptKey; } set { if (this.m_industryConceptKey != value) { this.m_industryConceptKey = value; this.m_industryConcept = null; } } } /// <summary> /// Forces reload of delay load properties /// </summary> public override void Refresh() { base.Refresh(); this.m_industryConcept = null; } /// <summary> /// Semantic equality function /// </summary> public override bool SemanticEquals(object obj) { var other = obj as Organization; if (other == null) return false; return base.SemanticEquals(obj) && this.IndustryConceptKey == other.IndustryConceptKey; } } }
29.315789
121
0.686073
[ "Apache-2.0" ]
santedb/openiz
OpenIZ.Core.Model/Entities/Organization.cs
3,901
C#
using FreeQuant.Instruments; using System.Collections.Generic; using System.Windows.Forms; namespace OpenQuant.Shared.Instruments { class GroupNode : TreeNode { protected Dictionary<Instrument, InstrumentNode> instrumentNodes; public Instrument[] Instruments { get { return new List<Instrument>((IEnumerable<Instrument>)this.instrumentNodes.Keys).ToArray(); } } public GroupNode() { this.instrumentNodes = new Dictionary<Instrument, InstrumentNode>(); this.SetText("Undefined"); this.UpdateIcon(); } public void UpdateIcon() { this.ImageIndex = this.SelectedImageIndex = this.IsExpanded ? 2 : 1; } public void AddInstrument(Instrument instrument) { if (this.instrumentNodes.ContainsKey(instrument)) return; InstrumentNode instrumentNode = new InstrumentNode(instrument); this.instrumentNodes.Add(instrument, instrumentNode); this.Nodes.Add(instrumentNode); this.UpdateToolTipText(); } public void RemoveInstrument(Instrument instrument) { if (!this.instrumentNodes.ContainsKey(instrument)) return; InstrumentNode instrumentNode = this.instrumentNodes[instrument]; this.instrumentNodes.Remove(instrument); instrumentNode.Remove(); if (this.Nodes.Count == 0) this.Remove(); else this.UpdateToolTipText(); } public virtual bool IsInstrumentValid(Instrument instrument) { return false; } protected void SetText(string text) { if (string.IsNullOrEmpty(text)) this.Text = "-"; else this.Text = text; } private void UpdateToolTipText() { this.ToolTipText = string.Format("{0:n0} instrument(s)", this.instrumentNodes.Count); } } }
23.013699
94
0.718452
[ "MIT" ]
aliostad/deep-learning-lang-detection
data/train/csharp/49afcdefe7ee88cb9e6ef2c0c1aefa6577240ba0GroupNode.cs
1,682
C#
// Copyright (c) Josef Pihrt and Contributors. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Syntax; using Roslynator.CSharp.Analysis.Documentation; namespace Roslynator.CSharp.Refactorings.Documentation { internal class AddTypeParamElementToDocumentationCommentRefactoring : DocumentationCommentRefactoring<TypeParameterSyntax> { public override XmlTag Tag { get { return XmlTag.TypeParam; } } public override bool ShouldBeBefore(XmlTag tag) { return tag == XmlTag.Summary; } public override string GetName(TypeParameterSyntax node) { return node.Identifier.ValueText; } public override ElementInfo<TypeParameterSyntax> CreateInfo(TypeParameterSyntax node, int insertIndex, NewLinePosition newLinePosition) { return new TypeParamElementInfo(node, insertIndex, newLinePosition); } protected override SeparatedSyntaxList<TypeParameterSyntax> GetSyntaxList(SyntaxNode node) { return CSharpUtility.GetTypeParameters(node); } } }
34.805556
156
0.706305
[ "Apache-2.0" ]
onexey/Roslynator
src/Analyzers.CodeFixes/CSharp/Refactorings/Documentation/AddTypeParamElementToDocumentationCommentRefactoring.cs
1,255
C#
 using Microsoft.Extensions.Caching.Memory; using System; using System.Collections; using System.Collections.Generic; using System.Reflection; namespace YC.Common.ShareUtils { public class CacheUtils { private IMemoryCache _cache = new MemoryCache(new MemoryCacheOptions()); public TimeSpan _defaultTimeSpan = TimeSpan.FromSeconds(7200); /// <summary> /// 判断是否在缓存中 /// </summary> /// <param name="key">关键字</param> /// <returns></returns> public bool IsInCache(string key) { List<string> keys = GetAllKeys(); foreach (var i in keys) { if (i == key) return true; } return false; } /// <summary> /// 获取所有缓存键 /// </summary> /// <returns></returns> public List<string> GetAllKeys() { const BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic; var entries = _cache.GetType().GetField("_entries", flags).GetValue(_cache); var cacheItems = entries as IDictionary; var keys = new List<string>(); if (cacheItems == null) return keys; foreach (DictionaryEntry cacheItem in cacheItems) { keys.Add(cacheItem.Key.ToString()); } return keys; } /// <summary> /// 获取所有的缓存值 /// </summary> /// <returns></returns> public List<T> GetAllValues<T>() { var cacheKeys = GetAllKeys(); List<T> vals = new List<T>(); cacheKeys.ForEach(i => { T t; if (_cache.TryGetValue<T>(i, out t)) { vals.Add(t); } }); return vals; } /// <summary> /// 取得缓存数据 /// </summary> /// <typeparam name="T">类型值</typeparam> /// <param name="key">关键字</param> /// <returns></returns> public T Get<T>(string key) { if (string.IsNullOrWhiteSpace(key)) throw new ArgumentNullException(nameof(key)); T value; _cache.TryGetValue<T>(key, out value); return value; } /// <summary> /// 设置缓存(永不过期) /// </summary> /// <param name="key">关键字</param> /// <param name="value">缓存值</param> public void Set_NotExpire<T>(string key, T value) { if (string.IsNullOrWhiteSpace(key)) throw new ArgumentNullException(nameof(key)); T v; if (_cache.TryGetValue(key, out v)) _cache.Remove(key); _cache.Set(key, value); } /// <summary> /// 设置缓存(滑动过期:超过一段时间不访问就会过期,一直访问就一直不过期) /// </summary> /// <param name="key">关键字</param> /// <param name="value">缓存值</param> public void Set_SlidingExpire<T>(string key, T value, TimeSpan span) { if (string.IsNullOrWhiteSpace(key)) throw new ArgumentNullException(nameof(key)); T v; if (_cache.TryGetValue(key, out v)) _cache.Remove(key); _cache.Set(key, value, new MemoryCacheEntryOptions() { SlidingExpiration = span }); } /// <summary> /// 设置缓存(绝对时间过期:从缓存开始持续指定的时间段后就过期,无论有没有持续的访问) /// </summary> /// <param name="key">关键字</param> /// <param name="value">缓存值</param> public void Set_AbsoluteExpire<T>(string key, T value, TimeSpan span) { if (string.IsNullOrWhiteSpace(key)) throw new ArgumentNullException(nameof(key)); T v; if (_cache.TryGetValue(key, out v)) _cache.Remove(key); _cache.Set(key, value, span); } /// <summary> /// 设置缓存(绝对时间过期+滑动过期:比如滑动过期设置半小时,绝对过期时间设置2个小时,那么缓存开始后只要半小时内没有访问就会立马过期,如果半小时内有访问就会向后顺延半小时,但最多只能缓存2个小时) /// </summary> /// <param name="key">关键字</param> /// <param name="value">缓存值</param> public void Set_SlidingAndAbsoluteExpire<T>(string key, T value, TimeSpan slidingSpan, TimeSpan absoluteSpan) { if (string.IsNullOrWhiteSpace(key)) throw new ArgumentNullException(nameof(key)); T v; if (_cache.TryGetValue(key, out v)) _cache.Remove(key); _cache.Set(key, value, new MemoryCacheEntryOptions() { SlidingExpiration = slidingSpan, AbsoluteExpiration = DateTimeOffset.Now.AddMilliseconds(absoluteSpan.Milliseconds) }); } /// <summary> /// 移除缓存 /// </summary> /// <param name="key">关键字</param> public void Remove(string key) { if (string.IsNullOrWhiteSpace(key)) throw new ArgumentNullException(nameof(key)); _cache.Remove(key); } /// <summary> /// 释放 /// </summary> public void Dispose() { if (_cache != null) _cache.Dispose(); GC.SuppressFinalize(this); } } }
29.966292
117
0.504687
[ "Apache-2.0" ]
boozzh/yc.boilerplate
src/Backstage/BasicLayer/YC.Common/ShareUtils/CacheUtils.cs
5,808
C#
using System; namespace Maki { /// <summary> /// Extensions for Variant. /// </summary> public static class VariantExtensions { /// <summary> /// Maps the function matching the item inhabiting the variant. Returns a new variant containing the /// result of the function. /// </summary> /// <typeparam name="T1">The first type of the variant.</typeparam> /// <typeparam name="T2">The second type of the variant.</typeparam> /// <typeparam name="U1">The first type of the returned variant.</typeparam> /// <typeparam name="U2">The second type of the returned variant.</typeparam> /// <param name="variant">This variant.</param> /// <param name="func1">The first function.</param> /// <param name="func2">The second function.</param> /// <returns>New variant containing the result of the applied function.</returns> public static Variant<U1, U2> Map<T1, T2, U1, U2>( this Variant<T1, T2> variant, Func<T1, U1> func1, Func<T2, U2> func2) { switch (variant.Index) { case 0: return func1(variant.Get<T1>()); case 1: return func2(variant.Get<T2>()); default: throw new InvalidOperationException(); } } /// <summary> /// Applies the function matching the item inhabiting the variant. Returns the result of the function. /// </summary> /// <typeparam name="T1">The first type of the variant.</typeparam> /// <typeparam name="T2">The second type of the variant.</typeparam> /// <typeparam name="U">The return type of the functions.</typeparam> /// <param name="variant">This variant.</param> /// <param name="func1">The first function.</param> /// <param name="func2">The second function.</param> /// <returns>Result of the applied function.</returns> public static U Apply<T1, T2, U>( this Variant<T1, T2> variant, Func<T1, U> func1, Func<T2, U> func2) { switch (variant.Index) { case 0: return func1(variant.Get<T1>()); case 1: return func2(variant.Get<T2>()); default: throw new InvalidOperationException(); } } /// <summary> /// Applies the action matching the item inhabiting the variant. /// </summary> /// <typeparam name="T1">The first type of the variant.</typeparam> /// <typeparam name="T2">The second type of the variant.</typeparam> /// <param name="variant">This variant.</param> /// <param name="act1">The first action.</param> /// <param name="act2">The second action.</param> public static void Apply<T1, T2>( this Variant<T1, T2> variant, Action<T1> act1, Action<T2> act2) { switch (variant.Index) { case 0: act1(variant.Get<T1>()); return; case 1: act2(variant.Get<T2>()); return; default: throw new InvalidOperationException(); } } /// <summary> /// Maps the function matching the item inhabiting the variant. Returns a new variant containing the /// result of the function. /// </summary> /// <typeparam name="T1">The first type of the variant.</typeparam> /// <typeparam name="T2">The second type of the variant.</typeparam> /// <typeparam name="T3">The third type of the variant.</typeparam> /// <typeparam name="U1">The first type of the returned variant.</typeparam> /// <typeparam name="U2">The second type of the returned variant.</typeparam> /// <typeparam name="U3">The third type of the returned variant.</typeparam> /// <param name="variant">This variant.</param> /// <param name="func1">The first function.</param> /// <param name="func2">The second function.</param> /// <param name="func3">The third function.</param> /// <returns>New variant containing the result of the applied function.</returns> public static Variant<U1, U2, U3> Map<T1, T2, T3, U1, U2, U3>( this Variant<T1, T2, T3> variant, Func<T1, U1> func1, Func<T2, U2> func2, Func<T3, U3> func3) { switch (variant.Index) { case 0: return func1(variant.Get<T1>()); case 1: return func2(variant.Get<T2>()); case 2: return func3(variant.Get<T3>()); default: throw new InvalidOperationException(); } } /// <summary> /// Applies the function matching the item inhabiting the variant. Returns the result of the function. /// </summary> /// <typeparam name="T1">The first type of the variant.</typeparam> /// <typeparam name="T2">The second type of the variant.</typeparam> /// <typeparam name="T3">The third type of the variant.</typeparam> /// <typeparam name="U">The return type of the functions.</typeparam> /// <param name="variant">This variant.</param> /// <param name="func1">The first function.</param> /// <param name="func2">The second function.</param> /// <param name="func3">The third function.</param> /// <returns>Result of the applied function.</returns> public static U Apply<T1, T2, T3, U>( this Variant<T1, T2, T3> variant, Func<T1, U> func1, Func<T2, U> func2, Func<T3, U> func3) { switch (variant.Index) { case 0: return func1(variant.Get<T1>()); case 1: return func2(variant.Get<T2>()); case 2: return func3(variant.Get<T3>()); default: throw new InvalidOperationException(); } } /// <summary> /// Applies the action matching the item inhabiting the variant. /// </summary> /// <typeparam name="T1">The first type of the variant.</typeparam> /// <typeparam name="T2">The second type of the variant.</typeparam> /// <typeparam name="T3">The third type of the variant.</typeparam> /// <param name="variant">This variant.</param> /// <param name="act1">The first action.</param> /// <param name="act2">The second action.</param> /// <param name="act3">The third action.</param> public static void Apply<T1, T2, T3>( this Variant<T1, T2, T3> variant, Action<T1> act1, Action<T2> act2, Action<T3> act3) { switch (variant.Index) { case 0: act1(variant.Get<T1>()); return; case 1: act2(variant.Get<T2>()); return; case 2: act3(variant.Get<T3>()); return; default: throw new InvalidOperationException(); } } /// <summary> /// Maps the function matching the item inhabiting the variant. Returns a new variant containing the /// result of the function. /// </summary> /// <typeparam name="T1">The first type of the variant.</typeparam> /// <typeparam name="T2">The second type of the variant.</typeparam> /// <typeparam name="T3">The third type of the variant.</typeparam> /// <typeparam name="T4">The fourth type of the variant.</typeparam> /// <typeparam name="U1">The first type of the returned variant.</typeparam> /// <typeparam name="U2">The second type of the returned variant.</typeparam> /// <typeparam name="U3">The third type of the returned variant.</typeparam> /// <typeparam name="U4">The fourth type of the returned variant.</typeparam> /// <param name="variant">This variant.</param> /// <param name="func1">The first function.</param> /// <param name="func2">The second function.</param> /// <param name="func3">The third function.</param> /// <param name="func4">The fourth function.</param> /// <returns>New variant containing the result of the applied function.</returns> public static Variant<U1, U2, U3, U4> Map<T1, T2, T3, T4, U1, U2, U3, U4>( this Variant<T1, T2, T3, T4> variant, Func<T1, U1> func1, Func<T2, U2> func2, Func<T3, U3> func3, Func<T4, U4> func4) { switch (variant.Index) { case 0: return func1(variant.Get<T1>()); case 1: return func2(variant.Get<T2>()); case 2: return func3(variant.Get<T3>()); case 3: return func4(variant.Get<T4>()); default: throw new InvalidOperationException(); } } /// <summary> /// Applies the function matching the item inhabiting the variant. Returns the result of the function. /// </summary> /// <typeparam name="T1">The first type of the variant.</typeparam> /// <typeparam name="T2">The second type of the variant.</typeparam> /// <typeparam name="T3">The third type of the variant.</typeparam> /// <typeparam name="T4">The fourth type of the variant.</typeparam> /// <typeparam name="U">The return type of the functions.</typeparam> /// <param name="variant">This variant.</param> /// <param name="func1">The first function.</param> /// <param name="func2">The second function.</param> /// <param name="func3">The third function.</param> /// <param name="func4">The fourth function.</param> /// <returns>Result of the applied function.</returns> public static U Apply<T1, T2, T3, T4, U>( this Variant<T1, T2, T3, T4> variant, Func<T1, U> func1, Func<T2, U> func2, Func<T3, U> func3, Func<T4, U> func4) { switch (variant.Index) { case 0: return func1(variant.Get<T1>()); case 1: return func2(variant.Get<T2>()); case 2: return func3(variant.Get<T3>()); case 3: return func4(variant.Get<T4>()); default: throw new InvalidOperationException(); } } /// <summary> /// Applies the action matching the item inhabiting the variant. /// </summary> /// <typeparam name="T1">The first type of the variant.</typeparam> /// <typeparam name="T2">The second type of the variant.</typeparam> /// <typeparam name="T3">The third type of the variant.</typeparam> /// <typeparam name="T4">The fourth type of the variant.</typeparam> /// <param name="variant">This variant.</param> /// <param name="act1">The first action.</param> /// <param name="act2">The second action.</param> /// <param name="act3">The third action.</param> /// <param name="act4">The fourth action.</param> public static void Apply<T1, T2, T3, T4>( this Variant<T1, T2, T3, T4> variant, Action<T1> act1, Action<T2> act2, Action<T3> act3, Action<T4> act4) { switch (variant.Index) { case 0: act1(variant.Get<T1>()); return; case 1: act2(variant.Get<T2>()); return; case 2: act3(variant.Get<T3>()); return; case 3: act4(variant.Get<T4>()); return; default: throw new InvalidOperationException(); } } /// <summary> /// Maps the function matching the item inhabiting the variant. Returns a new variant containing the /// result of the function. /// </summary> /// <typeparam name="T1">The first type of the variant.</typeparam> /// <typeparam name="T2">The second type of the variant.</typeparam> /// <typeparam name="T3">The third type of the variant.</typeparam> /// <typeparam name="T4">The fourth type of the variant.</typeparam> /// <typeparam name="T5">The fifth type of the variant.</typeparam> /// <typeparam name="U1">The first type of the returned variant.</typeparam> /// <typeparam name="U2">The second type of the returned variant.</typeparam> /// <typeparam name="U3">The third type of the returned variant.</typeparam> /// <typeparam name="U4">The fourth type of the returned variant.</typeparam> /// <typeparam name="U5">The fifth type of the returned variant.</typeparam> /// <param name="variant">This variant.</param> /// <param name="func1">The first function.</param> /// <param name="func2">The second function.</param> /// <param name="func3">The third function.</param> /// <param name="func4">The fourth function.</param> /// <param name="func5">The fifth function.</param> /// <returns>New variant containing the result of the applied function.</returns> public static Variant<U1, U2, U3, U4, U5> Map<T1, T2, T3, T4, T5, U1, U2, U3, U4, U5>( this Variant<T1, T2, T3, T4, T5> variant, Func<T1, U1> func1, Func<T2, U2> func2, Func<T3, U3> func3, Func<T4, U4> func4, Func<T5, U5> func5) { switch (variant.Index) { case 0: return func1(variant.Get<T1>()); case 1: return func2(variant.Get<T2>()); case 2: return func3(variant.Get<T3>()); case 3: return func4(variant.Get<T4>()); case 4: return func5(variant.Get<T5>()); default: throw new InvalidOperationException(); } } /// <summary> /// Applies the function matching the item inhabiting the variant. Returns the result of the function. /// </summary> /// <typeparam name="T1">The first type of the variant.</typeparam> /// <typeparam name="T2">The second type of the variant.</typeparam> /// <typeparam name="T3">The third type of the variant.</typeparam> /// <typeparam name="T4">The fourth type of the variant.</typeparam> /// <typeparam name="T5">The fifth type of the variant.</typeparam> /// <typeparam name="U">The return type of the functions.</typeparam> /// <param name="variant">This variant.</param> /// <param name="func1">The first function.</param> /// <param name="func2">The second function.</param> /// <param name="func3">The third function.</param> /// <param name="func4">The fourth function.</param> /// <param name="func5">The fifth function.</param> /// <returns>Result of the applied function.</returns> public static U Apply<T1, T2, T3, T4, T5, U>( this Variant<T1, T2, T3, T4, T5> variant, Func<T1, U> func1, Func<T2, U> func2, Func<T3, U> func3, Func<T4, U> func4, Func<T5, U> func5) { switch (variant.Index) { case 0: return func1(variant.Get<T1>()); case 1: return func2(variant.Get<T2>()); case 2: return func3(variant.Get<T3>()); case 3: return func4(variant.Get<T4>()); case 4: return func5(variant.Get<T5>()); default: throw new InvalidOperationException(); } } /// <summary> /// Applies the action matching the item inhabiting the variant. /// </summary> /// <typeparam name="T1">The first type of the variant.</typeparam> /// <typeparam name="T2">The second type of the variant.</typeparam> /// <typeparam name="T3">The third type of the variant.</typeparam> /// <typeparam name="T4">The fourth type of the variant.</typeparam> /// <typeparam name="T5">The fifth type of the variant.</typeparam> /// <param name="variant">This variant.</param> /// <param name="act1">The first action.</param> /// <param name="act2">The second action.</param> /// <param name="act3">The third action.</param> /// <param name="act4">The fourth action.</param> /// <param name="act5">The fifth action.</param> public static void Apply<T1, T2, T3, T4, T5>( this Variant<T1, T2, T3, T4, T5> variant, Action<T1> act1, Action<T2> act2, Action<T3> act3, Action<T4> act4, Action<T5> act5) { switch (variant.Index) { case 0: act1(variant.Get<T1>()); return; case 1: act2(variant.Get<T2>()); return; case 2: act3(variant.Get<T3>()); return; case 3: act4(variant.Get<T4>()); return; case 4: act5(variant.Get<T5>()); return; default: throw new InvalidOperationException(); } } /// <summary> /// Maps the function matching the item inhabiting the variant. Returns a new variant containing the /// result of the function. /// </summary> /// <typeparam name="T1">The first type of the variant.</typeparam> /// <typeparam name="T2">The second type of the variant.</typeparam> /// <typeparam name="T3">The third type of the variant.</typeparam> /// <typeparam name="T4">The fourth type of the variant.</typeparam> /// <typeparam name="T5">The fifth type of the variant.</typeparam> /// <typeparam name="T6">The sixth type of the variant.</typeparam> /// <typeparam name="U1">The first type of the returned variant.</typeparam> /// <typeparam name="U2">The second type of the returned variant.</typeparam> /// <typeparam name="U3">The third type of the returned variant.</typeparam> /// <typeparam name="U4">The fourth type of the returned variant.</typeparam> /// <typeparam name="U5">The fifth type of the returned variant.</typeparam> /// <typeparam name="U6">The sixth type of the returned variant.</typeparam> /// <param name="variant">This variant.</param> /// <param name="func1">The first function.</param> /// <param name="func2">The second function.</param> /// <param name="func3">The third function.</param> /// <param name="func4">The fourth function.</param> /// <param name="func5">The fifth function.</param> /// <param name="func6">The sixth function.</param> /// <returns>New variant containing the result of the applied function.</returns> public static Variant<U1, U2, U3, U4, U5, U6> Map<T1, T2, T3, T4, T5, T6, U1, U2, U3, U4, U5, U6>( this Variant<T1, T2, T3, T4, T5, T6> variant, Func<T1, U1> func1, Func<T2, U2> func2, Func<T3, U3> func3, Func<T4, U4> func4, Func<T5, U5> func5, Func<T6, U6> func6) { switch (variant.Index) { case 0: return func1(variant.Get<T1>()); case 1: return func2(variant.Get<T2>()); case 2: return func3(variant.Get<T3>()); case 3: return func4(variant.Get<T4>()); case 4: return func5(variant.Get<T5>()); case 5: return func6(variant.Get<T6>()); default: throw new InvalidOperationException(); } } /// <summary> /// Applies the function matching the item inhabiting the variant. Returns the result of the function. /// </summary> /// <typeparam name="T1">The first type of the variant.</typeparam> /// <typeparam name="T2">The second type of the variant.</typeparam> /// <typeparam name="T3">The third type of the variant.</typeparam> /// <typeparam name="T4">The fourth type of the variant.</typeparam> /// <typeparam name="T5">The fifth type of the variant.</typeparam> /// <typeparam name="T6">The sixth type of the variant.</typeparam> /// <typeparam name="U">The return type of the functions.</typeparam> /// <param name="variant">This variant.</param> /// <param name="func1">The first function.</param> /// <param name="func2">The second function.</param> /// <param name="func3">The third function.</param> /// <param name="func4">The fourth function.</param> /// <param name="func5">The fifth function.</param> /// <param name="func6">The sixth function.</param> /// <returns>Result of the applied function.</returns> public static U Apply<T1, T2, T3, T4, T5, T6, U>( this Variant<T1, T2, T3, T4, T5, T6> variant, Func<T1, U> func1, Func<T2, U> func2, Func<T3, U> func3, Func<T4, U> func4, Func<T5, U> func5, Func<T6, U> func6) { switch (variant.Index) { case 0: return func1(variant.Get<T1>()); case 1: return func2(variant.Get<T2>()); case 2: return func3(variant.Get<T3>()); case 3: return func4(variant.Get<T4>()); case 4: return func5(variant.Get<T5>()); case 5: return func6(variant.Get<T6>()); default: throw new InvalidOperationException(); } } /// <summary> /// Applies the action matching the item inhabiting the variant. /// </summary> /// <typeparam name="T1">The first type of the variant.</typeparam> /// <typeparam name="T2">The second type of the variant.</typeparam> /// <typeparam name="T3">The third type of the variant.</typeparam> /// <typeparam name="T4">The fourth type of the variant.</typeparam> /// <typeparam name="T5">The fifth type of the variant.</typeparam> /// <typeparam name="T6">The sixth type of the variant.</typeparam> /// <param name="variant">This variant.</param> /// <param name="act1">The first action.</param> /// <param name="act2">The second action.</param> /// <param name="act3">The third action.</param> /// <param name="act4">The fourth action.</param> /// <param name="act5">The fifth action.</param> /// <param name="act6">The sixth action.</param> public static void Apply<T1, T2, T3, T4, T5, T6>( this Variant<T1, T2, T3, T4, T5, T6> variant, Action<T1> act1, Action<T2> act2, Action<T3> act3, Action<T4> act4, Action<T5> act5, Action<T6> act6) { switch (variant.Index) { case 0: act1(variant.Get<T1>()); return; case 1: act2(variant.Get<T2>()); return; case 2: act3(variant.Get<T3>()); return; case 3: act4(variant.Get<T4>()); return; case 4: act5(variant.Get<T5>()); return; case 5: act6(variant.Get<T6>()); return; default: throw new InvalidOperationException(); } } /// <summary> /// Maps the function matching the item inhabiting the variant. Returns a new variant containing the /// result of the function. /// </summary> /// <typeparam name="T1">The first type of the variant.</typeparam> /// <typeparam name="T2">The second type of the variant.</typeparam> /// <typeparam name="T3">The third type of the variant.</typeparam> /// <typeparam name="T4">The fourth type of the variant.</typeparam> /// <typeparam name="T5">The fifth type of the variant.</typeparam> /// <typeparam name="T6">The sixth type of the variant.</typeparam> /// <typeparam name="T7">The seventh type of the variant.</typeparam> /// <typeparam name="U1">The first type of the returned variant.</typeparam> /// <typeparam name="U2">The second type of the returned variant.</typeparam> /// <typeparam name="U3">The third type of the returned variant.</typeparam> /// <typeparam name="U4">The fourth type of the returned variant.</typeparam> /// <typeparam name="U5">The fifth type of the returned variant.</typeparam> /// <typeparam name="U6">The sixth type of the returned variant.</typeparam> /// <typeparam name="U7">The seventh type of the returned variant.</typeparam> /// <param name="variant">This variant.</param> /// <param name="func1">The first function.</param> /// <param name="func2">The second function.</param> /// <param name="func3">The third function.</param> /// <param name="func4">The fourth function.</param> /// <param name="func5">The fifth function.</param> /// <param name="func6">The sixth function.</param> /// <param name="func7">The seventh function.</param> /// <returns>New variant containing the result of the applied function.</returns> public static Variant<U1, U2, U3, U4, U5, U6, U7> Map<T1, T2, T3, T4, T5, T6, T7, U1, U2, U3, U4, U5, U6, U7>( this Variant<T1, T2, T3, T4, T5, T6, T7> variant, Func<T1, U1> func1, Func<T2, U2> func2, Func<T3, U3> func3, Func<T4, U4> func4, Func<T5, U5> func5, Func<T6, U6> func6, Func<T7, U7> func7) { switch (variant.Index) { case 0: return func1(variant.Get<T1>()); case 1: return func2(variant.Get<T2>()); case 2: return func3(variant.Get<T3>()); case 3: return func4(variant.Get<T4>()); case 4: return func5(variant.Get<T5>()); case 5: return func6(variant.Get<T6>()); case 6: return func7(variant.Get<T7>()); default: throw new InvalidOperationException(); } } /// <summary> /// Applies the function matching the item inhabiting the variant. Returns the result of the function. /// </summary> /// <typeparam name="T1">The first type of the variant.</typeparam> /// <typeparam name="T2">The second type of the variant.</typeparam> /// <typeparam name="T3">The third type of the variant.</typeparam> /// <typeparam name="T4">The fourth type of the variant.</typeparam> /// <typeparam name="T5">The fifth type of the variant.</typeparam> /// <typeparam name="T6">The sixth type of the variant.</typeparam> /// <typeparam name="T7">The seventh type of the variant.</typeparam> /// <typeparam name="U">The return type of the functions.</typeparam> /// <param name="variant">This variant.</param> /// <param name="func1">The first function.</param> /// <param name="func2">The second function.</param> /// <param name="func3">The third function.</param> /// <param name="func4">The fourth function.</param> /// <param name="func5">The fifth function.</param> /// <param name="func6">The sixth function.</param> /// <param name="func7">The seventh function.</param> /// <returns>Result of the applied function.</returns> public static U Apply<T1, T2, T3, T4, T5, T6, T7, U>( this Variant<T1, T2, T3, T4, T5, T6, T7> variant, Func<T1, U> func1, Func<T2, U> func2, Func<T3, U> func3, Func<T4, U> func4, Func<T5, U> func5, Func<T6, U> func6, Func<T7, U> func7) { switch (variant.Index) { case 0: return func1(variant.Get<T1>()); case 1: return func2(variant.Get<T2>()); case 2: return func3(variant.Get<T3>()); case 3: return func4(variant.Get<T4>()); case 4: return func5(variant.Get<T5>()); case 5: return func6(variant.Get<T6>()); case 6: return func7(variant.Get<T7>()); default: throw new InvalidOperationException(); } } /// <summary> /// Applies the action matching the item inhabiting the variant. /// </summary> /// <typeparam name="T1">The first type of the variant.</typeparam> /// <typeparam name="T2">The second type of the variant.</typeparam> /// <typeparam name="T3">The third type of the variant.</typeparam> /// <typeparam name="T4">The fourth type of the variant.</typeparam> /// <typeparam name="T5">The fifth type of the variant.</typeparam> /// <typeparam name="T6">The sixth type of the variant.</typeparam> /// <typeparam name="T7">The seventh type of the variant.</typeparam> /// <param name="variant">This variant.</param> /// <param name="act1">The first action.</param> /// <param name="act2">The second action.</param> /// <param name="act3">The third action.</param> /// <param name="act4">The fourth action.</param> /// <param name="act5">The fifth action.</param> /// <param name="act6">The sixth action.</param> /// <param name="act7">The seventh action.</param> public static void Apply<T1, T2, T3, T4, T5, T6, T7>( this Variant<T1, T2, T3, T4, T5, T6, T7> variant, Action<T1> act1, Action<T2> act2, Action<T3> act3, Action<T4> act4, Action<T5> act5, Action<T6> act6, Action<T7> act7) { switch (variant.Index) { case 0: act1(variant.Get<T1>()); return; case 1: act2(variant.Get<T2>()); return; case 2: act3(variant.Get<T3>()); return; case 3: act4(variant.Get<T4>()); return; case 4: act5(variant.Get<T5>()); return; case 5: act6(variant.Get<T6>()); return; case 6: act7(variant.Get<T7>()); return; default: throw new InvalidOperationException(); } } /// <summary> /// Maps the function matching the item inhabiting the variant. Returns a new variant containing the /// result of the function. /// </summary> /// <typeparam name="T1">The first type of the variant.</typeparam> /// <typeparam name="T2">The second type of the variant.</typeparam> /// <typeparam name="T3">The third type of the variant.</typeparam> /// <typeparam name="T4">The fourth type of the variant.</typeparam> /// <typeparam name="T5">The fifth type of the variant.</typeparam> /// <typeparam name="T6">The sixth type of the variant.</typeparam> /// <typeparam name="T7">The seventh type of the variant.</typeparam> /// <typeparam name="T8">The eighth type of the variant.</typeparam> /// <typeparam name="U1">The first type of the returned variant.</typeparam> /// <typeparam name="U2">The second type of the returned variant.</typeparam> /// <typeparam name="U3">The third type of the returned variant.</typeparam> /// <typeparam name="U4">The fourth type of the returned variant.</typeparam> /// <typeparam name="U5">The fifth type of the returned variant.</typeparam> /// <typeparam name="U6">The sixth type of the returned variant.</typeparam> /// <typeparam name="U7">The seventh type of the returned variant.</typeparam> /// <typeparam name="U8">The eighth type of the returned variant.</typeparam> /// <param name="variant">This variant.</param> /// <param name="func1">The first function.</param> /// <param name="func2">The second function.</param> /// <param name="func3">The third function.</param> /// <param name="func4">The fourth function.</param> /// <param name="func5">The fifth function.</param> /// <param name="func6">The sixth function.</param> /// <param name="func7">The seventh function.</param> /// <param name="func8">The eighth function.</param> /// <returns>New variant containing the result of the applied function.</returns> public static Variant<U1, U2, U3, U4, U5, U6, U7, U8> Map<T1, T2, T3, T4, T5, T6, T7, T8, U1, U2, U3, U4, U5, U6, U7, U8>( this Variant<T1, T2, T3, T4, T5, T6, T7, T8> variant, Func<T1, U1> func1, Func<T2, U2> func2, Func<T3, U3> func3, Func<T4, U4> func4, Func<T5, U5> func5, Func<T6, U6> func6, Func<T7, U7> func7, Func<T8, U8> func8) { switch (variant.Index) { case 0: return func1(variant.Get<T1>()); case 1: return func2(variant.Get<T2>()); case 2: return func3(variant.Get<T3>()); case 3: return func4(variant.Get<T4>()); case 4: return func5(variant.Get<T5>()); case 5: return func6(variant.Get<T6>()); case 6: return func7(variant.Get<T7>()); case 7: return func8(variant.Get<T8>()); default: throw new InvalidOperationException(); } } /// <summary> /// Applies the function matching the item inhabiting the variant. Returns the result of the function. /// </summary> /// <typeparam name="T1">The first type of the variant.</typeparam> /// <typeparam name="T2">The second type of the variant.</typeparam> /// <typeparam name="T3">The third type of the variant.</typeparam> /// <typeparam name="T4">The fourth type of the variant.</typeparam> /// <typeparam name="T5">The fifth type of the variant.</typeparam> /// <typeparam name="T6">The sixth type of the variant.</typeparam> /// <typeparam name="T7">The seventh type of the variant.</typeparam> /// <typeparam name="T8">The eighth type of the variant.</typeparam> /// <typeparam name="U">The return type of the functions.</typeparam> /// <param name="variant">This variant.</param> /// <param name="func1">The first function.</param> /// <param name="func2">The second function.</param> /// <param name="func3">The third function.</param> /// <param name="func4">The fourth function.</param> /// <param name="func5">The fifth function.</param> /// <param name="func6">The sixth function.</param> /// <param name="func7">The seventh function.</param> /// <param name="func8">The eighth function.</param> /// <returns>Result of the applied function.</returns> public static U Apply<T1, T2, T3, T4, T5, T6, T7, T8, U>( this Variant<T1, T2, T3, T4, T5, T6, T7, T8> variant, Func<T1, U> func1, Func<T2, U> func2, Func<T3, U> func3, Func<T4, U> func4, Func<T5, U> func5, Func<T6, U> func6, Func<T7, U> func7, Func<T8, U> func8) { switch (variant.Index) { case 0: return func1(variant.Get<T1>()); case 1: return func2(variant.Get<T2>()); case 2: return func3(variant.Get<T3>()); case 3: return func4(variant.Get<T4>()); case 4: return func5(variant.Get<T5>()); case 5: return func6(variant.Get<T6>()); case 6: return func7(variant.Get<T7>()); case 7: return func8(variant.Get<T8>()); default: throw new InvalidOperationException(); } } /// <summary> /// Applies the action matching the item inhabiting the variant. /// </summary> /// <typeparam name="T1">The first type of the variant.</typeparam> /// <typeparam name="T2">The second type of the variant.</typeparam> /// <typeparam name="T3">The third type of the variant.</typeparam> /// <typeparam name="T4">The fourth type of the variant.</typeparam> /// <typeparam name="T5">The fifth type of the variant.</typeparam> /// <typeparam name="T6">The sixth type of the variant.</typeparam> /// <typeparam name="T7">The seventh type of the variant.</typeparam> /// <typeparam name="T8">The eighth type of the variant.</typeparam> /// <param name="variant">This variant.</param> /// <param name="act1">The first action.</param> /// <param name="act2">The second action.</param> /// <param name="act3">The third action.</param> /// <param name="act4">The fourth action.</param> /// <param name="act5">The fifth action.</param> /// <param name="act6">The sixth action.</param> /// <param name="act7">The seventh action.</param> /// <param name="act8">The eighth action.</param> public static void Apply<T1, T2, T3, T4, T5, T6, T7, T8>( this Variant<T1, T2, T3, T4, T5, T6, T7, T8> variant, Action<T1> act1, Action<T2> act2, Action<T3> act3, Action<T4> act4, Action<T5> act5, Action<T6> act6, Action<T7> act7, Action<T8> act8) { switch (variant.Index) { case 0: act1(variant.Get<T1>()); return; case 1: act2(variant.Get<T2>()); return; case 2: act3(variant.Get<T3>()); return; case 3: act4(variant.Get<T4>()); return; case 4: act5(variant.Get<T5>()); return; case 5: act6(variant.Get<T6>()); return; case 6: act7(variant.Get<T7>()); return; case 7: act8(variant.Get<T8>()); return; default: throw new InvalidOperationException(); } } } }
49.916667
130
0.554022
[ "MIT" ]
vladris/Maki.NET
Maki/Extensions/VariantExtensions.cs
38,338
C#
#region Apache License 2.0 /* Apache License 2.0 (Apache) Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: 1. You must give any other recipients of the Work or Derivative Works a copy of this License; and 2. You must cause any modified files to carry prominent notices stating that You changed the files; and 3. You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and 4. If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. */ #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.SqlServer.Dts.Pipeline.Wrapper; using Microsoft.SqlServer.Dts.Runtime; using Microsoft.SqlServer.Dts.Tasks.ExpressionTask; using Microsoft.SqlServer.Dts.Tasks.ExecuteSQLTask; using System.Reflection; namespace RandomThunks.API.SSiS { [ClassIdAttribute("STOCK:FORLOOP")] public class iForLoop : iControlFlowTask { public iForLoop() : base() { this.IsContainer = true; } ForLoop Me { get { return this.Executable as ForLoop; } } public void SetConditions(string init, string eval, string assign) { Me.InitExpression = init; Me.EvalExpression = eval; Me.AssignExpression = assign; } public string InitExpression { get { return Me.InitExpression; } set { Me.InitExpression = value; } } public string EvalExpression { get { return Me.EvalExpression; } set { Me.EvalExpression = value; } } public string AssignExpression { get { return Me.AssignExpression; } set { Me.AssignExpression = value; } } } }
73.568493
946
0.766968
[ "Apache-2.0" ]
RachelAmbler/SS-Eye-S
SS-eye-S/Control Flow Tasks/Tasks/iForLoop.cs
10,741
C#
namespace MRULib.Converters { using System; using System.Globalization; using System.Windows; using System.Windows.Data; using System.Windows.Markup; /// <summary> /// Source: http://stackoverflow.com/questions/534575/how-do-i-invert-booleantovisibilityconverter /// /// Implements a Boolean to Visibility converter /// Use ConverterParameter=true to negate the visibility - boolean interpretation. /// </summary> [ValueConversion(typeof(Boolean), typeof(Visibility))] [MarkupExtensionReturnType(typeof(IValueConverter))] public sealed class BoolToVisibilityConverter : MarkupExtension, IValueConverter { #region fields private static BoolToVisibilityConverter mConverter; #endregion fields /// <summary> /// Returns an object that is provided /// as the value of the target property for this markup extension. /// /// When a XAML processor processes a type node and member value that is a markup extension, /// it invokes the ProvideValue method of that markup extension and writes the result into the /// object graph or serialization stream. The XAML object writer passes service context to each /// such implementation through the serviceProvider parameter. /// </summary> /// <param name="serviceProvider"></param> /// <returns></returns> public override object ProvideValue(IServiceProvider serviceProvider) { if (BoolToVisibilityConverter.mConverter == null) BoolToVisibilityConverter.mConverter = new BoolToVisibilityConverter(); return BoolToVisibilityConverter.mConverter; } /// <summary> /// Converts a <seealso cref="Boolean"/> value /// into a <seealso cref="Visibility"/> value. /// </summary> /// <param name="value"></param> /// <param name="targetType"></param> /// <param name="parameter"></param> /// <param name="culture"></param> /// <returns></returns> public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { var flag = false; if (value is bool) { flag = (bool)value; } else if (value is bool?) { var nullable = (bool?)value; flag = nullable.GetValueOrDefault(); } if (parameter != null) { if (bool.Parse((string)parameter)) { flag = !flag; } } if (flag) { return Visibility.Visible; } else { return Visibility.Collapsed; } } /// <summary> /// Converts a <seealso cref="Visibility"/> value /// into a <seealso cref="Boolean"/> value. /// </summary> /// <param name="value"></param> /// <param name="targetType"></param> /// <param name="parameter"></param> /// <param name="culture"></param> /// <returns></returns> public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { var back = ((value is Visibility) && (((Visibility)value) == Visibility.Visible)); if (parameter != null) { if ((bool)parameter) { back = !back; } } return back; } } }
35.105769
103
0.551356
[ "MIT" ]
Dirkster99/MRULib
source/MRULib/Converters/BoolToVisibilityConverter.cs
3,653
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Sample { class Program { static void Main(string[] args) { } } }
12.625
33
0.722772
[ "MIT" ]
kholodovitch/libpng-csharp
tests/Sample/Program.cs
204
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using SftpFile = Renci.SshNet.Sftp.SftpFile; namespace Nameless.Libraries.Aura.Model { public class SftpFilter { /// <summary> /// The collection of extension files to ignore /// </summary> public String[] IgnoreExtensions; /// <summary> /// The collection of files to ignore /// </summary> public String[] IgnoreFiles; /// <summary> /// The collection of directories to ignore /// </summary> public String[] IgnoreDirectories; /// <summary> /// Initialize a new instance of a SftpFilter /// </summary> /// <param name="prj">The current project</param> public SftpFilter (Project prj) { this.IgnoreDirectories = prj.Data.IgnoreDirectories; this.IgnoreFiles = prj.Data.IgnoreFiles; this.IgnoreExtensions = prj.Data.IgnoreExtensions; } /// <summary> /// Validates if a unix path is valid /// </summary> /// <param name="unixPath">The unix path to validate</param> /// <returns>True if the unix file is valid</returns> public bool IsUnixFileValid (string unixPath) { String file = unixPath.Substring (unixPath.LastIndexOf ('/')+1); bool isInIgnoreList = this.IsIgnoreFile (file), isIgnoreExtension = this.IsIgnoreExtension (file); return !isInIgnoreList && !isIgnoreExtension; } /// <summary> /// Validates if a unix path is valid as a directory /// path /// </summary> /// <param name="unixFile">The unix path to validate</param> /// <returns>True if the unix file is valid</returns> public bool IsUnixDirValid (SftpFile unixFile) { return unixFile.Name != ".." && unixFile.Name != "." && !this.IgnoreDirectories.Contains (unixFile.Name); } /// <summary> /// Gets the file paths in the given directory /// </summary> /// <param name="localPath">The directory local path</param> /// <returns>The files in the directory</returns> public IEnumerable<string> FilesInDirectory (string localPath) { DirectoryInfo info = new DirectoryInfo (localPath); var files = new List<FileInfo> (); this.GetFiles (ref files, info); return files.Select (x => x.FullName); } /// <summary> /// Check if a file is ignore by its file extension /// </summary> /// <param name="file">The file to validate</param> /// <returns>True if the file is ignored</returns> public Boolean IsIgnoreExtension (FileInfo file) { return this.IgnoreExtensions.Select (x => x.ToLower ()).Contains (file.Extension.ToLower ()); } /// <summary> /// Check if a file is ignore by its name /// </summary> /// <param name="file">The file to validate</param> /// <returns>True if the file is ignored</returns> public Boolean IsIgnoreFile (FileInfo file) { return this.IgnoreFiles.Select (x => x.ToLower ()).Contains (file.Name.ToLower ()); } /// <summary> /// Check if a file is ignore by its file extension /// </summary> /// <param name="filename">The file name to validate</param> /// <returns>True if the file is ignored</returns> public Boolean IsIgnoreExtension (String filename) { String extension = filename.Contains ('.') ? filename.Substring (filename.LastIndexOf ('.')).ToLower () : ""; return this.IgnoreExtensions.Select (x => x.ToLower ()).Contains (extension); } /// <summary> /// Check if a file is ignore by its name /// </summary> /// <param name="filename">The file to validate</param> /// <returns>True if the file is ignored</returns> public Boolean IsIgnoreFile (String filename) { return this.IgnoreFiles.Select (x => x.ToLower ()).Contains (filename.ToLower ()); } /// <summary> /// Check if the directory name is in the ignore list /// </summary> /// <param name="dir">The directory to validate</param> /// <returns>True if the directory is ignored</returns> public Boolean IsIgnoreDirectory (DirectoryInfo dir) { return this.IgnoreFiles.Select (x => x.ToLower ()).Contains (dir.Name.ToLower ()); } /// <summary> /// Gets the files in a given directory /// </summary> /// <param name="files">The extracted files</param> /// <param name="info">The directory info</param> public void GetFiles (ref List<FileInfo> files, DirectoryInfo info) { foreach (FileInfo file in info.GetFiles ().Where (x => !IsIgnoreExtension (x) && !IsIgnoreFile (x))) files.Add (file); foreach (DirectoryInfo dir in info.GetDirectories ().Where (x => !IsIgnoreDirectory (x))) GetFiles (ref files, dir); } } }
45.043478
121
0.583977
[ "MIT" ]
ANamelessWolf/AuraSFTP
src/Model/SftpFilter.cs
5,180
C#
using System.Collections.Concurrent; using System.Collections.Generic; using PlatformRacing3.Server.Game.Client; using PlatformRacing3.Server.Game.Commands; namespace PlatformRacing3.Server.Game.Chat { internal sealed class ChatRoomManager { private readonly CommandManager commandManager; private ConcurrentDictionary<string, ChatRoom> ChatRooms; public ChatRoomManager(CommandManager commandManager) { this.commandManager = commandManager; this.ChatRooms = new ConcurrentDictionary<string, ChatRoom>(); this.TryCreate(ChatRoomType.System, 1, "chat-Home", "", "Join our offical Discord server! https://discord.gg/xYTvAGP", out _); //User id 1 is isokissa3 } internal ICollection<ChatRoom> Rooms => this.ChatRooms.Values; //Dont really like these methods tho I can't come up with better names and funcitonaly internal bool TryCreate(ChatRoomType type, string name, string pass, string note, out ChatRoom room) => this.ChatRooms.TryAdd(name, room = new ChatRoom(this, this.commandManager, type, name, pass, note)); internal bool TryCreate(ChatRoomType type, uint creatorUserId, string name, string pass, string note, out ChatRoom room) => this.ChatRooms.TryAdd(name, room = new ChatRoom(this, this.commandManager, type, creatorUserId, name, pass, note)); internal bool TryGet(string name, out ChatRoom chatRoom) => this.ChatRooms.TryGetValue(name, out chatRoom); internal ChatRoom JoinOrCreate(ClientSession session, string name, string pass, string note, out bool status, uint chatId = 0) { //Complexity added by concurrency while (true) { if (!this.ChatRooms.TryGetValue(name, out ChatRoom chat)) //Dont use GetOrAdd here to reduce the amount of allocations we do { if (!session.IsGuest) { chat = new ChatRoom(this, this.commandManager, ChatRoomType.UserCreated, session.UserData.Id, name, pass, note); //Create chat room with the user already listed in as member status = chat.Join(session, chatId); //Initial join on create should NEVER fail if (!this.ChatRooms.TryAdd(name, chat)) { chat.Leave(session); //Leave so we dont hold reference to the chat even tho GC will take care of it continue; //Failed to add the newly created room, check for already existing room } } else { status = false; return null; //We are guest, we can not create rooms } } else { //Password functionality is not properly implemented in the client but keep this anyway status = (string.IsNullOrWhiteSpace(chat.Pass) || chat.Pass == pass) ? chat.Join(session, chatId) : false; } //If we failed to join to the room return and dont try again if (!status) { return chat; } else if (this.ChatRooms.GetOrAdd(name, chat) == chat) //If it was succesfully joined then verify that the the room that we just joined in is listed in globally or add the room if the room is missing { return chat; } else //Everything failed, leave so we dont hold reference to the chat even tho GC will take care of it and try again { chat.Leave(session); } } } internal void Leave(ClientSession session, string name) { if (this.ChatRooms.TryGetValue(name, out ChatRoom chat)) { chat.Leave(session); } } internal void Die(ChatRoom chatRoom) { if (chatRoom.Type != ChatRoomType.System) { this.ChatRooms.TryRemove(chatRoom.Name, out _); } } } }
43.479592
247
0.578268
[ "MIT" ]
CoralCOasa/PlatformRacing3
PlatformRacing3.Server/Game/Chat/ChatRoomManager.cs
4,263
C#
using NBitcoin; using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using WalletWasabi.Blockchain.Keys; using WalletWasabi.Crypto.Randomness; using WalletWasabi.Logging; using WalletWasabi.WabiSabi.Backend.PostRequests; using WalletWasabi.WabiSabi.Backend.Rounds; using WalletWasabi.WabiSabi.Client.CredentialDependencies; using WalletWasabi.WabiSabi.Crypto; using WalletWasabi.WabiSabi.Models; using WalletWasabi.WabiSabi.Models.Decomposition; using WalletWasabi.WabiSabi.Models.MultipartyTransaction; using WalletWasabi.Wallets; namespace WalletWasabi.WabiSabi.Client { public class CoinJoinClient { public CoinJoinClient( IWabiSabiApiRequestHandler arenaRequestHandler, IEnumerable<Coin> coins, Kitchen kitchen, KeyManager keymanager, RoundStateUpdater roundStatusUpdater) { ArenaRequestHandler = arenaRequestHandler; Kitchen = kitchen; Keymanager = keymanager; RoundStatusUpdater = roundStatusUpdater; SecureRandom = new SecureRandom(); Coins = coins; } private IEnumerable<Coin> Coins { get; set; } private SecureRandom SecureRandom { get; } = new SecureRandom(); private Random Random { get; } = new(); public IWabiSabiApiRequestHandler ArenaRequestHandler { get; } public Kitchen Kitchen { get; } public KeyManager Keymanager { get; } private RoundStateUpdater RoundStatusUpdater { get; } public async Task<bool> StartCoinJoinAsync(CancellationToken cancellationToken) { var currentRoundState = await RoundStatusUpdater.CreateRoundAwaiter(roundState => roundState.Phase == Phase.InputRegistration, cancellationToken).ConfigureAwait(false); // This should be roughly log(#inputs), it could be set slightly // higher if more inputs are observed but that involves trusting the // coordinator with those values. Therefore, conservatively set this // so that a maximum of 5 blame rounds are executed. // FIXME should smaller rounds abort earlier? var tryLimit = 6; for (var tries = 0; tries < tryLimit; tries++) { if (await StartRoundAsync(currentRoundState, cancellationToken)) { return true; } else { var blameRoundState = await RoundStatusUpdater.CreateRoundAwaiter(roundState => roundState.BlameOf == currentRoundState.Id, cancellationToken).ConfigureAwait(false); currentRoundState = blameRoundState; } } return false; } /// <summary>Attempt to participate in a specified dround.</summary> /// <param name="roundState">Defines the round parameter and state information to use.</param> /// <returns>Whether or not the round resulted in a successful transaction.</returns> public async Task<bool> StartRoundAsync(RoundState roundState, CancellationToken cancellationToken) { var constructionState = roundState.Assert<ConstructionState>(); // Calculate outputs values var outputValues = DecomposeAmounts(roundState.FeeRate, roundState.CoinjoinState.Parameters.AllowedOutputAmounts.Min); // Get all locked internal keys we have and assert we have enough. Keymanager.AssertLockedInternalKeysIndexed(howMany: outputValues.Count()); var allLockedInternalKeys = Keymanager.GetKeys(x => x.IsInternal && x.KeyState == KeyState.Locked); var outputTxOuts = outputValues.Zip(allLockedInternalKeys, (amount, hdPubKey) => new TxOut(amount, hdPubKey.P2wpkhScript)); List<AliceClient> aliceClients = CreateAliceClients(roundState); DependencyGraph dependencyGraph = DependencyGraph.ResolveCredentialDependencies(aliceClients.Select(a => a.Coin), outputTxOuts, roundState.FeeRate, roundState.MaxVsizeAllocationPerAlice); DependencyGraphTaskScheduler scheduler = new(dependencyGraph); // Register coins. await RegisterCoinsAsync(aliceClients, cancellationToken).ConfigureAwait(false); // Confirm coins. await scheduler.StartConfirmConnectionsAsync(aliceClients, dependencyGraph, roundState.ConnectionConfirmationTimeout, RoundStatusUpdater, cancellationToken).ConfigureAwait(false); // Re-issuances. var bobClient = CreateBobClient(roundState); await scheduler.StartReissuancesAsync(aliceClients, bobClient, cancellationToken).ConfigureAwait(false); // Output registration. roundState = await RoundStatusUpdater.CreateRoundAwaiter(roundState.Id, rs => rs.Phase == Phase.OutputRegistration, cancellationToken).ConfigureAwait(false); await scheduler.StartOutputRegistrationsAsync(outputTxOuts, bobClient, cancellationToken).ConfigureAwait(false); // ReadyToSign. await ReadyToSignAsync(aliceClients, cancellationToken).ConfigureAwait(false); // Signing. roundState = await RoundStatusUpdater.CreateRoundAwaiter(roundState.Id, rs => rs.Phase == Phase.TransactionSigning, cancellationToken).ConfigureAwait(false); var signingState = roundState.Assert<SigningState>(); var unsignedCoinJoin = signingState.CreateUnsignedTransaction(); // Sanity check. if (!SanityCheck(outputTxOuts, unsignedCoinJoin)) { throw new InvalidOperationException($"Round ({roundState.Id}): My output is missing."); } // Send signature. await SignTransactionAsync(aliceClients, unsignedCoinJoin, cancellationToken).ConfigureAwait(false); var finalRoundState = await RoundStatusUpdater.CreateRoundAwaiter(s => s.Id == roundState.Id && s.Phase == Phase.Ended, cancellationToken).ConfigureAwait(false); return finalRoundState.WasTransactionBroadcast; } private List<AliceClient> CreateAliceClients(RoundState roundState) { List<AliceClient> aliceClients = new(); foreach (var coin in Coins) { var aliceArenaClient = new ArenaClient( roundState.CreateAmountCredentialClient(SecureRandom), roundState.CreateVsizeCredentialClient(SecureRandom), ArenaRequestHandler); var hdKey = Keymanager.GetSecrets(Kitchen.SaltSoup(), coin.ScriptPubKey).Single(); var secret = hdKey.PrivateKey.GetBitcoinSecret(Keymanager.GetNetwork()); aliceClients.Add(new AliceClient(roundState.Id, aliceArenaClient, coin, roundState.FeeRate, secret)); } return aliceClients; } private async Task RegisterCoinsAsync(IEnumerable<AliceClient> aliceClients, CancellationToken cancellationToken) { async Task RegisterInputTask(AliceClient aliceClient) { await aliceClient.RegisterInputAsync(cancellationToken).ConfigureAwait(false); } var registerRequests = aliceClients.Select(RegisterInputTask); await Task.WhenAll(registerRequests).ConfigureAwait(false); } private IEnumerable<Money> DecomposeAmounts(FeeRate feeRate, Money minimumOutputAmount) { GreedyDecomposer greedyDecomposer = new(StandardDenomination.Values.Where(x => x >= minimumOutputAmount)); var sum = Coins.Sum(c => c.EffectiveValue(feeRate)); return greedyDecomposer.Decompose(sum, feeRate.GetFee(31)); } private BobClient CreateBobClient(RoundState roundState) { return new BobClient( roundState.Id, new( roundState.CreateAmountCredentialClient(SecureRandom), roundState.CreateVsizeCredentialClient(SecureRandom), ArenaRequestHandler)); } private bool SanityCheck(IEnumerable<TxOut> expectedOutputs, Transaction unsignedCoinJoinTransaction) { var coinJoinOutputs = unsignedCoinJoinTransaction.Outputs.Select(o => (o.Value, o.ScriptPubKey)); var expectedOutputTuples = expectedOutputs.Select(o => (o.Value, o.ScriptPubKey)); return coinJoinOutputs.IsSuperSetOf(expectedOutputTuples); } private async Task SignTransactionAsync(IEnumerable<AliceClient> aliceClients, Transaction unsignedCoinJoinTransaction, CancellationToken cancellationToken) { async Task<AliceClient?> SignTransactionTask(AliceClient aliceClient) { try { await aliceClient.SignTransactionAsync(unsignedCoinJoinTransaction, cancellationToken).ConfigureAwait(false); return aliceClient; } catch (Exception e) { Logger.LogWarning($"Round ({aliceClient.RoundId}), Alice ({{aliceClient.AliceId}}): {nameof(AliceClient.SignTransactionAsync)} failed, reason:'{e}'."); return default; } } var signingRequests = aliceClients.Select(SignTransactionTask); await Task.WhenAll(signingRequests).ConfigureAwait(false); } private async Task ReadyToSignAsync(IEnumerable<AliceClient> aliceClients, CancellationToken cancellationToken) { async Task ReadyToSignTask(AliceClient aliceClient) { await aliceClient.ReadyToSignAsync(cancellationToken).ConfigureAwait(false); } var readyRequests = aliceClients.Select(ReadyToSignTask); await Task.WhenAll(readyRequests).ConfigureAwait(false); } } }
40.613208
190
0.776655
[ "MIT" ]
augustoproiete-forks/zkSNACKs--WalletWasabi
WalletWasabi/WabiSabi/Client/CoinJoinClient.cs
8,610
C#
//------------------------------------------------- // TNet 3 // Copyright © 2012-2018 Tasharen Entertainment Inc //------------------------------------------------- using UnityEngine; using System.Net; namespace TNet { /// <summary> /// Server Lobby Client is an abstract class designed to communicate with the Lobby Server. /// You should instantiate protocol-specific versions: TNTcpLobbyClient or TNUdpLobbyClient, /// and you should only have one of them active at a time, not both. /// </summary> public abstract class LobbyClient : MonoBehaviour { public delegate void OnListChange (); /// <summary> /// Error string set if something goes wrong. /// </summary> static public string errorString = ""; /// <summary> /// List of known servers. /// </summary> static public ServerList knownServers = new ServerList(); /// <summary> /// Callback that will be triggered every time the server list changes. /// </summary> static public OnListChange onChange; /// <summary> /// Whether some lobby client is currently active. /// </summary> static public bool isActive = false; /// <summary> /// Public address for the lobby client server's location. /// </summary> public string remoteAddress; /// <summary> /// Lobby server's port. /// </summary> public int remotePort = 5129; /// <summary> /// Clear the list of known servers when the component is disabled. /// </summary> protected virtual void OnDisable () { errorString = ""; knownServers.Clear(); } } }
22.485294
92
0.638326
[ "MIT" ]
The-ULTIMATE-MULTIPLAYER-EXPERIENCE/GameWithMultiplayerServer
Multiplayer Game Test/Assets/TNet/Client/TNLobbyClient.cs
1,530
C#
using Newtonsoft.Json; namespace ChaosTerraria.AI { public class Neuron { [JsonProperty("$TYPE")] public string type; [JsonProperty("_base_type")] public string baseType; [JsonProperty("$DEFAULT")] public bool Default; public double weight; public string activator; public Dependency[] dependencies; public string id; public string direction; public string range; public string x; public string y; public string attributeId; public string attributeValue; [JsonIgnore] public double value; [JsonIgnore] public bool evaluated; } }
24.241379
41
0.59744
[ "MIT" ]
RookieIndieDev/ChaosTerraria
AI/Neuron.cs
705
C#
using System; using Glass.Mapper.Sc.DataMappers; using NUnit.Framework; using Sitecore.Data; namespace Glass.Mapper.Sc.FakeDb.DataMappers { [TestFixture] public class SitecoreFieldFloatMapperFixture : AbstractMapperFixture { #region Method - GetField [Test] public void GetField_FieldContainsValidFloat_ReturnsFloat() { //Assign string fieldValue = "3.141592"; float expected = 3.141592F; var fieldId = Guid.NewGuid(); var item = Helpers.CreateFakeItem(fieldId, fieldValue); var field = item.Fields[new ID(fieldId)]; var mapper = new SitecoreFieldFloatMapper(); //Act var result = (float)mapper.GetField(field, null, null); //Assert Assert.AreEqual(expected, result); } [Test] public void GetField_FieldContainsEmptyString_ReturnsFloatZero() { //Assign string fieldValue = string.Empty; float expected = 0f; var fieldId = Guid.NewGuid(); var item = Helpers.CreateFakeItem(fieldId, fieldValue); var field = item.Fields[new ID(fieldId)]; var mapper = new SitecoreFieldFloatMapper(); //Act var result = (float)mapper.GetField(field, null, null); //Assert Assert.AreEqual(expected, result); } [Test] public void GetField_FieldContainsInvalidValidFloat_ReturnsFloat() { //Assign string fieldValue = "hello world"; float expected = 3.141592f; var fieldId = Guid.NewGuid(); var item = Helpers.CreateFakeItem(fieldId, fieldValue); var field = item.Fields[new ID(fieldId)]; var mapper = new SitecoreFieldFloatMapper(); //Act Assert.Throws<MapperException>(() => { var result = (float) mapper.GetField(field, null, null); }); //Assert } #endregion #region Method - GetField [Test] public void SetField_ObjectisValidFloat_SetsFieldValue() { //Assign string expected = "3.141592"; float objectValue = 3.141592f; var fieldId = Guid.NewGuid(); var item = Helpers.CreateFakeItem(fieldId, string.Empty); var field = item.Fields[new ID(fieldId)]; var mapper = new SitecoreFieldFloatMapper(); item.Editing.BeginEdit(); //Act mapper.SetField(field, objectValue, null, null); //Assert Assert.AreEqual(expected, field.Value); } [Test] public void SetField_ObjectIsInt_ThrowsException() { //Assign int objectValue = 3; var fieldId = Guid.NewGuid(); var item = Helpers.CreateFakeItem(fieldId, string.Empty); var field = item.Fields[new ID(fieldId)]; var mapper = new SitecoreFieldFloatMapper(); item.Editing.BeginEdit(); //Act Assert.Throws<NotSupportedException>(() => { mapper.SetField(field, objectValue, null, null); }); //Assert } #endregion } }
25.533333
74
0.53931
[ "Apache-2.0" ]
Amir818/Glass.Mapper
Tests/Unit Tests/Glass.Mapper.Sc.FakeDb/DataMappers/SitecoreFieldFloatMapperFixture.cs
3,447
C#
using Amazon.JSII.Runtime.Deputy; #pragma warning disable CS0672,CS0809,CS1591 namespace aws { [JsiiInterface(nativeType: typeof(IWafv2WebAclRuleStatementRateBasedStatementScopeDownStatementOrStatementStatementAndStatementStatementRegexPatternSetReferenceStatementFieldToMatchSingleQueryArgument), fullyQualifiedName: "aws.Wafv2WebAclRuleStatementRateBasedStatementScopeDownStatementOrStatementStatementAndStatementStatementRegexPatternSetReferenceStatementFieldToMatchSingleQueryArgument")] public interface IWafv2WebAclRuleStatementRateBasedStatementScopeDownStatementOrStatementStatementAndStatementStatementRegexPatternSetReferenceStatementFieldToMatchSingleQueryArgument { [JsiiProperty(name: "name", typeJson: "{\"primitive\":\"string\"}")] string Name { get; } [JsiiTypeProxy(nativeType: typeof(IWafv2WebAclRuleStatementRateBasedStatementScopeDownStatementOrStatementStatementAndStatementStatementRegexPatternSetReferenceStatementFieldToMatchSingleQueryArgument), fullyQualifiedName: "aws.Wafv2WebAclRuleStatementRateBasedStatementScopeDownStatementOrStatementStatementAndStatementStatementRegexPatternSetReferenceStatementFieldToMatchSingleQueryArgument")] internal sealed class _Proxy : DeputyBase, aws.IWafv2WebAclRuleStatementRateBasedStatementScopeDownStatementOrStatementStatementAndStatementStatementRegexPatternSetReferenceStatementFieldToMatchSingleQueryArgument { private _Proxy(ByRefValue reference): base(reference) { } [JsiiProperty(name: "name", typeJson: "{\"primitive\":\"string\"}")] public string Name { get => GetInstanceProperty<string>()!; } } } }
57.16129
404
0.797404
[ "MIT" ]
scottenriquez/cdktf-alpha-csharp-testing
resources/.gen/aws/aws/IWafv2WebAclRuleStatementRateBasedStatementScopeDownStatementOrStatementStatementAndStatementStatementRegexPatternSetReferenceStatementFieldToMatchSingleQueryArgument.cs
1,772
C#
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information. using AExpense.DataAccessLayer; using AExpense.Model; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Configuration; using Microsoft.Practices.Unity; using AExpense.Tests.Util; using AExpense.FunctionalTests.Properties; using AExpense.FunctionalTests.DataAccess; namespace AExpense.Tests.Functional { [TestClass] public class TracingAndInterceptionAppBlockFixture { private static readonly string TestDatabaseConnectionString = ConfigurationManager.ConnectionStrings["aExpense"].ConnectionString; private static readonly string LoggingDatabaseConnectionString = ConfigurationManager.ConnectionStrings["Logging"].ConnectionString; private static readonly Guid testGuid = Guid.NewGuid(); private UnityContainer container; [TestInitialize] public void TestInit() { DatabaseHelper.CleanLoggingDB(LoggingDatabaseConnectionString); this.container = new UnityContainer(); ContainerBootstrapper.Configure(container); } [TestCleanup] public void TestCleanup() { this.container.Dispose(); DatabaseHelper.DeleteExpenseInDB(TestDatabaseConnectionString, testGuid); } /// <summary> /// Tracing and interception happy path, for negative scenarios check exceptionHandling fixture. /// </summary> [TestMethod] public void CanInterceptAndTraceWithValidApprover() { var newExpense = new Model.Expense(); newExpense.Id = testGuid; newExpense.Title = "testing title"; newExpense.CostCenter = "testing cost center"; newExpense.ReimbursementMethod = ReimbursementMethod.DirectDeposit; newExpense.User = new Model.User() { FullName = "test user", UserName = "tester" }; newExpense.Date = System.DateTime.Today; newExpense.ApproverName = "ADATUM\\mary"; newExpense.Details.Add(new Model.ExpenseItem() { Description = "test item", Amount = 10, Id = Guid.NewGuid() }); var repository = container.Resolve<IExpenseRepository>(); repository.SaveExpense(newExpense); Log log = DatabaseHelper.GetFirstLog(LoggingDatabaseConnectionString); Assert.IsNotNull(log); Assert.AreEqual("Call Logging", log.Title); } [TestMethod] public void CanInterceptAndTraceWhenUserNameIsSet() { var user = container.Resolve<Model.User>(); user.UserName = "foo"; Log log = DatabaseHelper.GetFirstLog(LoggingDatabaseConnectionString); Assert.IsNotNull(log, "No data logged"); StringAssert.Contains(log.FormattedMessage, Resources.SetUserNameWasExecutedMessage); } } }
38.558442
140
0.678343
[ "Apache-2.0" ]
Herschel2013/EnterpriseLibrary6
RI/aExpense/EL-V5/aExpense.Tests/TracingAndInterceptionAppBlockFixture.cs
2,971
C#
using System.Drawing; using System.Windows.Forms; namespace Free.Controls.TreeView.Tree { public class TreeViewRowDrawEventArgs : PaintEventArgs { TreeNodeAdv _node; DrawContext _context; int _row; Rectangle _rowRect; public TreeViewRowDrawEventArgs(Graphics graphics, Rectangle clipRectangle, TreeNodeAdv node, DrawContext context, int row, Rectangle rowRect) : base(graphics, clipRectangle) { _node=node; _context=context; _row=row; _rowRect=rowRect; } public TreeNodeAdv Node { get { return _node; } } public DrawContext Context { get { return _context; } } public int Row { get { return _row; } } public Rectangle RowRect { get { return _rowRect; } } } }
16.681818
144
0.702997
[ "BSD-2-Clause" ]
shintadono/Free.Controls.TreeView
Tree/TreeViewRowDrawEventArgs.cs
734
C#
// Copyright 2020 MaidSafe.net limited. // // This SAFE Network Software is licensed to you under the MIT license <LICENSE-MIT // http://opensource.org/licenses/MIT> or the Modified BSD license <LICENSE-BSD // https://opensource.org/licenses/BSD-3-Clause>, at your option. This file may not be copied, // modified, or distributed except according to those terms. Please review the Licences for the // specific language governing permissions and limitations relating to use of the SAFE Network // Software. using System; using System.Diagnostics; using System.IO; using System.Threading.Tasks; using Foundation; using SafeAuthenticatorApp; using SafeAuthenticatorApp.Helpers; using SafeAuthenticatorApp.Services; using UIKit; using Xamarin.Forms; using Xamarin.Forms.Platform.iOS; using CarouselViewRenderer = CarouselView.FormsPlugin.iOS.CarouselViewRenderer; namespace SafeAuthenticator.iOS { [Register("AppDelegate")] public class AppDelegate : FormsApplicationDelegate { private static string LogFolderPath => DependencyService.Get<IFileOps>().ConfigFilesPath; private AuthService Authenticator => DependencyService.Get<AuthService>(); public override bool FinishedLaunching(UIApplication uiApplication, NSDictionary launchOptions) { Rg.Plugins.Popup.Popup.Init(); Forms.Init(); Plugin.InputKit.Platforms.iOS.Config.Init(); FormsMaterial.Init(); XamEffects.iOS.Effects.Init(); CarouselViewRenderer.Init(); LoadApplication(new App()); AppDomain.CurrentDomain.UnhandledException += CurrentDomainOnUnhandledException; TaskScheduler.UnobservedTaskException += TaskSchedulerOnUnobservedTaskException; DisplayCrashReport(); return base.FinishedLaunching(uiApplication, launchOptions); } public override bool OpenUrl(UIApplication app, NSUrl url, NSDictionary options) { Device.BeginInvokeOnMainThread( async () => { try { await Authenticator.HandleUrlActivationAsync(url.ToString()); Debug.WriteLine("IPC Msg Handling Completed"); } catch (Exception ex) { Debug.WriteLine($"Error: {ex.Message}"); } }); return true; } #region Error Handling private static void TaskSchedulerOnUnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs exEventArgs) { var newExc = new Exception("TaskSchedulerOnUnobservedTaskException", exEventArgs.Exception); LogUnhandledException(newExc); } private static void CurrentDomainOnUnhandledException(object sender, UnhandledExceptionEventArgs exEventArgs) { var newExc = new Exception("CurrentDomainOnUnhandledException", exEventArgs.ExceptionObject as Exception); LogUnhandledException(newExc); } private static void LogUnhandledException(Exception exception) { try { const string errorFileName = "Fatal.log"; var errorFilePath = Path.Combine(LogFolderPath, errorFileName); var errorMessage = $"Time: {DateTime.Now}\nError: Unhandled Exception\n{exception}\n\n"; File.AppendAllText(errorFilePath, errorMessage); } catch { // just suppress any error logging exceptions } } private static void DisplayCrashReport() { const string errorFilename = "Fatal.log"; var errorFilePath = Path.Combine(LogFolderPath, errorFilename); if (!File.Exists(errorFilePath)) { return; } var errorText = File.ReadAllText(errorFilePath); Device.BeginInvokeOnMainThread(() => { var vc = UIApplication.SharedApplication?.KeyWindow?.RootViewController; if (vc == null) { return; } var alert = UIAlertController.Create("Crash Report", errorText, UIAlertControllerStyle.Alert); alert.AddAction(UIAlertAction.Create("Close", UIAlertActionStyle.Cancel, null)); alert.AddAction(UIAlertAction.Create("Clear", UIAlertActionStyle.Default, action => { File.Delete(errorFilePath); })); vc.PresentViewController(alert, true, null); }); } #endregion } }
37.579365
134
0.624287
[ "MIT", "BSD-3-Clause" ]
maidsafe/sn_authenticator_mobile
SafeAuthenticator.iOS/AppDelegate.cs
4,737
C#
/* Copyright (c) 2011 Microsoft Corporation. All rights reserved. Use of this sample source code is subject to the terms of the Microsoft license agreement under which you licensed this sample source code and is provided AS-IS. If you did not accept the terms of the license agreement, you are not authorized to use this sample source code. For the terms of the license, please see the license agreement between you and Microsoft. To see all Code Samples for Windows Phone, visit http://go.microsoft.com/fwlink/?LinkID=219604 */ using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; using Microsoft.Phone.Controls; // Directives using System.ComponentModel; using System.Threading; using System.IO; using System.IO.IsolatedStorage; using Microsoft.Phone.Shell; using System.Windows.Navigation; using Microsoft.Devices; namespace sdkVideoRecorderCS { public partial class MainPage : PhoneApplicationPage { // Viewfinder for capturing video. private VideoBrush videoRecorderBrush; // Source and device for capturing video. private CaptureSource captureSource; private VideoCaptureDevice videoCaptureDevice; // File details for storing the recording. private IsolatedStorageFileStream isoVideoFile; private FileSink fileSink; private string isoVideoFileName = "CameraMovie.mp4"; // For managing button and application state. private enum ButtonState { Initialized, Ready, Recording, Playback, Paused, NoChange, CameraNotSupported }; private ButtonState currentAppState; // Constructor public MainPage() { InitializeComponent(); // Prepare ApplicationBar and buttons. PhoneAppBar = (ApplicationBar)ApplicationBar; PhoneAppBar.IsVisible = true; StartRecording = ((ApplicationBarIconButton)ApplicationBar.Buttons[0]); StopPlaybackRecording = ((ApplicationBarIconButton)ApplicationBar.Buttons[1]); StartPlayback = ((ApplicationBarIconButton)ApplicationBar.Buttons[2]); PausePlayback = ((ApplicationBarIconButton)ApplicationBar.Buttons[3]); } protected override void OnNavigatedTo(NavigationEventArgs e) { base.OnNavigatedTo(e); // Initialize the video recorder. InitializeVideoRecorder(); } protected override void OnNavigatedFrom(NavigationEventArgs e) { // Dispose of camera and media objects. DisposeVideoPlayer(); DisposeVideoRecorder(); base.OnNavigatedFrom(e); } // Update the buttons and text on the UI thread based on app state. private void UpdateUI(ButtonState currentButtonState, string statusMessage) { // Run code on the UI thread. Dispatcher.BeginInvoke(delegate { switch (currentButtonState) { // When the camera is not supported by the device. case ButtonState.CameraNotSupported: StartRecording.IsEnabled = false; StopPlaybackRecording.IsEnabled = false; StartPlayback.IsEnabled = false; PausePlayback.IsEnabled = false; break; // First launch of the application, so no video is available. case ButtonState.Initialized: StartRecording.IsEnabled = true; StopPlaybackRecording.IsEnabled = false; StartPlayback.IsEnabled = false; PausePlayback.IsEnabled = false; break; // Ready to record, so video is available for viewing. case ButtonState.Ready: StartRecording.IsEnabled = true; StopPlaybackRecording.IsEnabled = false; StartPlayback.IsEnabled = true; PausePlayback.IsEnabled = false; break; // Video recording is in progress. case ButtonState.Recording: StartRecording.IsEnabled = false; StopPlaybackRecording.IsEnabled = true; StartPlayback.IsEnabled = false; PausePlayback.IsEnabled = false; break; // Video playback is in progress. case ButtonState.Playback: StartRecording.IsEnabled = false; StopPlaybackRecording.IsEnabled = true; StartPlayback.IsEnabled = false; PausePlayback.IsEnabled = true; break; // Video playback has been paused. case ButtonState.Paused: StartRecording.IsEnabled = false; StopPlaybackRecording.IsEnabled = true; StartPlayback.IsEnabled = true; PausePlayback.IsEnabled = false; break; default: break; } // Display a message. txtDebug.Text = statusMessage; // Note the current application state. currentAppState = currentButtonState; }); } public void InitializeVideoRecorder() { if (captureSource == null) { // Create the VideoRecorder objects. captureSource = new CaptureSource(); fileSink = new FileSink(); videoCaptureDevice = CaptureDeviceConfiguration.GetDefaultVideoCaptureDevice(); // Add eventhandlers for captureSource. captureSource.CaptureFailed += new EventHandler<ExceptionRoutedEventArgs>(OnCaptureFailed); // Initialize the camera if it exists on the device. if (videoCaptureDevice != null) { // Create the VideoBrush for the viewfinder. videoRecorderBrush = new VideoBrush(); videoRecorderBrush.SetSource(captureSource); // Display the viewfinder image on the rectangle. viewfinderRectangle.Fill = videoRecorderBrush; // Start video capture and display it on the viewfinder. captureSource.Start(); // Set the button state and the message. UpdateUI(ButtonState.Initialized, "Tap record to start recording..."); } else { // Disable buttons when the camera is not supported by the device. UpdateUI(ButtonState.CameraNotSupported, "A camera is not supported on this device."); } } } // Set recording state: start recording. private void StartVideoRecording() { try { // Connect fileSink to captureSource. if (captureSource.VideoCaptureDevice != null && captureSource.State == CaptureState.Started) { captureSource.Stop(); // Connect the input and output of fileSink. fileSink.CaptureSource = captureSource; fileSink.IsolatedStorageFileName = isoVideoFileName; } // Begin recording. if (captureSource.VideoCaptureDevice != null && captureSource.State == CaptureState.Stopped) { captureSource.Start(); } // Set the button states and the message. UpdateUI(ButtonState.Recording, "Recording..."); } // If recording fails, display an error. catch (Exception e) { this.Dispatcher.BeginInvoke(delegate() { txtDebug.Text = "ERROR: " + e.Message.ToString(); }); } } // Set the recording state: stop recording. private void StopVideoRecording() { try { // Stop recording. if (captureSource.VideoCaptureDevice != null && captureSource.State == CaptureState.Started) { captureSource.Stop(); // Disconnect fileSink. fileSink.CaptureSource = null; fileSink.IsolatedStorageFileName = null; // Set the button states and the message. UpdateUI(ButtonState.NoChange, "Preparing viewfinder..."); StartVideoPreview(); } } // If stop fails, display an error. catch (Exception e) { this.Dispatcher.BeginInvoke(delegate() { txtDebug.Text = "ERROR: " + e.Message.ToString(); }); } } // Set the recording state: display the video on the viewfinder. private void StartVideoPreview() { try { // Display the video on the viewfinder. if (captureSource.VideoCaptureDevice != null && captureSource.State == CaptureState.Stopped) { // Add captureSource to videoBrush. videoRecorderBrush.SetSource(captureSource); // Add videoBrush to the visual tree. viewfinderRectangle.Fill = videoRecorderBrush; captureSource.Start(); // Set the button states and the message. UpdateUI(ButtonState.Ready, "Ready to record."); } } // If preview fails, display an error. catch (Exception e) { this.Dispatcher.BeginInvoke(delegate() { txtDebug.Text = "ERROR: " + e.Message.ToString(); }); } } // Start the video recording. private void StartRecording_Click(object sender, EventArgs e) { // Avoid duplicate taps. StartRecording.IsEnabled = false; StartVideoRecording(); } // Handle stop requests. private void StopPlaybackRecording_Click(object sender, EventArgs e) { // Avoid duplicate taps. StopPlaybackRecording.IsEnabled = false; // Stop during video recording. if (currentAppState == ButtonState.Recording) { StopVideoRecording(); // Set the button state and the message. UpdateUI(ButtonState.NoChange, "Recording stopped."); } // Stop during video playback. else { // Remove playback objects. DisposeVideoPlayer(); StartVideoPreview(); // Set the button state and the message. UpdateUI(ButtonState.NoChange, "Playback stopped."); } } // Start video playback. private void StartPlayback_Click(object sender, EventArgs e) { // Avoid duplicate taps. StartPlayback.IsEnabled = false; // Start video playback when the file stream exists. if (isoVideoFile != null) { VideoPlayer.Play(); } // Start the video for the first time. else { // Stop the capture source. captureSource.Stop(); // Remove VideoBrush from the tree. viewfinderRectangle.Fill = null; // Create the file stream and attach it to the MediaElement. isoVideoFile = new IsolatedStorageFileStream(isoVideoFileName, FileMode.Open, FileAccess.Read, IsolatedStorageFile.GetUserStoreForApplication()); VideoPlayer.SetSource(isoVideoFile); // Add an event handler for the end of playback. VideoPlayer.MediaEnded += new RoutedEventHandler(VideoPlayerMediaEnded); // Start video playback. VideoPlayer.Play(); } // Set the button state and the message. UpdateUI(ButtonState.Playback, "Playback started."); } // Pause video playback. private void PausePlayback_Click(object sender, EventArgs e) { // Avoid duplicate taps. PausePlayback.IsEnabled = false; // If mediaElement exists, pause playback. if (VideoPlayer != null) { VideoPlayer.Pause(); } // Set the button state and the message. UpdateUI(ButtonState.Paused, "Playback paused."); } private void DisposeVideoPlayer() { if (VideoPlayer != null) { // Stop the VideoPlayer MediaElement. VideoPlayer.Stop(); // Remove playback objects. VideoPlayer.Source = null; isoVideoFile = null; // Remove the event handler. VideoPlayer.MediaEnded -= VideoPlayerMediaEnded; } } private void DisposeVideoRecorder() { if (captureSource != null) { // Stop captureSource if it is running. if (captureSource.VideoCaptureDevice != null && captureSource.State == CaptureState.Started) { captureSource.Stop(); } // Remove the event handlers for capturesource and the shutter button. captureSource.CaptureFailed -= OnCaptureFailed; // Remove the video recording objects. captureSource = null; videoCaptureDevice = null; fileSink = null; videoRecorderBrush = null; } } // If recording fails, display an error message. private void OnCaptureFailed(object sender, ExceptionRoutedEventArgs e) { this.Dispatcher.BeginInvoke(delegate() { txtDebug.Text = "ERROR: " + e.ErrorException.Message.ToString(); }); } // Display the viewfinder when playback ends. public void VideoPlayerMediaEnded(object sender, RoutedEventArgs e) { // Remove the playback objects. DisposeVideoPlayer(); StartVideoPreview(); } } }
35.454338
115
0.533325
[ "MIT" ]
Ranin26/msdn-code-gallery-microsoft
Official Windows Platform Sample/Video Recorder Sample/[C#]-Video Recorder Sample/C#/sdkVideoRecorderCS/MainPage.xaml.cs
15,529
C#
/* * Square Connect API * * Client library for accessing the Square Connect APIs * * OpenAPI spec version: 2.0 * Contact: developers@squareup.com * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using NUnit.Framework; using System; using System.Linq; using System.IO; using System.Collections.Generic; using Square.Connect.Api; using Square.Connect.Model; using Square.Connect.Client; using System.Reflection; namespace Square.Connect.Test { /// <summary> /// Class for testing CreateCatalogImageRequest /// </summary> /// <remarks> /// This file is automatically generated by Swagger Codegen. /// Please update the test case below to test the model. /// </remarks> [TestFixture] public class CreateCatalogImageRequestTests { // TODO uncomment below to declare an instance variable for CreateCatalogImageRequest //private CreateCatalogImageRequest instance; /// <summary> /// Setup before each test /// </summary> [SetUp] public void Init() { // TODO uncomment below to create an instance of CreateCatalogImageRequest //instance = new CreateCatalogImageRequest(); } /// <summary> /// Clean up after each test /// </summary> [TearDown] public void Cleanup() { } /// <summary> /// Test an instance of CreateCatalogImageRequest /// </summary> [Test] public void CreateCatalogImageRequestInstanceTest() { // TODO uncomment below to test "IsInstanceOfType" CreateCatalogImageRequest //Assert.IsInstanceOfType<CreateCatalogImageRequest> (instance, "variable 'instance' is a CreateCatalogImageRequest"); } /// <summary> /// Test the property 'IdempotencyKey' /// </summary> [Test] public void IdempotencyKeyTest() { // TODO unit test for the property 'IdempotencyKey' } /// <summary> /// Test the property 'ObjectId' /// </summary> [Test] public void ObjectIdTest() { // TODO unit test for the property 'ObjectId' } /// <summary> /// Test the property 'Image' /// </summary> [Test] public void ImageTest() { // TODO unit test for the property 'Image' } } }
26.021053
130
0.593042
[ "Apache-2.0" ]
square/connect-csharp-sdk
src/Square.Connect.Test/Model/CreateCatalogImageRequestTests.cs
2,472
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microservice.Whatevers.Domain.Entities.Things; using Microservice.Whatevers.Domain.Exceptions; using Microservice.Whatevers.Repositories; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; namespace Microservice.Whatevers.WebApi.Controllers { [ApiVersion("1")] public class WeatherForecastController : ApiControllerBase { 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, IWhateverRepository repository) { _logger = logger; } [HttpGet] public IEnumerable<WeatherForecast> Get() { throw new Exception("Muito erro"); throw new BusinessException("Erro de negócio"); new ThingBuilder().Build(); 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(); } } }
31.979167
116
0.603909
[ "MIT" ]
IgortRamos/Microservice.Whatevers
src/Microservice.Whatevers.WebApi/Controllers/WeatherForecastController.cs
1,538
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.Azure.Automation { /// <summary> /// Manages a Automation DSC Configuration. /// /// ## Import /// /// Automation DSC Configuration's can be imported using the `resource id`, e.g. /// /// ```sh /// $ pulumi import azure:automation/dscConfiguration:DscConfiguration configuration1 /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/group1/providers/Microsoft.Automation/automationAccounts/account1/configurations/configuration1 /// ``` /// </summary> [AzureResourceType("azure:automation/dscConfiguration:DscConfiguration")] public partial class DscConfiguration : Pulumi.CustomResource { /// <summary> /// The name of the automation account in which the DSC Configuration is created. Changing this forces a new resource to be created. /// </summary> [Output("automationAccountName")] public Output<string> AutomationAccountName { get; private set; } = null!; /// <summary> /// The PowerShell DSC Configuration script. /// </summary> [Output("contentEmbedded")] public Output<string> ContentEmbedded { get; private set; } = null!; /// <summary> /// Description to go with DSC Configuration. /// </summary> [Output("description")] public Output<string?> Description { get; private set; } = null!; /// <summary> /// Must be the same location as the Automation Account. /// </summary> [Output("location")] public Output<string> Location { get; private set; } = null!; /// <summary> /// Verbose log option. /// </summary> [Output("logVerbose")] public Output<bool?> LogVerbose { get; private set; } = null!; /// <summary> /// Specifies the name of the DSC Configuration. Changing this forces a new resource to be created. /// </summary> [Output("name")] public Output<string> Name { get; private set; } = null!; /// <summary> /// The name of the resource group in which the DSC Configuration is created. Changing this forces a new resource to be created. /// </summary> [Output("resourceGroupName")] public Output<string> ResourceGroupName { get; private set; } = null!; [Output("state")] public Output<string> State { get; private set; } = null!; /// <summary> /// A mapping of tags to assign to the resource. /// </summary> [Output("tags")] public Output<ImmutableDictionary<string, string>?> Tags { get; private set; } = null!; /// <summary> /// Create a DscConfiguration resource with the given unique name, arguments, and options. /// </summary> /// /// <param name="name">The unique name of the resource</param> /// <param name="args">The arguments used to populate this resource's properties</param> /// <param name="options">A bag of options that control this resource's behavior</param> public DscConfiguration(string name, DscConfigurationArgs args, CustomResourceOptions? options = null) : base("azure:automation/dscConfiguration:DscConfiguration", name, args ?? new DscConfigurationArgs(), MakeResourceOptions(options, "")) { } private DscConfiguration(string name, Input<string> id, DscConfigurationState? state = null, CustomResourceOptions? options = null) : base("azure:automation/dscConfiguration:DscConfiguration", name, state, MakeResourceOptions(options, id)) { } private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id) { var defaultOptions = new CustomResourceOptions { Version = Utilities.Version, }; var merged = CustomResourceOptions.Merge(defaultOptions, options); // Override the ID if one was specified for consistency with other language SDKs. merged.Id = id ?? merged.Id; return merged; } /// <summary> /// Get an existing DscConfiguration resource's state with the given name, ID, and optional extra /// properties used to qualify the lookup. /// </summary> /// /// <param name="name">The unique name of the resulting resource.</param> /// <param name="id">The unique provider ID of the resource to lookup.</param> /// <param name="state">Any extra arguments used during the lookup.</param> /// <param name="options">A bag of options that control this resource's behavior</param> public static DscConfiguration Get(string name, Input<string> id, DscConfigurationState? state = null, CustomResourceOptions? options = null) { return new DscConfiguration(name, id, state, options); } } public sealed class DscConfigurationArgs : Pulumi.ResourceArgs { /// <summary> /// The name of the automation account in which the DSC Configuration is created. Changing this forces a new resource to be created. /// </summary> [Input("automationAccountName", required: true)] public Input<string> AutomationAccountName { get; set; } = null!; /// <summary> /// The PowerShell DSC Configuration script. /// </summary> [Input("contentEmbedded", required: true)] public Input<string> ContentEmbedded { get; set; } = null!; /// <summary> /// Description to go with DSC Configuration. /// </summary> [Input("description")] public Input<string>? Description { get; set; } /// <summary> /// Must be the same location as the Automation Account. /// </summary> [Input("location")] public Input<string>? Location { get; set; } /// <summary> /// Verbose log option. /// </summary> [Input("logVerbose")] public Input<bool>? LogVerbose { get; set; } /// <summary> /// Specifies the name of the DSC Configuration. Changing this forces a new resource to be created. /// </summary> [Input("name")] public Input<string>? Name { get; set; } /// <summary> /// The name of the resource group in which the DSC Configuration is created. Changing this forces a new resource to be created. /// </summary> [Input("resourceGroupName", required: true)] public Input<string> ResourceGroupName { get; set; } = null!; [Input("tags")] private InputMap<string>? _tags; /// <summary> /// A mapping of tags to assign to the resource. /// </summary> public InputMap<string> Tags { get => _tags ?? (_tags = new InputMap<string>()); set => _tags = value; } public DscConfigurationArgs() { } } public sealed class DscConfigurationState : Pulumi.ResourceArgs { /// <summary> /// The name of the automation account in which the DSC Configuration is created. Changing this forces a new resource to be created. /// </summary> [Input("automationAccountName")] public Input<string>? AutomationAccountName { get; set; } /// <summary> /// The PowerShell DSC Configuration script. /// </summary> [Input("contentEmbedded")] public Input<string>? ContentEmbedded { get; set; } /// <summary> /// Description to go with DSC Configuration. /// </summary> [Input("description")] public Input<string>? Description { get; set; } /// <summary> /// Must be the same location as the Automation Account. /// </summary> [Input("location")] public Input<string>? Location { get; set; } /// <summary> /// Verbose log option. /// </summary> [Input("logVerbose")] public Input<bool>? LogVerbose { get; set; } /// <summary> /// Specifies the name of the DSC Configuration. Changing this forces a new resource to be created. /// </summary> [Input("name")] public Input<string>? Name { get; set; } /// <summary> /// The name of the resource group in which the DSC Configuration is created. Changing this forces a new resource to be created. /// </summary> [Input("resourceGroupName")] public Input<string>? ResourceGroupName { get; set; } [Input("state")] public Input<string>? State { get; set; } [Input("tags")] private InputMap<string>? _tags; /// <summary> /// A mapping of tags to assign to the resource. /// </summary> public InputMap<string> Tags { get => _tags ?? (_tags = new InputMap<string>()); set => _tags = value; } public DscConfigurationState() { } } }
38.317073
253
0.598875
[ "ECL-2.0", "Apache-2.0" ]
ScriptBox99/pulumi-azure
sdk/dotnet/Automation/DscConfiguration.cs
9,426
C#
using FastFoodRestaurant.Controllers; using FastFoodRestaurant.Views.UserControls; using FastFoodRestaurant.Views.UserControls.CollectionControlPages; using System; using System.Windows.Forms; namespace FastFoodRestaurant { public partial class MainView : Form { // Initialize Controllers. MainViewController mainController = new MainViewController(); CollectionController collectionController = new CollectionController(); public MainView() { InitializeComponent(); } private void HomeButton_Click(object sender, EventArgs e) { // Control the swap of red side panel between buttons on click. mainController.SidePanelSwapOnClick(HomeButton, SidePanel); // Bring to the front user control. PromoControl.BringToFront(); } private void EatButton_Click(object sender, EventArgs e) { mainController.SidePanelSwapOnClick(EatButton, SidePanel); EatControl.BringToFront(); } private void CollectionButton_Click(object sender, EventArgs e) { mainController.SidePanelSwapOnClick(CollectionButton, SidePanel); CollectionControl.BringToFront(); // Invoke the Collection itself to set state of usercontrols to false. CollectionControl.CollectionControl_Load(CollectionControl, e); } private void DeliveryButton_Click(object sender, EventArgs e) { mainController.SidePanelSwapOnClick(DeliveryButton, SidePanel); DeliveryControlPage.BringToFront(); } private void TakeButton_Click(object sender, EventArgs e) { mainController.SidePanelSwapOnClick(TakeButton, SidePanel); takeAwayControl1.BringToFront(); } private void DriverPayButton_Click(object sender, EventArgs e) { mainController.SidePanelSwapOnClick(DriverPayButton, SidePanel); DriverPayControl.BringToFront(); } private void CustomersButton_Click(object sender, EventArgs e) { mainController.SidePanelSwapOnClick(CustomersButton, SidePanel); customersControl1.BringToFront(); } private void CloseButton_Click(object sender, EventArgs e) { Environment.Exit(0); } private void MaximizeButton_Click(object sender, EventArgs e) { if(WindowState == FormWindowState.Normal) { WindowState = FormWindowState.Maximized; } else { WindowState = FormWindowState.Normal; } } private void MinimizeButton_Click(object sender, EventArgs e) { WindowState = FormWindowState.Minimized; } private void FacebookButton_Click(object sender, EventArgs e) { // System.Diagnostics.Process.Start("https://www.facebook.com/"); } private void InstagramButton_Click(object sender, EventArgs e) { // System.Diagnostics.Process.Start("https://www.instagram.com/"); } private void TwitterButton_Click(object sender, EventArgs e) { // System.Diagnostics.Process.Start("https://twitter.com/"); } private void ShoppingCart_Click(object sender, EventArgs e) { ShoppingCartControl.BringToFront(); ShoppingCart.BringToFront(); } } }
32.216216
82
0.628076
[ "BSD-3-Clause" ]
viniciusmorgado/FastFoodRestaurant
preview/Views/MainView.cs
3,578
C#
//****************************************************************************************************** // D3Series.cs - Gbtc // // Copyright © 2020, Grid Protection Alliance. All Rights Reserved. // // Licensed to the Grid Protection Alliance (GPA) under one or more contributor license agreements. See // the NOTICE file distributed with this work for additional information regarding copyright ownership. // The GPA licenses this file to you under the MIT License (MIT), the "License"; you may not use this // file except in compliance with the License. You may obtain a copy of the License at: // // http://opensource.org/licenses/MIT // // Unless agreed to in writing, the subject software distributed under the License is distributed on an // "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the // License for the specific language governing permissions and limitations. // // Code Modification History: // ---------------------------------------------------------------------------------------------------- // 08/10/2020 - C. Lackner // Generated original version of source code. // //****************************************************************************************************** using GSF; using GSF.Data.Model; using GSF.Web; using GSF.Web.Model; using System; using System.Web; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; namespace OpenSEE.Model { /// <summary> /// Defines a Data Series that can be plotteg on a Graph. /// </summary> public class D3Series { #region [ Constructors ] /// <summary> /// Creates a new <see cref="D3Series"/>. /// </summary> public D3Series() { this.LegendHorizontal = ""; this.LegendVertical = ""; this.LegendClass = ""; this.SecondaryLegendClass = ""; this.ChannelID = 0; } #endregion #region [ Properties ] /// <summary> /// Label of this Channel /// </summary> public string ChartLabel; // -> not sure We need this one /// <summary> /// Group used to determine buttons on top of the Legend /// </summary> public string LegendGroup;// -> Button on Top /// <summary> /// Horizontal Legend Category /// </summary> public string LegendHorizontal; // => Horizontal Category /// <summary> /// Vertical Legend Category /// </summary> public string LegendVertical; // => Vertical category /// <summary> /// Unit of the Channel /// </summary> public string Unit; /// <summary> /// Color of the Channel /// </summary> public string Color; /// <summary> /// Group used to determine vertical category - if applicable /// </summary> public string LegendVGroup; /// <summary> /// Base Value used for p.u. computations /// </summary> public double BaseValue; /// <summary> /// Datapoints /// </summary> public List<double[]> DataPoints = new List<double[]>(); /// <summary> /// Markes to indicate specific points - if applicable /// </summary> public List<double[]> DataMarker = new List<double[]>(); #endregion // ---------------------- These Are unneccesarry ------------------- public string LegendClass; public string SecondaryLegendClass; public int ChannelID; } }
31.252101
105
0.535359
[ "MIT" ]
GridProtectionAlliance/openSEE
src/OpenSEE/Model/D3Series.cs
3,722
C#
using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace Nest { [JsonConverter(typeof(StringEnumConverter))] public enum RangeRelation { [EnumMember(Value="within")] Within, [EnumMember(Value="contains")] Contains, [EnumMember(Value="intersects")] Intersects } }
21.4
45
0.766355
[ "Apache-2.0" ]
Tchami/elasticsearch-net
src/Nest/QueryDsl/TermLevel/Range/RangeRelation.cs
323
C#
/* Copyright (c) 2011-2020 Oleg Zee 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.IO; using System.Linq; using System.Text; namespace NEbml.Core { /// <summary> /// Writes EBML file /// </summary> public class EbmlWriter { protected readonly Stream _stream; /// <summary> /// Initializes a new instance of the EbmlWriter class /// </summary> /// <param name="stream"></param> public EbmlWriter(Stream stream) { _stream = stream ?? throw new ArgumentNullException(nameof(stream)); } /// <summary> /// Starts nested stream. Upon disposal of nested stream, the size is calculated and written to nested element header. /// Example: /// using(var data = writer.StartMasterElement(InnerDataElementId)) /// { /// data.WriteInt(DataItem1Id, 139874) /// data.WriteUtf(DataItem2Id, "Hello world"); /// } /// </summary> /// <param name="elementId"></param> /// <returns></returns> public MasterBlockWriter StartMasterElement(VInt elementId) { return new MasterBlockWriter(this, elementId); } /// <summary> /// Writes element header /// </summary> /// <param name="elementId"></param> /// <param name="size"></param> /// <returns></returns> public int WriteElementHeader(VInt elementId, VInt size) { return elementId.Write(_stream) + size.Write(_stream); } #region Writing atomic elements /// <summary> /// Writes signed integer value /// </summary> /// <param name="elementId"></param> /// <param name="value"></param> /// <returns></returns> public int Write(VInt elementId, long value) { var length = value == 0 ? 0u : 1u; unchecked { var mask = (long)0xffffffffffffff80L; for (var expected = value < 0L ? mask : 0L; length < 8 && (mask & value) != expected; mask <<= 8, expected <<= 8) { length++; } } return elementId.Write(_stream) + EncodeWidth(length).Write(_stream) + WriteInt(value, length); } /// <summary> /// Writes unsigned integer value /// </summary> /// <param name="elementId"></param> /// <param name="value"></param> /// <returns></returns> public int Write(VInt elementId, ulong value) { var length = 0u; for (var mask = UInt64.MaxValue; (value & mask) != 0 && length < 8; mask <<= 8) { length++; } return elementId.Write(_stream) + EncodeWidth(length).Write(_stream) + WriteUInt(value, length); } /// <summary> /// Writes datetime value /// </summary> /// <param name="elementId"></param> /// <param name="dateTime"></param> /// <returns></returns> public int Write(VInt elementId, DateTime dateTime) { var d = (dateTime - EbmlReader.MilleniumStart).Ticks * 100; return elementId.Write(_stream) + EncodeWidth(8).Write(_stream) + WriteInt(d, 8); } /// <summary> /// Writes floating point number /// </summary> /// <param name="elementId"></param> /// <param name="value"></param> /// <returns></returns> public int Write(VInt elementId, float value) { var u = new Union {fval = value}.uival; return elementId.Write(_stream) + EncodeWidth(4).Write(_stream) + WriteInt(u, 4); } /// <summary> /// Writes floating point number with double precision /// </summary> /// <param name="elementId"></param> /// <param name="value"></param> /// <returns></returns> public int Write(VInt elementId, double value) { var u = new Union { dval = value }.ulval; return elementId.Write(_stream) + EncodeWidth(8).Write(_stream) + WriteUInt(u, 8); } /// <summary> /// Writes binary data /// </summary> /// <param name="elementId"></param> /// <param name="data"></param> /// <param name="offset"></param> /// <param name="length"></param> /// <returns></returns> public int Write(VInt elementId, byte[] data, int offset, int length) { var headLen = elementId.Write(_stream) + EncodeWidth((uint) length).Write(_stream); _stream.Write(data, offset, length); return headLen + length; } /// <summary> /// Writes binary data /// </summary> /// <param name="elementId"></param> /// <param name="data"></param> /// <returns></returns> public int Write(VInt elementId, byte[] data) { return Write(elementId, data, 0, data.Length); } /// <summary> /// Writes string in ASCII encoding /// </summary> /// <param name="elementId"></param> /// <param name="value"></param> /// <returns></returns> public int WriteAscii(VInt elementId, string value) { if (value == null) throw new ArgumentNullException(nameof(value)); var buffer = string.IsNullOrEmpty(value) ? new byte[0] : Encoding.ASCII.GetBytes(value); return Write(elementId, buffer, 0, buffer.Length); } /// <summary> /// Writes string in UTF-8 encoding /// </summary> /// <param name="elementId"></param> /// <param name="value"></param> /// <returns></returns> public int WriteUtf(VInt elementId, string value) { if (value == null) throw new ArgumentNullException(nameof(value)); if (!value.IsNormalized(NormalizationForm.FormC)) { value = value.Normalize(NormalizationForm.FormC); } var buffer = string.IsNullOrEmpty(value) ? new byte[0] : Encoding.UTF8.GetBytes(value); return Write(elementId, buffer, 0, buffer.Length); } /// <summary> /// Writes raw binary data /// </summary> /// <param name="buffer"></param> /// <param name="offset"></param> /// <param name="length"></param> /// <returns></returns> public int Write(byte[] buffer, int offset, int length) { _stream.Write(buffer, offset, length); return length; } #endregion #region Implementation private int WriteInt(Int64 value, uint length) { if(length > 8) throw new ArgumentOutOfRangeException(nameof(length)); if (value == 0 && length == 0) return 0; var buffer = new byte[length]; var p = (int)length; for (var data = value; --p >= 0; data >>= 8) { buffer[p] = (byte)(data & 0xff); } return Write(buffer, 0, (int)length); } private int WriteUInt(UInt64 value, uint length) { if (length > 8) throw new ArgumentOutOfRangeException(nameof(length)); if (value == 0 && length == 0) return 0; var buffer = new byte[length]; var p = (int)length; for (var data = value; --p >= 0; data >>= 8) { buffer[p] = (byte)(data & 0xff); } return Write(buffer, 0, (int) length); } [ThreadStatic] // avoid thread sync code private static VInt[] __smallSizes; private const int CachedWidthCount = 20; private static VInt EncodeWidth(uint width) { if (__smallSizes == null) { __smallSizes = Enumerable.Range(0, CachedWidthCount).Select(i => VInt.EncodeSize((ulong)i)).ToArray(); } return width < CachedWidthCount ? __smallSizes[width] : VInt.EncodeSize(width); } #endregion } }
29.763838
121
0.633152
[ "MIT" ]
OlegZee/NEbml
Src/Core/EbmlWriter.cs
8,068
C#
namespace AlgorithmsProvider.Models { public class HorspoolModel { public string InputString { get; set; } public string SearchString { get; set; } public int NumberOfLine { get; set; } public bool IsFound { get; set; } } }
26.8
48
0.619403
[ "Apache-2.0" ]
Kralizets/Algorithms
AlgorithmsProvider/Models/HorspoolModel.cs
270
C#
using System; using System.Collections.Generic; using System.Linq; internal class ArrayManipulator { private static void Main() { List<short> input = Console.ReadLine() .Split(new char[] { ' ' }, StringSplitOptions .RemoveEmptyEntries) .Select(short.Parse) .ToList(); string[] commands = Console.ReadLine() .Split(new char[] { ' ' }, StringSplitOptions .RemoveEmptyEntries) .ToArray(); while (commands[0] != "print") { short commandsLength = (short)commands.Length; short indexOrElementOrPosition = 0; if (commandsLength > 1) { indexOrElementOrPosition = short.Parse(commands[1]); } switch (commands[0]) { case "add": input.Insert(indexOrElementOrPosition, short.Parse(commands[2])); break; case "addMany": input.InsertRange(indexOrElementOrPosition, commands .Skip(2) .Select(short.Parse) .ToArray()); break; case "contains": Console.WriteLine(input.IndexOf(indexOrElementOrPosition)); break; case "remove": input.RemoveAt(indexOrElementOrPosition); break; case "shift": for (short i = 0; i < indexOrElementOrPosition % input.Count; i++) { input.Add(input[0]); input.RemoveAt(0); } break; case "sumPairs": for (short i = 0; i < input.Count - 1; i++) { input[i] += input[i + 1]; input.RemoveAt(i + 1); } break; } commands = Console.ReadLine() .Split(new char[] { ' ' }, StringSplitOptions .RemoveEmptyEntries) .ToArray(); } Console.WriteLine("[" + string.Join(", ", input) + "]"); } }
30.181818
86
0.427711
[ "MIT" ]
lapd87/SoftUniProgrammingFundamentalsCSharp
ProgrammingFundamentalsCSharp/07Lists/05ArrayManipulator/ArrayManipulator.cs
2,326
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace FlagsHW.Properties { /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if ((resourceMan == null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("FlagsHW.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } } }
38.486111
173
0.601949
[ "MIT" ]
mxttwoods/ISM240-ClassMaterial
archive/ISM240HW1/FlagsHW/Properties/Resources.Designer.cs
2,773
C#
/* * 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. */ using System.Collections.Generic; using Aliyun.Acs.Core; namespace Aliyun.Acs.digitalstore.Model.V20200107 { public class GrantRightsResponse : AcsResponse { private string userId; private string requestId; private bool? success; public string UserId { get { return userId; } set { userId = value; } } public string RequestId { get { return requestId; } set { requestId = value; } } public bool? Success { get { return success; } set { success = value; } } } }
20.15493
63
0.663173
[ "Apache-2.0" ]
AxiosCros/aliyun-openapi-net-sdk
aliyun-net-sdk-digitalstore/Digitalstore/Model/V20200107/GrantRightsResponse.cs
1,431
C#
using System; using System.Collections.Generic; using System.Reflection; using System.Xml.Linq; using Mono.Cecil; namespace Project { public sealed class Reference: Item { private XElement _originalItemElement; public string Include { get; private set; } public Version ReferenceAssemblyVersion { get; private set; } public Reference CloneWith( string include = null, Version version = null ) { Reference copy = (Reference) MemberwiseClone(); if ( include != null ) { copy.Include = include; copy._originalItemElement = null; } if ( version != null ) { copy.ReferenceAssemblyVersion = version; copy._originalItemElement = null; } return copy; } public string ReferenceAssemblyFullName { get; private set; } public string ReferenceAssemblyName { get; private set; } public AssemblyName GetAssemblyName() { return new AssemblyName( Include ); } public bool? SpecificVersion { get; private set; } public string HintPath { get; private set; } public bool? Private { get; private set; } public string RequiredTargetFramework { get; private set; } public string Name { get; private set; } public bool? EmbedInteropTypes { get; private set; } public string Aliases { get; private set; } public string FusionName { get; private set; } // In case we cannot parse the assembly name we fall back to the full assembly name. public override string Key => ReferenceAssemblyName ?? ReferenceAssemblyFullName; public override string ToString() { var propertyNames = new List<string>(); propertyNames.Add( Include ); propertyNames.AddPropertyIfNotNull( HintPath, "HintPath" ); propertyNames.AddPropertyIfNotNull( Private, "Private" ); propertyNames.AddPropertyIfNotNull( SpecificVersion, "SpecificVersion" ); propertyNames.AddPropertyIfNotNull( RequiredTargetFramework, "RequiredTargetFramework" ); return string.Join( Environment.NewLine, propertyNames ); } public override bool Equals( Item other ) { return Equals( (object) other ); } public override XElement ToElement( XNamespace ns ) { if ( _originalItemElement != null ) { return _originalItemElement; } XElement e = new XElement( ns.GetName( Action ) ); e.Add( new XAttribute( "Include", Include ) ); e.AddElement( "Name", Name ); e.AddElement( "FusionName", FusionName ); e.AddElement( "HintPath", HintPath ); e.AddElement( "Private", Private ); e.AddElement( "EmbedInteropTypes", EmbedInteropTypes ); e.AddElement( "Aliases", Aliases ); e.AddElement( "SpecificVersion", SpecificVersion ); e.AddElement( "RequiredTargetFramework", RequiredTargetFramework ); return e; } private static void AddElement( XElement parent, string elementName, object value ) { if ( value != null ) { parent.Add( new XElement( parent.Name.Namespace.GetName( elementName ), value ) ); } } public bool Equals( Reference other ) { if ( ReferenceEquals( null, other ) ) { return false; } if ( ReferenceEquals( this, other ) ) { return true; } return string.Equals( HintPath, other.HintPath ) && SpecificVersion == other.SpecificVersion && string.Equals( Include, other.Include ); } public override bool Equals( object obj ) { if ( ReferenceEquals( null, obj ) ) { return false; } if ( ReferenceEquals( this, obj ) ) { return true; } return obj.GetType() == GetType() && Equals( (Reference) obj ); } public override int GetHashCode() { unchecked { var hashCode = HintPath?.GetHashCode() ?? 0; hashCode = ( hashCode * 397 ) ^ SpecificVersion.GetHashCode(); hashCode = ( hashCode * 397 ) ^ ( Include?.GetHashCode() ?? 0 ); return hashCode; } } public Reference( XElement originalItemElement ) { _originalItemElement = originalItemElement; Include = originalItemElement.Attribute( "Include" ).Value; SetAssemblyName( Include ); Name = originalItemElement.SameNsElement( "Name" ).GetValueOrNull(); EmbedInteropTypes = originalItemElement.SameNsElement( "EmbedInteropTypes" ).GetBoolOrNull(); Aliases = originalItemElement.SameNsElement( "Aliases" ).GetValueOrNull(); FusionName = originalItemElement.SameNsElement( "FusionName" ).GetValueOrNull(); RequiredTargetFramework = originalItemElement.SameNsElement( "RequiredTargetFramework" ).GetValueOrNull(); Private = originalItemElement.SameNsElement( "Private" ).GetBoolOrNull(); SpecificVersion = originalItemElement.SameNsElement( "SpecificVersion" ).GetBoolOrNull(); HintPath = originalItemElement.SameNsElement( "HintPath" ).GetValueOrNull(); } private void SetAssemblyName( string include ) { if ( string.IsNullOrEmpty( include ) ) { return; } try { AssemblyNameReference reference = AssemblyNameReference.Parse( include ); ReferenceAssemblyVersion = reference.Version; ReferenceAssemblyFullName = reference.FullName; ReferenceAssemblyName = reference.Name; } catch ( Exception ) { // Sometimes we cannot parse the full name due say $(MyVersion) in the project file // so for now we use this hack. ReferenceAssemblyFullName = Include.Split( new[] { ',' }, StringSplitOptions.RemoveEmptyEntries )[0]; ReferenceAssemblyVersion = null; } } public Reference( string include, bool? specificVersion, bool? @private, string hintPath ) { Include = include; SetAssemblyName( Include ); SpecificVersion = specificVersion; Private = @private; HintPath = hintPath; } private Reference() { } public Reference Clone() { return new Reference { Include = Include, SpecificVersion = SpecificVersion, Private = Private, HintPath = HintPath, Aliases = Aliases, EmbedInteropTypes = EmbedInteropTypes, FusionName = FusionName, Name = Name, RequiredTargetFramework = RequiredTargetFramework, }; } } }
34.086022
112
0.656782
[ "MIT" ]
configit-open-source/csmerge
Project/Reference.cs
6,340
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Indentation; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editor.UnitTests.Formatting; using Microsoft.CodeAnalysis.Editor.UnitTests.Utilities; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Formatting.Rules; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Text; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Formatting.Indentation { [UseExportProvider] public class CSharpFormatterTestsBase : CoreFormatterTestsBase { protected const string HtmlMarkup = @"<html> <body> <%{|S1:|}%> </body> </html>"; protected const int BaseIndentationOfNugget = 8; internal override string GetLanguageName() => LanguageNames.CSharp; protected static async Task<int> GetSmartTokenFormatterIndentationWorkerAsync( TestWorkspace workspace, ITextBuffer buffer, int indentationLine, char ch) { await TokenFormatWorkerAsync(workspace, buffer, indentationLine, ch); return buffer.CurrentSnapshot.GetLineFromLineNumber(indentationLine).GetColumnOfFirstNonWhitespaceCharacterOrEndOfLine(TestEditorOptions.Instance); } protected static async Task<string> TokenFormatAsync( TestWorkspace workspace, ITextBuffer buffer, int indentationLine, char ch) { await TokenFormatWorkerAsync(workspace, buffer, indentationLine, ch); return buffer.CurrentSnapshot.GetText(); } private static async Task TokenFormatWorkerAsync(TestWorkspace workspace, ITextBuffer buffer, int indentationLine, char ch) { var document = buffer.CurrentSnapshot.GetRelatedDocumentsWithChanges().First(); var root = (CompilationUnitSyntax)await document.GetSyntaxRootAsync(); var line = root.GetText().Lines[indentationLine]; var index = line.ToString().LastIndexOf(ch); Assert.InRange(index, 0, int.MaxValue); // get token var position = line.Start + index; var token = root.FindToken(position); var formattingRuleProvider = workspace.Services.GetService<IHostDependentFormattingRuleFactoryService>(); var rules = formattingRuleProvider.CreateRule(document, position).Concat(Formatter.GetDefaultFormattingRules(document)); var documentOptions = await document.GetOptionsAsync(); var formatter = new CSharpSmartTokenFormatter(documentOptions, rules, root); var changes = await formatter.FormatTokenAsync(workspace, token, CancellationToken.None); ApplyChanges(buffer, changes); } private static void ApplyChanges(ITextBuffer buffer, IList<TextChange> changes) { using var edit = buffer.CreateEdit(); foreach (var change in changes) { edit.Replace(change.Span.ToSpan(), change.NewText); } edit.Apply(); } protected async Task<int> GetSmartTokenFormatterIndentationAsync( string code, int indentationLine, char ch, int? baseIndentation = null, TextSpan span = default) { // create tree service using var workspace = TestWorkspace.CreateCSharp(code); if (baseIndentation.HasValue) { var factory = workspace.Services.GetService<IHostDependentFormattingRuleFactoryService>() as TestFormattingRuleFactoryServiceFactory.Factory; factory.BaseIndentation = baseIndentation.Value; factory.TextSpan = span; } var buffer = workspace.Documents.First().GetTextBuffer(); return await GetSmartTokenFormatterIndentationWorkerAsync(workspace, buffer, indentationLine, ch); } } }
38.525424
161
0.678619
[ "Apache-2.0" ]
GigabyteUB1B1/roslyn
src/EditorFeatures/CSharpTest/Formatting/Indentation/CSharpFormatterTestsBase.cs
4,548
C#
// Copyright (c) 2009, Semyon A. Chertkov (semyonc@gmail.com) // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of author nor the // names of its contributors may be used to endorse or promote products // derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL AUTHOR BE LIABLE FOR ANY // DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using System; using DataEngine.CoreServices; namespace DataEngine.XQuery { public class XQueryParameter { public XQueryParameter() { } public XQueryParameter(String localName, Object value) : this(localName, String.Empty, value) { } public XQueryParameter(String localName, String namespaceUri, Object value) { LocalName = localName; NamespaceUri = namespaceUri; Value = value; } public String LocalName { get; set; } public String NamespaceUri { get; set; } public object Value { get; set; } internal object ID { get; set; } } }
42.172414
88
0.637367
[ "BSD-3-Clause" ]
3rdandUrban-dev/Nuxleus
src/Xameleon/QueryMachine/QueryMachine.XQuery/XQueryParameter.cs
2,448
C#
using AmuletOfManyMinions.Projectiles.Minions.MinonBaseClasses; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using System; using Terraria; using Terraria.ID; using Terraria.ModLoader; using static Terraria.ModLoader.ModContent; namespace AmuletOfManyMinions.Projectiles.Minions.EclipseHerald { public class EclipseHeraldMinionBuff : MinionBuff { public EclipseHeraldMinionBuff() : base(ProjectileType<EclipseHeraldCounterMinion>()) { } public override void SetDefaults() { base.SetDefaults(); DisplayName.SetDefault("Eclipse Herald"); Description.SetDefault("A herald of the eclipse will fight for you!"); } } public class EclipseHeraldMinionItem : MinionItem<EclipseHeraldMinionBuff, EclipseHeraldCounterMinion> { public override void SetStaticDefaults() { base.SetStaticDefaults(); DisplayName.SetDefault("Eclipse Herald Staff"); Tooltip.SetDefault("Can't come to grips \nWith the total eclipse \nJust a slip of your lips \nand you're gone..."); } public override void SetDefaults() { base.SetDefaults(); item.knockBack = 3f; item.mana = 10; item.width = 32; item.height = 32; item.damage = 55; item.value = Item.buyPrice(0, 20, 0, 0); item.rare = ItemRarityID.Red; } public override void AddRecipes() { ModRecipe recipe = new ModRecipe(mod); recipe.AddIngredient(ItemID.FragmentSolar, 18); recipe.AddTile(TileID.LunarCraftingStation); recipe.SetResult(this); recipe.AddRecipe(); } } public class EclipseHeraldCounterMinion : CounterMinion { internal override int BuffId => BuffType<EclipseHeraldMinionBuff>(); protected override int MinionType => ProjectileType<EclipseHeraldMinion>(); } /// <summary> /// Uses ai[1] to track animation frames /// </summary> public class EclipseHeraldMinion : EmpoweredMinion { internal override int BuffId => BuffType<EclipseHeraldMinionBuff>(); private int framesSinceLastHit; private const int AnimationFrames = 120; protected override int dustType => DustID.GoldFlame; protected override int CounterType => ProjectileType<EclipseHeraldCounterMinion>(); public override void SetStaticDefaults() { base.SetStaticDefaults(); DisplayName.SetDefault("Eclipse Herald"); // Sets the amount of frames this minion has on its spritesheet Main.projFrames[projectile.type] = 9; IdleLocationSets.trailingInAir.Add(projectile.type); } public sealed override void SetDefaults() { base.SetDefaults(); projectile.width = 66; projectile.height = 60; projectile.tileCollide = false; framesSinceLastHit = 0; projectile.friendly = true; attackThroughWalls = true; useBeacon = false; frameSpeed = 5; } private Color ShadowColor(Color original) { return new Color(original.R / 2, original.G / 2, original.B / 2); } private void DrawSuns(SpriteBatch spriteBatch, Color lightColor) { Vector2 pos = projectile.Center; pos.Y -= 24; pos.X -= 8 * projectile.spriteDirection; float r = (float)(2 * Math.PI * projectile.ai[1]) / AnimationFrames; int index = Math.Min(5, (int)EmpowerCount - 1); Rectangle bounds = new Rectangle(0, 64 * index, 64, 64); Vector2 origin = new Vector2(bounds.Width / 2, bounds.Height / 2); Texture2D texture = Main.projectileTexture[ProjectileType<EclipseSphere>()]; // main spriteBatch.Draw(texture, pos - Main.screenPosition, bounds, lightColor, r, origin, 1, 0, 0); } private void DrawShadows(SpriteBatch spriteBatch, Color lightColor) { Vector2 pos = projectile.Center; pos.Y -= 4; // don't know why this offset needs to exist Rectangle bounds = new Rectangle(0, 52 * projectile.frame, 66, 52); Vector2 origin = new Vector2(bounds.Width / 2, bounds.Height / 2); Color shadowColor = ShadowColor(lightColor); Texture2D texture = Main.projectileTexture[projectile.type]; SpriteEffects effects = projectile.spriteDirection == 1 ? 0 : SpriteEffects.FlipHorizontally; // echo 1 float offset = 2f * (float)Math.Sin(Math.PI * (projectile.ai[1] % 60) / 30); spriteBatch.Draw(texture, pos - Main.screenPosition + Vector2.One * offset, bounds, shadowColor, projectile.rotation, origin, 1, effects, 0); // echo 2 spriteBatch.Draw(texture, pos - Main.screenPosition - Vector2.One * offset, bounds, shadowColor, projectile.rotation, origin, 1, effects, 0); } public override bool PreDraw(SpriteBatch spriteBatch, Color lightColor) { projectile.ai[1] = (projectile.ai[1] + 1) % AnimationFrames; DrawSuns(spriteBatch, lightColor); DrawShadows(spriteBatch, lightColor); return true; } public override Vector2 IdleBehavior() { base.IdleBehavior(); Vector2 idlePosition = player.Top; idlePosition.X += -player.direction * IdleLocationSets.GetXOffsetInSet(IdleLocationSets.trailingInAir, projectile); idlePosition.Y += -32; if (!Collision.CanHitLine(idlePosition, 1, 1, player.Center, 1, 1)) { idlePosition.X = player.Top.X; idlePosition.Y = player.Top.Y - 16; } Vector2 vectorToIdlePosition = idlePosition - projectile.Center; TeleportToPlayer(ref vectorToIdlePosition, 2000f); return vectorToIdlePosition; } public override void IdleMovement(Vector2 vectorToIdlePosition) { base.IdleMovement(vectorToIdlePosition); Lighting.AddLight(projectile.position, Color.White.ToVector3() * 0.5f); } public override void TargetedMovement(Vector2 vectorToTargetPosition) { // stay floating behind the player at all times IdleMovement(vectorToIdle); framesSinceLastHit++; if (framesSinceLastHit++ > 60 && targetNPCIndex is int npcIndex) { vectorToTargetPosition.SafeNormalize(); vectorToTargetPosition *= 8; Vector2 pos = projectile.Center; pos.Y -= 24; if (Main.myPlayer == player.whoAmI) { Projectile.NewProjectile( pos, vectorToTargetPosition, ProjectileType<EclipseSphere>(), projectile.damage, projectile.knockBack, Main.myPlayer, EmpowerCount - 1, npcIndex); } framesSinceLastHit = 0; } } protected override int ComputeDamage() { return baseDamage / 2 + (baseDamage / 2) * (int)EmpowerCount; } private Vector2? GetTargetVector() { float searchDistance = ComputeSearchDistance(); if (PlayerTargetPosition(searchDistance, player.Center, searchDistance / 2) is Vector2 target) { return target - projectile.Center; } else if (SelectedEnemyInRange(searchDistance, searchDistance / 2) is Vector2 target2) { return target2 - projectile.Center; } else { return null; } } public override Vector2? FindTarget() { Vector2? target = GetTargetVector(); return target; } protected override float ComputeSearchDistance() { return 700 + 100 * EmpowerCount; } protected override float ComputeInertia() { return 5; } protected override float ComputeTargetedSpeed() { return 16; } protected override float ComputeIdleSpeed() { return 16; } protected override void SetMinAndMaxFrames(ref int minFrame, ref int maxFrame) { if (vectorToTarget != null) { minFrame = 5; maxFrame = 9; } else if (projectile.velocity.Y < 3) { minFrame = 0; maxFrame = 4; } else { minFrame = 4; maxFrame = 4; } } public override void Animate(int minFrame = 0, int? maxFrame = null) { base.Animate(minFrame, maxFrame); if (Math.Abs(projectile.velocity.X) > 2) { projectile.spriteDirection = projectile.velocity.X > 0 ? 1 : -1; } projectile.rotation = projectile.velocity.X * 0.05f; } } }
28.75188
118
0.705936
[ "MIT" ]
TheBambino/tModLoader_Minions
Projectiles/Minions/EclipseHerald/EclipseHerald.cs
7,650
C#
using Newtonsoft.Json; namespace io.nem2.sdk.Infrastructure.Buffers.Model { public class MultisigAccountInfoDTO { [JsonProperty("multisig")] public MultisigDTO Multisig { get; set; } } }
19.727273
50
0.677419
[ "Apache-2.0" ]
SoloEnergy/nem2-sdk-csharp
src/nem2-sdk/src/Infrastructure/Buffers/Model/MultisigInfoDTO.cs
219
C#
namespace MrRobot.Core.Boundaries.Clean { public sealed class Response { public int UniquePlacesCleaned { get; } public Response(int uniquePlacesCleaned) { UniquePlacesCleaned = uniquePlacesCleaned; } } }
23.636364
54
0.634615
[ "Apache-2.0" ]
ivanpaulovich/MrRobot
source/MrRobot.Core/Boundaries/Clean/Response.cs
260
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("Person")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Person")] [assembly: AssemblyCopyright("Copyright © 2015")] [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("5b6deea1-25a3-4700-9cc3-134ac26ae1e3")] // 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.432432
84
0.74296
[ "MIT" ]
mdraganov/Telerik-Academy
C#/OOP/CommonTypeSystem/Person/Properties/AssemblyInfo.cs
1,388
C#
using System; using System.Text.RegularExpressions; using Coypu.Drivers; using Coypu.Drivers.Selenium; using NUnit.Framework; using OpenQA.Selenium; namespace Coypu.AcceptanceTests { [TestFixture] public class ExternalExamples { private SessionConfiguration SessionConfiguration; private BrowserSession browser; [SetUp] public void SetUp() { SessionConfiguration = new SessionConfiguration(); SessionConfiguration.AppHost = "www.google.com"; SessionConfiguration.Driver = typeof(SeleniumWebDriver); SessionConfiguration.Timeout = TimeSpan.FromSeconds(10); browser = new BrowserSession(SessionConfiguration); } [TearDown] public void TearDown() { browser.Dispose(); } [Test] public void AppHostContainsScheme() { SessionConfiguration = new SessionConfiguration(); SessionConfiguration.AppHost = "https://www.google.co.uk/"; SessionConfiguration.Driver = typeof(SeleniumWebDriver); browser = new BrowserSession(SessionConfiguration); browser.Visit("/"); Assert.That(browser.Location.ToString(), Is.EqualTo("https://www.google.co.uk/")); } [Test, Explicit] public void Retries_Autotrader() { browser.Visit("http://www.autotrader.co.uk/used-cars"); browser.FillIn("postcode").With("N1 1AA"); browser.FindField("make").Click(); browser.Select("citroen").From("make"); browser.Select("c4_grand_picasso").From("model"); browser.Select("National").From("radius"); browser.Select("diesel").From("fuel-type"); browser.Select("up_to_7_years_old").From("maximum-age"); browser.Select("up_to_60000_miles").From("maximum-mileage"); browser.FillIn("Add keyword").With("vtr"); } [Test, Explicit] public void Visibility_NewTwitterLogin() { browser.Visit("http://www.twitter.com"); browser.FillIn("session[username_or_email]").With("coyputester2"); browser.FillIn("session[password]").With("Nappybara"); } [Test, Ignore("Make checkboxes on carbuzz are jumping around after you click each one. Re-enable when that is fixed")] public void FindingStuff_CarBuzz() { browser.Visit("http://carbuzz.heroku.com/car_search"); Console.WriteLine(browser.FindSection("Make").Exists()); Console.WriteLine(browser.FindSection("Bake").Exists()); browser.Check("Audi"); browser.Check("BMW"); browser.Check("Mercedes"); Assert.That(browser.HasContentMatch(new Regex(@"\b83 car reviews found"))); browser.FindSection("Seats").Click(); browser.ClickButton("4"); Assert.That(browser.HasContentMatch(new Regex(@"\b28 car reviews found"))); } [Test] public void HtmlUnitDriver() { SessionConfiguration.AppHost = "www.google.com"; SessionConfiguration.Browser = Drivers.Browser.HtmlUnit; try { using (var htmlUnit = new BrowserSession(SessionConfiguration)) { htmlUnit.Visit("/"); } Assert.Fail("Expected an exception attempting to connect to HtmlUnit driver"); } catch (WebDriverException e) { Assert.That(e.Message, Is.StringContaining("No connection could be made because the target machine actively refused it 127.0.0.1:4444")); } } } }
33.449153
154
0.568026
[ "Unlicense", "MIT" ]
KMASubhani/coypu
src/Coypu.AcceptanceTests/ExternalExamples.cs
3,949
C#
// // Copyright (C) 2015 crosire & contributors // License: https://github.com/crosire/scripthookvdotnet#license // namespace GTA { public interface IPedVariation { int Count { get; } int Index { get; set; } int TextureCount { get; } int TextureIndex { get; set; } string Name { get; } bool SetVariation(int index, int textureIndex = 0); bool IsVariationValid(int index, int textureIndex = 0); bool HasVariations { get; } bool HasTextureVariations { get; } bool HasAnyVariations { get; } } }
11.52
64
0.618056
[ "MIT" ]
cekkr/gtav-js
thirds/scripthookvdotnet-master/source/scripting_v3/GTA/Entities/Peds/IPedVariation.cs
576
C#
using System; using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo("PivotSecurity.IntegrationTests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100fda57af14a288d46e3efea89617037585c4de57159cd536ca6dff792ea1d6addc665f2fccb4285413d9d44db5a1be87cb82686db200d16325ed9c42c89cd4824d8cc447f7cee2ac000924c3bceeb1b7fcb5cc1a3901785964d48ce14172001084134f4dcd9973c3776713b595443b1064bb53e2eeb924969244d354e46495e9d"), InternalsVisibleTo("PivotSecurity.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100fda57af14a288d46e3efea89617037585c4de57159cd536ca6dff792ea1d6addc665f2fccb4285413d9d44db5a1be87cb82686db200d16325ed9c42c89cd4824d8cc447f7cee2ac000924c3bceeb1b7fcb5cc1a3901785964d48ce14172001084134f4dcd9973c3776713b595443b1064bb53e2eeb924969244d354e46495e9d")] [assembly: CLSCompliant(true)]
144.666667
396
0.942396
[ "Apache-2.0" ]
Pivotsecurity/pivotsecurity-dotnet
PivotSecurity/AssemblyInfo.cs
870
C#
using System.Collections.Generic; namespace WebForum.Entities { public class BoardEntity { public int Id { get; set; } public string Title { get; set; } public IEnumerable<ForumEntity> Forums { get; set; } } }
14.933333
54
0.696429
[ "MIT" ]
Zsombi55/CS_ASP.NET_Forum
MyWebForum/WebForum/Entities/BoardEntity.cs
226
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Runtime.InteropServices; using Microsoft.VisualStudio.LanguageServices.CSharp.CodeModel.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; namespace Microsoft.VisualStudio.LanguageServices.CSharp.CodeModel.Extenders { [ComVisible(true)] [ComDefaultInterface(typeof(ICSExtensionMethodExtender))] public class ExtensionMethodExtender : ICSExtensionMethodExtender { internal static ICSExtensionMethodExtender Create(bool isExtension) { var result = new ExtensionMethodExtender(isExtension); return (ICSExtensionMethodExtender)ComAggregate.CreateAggregatedObject(result); } private readonly bool _isExtension; private ExtensionMethodExtender(bool isExtension) { _isExtension = isExtension; } public bool IsExtension { get { return _isExtension; } } } }
34.53125
161
0.723077
[ "Apache-2.0" ]
20chan/roslyn
src/VisualStudio/CSharp/Impl/CodeModel/Extenders/ExtensionMethodExtender.cs
1,107
C#
//------------------------------------------------------------------------------ // <auto-generated> // このコードはツールによって生成されました。 // ランタイム バージョン:4.0.30319.42000 // // このファイルへの変更は、以下の状況下で不正な動作の原因になったり、 // コードが再生成されるときに損失したりします // </auto-generated> //------------------------------------------------------------------------------ namespace playSound.Properties { /// <summary> /// ローカライズされた文字列などを検索するための、厳密に型指定されたリソース クラスです。 /// </summary> // このクラスは StronglyTypedResourceBuilder クラスによって ResGen // または Visual Studio のようなツールを使用して自動生成されました。 // メンバーを追加または削除するには、.ResX ファイルを編集して、/str オプションと共に // ResGen を実行し直すか、または VS プロジェクトをリビルドします。 [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// このクラスで使用されるキャッシュされた ResourceManager インスタンスを返します。 /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if ((resourceMan == null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("playSound.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// 厳密に型指定されたこのリソース クラスを使用して、すべての検索リソースに対し、 /// 現在のスレッドの CurrentUICulture プロパティをオーバーライドします。 /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } } }
35.888889
175
0.599845
[ "MIT" ]
isudzumi/Per30minSound
playSound/Properties/Resources.Designer.cs
3,226
C#
using Abp.Application.Features; using Abp.Domain.Repositories; using Abp.Domain.Uow; using Abp.MultiTenancy; using Abp.Runtime.Caching; using ASPNetCoreAngularApp2.Authorization.Users; using ASPNetCoreAngularApp2.MultiTenancy; namespace ASPNetCoreAngularApp2.Features { public class FeatureValueStore : AbpFeatureValueStore<Tenant, User> { public FeatureValueStore( ICacheManager cacheManager, IRepository<TenantFeatureSetting, long> tenantFeatureRepository, IRepository<Tenant> tenantRepository, IRepository<EditionFeatureSetting, long> editionFeatureRepository, IFeatureManager featureManager, IUnitOfWorkManager unitOfWorkManager) : base( cacheManager, tenantFeatureRepository, tenantRepository, editionFeatureRepository, featureManager, unitOfWorkManager) { } } }
32.516129
79
0.657738
[ "MIT" ]
eduflornet/ASPNetCoreAngularApp2
aspnet-core/src/ASPNetCoreAngularApp2.Core/Features/FeatureValueStore.cs
1,008
C#
using System; using System.Collections.Generic; using System.Runtime; using System.Text; using System.Text.RegularExpressions; using System.Reflection; using System.IO; using System.Linq; namespace Libraries.Starlight { public interface IRule : ICloneable { string Name { get; } IProduction this[int index] { get; } int Count { get; } IEnumerable<IProduction> GetEnumerableInterface(); } ///<summary> /// Represents a rule that is fixed on a target production. /// This is not the same as an advancible rule because the actual /// production is not be advanced itself. ///</summary> public interface IFixedRule : IRule { int Offset { get; } IProduction Current { get; } new IProduction this[int index] { get; } int GetHashCode(); bool Equals(object other); } public interface IAdvanceableRule : IRule { new IAdvanceableProduction this[int index] { get; } bool Equals(object other); int GetHashCode(); new IEnumerable<IAdvanceableProduction> GetEnumerableInterface(); } }
25.3
67
0.733202
[ "BSD-3-Clause" ]
DrItanium/ImageProcessingApplication
src/lib/Starlight/IFixedRule.cs
1,012
C#
using System.Collections.Generic; using JetBrains.Annotations; using EasyAbp.Abp.TencentCloud.Common.Models; namespace EasyAbp.Abp.TencentCloud.CloudMonitor.BaseMonitor { public class GetMonitorDataRequest : CommonRequest { public GetMonitorDataRequest(string region, List<Instance> instances, string @namespace, string metricName, int? period = null, [CanBeNull] string startTime = null, [CanBeNull] string endTime = null) { SetAction("GetMonitorData"); SetVersion("2018-07-24"); SetRegion(region); SetRequestBody(new { Namespace = @namespace, MetricName = metricName, Instances = instances, Period = period, StartTime = startTime, EndTime = endTime }); } } public class Dimension { public string Name { get; set; } public string Value { get; set; } public Dimension(string name, string value) { Name = name; Value = value; } public Dimension() { } } public class Instance { public List<Dimension> Dimensions { get; set; } } }
24.648148
59
0.534185
[ "MIT" ]
EasyAbp/Abp.TencentCloud
src/EasyAbp.Abp.TencentCloud.CloudMonitor/BaseMonitor/GetMonitorDataRequest.cs
1,333
C#
namespace UsersData.Models.Attributes { using System; using System.ComponentModel.DataAnnotations; [AttributeUsage(AttributeTargets.Property)] public class TagAttribute : ValidationAttribute { protected override ValidationResult IsValid(object value, ValidationContext validationContext) { var valueAsString = (string) value; if (valueAsString[0] != '#') { return new ValidationResult($"Tag must start with '#'."); } foreach (var ch in valueAsString) { if (char.IsWhiteSpace(ch)) { return new ValidationResult($"Tag can not contain white spaces."); } } return ValidationResult.Success; } } }
28.413793
102
0.56068
[ "MIT" ]
pirocorp/Databases-Advanced---Entity-Framework
06. Advanced Relations/Exercises/UsersData/UsersData.Models/Attributes/TagAttribute.cs
826
C#
/* * * (c) Copyright Ascensio System Limited 2010-2021 * * 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.Web; using ASC.Common.Utils; using ASC.Files.Core; using ASC.Web.Core.Files; using ASC.Web.Files.Classes; using ASC.Web.Studio.Utility; using File = ASC.Files.Core.File; using FileShare = ASC.Files.Core.Security.FileShare; namespace ASC.Web.Files.Utils { public static class FileShareLink { public static string GetLink(File file, bool withHash = true) { var url = file.DownloadUrl; if (FileUtility.CanWebView(file.Title)) url = FilesLinkUtility.GetFileWebPreviewUrl(file.Title, file.ID); if (withHash) { var linkParams = CreateKey(file.ID.ToString()); url += "&" + FilesLinkUtility.DocShareKey + "=" + HttpUtility.UrlEncode(linkParams); } return CommonLinkUtility.GetFullAbsolutePath(url); } public static string CreateKey(string fileId) { return Signature.Create(fileId, Global.GetDocDbKey()); } public static string Parse(string doc) { return Signature.Read<string>(doc ?? String.Empty, Global.GetDocDbKey()); } public static bool Check(string doc, bool checkRead, IFileDao fileDao, out File file) { var fileShare = Check(doc, fileDao, out file); return (!checkRead && (fileShare == FileShare.ReadWrite || fileShare == FileShare.CustomFilter || fileShare == FileShare.Review || fileShare == FileShare.FillForms || fileShare == FileShare.Comment)) || (checkRead && fileShare != FileShare.Restrict); } public static FileShare Check(string doc, IFileDao fileDao, out File file) { file = null; if (string.IsNullOrEmpty(doc)) return FileShare.Restrict; var fileId = Parse(doc); file = fileDao.GetFile(fileId); if (file == null) return FileShare.Restrict; var filesSecurity = Global.GetFilesSecurity(); if (filesSecurity.CanEdit(file, FileConstant.ShareLinkId)) return FileShare.ReadWrite; if (filesSecurity.CanCustomFilterEdit(file, FileConstant.ShareLinkId)) return FileShare.CustomFilter; if (filesSecurity.CanReview(file, FileConstant.ShareLinkId)) return FileShare.Review; if (filesSecurity.CanFillForms(file, FileConstant.ShareLinkId)) return FileShare.FillForms; if (filesSecurity.CanComment(file, FileConstant.ShareLinkId)) return FileShare.Comment; if (filesSecurity.CanRead(file, FileConstant.ShareLinkId)) return FileShare.Read; return FileShare.Restrict; } } }
38.866667
114
0.621498
[ "Apache-2.0" ]
jeanluctritsch/CommunityServer
web/studio/ASC.Web.Studio/Products/Files/Utils/FileShareLink.cs
3,498
C#
// %BANNERBEGIN% // --------------------------------------------------------------------- // %COPYRIGHTBEGIN% // <copyright file="MLLocation.cs" company="Magic Leap"> // // Copyright (c) 2018-present, Magic Leap, Inc. All Rights Reserved. // // </copyright> // // %COPYRIGHTEND% // --------------------------------------------------------------------- // %BANNEREND% #if PLATFORM_LUMIN namespace UnityEngine.XR.MagicLeap { using System; using System.Runtime.InteropServices; /// <summary> /// MLLocation provides device location data including; Latitude, Longitude, and approximate Postal Code. /// Currently location is only received on Wi-Fi connect. If connection is lost, a new location will be /// provided on connect. /// </summary> public sealed partial class MLLocation : MLAPISingleton<MLLocation> { /// <summary> /// Gets a readable version of the result code as an ASCII string. /// </summary> /// <param name="resultCode">The MLResult that should be converted.</param> /// <returns>ASCII string containing a readable version of the result code.</returns> [Obsolete("Please use MLResult.CodeToString(MLResult.Code) instead.", true)] public static string GetResultString(MLResultCode resultCode) { return "This function is obsolete. Use MLLocation.GetResultString(MLResult.Code) instead."; } /// <summary> /// External call for querying the last known fine location. /// The accuracy field of the MLLocation.Location provides the estimate accuracy radius in meters. /// Returns the last known fine location data on success and returns the last queried fine location data on failure. Latitude and Longitude of /// 0 should be assumed an Invalid Location. /// </summary> /// <param name="fineLocation">Where to store the last known fine location. Only updates when getting the location succeeds. Latitude and Longitude of 0 should be assumed an Invalid Location.</param> /// <returns> /// MLResult.Result will be <c>MLResult.Code.Ok</c> if the location was queried successfully. /// MLResult.Result will be <c>MLResult.Code.UnspecifiedFailure</c> if there was an internal error. /// MLResult.Result will be <c>MLResult.Code.InvalidParam</c> if there was an invalid location. /// MLResult.Result will be <c>MLResult.Code.PrivilegeDenied</c> if there was a lack of privilege(s). /// MLResult.Result will be <c>MLResult.Code.LocationProviderNotFound</c> if there was no provider or an invalid request was made. /// MLResult.Result will be <c>MLResult.Code.LocationNetworkConnection</c> if there was no internet connection. /// MLResult.Result will be <c>MLResult.Code.LocationNoLocation</c> if the location could not be found. /// </returns> [Obsolete("Please use GetLastFineLocation with the MLLocation.Location struct instead.")] public static MLResult GetLastFineLocation(out MLLocationData fineLocation) { MLResult result = Instance.GetLastLocationInternal(out fineLocation, false); return result; } /// <summary> /// External call for querying the last known coarse location. /// Coarse location provides latitude and longitude estimate from block to city accuracy. /// Returns the last known coarse location data on success and returns the last queried coarse location data on failure. Latitude and Longitude of /// 0 should be assumed an Invalid Location. /// </summary> /// <param name="coarseLocation">Where to store the last known coarse location.</param> /// <returns> /// MLResult.Result will be <c>MLResult.Code.UnspecifiedFailure</c> because this function is deprecated. /// </returns> [Obsolete("Please use GetLastCoarseLocation with the MLLocation.Location struct instead.")] public static MLResult GetLastCoarseLocation(out MLLocationData coarseLocation) { MLResult result = Instance.GetLastLocationInternal(out coarseLocation, true); return result; } /// <summary> /// Internal call for querying the last known coarse/fine location. /// The accuracy field of the MLLocation.Location provides the estimate accuracy radius in meters. /// Returns the last known data on success and returns the last queried location data on failure. Latitude and Longitude of /// 0 should be assumed an Invalid Location. /// </summary> /// <param name="outLocation">Where to store the last known fine location. Only updates when getting the location succeeds. Latitude and Longitude of 0 should be assumed an Invalid Location.</param> /// <param name="isFine">Determines whether to query for fine location or coarse location.</param> /// <returns> /// MLResult.Result will be <c>MLResult.Code.Ok</c> if the location was queried successfully. /// MLResult.Result will be <c>MLResult.Code.UnspecifiedFailure</c> if there was an internal error. /// MLResult.Result will be <c>MLResult.Code.InvalidParam</c> if there was an invalid location. /// MLResult.Result will be <c>MLResult.Code.PrivilegeDenied</c> if there was a lack of privilege(s). /// MLResult.Result will be <c>MLResult.Code.LocationProviderNotFound</c> if there was no provider or an invalid request was made. /// MLResult.Result will be <c>MLResult.Code.LocationNetworkConnection</c> if there was no internet connection. /// MLResult.Result will be <c>MLResult.Code.LocationNoLocation</c> if the location could not be found. /// </returns> [Obsolete("Please use GetLastLocationInternal with the MLLocation.Location struct instead.")] private MLResult GetLastLocationInternal(out MLLocationData outLocation, bool isFine) { // The automatic marshaling was not working properly for this structure. TimeStamp was always 0. To solve this // we use an IntPtr that has the proper default values set. NativeBindings.LocationNative location = NativeBindings.LocationNative.Create(); MLResult.Code resultCode; IntPtr myPointer = Marshal.AllocHGlobal(Marshal.SizeOf(location)); Marshal.StructureToPtr(location, myPointer, false); try { resultCode = isFine ? NativeBindings.MLLocationGetLastFineLocation(myPointer) : NativeBindings.MLLocationGetLastCoarseLocation(myPointer); if (resultCode != MLResult.Code.Ok) { MLPluginLog.ErrorFormat("MLLocation.GetLastLocationInternal failed to get location. Reason: {0}", resultCode); location.Latitude = 0.0000f; location.Longitude = 0.0000f; } location = (NativeBindings.LocationNative)Marshal.PtrToStructure(myPointer, typeof(NativeBindings.LocationNative)); Marshal.FreeHGlobal(myPointer); MLResult finalResult = MLResult.Create(resultCode); outLocation = location.DataEx; if (finalResult.IsOk) { if (isFine) { this.lastValidFineLocation = location.Data; } else { this.lastValidCoarseLocation = location.Data; } } return finalResult; } catch (EntryPointNotFoundException) { outLocation = new MLLocationData(); MLPluginLog.Error("MLLocation.GetLastLocationInternal failed. Reason: API symbols not found."); return MLResult.Create(MLResult.Code.UnspecifiedFailure, "MLLocation.GetLastLocationInternal failed. Reason: API symbols not found."); } } } } #endif
53.256579
207
0.645707
[ "Apache-2.0" ]
kedarshashi/UnityTemplate
Assets/MagicLeap/Lumin/Deprecated/MLLocation.cs
8,095
C#
using UnityEngine; public interface NextStationSelector { Station GetNextStation (Station station, Vector3 position, Camera camera); }
19.571429
75
0.817518
[ "Apache-2.0" ]
alvarogzp/nextation
Assets/Scripts/Station/NextStationSelector/NextStationSelector.cs
137
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Linq; namespace Microsoft.CodeAnalysis.Shared.Utilities { internal class SignatureComparer { public static readonly SignatureComparer Instance = new SignatureComparer(SymbolEquivalenceComparer.Instance); public static readonly SignatureComparer IgnoreAssembliesInstance = new SignatureComparer(SymbolEquivalenceComparer.IgnoreAssembliesInstance); private readonly SymbolEquivalenceComparer _symbolEquivalenceComparer; private SignatureComparer(SymbolEquivalenceComparer symbolEquivalenceComparer) => _symbolEquivalenceComparer = symbolEquivalenceComparer; private IEqualityComparer<IParameterSymbol> ParameterEquivalenceComparer => _symbolEquivalenceComparer.ParameterEquivalenceComparer; private IEqualityComparer<ITypeSymbol> SignatureTypeEquivalenceComparer => _symbolEquivalenceComparer.SignatureTypeEquivalenceComparer; public bool HaveSameSignature(ISymbol symbol1, ISymbol symbol2, bool caseSensitive) { // NOTE - we're deliberately using reference equality here for speed. if (symbol1 == symbol2) { return true; } if (symbol1 == null || symbol2 == null) { return false; } if (symbol1.Kind != symbol2.Kind) { return false; } switch (symbol1.Kind) { case SymbolKind.Method: return HaveSameSignature((IMethodSymbol)symbol1, (IMethodSymbol)symbol2, caseSensitive); case SymbolKind.Property: return HaveSameSignature((IPropertySymbol)symbol1, (IPropertySymbol)symbol2, caseSensitive); case SymbolKind.Event: return HaveSameSignature((IEventSymbol)symbol1, (IEventSymbol)symbol2, caseSensitive); } return true; } private static bool HaveSameSignature(IEventSymbol event1, IEventSymbol event2, bool caseSensitive) => IdentifiersMatch(event1.Name, event2.Name, caseSensitive); public bool HaveSameSignature(IPropertySymbol property1, IPropertySymbol property2, bool caseSensitive) { if (!IdentifiersMatch(property1.Name, property2.Name, caseSensitive) || property1.Parameters.Length != property2.Parameters.Length || property1.IsIndexer != property2.IsIndexer) { return false; } return property1.Parameters.SequenceEqual( property2.Parameters, this.ParameterEquivalenceComparer); } private static bool BadPropertyAccessor(IMethodSymbol method1, IMethodSymbol method2) { return method1 != null && (method2 == null || method2.DeclaredAccessibility != Accessibility.Public); } public bool HaveSameSignature(IMethodSymbol method1, IMethodSymbol method2, bool caseSensitive, bool compareParameterName = false, bool isParameterCaseSensitive = false) { if ((method1.MethodKind == MethodKind.AnonymousFunction) != (method2.MethodKind == MethodKind.AnonymousFunction)) { return false; } if (method1.MethodKind != MethodKind.AnonymousFunction) { if (!IdentifiersMatch(method1.Name, method2.Name, caseSensitive)) { return false; } } if (method1.MethodKind != method2.MethodKind || method1.Arity != method2.Arity) { return false; } return HaveSameSignature(method1.Parameters, method2.Parameters, compareParameterName, isParameterCaseSensitive); } private static bool IdentifiersMatch(string identifier1, string identifier2, bool caseSensitive) { return caseSensitive ? identifier1 == identifier2 : string.Equals(identifier1, identifier2, StringComparison.OrdinalIgnoreCase); } public bool HaveSameSignature( IList<IParameterSymbol> parameters1, IList<IParameterSymbol> parameters2) { if (parameters1.Count != parameters2.Count) { return false; } return parameters1.SequenceEqual(parameters2, this.ParameterEquivalenceComparer); } public bool HaveSameSignature( IList<IParameterSymbol> parameters1, IList<IParameterSymbol> parameters2, bool compareParameterName, bool isCaseSensitive) { if (parameters1.Count != parameters2.Count) { return false; } for (var i = 0; i < parameters1.Count; ++i) { if (!_symbolEquivalenceComparer.ParameterEquivalenceComparer.Equals(parameters1[i], parameters2[i], compareParameterName, isCaseSensitive)) { return false; } } return true; } public bool HaveSameSignatureAndConstraintsAndReturnTypeAndAccessors(ISymbol symbol1, ISymbol symbol2, bool caseSensitive) { // NOTE - we're deliberately using reference equality here for speed. if (symbol1 == symbol2) { return true; } if (!HaveSameSignature(symbol1, symbol2, caseSensitive)) { return false; } switch (symbol1.Kind) { case SymbolKind.Method: var method1 = (IMethodSymbol)symbol1; var method2 = (IMethodSymbol)symbol2; return HaveSameSignatureAndConstraintsAndReturnType(method1, method2); case SymbolKind.Property: var property1 = (IPropertySymbol)symbol1; var property2 = (IPropertySymbol)symbol2; return HaveSameReturnType(property1, property2) && HaveSameAccessors(property1, property2); case SymbolKind.Event: var ev1 = (IEventSymbol)symbol1; var ev2 = (IEventSymbol)symbol2; return HaveSameReturnType(ev1, ev2); } return true; } private static bool HaveSameAccessors(IPropertySymbol property1, IPropertySymbol property2) { if (property1.ContainingType == null || property1.ContainingType.TypeKind == TypeKind.Interface) { if (BadPropertyAccessor(property1.GetMethod, property2.GetMethod) || BadPropertyAccessor(property1.SetMethod, property2.SetMethod)) { return false; } } if (property2.ContainingType == null || property2.ContainingType.TypeKind == TypeKind.Interface) { if (BadPropertyAccessor(property2.GetMethod, property1.GetMethod) || BadPropertyAccessor(property2.SetMethod, property1.SetMethod)) { return false; } } return true; } private bool HaveSameSignatureAndConstraintsAndReturnType(IMethodSymbol method1, IMethodSymbol method2) { if (method1.ReturnsVoid != method2.ReturnsVoid) { return false; } if (!method1.ReturnsVoid && !this.SignatureTypeEquivalenceComparer.Equals(method1.ReturnType, method2.ReturnType)) { return false; } for (var i = 0; i < method1.TypeParameters.Length; i++) { var typeParameter1 = method1.TypeParameters[i]; var typeParameter2 = method2.TypeParameters[i]; if (!HaveSameConstraints(typeParameter1, typeParameter2)) { return false; } } return true; } private bool HaveSameConstraints(ITypeParameterSymbol typeParameter1, ITypeParameterSymbol typeParameter2) { if (typeParameter1.HasConstructorConstraint != typeParameter2.HasConstructorConstraint || typeParameter1.HasReferenceTypeConstraint != typeParameter2.HasReferenceTypeConstraint || typeParameter1.HasValueTypeConstraint != typeParameter2.HasValueTypeConstraint) { return false; } if (typeParameter1.ConstraintTypes.Length != typeParameter2.ConstraintTypes.Length) { return false; } return typeParameter1.ConstraintTypes.SetEquals( typeParameter2.ConstraintTypes, this.SignatureTypeEquivalenceComparer); } private bool HaveSameReturnType(IPropertySymbol property1, IPropertySymbol property2) => this.SignatureTypeEquivalenceComparer.Equals(property1.Type, property2.Type); private bool HaveSameReturnType(IEventSymbol ev1, IEventSymbol ev2) => this.SignatureTypeEquivalenceComparer.Equals(ev1.Type, ev2.Type); } }
37.407692
155
0.595826
[ "MIT" ]
06needhamt/roslyn
src/Workspaces/Core/Portable/Shared/Utilities/SignatureComparer.cs
9,728
C#
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Media; using System.Collections; namespace GameDev_2DGame { class Button : GameObject { // The number on the button private int number; // The index of the button private int buttonID; // The collection of sprites that may be used to display the private ArrayList textures; /// <summary> /// The button constructor. /// </summary> /// <param name="buttonID">The index of the button.</param> /// <param name="pos">Position to place the object.</param> /// <param name="textures">The object images.</param> /// <param name="game1">Reference to the game object.</param> public Button(int buttonID, Vector2 pos, ArrayList textures, Game1 game1) : base(Type.Button, pos, (Texture2D)textures[0], game1) { this.textures = textures; this.buttonID = buttonID; number = 0; } /// <summary> /// Handle the event that the button is collided with by a bullet. /// </summary> /// <param name="obj">The object that has been collided with.</param> public override void onCollision(GameObject obj) { // if object is a bullet shuffle the number to the next value if (obj.type == GameObject.Type.Bullet) { number++; if (number > 9) number = 0; currentSprite = (Texture2D)textures[number]; } } /// <summary> /// Get the number displayed on the button. /// </summary> /// <returns>The displayed number.</returns> public int getNumber() { return number; } /// <summary> /// Get the index of the button. /// </summary> /// <returns>The index.</returns> public int getButtonID() { return buttonID; } } }
31.342466
81
0.577797
[ "MIT" ]
Squirrelbear/Overrun-City
Project Source Code/GameDev2D/GameObjects/Button.cs
2,290
C#
namespace Milou.Deployer.Waws { internal class DeploymentRule { public static readonly DeploymentRule DoNotDeleteRule = new(nameof(DoNotDeleteRule)); public DeploymentRule(string name) => Name = name; public string Name { get; } } }
24.636364
93
0.675277
[ "MIT" ]
niklaslundberg/milou.deployer
src/Milou.Deployer.Waws/DeploymentRule.cs
273
C#
namespace Naos.Tracing.Domain { public enum SpanStatus { /// <summary> /// The operation is running. /// </summary> Transient = 0, /// <summary> /// The operation completed successfully. /// </summary> Succeeded = 1, /// <summary> /// The operation was cancelled (typically by the client/consumer). /// </summary> Cancelled = 2, /// <summary> /// The operation has failed (error). /// </summary> Failed = 3, } }
22.2
75
0.488288
[ "MIT" ]
vip32/Naos.Core
src/Tracing.Domain/Model/Span/SpanStatus.cs
557
C#
using STUN.Utils; using System; using System.Collections.Generic; using System.Linq; using System.Net; namespace STUN.Message.Attributes { /// <summary> /// https://tools.ietf.org/html/rfc5389#section-15.2 /// </summary> public class XorMappedAddressAttribute : AddressAttribute { private readonly byte[] _magicCookie; private readonly byte[] _transactionId; public XorMappedAddressAttribute(byte[] magicCookie, byte[] transactionId) { _magicCookie = magicCookie; _transactionId = transactionId; } public override IEnumerable<byte> Bytes { get { if (Address is null) { return Array.Empty<byte>(); } var res = new List<byte> { 0, (byte)Family }; res.AddRange(Xor(Port).ToBe()); res.AddRange(Xor(Address).GetAddressBytes()); return res; } } public override bool TryParse(byte[] bytes) { if (!base.TryParse(bytes)) { return false; } Port = Xor(Port); Address = Xor(Address!); return true; } private ushort Xor(ushort port) { var b = port.ToBe().ToArray(); var xPort = BitUtils.FromBe((byte)(_magicCookie[0] ^ b[0]), (byte)(_magicCookie[1] ^ b[1])); return xPort; } private IPAddress Xor(IPAddress address) { var b = address.GetAddressBytes(); var xor = _magicCookie.Concat(_transactionId).ToArray(); for (var i = 0; i < b.Length; ++i) { b[i] ^= xor[i]; } return new IPAddress(b); } } }
19.916667
95
0.647141
[ "MIT" ]
MarkZJQ/NatTypeTester
STUN/Message/Attributes/XorMappedAddressAttribute.cs
1,434
C#
using FewBox.Core.Utility.Formatter; using Microsoft.Extensions.Caching.Distributed; using System; using System.Linq; using System.Security.Claims; namespace FewBox.Core.Web.Token { public class DistributedTokenCache : TokenService { private IDistributedCache DistributedCache { get; set; } public DistributedTokenCache(IDistributedCache distributedCache) : base() { this.DistributedCache = distributedCache; } public override string GenerateToken(UserProfile userProfile, DateTime expiredTime) { string token = Guid.NewGuid().ToString(); if(expiredTime == DateTime.MaxValue) { this.DistributedCache.SetString(token.ToString(), JsonUtility.Serialize<UserProfile>(userProfile)); } else { DistributedCacheEntryOptions distributedCacheEntryOptions = new DistributedCacheEntryOptions { AbsoluteExpirationRelativeToNow = TimeSpan.FromTicks(expiredTime.Ticks) }; this.DistributedCache.SetString(token.ToString(), JsonUtility.Serialize<UserProfile>(userProfile), distributedCacheEntryOptions); } return token; } public override string GetUserIdByToken(string token) { string userId = null; var userProfile = this.GetUserProfileByToken(token); if(userProfile!=null) { userId = userProfile.Id; } return userId; } public override UserProfile GetUserProfileByToken(string token) { string userProfileString = this.DistributedCache.GetString(token.ToString()); return JsonUtility.Deserialize<UserProfile>(userProfileString); } public override bool ValidateToken(string token, string key, string issuer, string audience) { string userProfileString = this.DistributedCache.GetString(token.ToString()); return !String.IsNullOrEmpty(userProfileString); } } }
35.55
145
0.634318
[ "Apache-2.0" ]
FewBox/FewBox.Core.Web
FewBox.Core.Web/Token/DistributedTokenCache.cs
2,135
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace Opereta.Models { public class CompanyTask { public int Id { get; set; } public CompanyTask() { this.Participants = new HashSet<TaskEmployee>(); } public string Name { get; set; } public DateTime CreatedOn { get; set; } = DateTime.UtcNow; public DateTime PlanedEndTime { get; set; } public DateTime ActualEndTime { get; set; } public bool IsInProgress { get; set; } = true; public bool IsOverdue { get; set; } = false; public Priority Priority { get; set; } public string ApplicationUserId { get; set; } public virtual ApplicationUser Supervisor { get; set; } public virtual ICollection<TaskEmployee> Participants { get; set; } } }
27.057143
75
0.62302
[ "MIT" ]
morskibg/MVC_Individual_Project
Opereta/Opereta/Models/CompanyTask.cs
949
C#
using Microsoft.ML.Data; namespace FraudPredictionFunction { internal class FraudPrediction { [ColumnName("PredictedLabel")] public bool IsFraud { get; set; } [ColumnName("Score")] public float Score { get; set; } } }
18.928571
41
0.618868
[ "MIT" ]
JohnnyFayad/mldotnet-real-time-data-streaming-workshop
src/real-time-data-streaming/fraud-prediction-function/FraudPrediction.cs
267
C#
using System; using System.Collections.Generic; public class NaturalComparer<T> : IComparer<T> where T: IComparable<T> { public int Compare (T a, T b) { return a.CompareTo (b); } } public class X { class Test : IComparable<Test> { public int CompareTo (Test that) { return 0; } public bool Equals (Test that) { return false; } } static void Main () { IComparer<Test> cmp = new NaturalComparer<Test> (); Test a = new Test (); Test b = new Test (); cmp.Compare (a, b); } }
14.25
53
0.631579
[ "Apache-2.0" ]
CRivlaldo/mono
mcs/tests/gtest-114.cs
513
C#
//------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------ namespace Microsoft.Azure.Cosmos.Scripts { using System; using System.IO; using System.Threading; using System.Threading.Tasks; // This class acts as a wrapper for environments that use SynchronizationContext. internal sealed class ScriptsInlineCore : ScriptsCore { internal ScriptsInlineCore( ContainerInternal container, CosmosClientContext clientContext) : base( container, clientContext) { } public override Task<StoredProcedureResponse> CreateStoredProcedureAsync( StoredProcedureProperties storedProcedureProperties, RequestOptions requestOptions = null, CancellationToken cancellationToken = default) { return this.ClientContext.OperationHelperAsync( nameof(CreateStoredProcedureAsync), requestOptions, (diagnostics) => base.CreateStoredProcedureAsync(diagnostics, storedProcedureProperties, requestOptions, cancellationToken)); } public override FeedIterator<T> GetStoredProcedureQueryIterator<T>( QueryDefinition queryDefinition, string continuationToken = null, QueryRequestOptions requestOptions = null) { return new FeedIteratorInlineCore<T>(base.GetStoredProcedureQueryIterator<T>( queryDefinition, continuationToken, requestOptions)); } public override FeedIterator GetStoredProcedureQueryStreamIterator( QueryDefinition queryDefinition, string continuationToken = null, QueryRequestOptions requestOptions = null) { return new FeedIteratorInlineCore(base.GetStoredProcedureQueryStreamIterator( queryDefinition, continuationToken, requestOptions)); } public override FeedIterator<T> GetStoredProcedureQueryIterator<T>( string queryText = null, string continuationToken = null, QueryRequestOptions requestOptions = null) { return new FeedIteratorInlineCore<T>(base.GetStoredProcedureQueryIterator<T>( queryText, continuationToken, requestOptions)); } public override FeedIterator GetStoredProcedureQueryStreamIterator( string queryText = null, string continuationToken = null, QueryRequestOptions requestOptions = null) { return new FeedIteratorInlineCore(base.GetStoredProcedureQueryStreamIterator( queryText, continuationToken, requestOptions)); } public override Task<StoredProcedureResponse> ReadStoredProcedureAsync( string id, RequestOptions requestOptions = null, CancellationToken cancellationToken = default) { return this.ClientContext.OperationHelperAsync( nameof(ReadStoredProcedureAsync), requestOptions, (diagnostics) => base.ReadStoredProcedureAsync(diagnostics, id, requestOptions, cancellationToken)); } public override Task<StoredProcedureResponse> ReplaceStoredProcedureAsync( StoredProcedureProperties storedProcedureProperties, RequestOptions requestOptions = null, CancellationToken cancellationToken = default) { return this.ClientContext.OperationHelperAsync( nameof(ReplaceStoredProcedureAsync), requestOptions, (diagnostics) => base.ReplaceStoredProcedureAsync(diagnostics, storedProcedureProperties, requestOptions, cancellationToken)); } public override Task<StoredProcedureResponse> DeleteStoredProcedureAsync( string id, RequestOptions requestOptions = null, CancellationToken cancellationToken = default) { return this.ClientContext.OperationHelperAsync( nameof(DeleteStoredProcedureAsync), requestOptions, (diagnostics) => base.DeleteStoredProcedureAsync(diagnostics, id, requestOptions, cancellationToken)); } public override Task<StoredProcedureExecuteResponse<TOutput>> ExecuteStoredProcedureAsync<TOutput>( string storedProcedureId, Cosmos.PartitionKey partitionKey, dynamic[] parameters, StoredProcedureRequestOptions requestOptions = null, CancellationToken cancellationToken = default) { return this.ClientContext.OperationHelperAsync( nameof(ExecuteStoredProcedureAsync), requestOptions, (diagnostics) => base.ExecuteStoredProcedureAsync<TOutput>(diagnostics, storedProcedureId, partitionKey, parameters, requestOptions, cancellationToken)); } public override Task<ResponseMessage> ExecuteStoredProcedureStreamAsync( string storedProcedureId, Cosmos.PartitionKey partitionKey, dynamic[] parameters, StoredProcedureRequestOptions requestOptions = null, CancellationToken cancellationToken = default) { return this.ClientContext.OperationHelperAsync( nameof(ExecuteStoredProcedureStreamAsync), requestOptions, (diagnostics) => base.ExecuteStoredProcedureStreamAsync(diagnostics, storedProcedureId, partitionKey, parameters, requestOptions, cancellationToken)); } public override Task<ResponseMessage> ExecuteStoredProcedureStreamAsync( string storedProcedureId, Stream streamPayload, Cosmos.PartitionKey partitionKey, StoredProcedureRequestOptions requestOptions = null, CancellationToken cancellationToken = default) { return this.ClientContext.OperationHelperAsync( nameof(ExecuteStoredProcedureStreamAsync), requestOptions, (diagnostics) => base.ExecuteStoredProcedureStreamAsync(diagnostics, storedProcedureId, streamPayload, partitionKey, requestOptions, cancellationToken)); } public override Task<TriggerResponse> CreateTriggerAsync( TriggerProperties triggerProperties, RequestOptions requestOptions = null, CancellationToken cancellationToken = default) { return this.ClientContext.OperationHelperAsync( nameof(CreateTriggerAsync), requestOptions, (diagnostics) => base.CreateTriggerAsync(diagnostics, triggerProperties, requestOptions, cancellationToken)); } public override FeedIterator<T> GetTriggerQueryIterator<T>( QueryDefinition queryDefinition, string continuationToken = null, QueryRequestOptions requestOptions = null) { return new FeedIteratorInlineCore<T>(base.GetTriggerQueryIterator<T>( queryDefinition, continuationToken, requestOptions)); } public override FeedIterator GetTriggerQueryStreamIterator( QueryDefinition queryDefinition, string continuationToken = null, QueryRequestOptions requestOptions = null) { return new FeedIteratorInlineCore(base.GetTriggerQueryStreamIterator( queryDefinition, continuationToken, requestOptions)); } public override FeedIterator<T> GetTriggerQueryIterator<T>( string queryText = null, string continuationToken = null, QueryRequestOptions requestOptions = null) { return new FeedIteratorInlineCore<T>(base.GetTriggerQueryIterator<T>( queryText, continuationToken, requestOptions)); } public override FeedIterator GetTriggerQueryStreamIterator( string queryText = null, string continuationToken = null, QueryRequestOptions requestOptions = null) { return new FeedIteratorInlineCore(base.GetTriggerQueryStreamIterator( queryText, continuationToken, requestOptions)); } public override Task<TriggerResponse> ReadTriggerAsync( string id, RequestOptions requestOptions = null, CancellationToken cancellationToken = default) { return this.ClientContext.OperationHelperAsync( nameof(ReadTriggerAsync), requestOptions, (diagnostics) => base.ReadTriggerAsync(diagnostics, id, requestOptions, cancellationToken)); } public override Task<TriggerResponse> ReplaceTriggerAsync( TriggerProperties triggerProperties, RequestOptions requestOptions = null, CancellationToken cancellationToken = default) { return this.ClientContext.OperationHelperAsync( nameof(ReplaceTriggerAsync), requestOptions, (diagnostics) => base.ReplaceTriggerAsync(diagnostics, triggerProperties, requestOptions, cancellationToken)); } public override Task<TriggerResponse> DeleteTriggerAsync( string id, RequestOptions requestOptions = null, CancellationToken cancellationToken = default) { return this.ClientContext.OperationHelperAsync( nameof(DeleteTriggerAsync), requestOptions, (diagnostics) => base.DeleteTriggerAsync(diagnostics, id, requestOptions, cancellationToken)); } public override Task<UserDefinedFunctionResponse> CreateUserDefinedFunctionAsync( UserDefinedFunctionProperties userDefinedFunctionProperties, RequestOptions requestOptions = null, CancellationToken cancellationToken = default) { return this.ClientContext.OperationHelperAsync( nameof(CreateUserDefinedFunctionAsync), requestOptions, (diagnostics) => base.CreateUserDefinedFunctionAsync(diagnostics, userDefinedFunctionProperties, requestOptions, cancellationToken)); } public override FeedIterator<T> GetUserDefinedFunctionQueryIterator<T>( QueryDefinition queryDefinition, string continuationToken = null, QueryRequestOptions requestOptions = null) { return new FeedIteratorInlineCore<T>(base.GetUserDefinedFunctionQueryIterator<T>( queryDefinition, continuationToken, requestOptions)); } public override FeedIterator GetUserDefinedFunctionQueryStreamIterator( QueryDefinition queryDefinition, string continuationToken = null, QueryRequestOptions requestOptions = null) { return new FeedIteratorInlineCore(base.GetUserDefinedFunctionQueryStreamIterator( queryDefinition, continuationToken, requestOptions)); } public override FeedIterator<T> GetUserDefinedFunctionQueryIterator<T>( string queryText = null, string continuationToken = null, QueryRequestOptions requestOptions = null) { return new FeedIteratorInlineCore<T>(base.GetUserDefinedFunctionQueryIterator<T>( queryText, continuationToken, requestOptions)); } public override FeedIterator GetUserDefinedFunctionQueryStreamIterator( string queryText = null, string continuationToken = null, QueryRequestOptions requestOptions = null) { return new FeedIteratorInlineCore(base.GetUserDefinedFunctionQueryStreamIterator( queryText, continuationToken, requestOptions)); } public override Task<UserDefinedFunctionResponse> ReadUserDefinedFunctionAsync( string id, RequestOptions requestOptions = null, CancellationToken cancellationToken = default) { return this.ClientContext.OperationHelperAsync( nameof(ReadUserDefinedFunctionAsync), requestOptions, (diagnostics) => base.ReadUserDefinedFunctionAsync(diagnostics, id, requestOptions, cancellationToken)); } public override Task<UserDefinedFunctionResponse> ReplaceUserDefinedFunctionAsync( UserDefinedFunctionProperties userDefinedFunctionProperties, RequestOptions requestOptions = null, CancellationToken cancellationToken = default) { return this.ClientContext.OperationHelperAsync( nameof(ReplaceUserDefinedFunctionAsync), requestOptions, (diagnostics) => base.ReplaceUserDefinedFunctionAsync(diagnostics, userDefinedFunctionProperties, requestOptions, cancellationToken)); } public override Task<UserDefinedFunctionResponse> DeleteUserDefinedFunctionAsync( string id, RequestOptions requestOptions = null, CancellationToken cancellationToken = default) { return this.ClientContext.OperationHelperAsync( nameof(DeleteUserDefinedFunctionAsync), requestOptions, (diagnostics) => base.DeleteUserDefinedFunctionAsync(diagnostics, id, requestOptions, cancellationToken)); } } }
42.957317
169
0.64017
[ "MIT" ]
Liphi/azure-cosmos-dotnet-v3
Microsoft.Azure.Cosmos/src/Resource/Scripts/ScriptsInlineCore.cs
14,092
C#
using System.Collections.Generic; using osuTK; namespace GD.Game.Legacy { public static class Dictionaries { public static readonly List<DefaultLevel> DEFAULT_LEVELS = new() { new DefaultLevel { Name = "Stereo Madness", StarDiff = 1, Orbs = new Vector2(50, 0), LegacyDiff = LegacyDiff.Easy, Colour = LegacyColour.Blue }, new DefaultLevel { Name = "Back On Track", StarDiff = 2, Orbs = new Vector2(75, 0), LegacyDiff = LegacyDiff.Easy, Colour = LegacyColour.Purple }, new DefaultLevel { Name = "Polargeist", StarDiff = 3, Orbs = new Vector2(100, 0), LegacyDiff = LegacyDiff.Normal, Colour = LegacyColour.PurpleRed }, new DefaultLevel { Name = "Dry Out", StarDiff = 4, Orbs = new Vector2(125, 0), LegacyDiff = LegacyDiff.Normal, Colour = LegacyColour.Red }, new DefaultLevel { Name = "Base After Base", StarDiff = 5, Orbs = new Vector2(150, 0), LegacyDiff = LegacyDiff.Hard, Colour = LegacyColour.Orange }, new DefaultLevel { Name = "Cant Let Go", StarDiff = 6, Orbs = new Vector2(175, 0), LegacyDiff = LegacyDiff.Hard, Colour = LegacyColour.Yellow }, new DefaultLevel { Name = "Jumper", StarDiff = 7, Orbs = new Vector2(200, 0), LegacyDiff = LegacyDiff.Harder, Colour = LegacyColour.Green }, new DefaultLevel { Name = "Time Machine", StarDiff = 8, Orbs = new Vector2(225, 0), LegacyDiff = LegacyDiff.Harder, Colour = LegacyColour.Cyan }, new DefaultLevel { Name = "Cycles", StarDiff = 9, Orbs = new Vector2(250, 0), LegacyDiff = LegacyDiff.Harder, Colour = LegacyColour.BlueSky }, new DefaultLevel { Name = "xStep", StarDiff = 10, Orbs = new Vector2(275, 0), LegacyDiff = LegacyDiff.Insane, Colour = LegacyColour.Blue }, new DefaultLevel { Name = "Clutterfunk", StarDiff = 11, Orbs = new Vector2(300, 0), LegacyDiff = LegacyDiff.Insane, Colour = LegacyColour.Purple }, new DefaultLevel { Name = "Theory of Everything", StarDiff = 12, Orbs = new Vector2(325, 0), LegacyDiff = LegacyDiff.Insane, Colour = LegacyColour.PurpleRed }, new DefaultLevel { Name = "Electroman Adventures", StarDiff = 10, Orbs = new Vector2(275, 0), LegacyDiff = LegacyDiff.Insane, Colour = LegacyColour.Red }, new DefaultLevel { Name = "Clubstep", StarDiff = 14, Orbs = new Vector2(500, 0), LegacyDiff = LegacyDiff.Demon, Colour = LegacyColour.Orange }, new DefaultLevel { Name = "Electrodynamix", StarDiff = 12, Orbs = new Vector2(325, 0), LegacyDiff = LegacyDiff.Insane, Colour = LegacyColour.Yellow }, new DefaultLevel { Name = "Hexagon Force", StarDiff = 12, Orbs = new Vector2(325, 0), LegacyDiff = LegacyDiff.Insane, Colour = LegacyColour.Green }, new DefaultLevel { Name = "Blast Processing", StarDiff = 10, Orbs = new Vector2(275, 0), LegacyDiff = LegacyDiff.Harder, Colour = LegacyColour.Cyan }, new DefaultLevel { Name = "Theory of Everything 2", StarDiff = 14, Orbs = new Vector2(500, 0), LegacyDiff = LegacyDiff.Demon, Colour = LegacyColour.BlueSky }, new DefaultLevel { Name = "Geometrical Dominator", StarDiff = 10, Orbs = new Vector2(275, 0), LegacyDiff = LegacyDiff.Harder, Colour = LegacyColour.Blue }, new DefaultLevel { Name = "Deadlocked", StarDiff = 15, Orbs = new Vector2(500, 0), LegacyDiff = LegacyDiff.Demon, Colour = LegacyColour.Purple } }; } }
31.809249
72
0.415591
[ "MIT" ]
EVAST9919/GDUI
GD.Game/Legacy/Dictionaries.cs
5,505
C#
using System; using System.IO; namespace C_fileIO101.Files { public class CreateFolder { public string createFolder(string path) { string pathReady = ""; try { if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } else { Console.WriteLine("Folder already exist"); } pathReady = path; } catch (System.Exception e) { throw e; } return pathReady; } } }
20.151515
62
0.4
[ "MIT" ]
giprim/C_fileIO101
Files/MenuItems/CreateFolder.cs
665
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace YPIConnect.Persistence { public class ListProperty : System.Attribute { private string m_SqlPropertyName; public ListProperty(string sqlPropertyName) { this.m_SqlPropertyName = sqlPropertyName; } public string SqlPropertyName { get { return this.m_SqlPropertyName; } } } }
19.416667
53
0.643777
[ "MIT" ]
SidHarder/ypi-connect
Persistence/ListProperty.cs
468
C#
// OCSPRef.cs // // XAdES Starter Kit for Microsoft .NET 3.5 (and above) // 2010 Microsoft France // Published under the CECILL-B Free Software license agreement. // (http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.txt) // // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, // WHETHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE. // THE ENTIRE RISK OF USE OR RESULTS IN CONNECTION WITH THE USE OF THIS CODE // AND INFORMATION REMAINS WITH THE USER. // using System; using System.Xml; using System.Security.Cryptography; namespace Microsoft.Xades { /// <summary> /// This class identifies one OCSP response /// </summary> public class OCSPRef { #region Private variables private OCSPIdentifier ocspIdentifier; private DigestAlgAndValueType digestAlgAndValue; #endregion #region Public properties /// <summary> /// Identification of one OCSP response /// </summary> public OCSPIdentifier OCSPIdentifier { get { return this.ocspIdentifier; } set { this.ocspIdentifier = value; } } /// <summary> /// The digest computed on the DER encoded OCSP response, since it may be /// needed to differentiate between two OCSP responses by the same server /// with their "ProducedAt" fields within the same second. /// </summary> public DigestAlgAndValueType CertDigest { get { return this.digestAlgAndValue; } set { this.digestAlgAndValue = value; } } #endregion #region Constructors /// <summary> /// Default constructor /// </summary> public OCSPRef() { this.ocspIdentifier = new OCSPIdentifier(); this.digestAlgAndValue = new DigestAlgAndValueType("DigestAlgAndValue"); } #endregion #region Public methods /// <summary> /// Check to see if something has changed in this instance and needs to be serialized /// </summary> /// <returns>Flag indicating if a member needs serialization</returns> public bool HasChanged() { bool retVal = false; if (this.ocspIdentifier != null && this.ocspIdentifier.HasChanged()) { retVal = true; } if (this.digestAlgAndValue != null && this.digestAlgAndValue.HasChanged()) { retVal = true; } return retVal; } /// <summary> /// Load state from an XML element /// </summary> /// <param name="xmlElement">XML element containing new state</param> public void LoadXml(System.Xml.XmlElement xmlElement) { XmlNamespaceManager xmlNamespaceManager; XmlNodeList xmlNodeList; if (xmlElement == null) { throw new ArgumentNullException("xmlElement"); } xmlNamespaceManager = new XmlNamespaceManager(xmlElement.OwnerDocument.NameTable); xmlNamespaceManager.AddNamespace("xsd", XadesSignedXml.XadesNamespaceUri); xmlNodeList = xmlElement.SelectNodes("xsd:OCSPIdentifier", xmlNamespaceManager); if (xmlNodeList.Count == 0) { throw new CryptographicException("OCSPIdentifier missing"); } this.ocspIdentifier = new OCSPIdentifier(); this.ocspIdentifier.LoadXml((XmlElement)xmlNodeList.Item(0)); xmlNodeList = xmlElement.SelectNodes("xsd:DigestAlgAndValue", xmlNamespaceManager); if (xmlNodeList.Count == 0) { this.digestAlgAndValue = null; } else { this.digestAlgAndValue = new DigestAlgAndValueType("DigestAlgAndValue"); this.digestAlgAndValue.LoadXml((XmlElement)xmlNodeList.Item(0)); } } /// <summary> /// Returns the XML representation of the this object /// </summary> /// <returns>XML element containing the state of this object</returns> public XmlElement GetXml() { XmlDocument creationXmlDocument; XmlElement retVal; creationXmlDocument = new XmlDocument(); retVal = creationXmlDocument.CreateElement("xades", "OCSPRef", XadesSignedXml.XadesNamespaceUri); if (this.ocspIdentifier != null && this.ocspIdentifier.HasChanged()) { retVal.AppendChild(creationXmlDocument.ImportNode(this.ocspIdentifier.GetXml(), true)); } else { throw new CryptographicException("OCSPIdentifier element missing in OCSPRef"); } if (this.digestAlgAndValue != null && this.digestAlgAndValue.HasChanged()) { retVal.AppendChild(creationXmlDocument.ImportNode(this.digestAlgAndValue.GetXml(), true)); } return retVal; } #endregion } }
26.578313
109
0.707389
[ "BSD-3-Clause" ]
RIP-webmaster/CommunalServices.Communication
Library/OCSPRef.cs
4,412
C#
using System; using System.Data; using System.Web.Mvc; using BrnShop.Core; using BrnShop.Services; using BrnShop.Web.Framework; using BrnShop.Web.Admin.Models; namespace BrnShop.Web.Admin.Controllers { /// <summary> /// 后台商品评价控制器类 /// </summary> public partial class ProductReviewController : BaseAdminController { /// <summary> /// 商品评价列表 /// </summary> public ActionResult ProductReviewList(string productName, string message, string rateStartTime, string rateEndTime, int pid = -1, int pageNumber = 1, int pageSize = 15) { string condition = AdminProductReviews.AdminGetProductReviewListCondition(pid, message, rateStartTime, rateEndTime); PageModel pageModel = new PageModel(pageSize, pageNumber, AdminProductReviews.AdminGetProductReviewCount(condition)); ProductReviewListModel model = new ProductReviewListModel() { PageModel = pageModel, ProductReviewList = AdminProductReviews.AdminGetProductReviewList(pageModel.PageSize, pageModel.PageNumber, condition), Pid = pid, ProductName = pid > 0 ? productName : "选择商品", Message = message, StartTime = rateStartTime, EndTime = rateEndTime }; ShopUtils.SetAdminRefererCookie(string.Format("{0}?pageNumber={1}&pageSize={2}&message={3}&pid={4}&productName={5}&startTime={6}&endTime={7}", Url.Action("productreviewlist"), pageModel.PageNumber, pageModel.PageSize, message, pid, productName, rateStartTime, rateEndTime)); return View(model); } /// <summary> /// 商品评价回复列表 /// </summary> public ActionResult ProductReviewReplyList(int reviewId = -1) { ProductReviewInfo productReviewInfo = AdminProductReviews.AdminGetProductReviewById(reviewId); if (productReviewInfo == null) return PromptView("商品评价不存在"); ProductReviewReplyListModel model = new ProductReviewReplyListModel() { ProductReviewReplyList = AdminProductReviews.AdminGetProductReviewReplyList(reviewId), }; ShopUtils.SetAdminRefererCookie(string.Format("{0}?reviewId={1}", Url.Action("productreviewreplylist"), reviewId)); return View(model); } /// <summary> /// 改变商品评价的状态 /// </summary> public ActionResult ChangeProductReviewState(int reviewId = -1, int state = -1) { bool result = AdminProductReviews.ChangeProductReviewState(reviewId, state); if (result) { AddAdminOperateLog("修改商品评价状态", "修改商品评价状态,商品评价ID和状态为:" + reviewId + "_" + state); return Content("1"); } else { return Content("0"); } } /// <summary> /// 删除商品评价 /// </summary> public ActionResult DelProductReview(int reviewId) { AdminProductReviews.DeleteProductReviewById(reviewId); AddAdminOperateLog("删除商品评价", "删除商品评价,商品评价ID为:" + reviewId); return PromptView("商品评价删除成功"); } } }
39.5
176
0.558931
[ "MIT" ]
leafcxy/BrnShop
Presentation/BrnShop.Web/administration/controllers/ProductReviewController.cs
3,755
C#
using ao_id_extractor.Helpers; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Xml; namespace ao_id_extractor.Extractors { public class ItemExtractor : BaseExtractor { protected override void ExtractFromXML(Stream inputXmlFile, MultiStream outputStream, Action<MultiStream, IDContainer, bool> writeItem, LocalizationData localizationData = default) { var journals = new List<IDContainer>(); var xmlDoc = new XmlDocument(); xmlDoc.Load(inputXmlFile); var rootNode = xmlDoc.LastChild; var index = 1; var first = true; foreach (XmlNode node in rootNode.ChildNodes) { if (node.NodeType == XmlNodeType.Element && !string.IsNullOrEmpty(node.Attributes["uniquename"]?.Value)) { var uniqueName = node.Attributes["uniquename"].Value; var enchantmentLevel = node.Attributes["enchantmentlevel"]; var description = node.Attributes["descriptionlocatag"]; var name = node.Attributes["descvariable0"]; var enchantment = ""; if (enchantmentLevel != null && enchantmentLevel.Value != "0") { enchantment = "@" + enchantmentLevel.Value; } var localizationNameVariable = name != null ? name.Value : LocalizationData.ItemPrefix + uniqueName; if (uniqueName.Contains("ARTEFACT")) { localizationNameVariable = LocalizationData.ItemPrefix + uniqueName; } var container = new ItemContainer() { Index = index.ToString(), UniqueName = uniqueName + enchantment, LocalizationDescriptionVariable = description != null ? description.Value : LocalizationData.ItemPrefix + uniqueName + LocalizationData.DescPostfix, LocalizationNameVariable = localizationNameVariable }; SetLocalization(localizationData, container); writeItem(outputStream, container, first); if (first) { first = false; } index++; if (node.Name == "journalitem") { journals.Add(new ItemContainer() { UniqueName = uniqueName }); } var element = FindElement(node, "enchantments"); if (element != null) { foreach (XmlElement childNode in element.ChildNodes) { var enchantmentName = node.Attributes["uniquename"].Value + "@" + childNode.Attributes["enchantmentlevel"].Value; container = new ItemContainer() { Index = index.ToString(), UniqueName = enchantmentName, LocalizationDescriptionVariable = description != null ? description.Value : LocalizationData.ItemPrefix + uniqueName + LocalizationData.DescPostfix, LocalizationNameVariable = name != null ? name.Value : LocalizationData.ItemPrefix + uniqueName }; SetLocalization(localizationData, container); writeItem(outputStream, container, false); index++; } } } } foreach (ItemContainer j in journals) { var container = new ItemContainer() { Index = index.ToString(), UniqueName = j.UniqueName + "_EMPTY", LocalizationDescriptionVariable = LocalizationData.ItemPrefix + j.UniqueName + "_EMPTY" + LocalizationData.DescPostfix, LocalizationNameVariable = LocalizationData.ItemPrefix + j.UniqueName + "_EMPTY" }; SetLocalization(localizationData, container); writeItem(outputStream, container, false); index++; container = new ItemContainer() { Index = index.ToString(), UniqueName = j.UniqueName + "_FULL", LocalizationDescriptionVariable = LocalizationData.ItemPrefix + j.UniqueName + "_FULL" + LocalizationData.DescPostfix, LocalizationNameVariable = LocalizationData.ItemPrefix + j.UniqueName + "_FULL" }; SetLocalization(localizationData, container); writeItem(outputStream, container, false); index++; } } private void SetLocalization(LocalizationData data, ItemContainer item) { if (data == default) return; if (data.LocalizedDescriptions.TryGetValue(item.LocalizationDescriptionVariable, out var descriptions)) { item.LocalizedDescriptions = descriptions; } if (data.LocalizedNames.TryGetValue(item.LocalizationNameVariable, out var names)) { item.LocalizedNames = names; } } protected override string GetBinFilePath() { return Path.Combine(Program.MainGameFolder, @".\game\Albion-Online_Data\StreamingAssets\GameData\items.bin"); } } }
37.661538
184
0.625613
[ "MIT" ]
ao-data/ao-id-extractor
Extractors/ItemExtractor.cs
4,898
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace DataExplorer.Presentation.Panes.Navigation.StartMenu { /// <summary> /// Interaction logic for StartMenuView.xaml /// </summary> public partial class StartMenuView : UserControl { public StartMenuView() { InitializeComponent(); } } }
23.724138
62
0.731105
[ "BSD-3-Clause" ]
dataexplorer/dataexplorer
Presentation/Panes/Navigation/StartMenu/StartMenuView.xaml.cs
690
C#
using System.Drawing; namespace GdiPlusExtensions.Filters { /// <summary> /// These filters process the image based on the process of convolution /// </summary> public struct ConvolutionFilter : IFilterType { /// <inheritdoc/> public string FilterName { get; private set; } /// <inheritdoc/> public byte KernelSize => (byte)_kernel.GetLength(0); private readonly int[,] _kernel; private readonly int _denominator; /// <summary> /// For creating a custom Convolution Filter /// </summary> /// <param name="name">The name for the filter</param> /// <param name="kernel">The rectangular kernel matrix</param> /// <param name="den">The common denominator</param> public ConvolutionFilter(string name, int[,] kernel, int den) { FilterName = name; _kernel = kernel; _denominator = den; } /// <inheritdoc/> public Color ProcessPixelOfKernel(ref Bitmap bitmap, int x, int y) { int w = bitmap.Width - 1, h = bitmap.Height - 1, kh = KernelSize / 2; (int R, int G, int B) = (0, 0, 0); for (int i1 = x - kh, i2 = KernelSize - 1, il = x + kh; i1 <= il; i1++, i2--) { for (int j1 = y - kh, j2 = KernelSize - 1, jl = y + kh; j1 < jl; j1++, j2--) { int i = Common.Clamp(i1, 0, w), j = Common.Clamp(j1, 0, h); Color c = bitmap.GetPixel(i, j); float val = _kernel[i2, j2] / (float)_denominator; R += (int)(val * c.R); G += (int)(val * c.G); B += (int)(val * c.B); } } return Color.FromArgb((byte)R, (byte)G, (byte)B); } /// <inheritdoc/> public void Setup() => Filters.DefaultSetup(this); /// <summary> /// a spatial domain linear filter in which each pixel in the resulting image has a value equal to the average value of its neighboring pixels in the input image. It is a form of low-pass ("blurring") filter. /// </summary> public static ConvolutionFilter BoxBlur => new ConvolutionFilter ( "Box Blur Filter", new int[3, 3] { {1,1,1}, {1,1,1}, {1,1,1} }, 9 ); /// <summary> /// a Gaussian blur (also known as Gaussian smoothing) /// is the result of blurring an image by a Gaussian function.<br/> /// It is a widely used effect in graphics software, typically to reduce image noise /// and reduce detail. /// The visual effect of this blurring technique is a smooth blur resembling that of /// viewing the image through a translucent screen, distinctly different from the /// bokeh effect produced by an out-of-focus lens or the /// shadow of an object under usual illumination. /// </summary> public static ConvolutionFilter GaussianFilter => new ConvolutionFilter ( "Gaussian Blur Filter", new int[3, 3] { {1,2,1}, {2,4,2}, {1,2,1} }, 16 ); } }
32.247059
210
0.631157
[ "MIT" ]
AzuxirenLeadGuy/GdiPlusExtension
GdiPlusExtensions/src/Filters/ConvolutionFilter.cs
2,741
C#
using System; using System.Diagnostics; using System.Text.RegularExpressions; using Unity.Collections; #if UNITY_EDITOR using UnityEditor; #endif using UnityEngine; using UnityEngine.Experimental.Rendering; using UnityEngine.Perception.GroundTruth; namespace GroundTruthTests { static class TestHelper { #if UNITY_EDITOR private static EditorWindow s_GameView; #endif public static GameObject CreateLabeledPlane(float scale = 10, string label = "label") { GameObject planeObject; planeObject = GameObject.CreatePrimitive(PrimitiveType.Plane); planeObject.transform.SetPositionAndRotation(new Vector3(0, 0, 10), Quaternion.Euler(90, 0, 0)); planeObject.transform.localScale = new Vector3(scale, -1, scale); var labeling = planeObject.AddComponent<Labeling>(); labeling.labels.Add(label); return planeObject; } public static GameObject CreateLabeledCube(float scale = 10, string label = "label", float x = 0, float y = 0, float z = 0, float roll = 0, float pitch = 0, float yaw = 0) { var cube = GameObject.CreatePrimitive(PrimitiveType.Cube); return SetupLabeledCube(cube, scale, label, x, y, z, roll, pitch, yaw); } public static GameObject SetupLabeledCube(GameObject cube, float scale = 10, string label = "label", float x = 0, float y = 0, float z = 0, float roll = 0, float pitch = 0, float yaw = 0) { cube.transform.SetPositionAndRotation(new Vector3(x, y, z), Quaternion.Euler(pitch, yaw, roll)); cube.transform.localScale = new Vector3(scale, scale, scale); var labeling = cube.AddComponent<Labeling>(); labeling.labels.Add(label); return cube; } public static void ReadRenderTextureRawData<T>(RenderTexture renderTexture, Action<NativeArray<T>> callback) where T : struct { RenderTexture.active = renderTexture; var cpuTexture = new Texture2D(renderTexture.width, renderTexture.height, renderTexture.graphicsFormat, TextureCreationFlags.None); cpuTexture.ReadPixels(new Rect( Vector2.zero, new Vector2(renderTexture.width, renderTexture.height)), 0, 0); RenderTexture.active = null; var data = cpuTexture.GetRawTextureData<T>(); callback(data); } #if UNITY_EDITOR public static void LoadAndStartRenderDocCapture() { UnityEditorInternal.RenderDoc.Load(); System.Reflection.Assembly assembly = typeof(UnityEditor.EditorWindow).Assembly; Type type = assembly.GetType("UnityEditor.GameView"); s_GameView = UnityEditor.EditorWindow.GetWindow(type); UnityEditorInternal.RenderDoc.BeginCaptureRenderDoc(s_GameView); } [Conditional("UNITY_EDITOR")] public static void EndCaptureRenderDoc() { UnityEditorInternal.RenderDoc.EndCaptureRenderDoc(s_GameView); } #endif public static string NormalizeJson(string json, bool normalizeFormatting = false) { if (normalizeFormatting) json = Regex.Replace(json, "^\\s*", "", RegexOptions.Multiline); return json.Replace("\r\n", "\n"); } } }
39.195402
195
0.641056
[ "Apache-2.0" ]
2dpodcast/com.unity.perception
com.unity.perception/Tests/Runtime/GroundTruthTests/TestHelper.cs
3,410
C#
using Godot; using Quadrecep.GameMode.Navigate.Map; namespace Quadrecep.GameMode.Navigate { public class NoteNode : Node2D { /// <summary> /// How long before the note is actually pressed /// </summary> public const float FadeInTime = 1000; /// <summary> /// How long the transition from alpha 0 to 1 takes /// </summary> public const float FadeLength = 750; public static PackedScene Scene; private bool _finished; private LogTransition _transition; public DirectionObject InputLeft; public NoteObject Note; public APlay<NoteObject> Parent; public override void _Ready() { _transition = new LogTransition(Note.StartTime - FadeInTime, FadeLength); Note.BindNode = this; InputLeft = new DirectionObject(Note.Direction); UpdateVisibility(); } public override void _Process(float delta) { if (!_finished && InputLeft == 0) { _finished = true; FadeOut(); } UpdateVisibility(); } private void UpdateVisibility() { Modulate = GetAlphaModulate(); Visible = Modulate.a > 0; } public void FadeOut() { Visible = false; QueueFree(); } private Color GetAlphaModulate() { var mod = Modulate; mod.a = _transition.GetCurrent(Parent.Time); return mod; } } }
24.861538
85
0.532797
[ "MIT" ]
QiuFeng54321/Quadrecep
Scripts/GameMode/Navigate/NoteNode.cs
1,616
C#
namespace Authentiqr.NET.Code.EncryptionV3 { public class CryptoConfig { /// <summary> /// Number of iterations to derive a strong password /// </summary> public int Iterations { get; set; } /// <summary> /// Size of salt to prepend to data prior to encryption, in bytes, minimum of 8 /// </summary> public int SaltSize { get; set; } /// <summary> /// Size of checksum to append to data, in bytes, valid range of 0-20 /// </summary> public int ChecksumSize { get; set; } } }
27.904762
87
0.559727
[ "MIT" ]
richard-green/Authentiqr.NET
src/Authentiqr.NET/Code/EncryptionV3/CryptoConfig.cs
588
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("AkureTraining.Web")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("AkureTraining.Web")] [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("06663537-a447-487b-b346-01b12d172bc1")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.972222
84
0.749086
[ "Apache-2.0" ]
Smartware/AkureMvcTraining
AkureTraining.Web/Properties/AssemblyInfo.cs
1,370
C#
using HealthyNutGuysDomain.Models; using HealthyNutGuysDomain.Repositories; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace HealthyNutGuysDataCore.Repositories { public class SpecialOfferRepository : ISpecialOfferRepository { public SpecialOfferRepository(HealthyNutGuysContext dbContext) { this._dbContext = dbContext; } private readonly HealthyNutGuysContext _dbContext; public async Task<List<SpecialOffer>> GetAllAsync(CancellationToken ct = default) { return await this._dbContext.SpecialOffers.Where(o => o.Deleted == false).ToListAsync(ct); } } }
27.241379
102
0.734177
[ "MIT" ]
omikolaj/healthy-nut-guys-api
HealthyNutGuysDataCore/Repositories/SpecialOfferRepository.cs
792
C#
using System.Threading; using System.Threading.Tasks; using Acs3; using AElf.Contracts.MultiToken; using AElf.Contracts.TestKit; using AElf.Cryptography.ECDSA; using AElf.Sdk.CSharp; using AElf.Types; using Google.Protobuf; using Google.Protobuf.WellKnownTypes; using Shouldly; using Xunit; using ApproveInput = Acs3.ApproveInput; namespace AElf.Contracts.ParliamentAuth { public class ParliamentAuthContractTest : ParliamentAuthContractTestBase { public ParliamentAuthContractTest() { InitializeContracts(); } [Fact] public async Task Get_DefaultOrganizationAddressFailed_Test() { var transactionResult = await OtherParliamentAuthContractStub.GetGenesisOwnerAddress.SendAsync(new Empty()); transactionResult.TransactionResult.Status.ShouldBe(TransactionResultStatus.Failed); transactionResult.TransactionResult.Error.Contains("Not initialized.").ShouldBeTrue(); } [Fact] public async Task ParliamentAuthContract_Initialize_Test() { var result = await ParliamentAuthContractStub.Initialize.SendAsync( new InitializeInput {GenesisOwnerReleaseThreshold = 6666}); result.TransactionResult.Status.ShouldBe(TransactionResultStatus.Mined); } [Fact] public async Task ParliamentAuthContract_InitializeTwice_Test() { await ParliamentAuthContract_Initialize_Test(); var result = await ParliamentAuthContractStub.Initialize.SendAsync( new InitializeInput {GenesisOwnerReleaseThreshold = 6666}); result.TransactionResult.Status.ShouldBe(TransactionResultStatus.Failed); result.TransactionResult.Error.Contains("Already initialized.").ShouldBeTrue(); } [Fact] public async Task Get_Organization_Test() { var createOrganizationInput = new CreateOrganizationInput { ReleaseThreshold = 10000 / MinersCount }; var transactionResult = await ParliamentAuthContractStub.CreateOrganization.SendAsync(createOrganizationInput); var organizationAddress = transactionResult.Output; var getOrganization = await ParliamentAuthContractStub.GetOrganization.CallAsync(organizationAddress); getOrganization.OrganizationAddress.ShouldBe(organizationAddress); getOrganization.ReleaseThreshold.ShouldBe(10000 / MinersCount); getOrganization.OrganizationHash.ShouldBe(Hash.FromTwoHashes( Hash.FromMessage(ParliamentAuthContractAddress), Hash.FromMessage(createOrganizationInput))); getOrganization.ProposerAuthorityRequired.ShouldBe(false); } [Fact] public async Task Get_OrganizationFailed_Test() { var organization = await ParliamentAuthContractStub.GetOrganization.CallAsync(SampleAddress.AddressList[0]); organization.ShouldBe(new Organization()); } [Fact] public async Task Get_Proposal_Test() { var organizationAddress = await CreateOrganizationAsync(); var transferInput = new TransferInput() { Symbol = "ELF", Amount = 100, To = Tester, Memo = "Transfer" }; var proposalId = await CreateProposalAsync(DefaultSenderKeyPair, organizationAddress); var getProposal = await ParliamentAuthContractStub.GetProposal.SendAsync(proposalId); getProposal.Output.Proposer.ShouldBe(DefaultSender); getProposal.Output.ContractMethodName.ShouldBe(nameof(TokenContractStub.Transfer)); getProposal.Output.ProposalId.ShouldBe(proposalId); getProposal.Output.OrganizationAddress.ShouldBe(organizationAddress); getProposal.Output.ToAddress.ShouldBe(TokenContractAddress); getProposal.Output.Params.ShouldBe(transferInput.ToByteString()); } [Fact] public async Task Get_ProposalFailed_Test() { var proposalOutput = await ParliamentAuthContractStub.GetProposal.CallAsync(Hash.FromString("Test")); proposalOutput.ShouldBe(new ProposalOutput()); } [Fact] public async Task Create_OrganizationFailed_Test() { var createOrganizationInput = new CreateOrganizationInput { ReleaseThreshold = 0 }; { var transactionResult = await ParliamentAuthContractStub.CreateOrganization.SendAsync(createOrganizationInput); transactionResult.TransactionResult.Status.ShouldBe(TransactionResultStatus.Failed); transactionResult.TransactionResult.Error.Contains("Invalid organization.").ShouldBeTrue(); } { createOrganizationInput.ReleaseThreshold = 100000; var transactionResult = await ParliamentAuthContractStub.CreateOrganization.SendAsync(createOrganizationInput); transactionResult.TransactionResult.Status.ShouldBe(TransactionResultStatus.Failed); transactionResult.TransactionResult.Error.Contains("Invalid organization.").ShouldBeTrue(); } } [Fact] public async Task Create_ProposalFailed_Test() { var organizationAddress = await CreateOrganizationAsync(); var blockTime = BlockTimeProvider.GetBlockTime(); var createProposalInput = new CreateProposalInput { ToAddress = SampleAddress.AddressList[0], Params = ByteString.CopyFromUtf8("Test"), ExpiredTime = blockTime.AddDays(1), OrganizationAddress = organizationAddress }; //"Invalid proposal." //ContractMethodName is null or white space { var transactionResult = await ParliamentAuthContractStub.CreateProposal.SendAsync(createProposalInput); transactionResult.TransactionResult.Status.ShouldBe(TransactionResultStatus.Failed); transactionResult.TransactionResult.Error.Contains("Invalid proposal.").ShouldBeTrue(); } //ToAddress is null { createProposalInput.ContractMethodName = "Test"; createProposalInput.ToAddress = null; var transactionResult = await ParliamentAuthContractStub.CreateProposal.SendAsync(createProposalInput); transactionResult.TransactionResult.Status.ShouldBe(TransactionResultStatus.Failed); transactionResult.TransactionResult.Error.Contains("Invalid proposal.").ShouldBeTrue(); } //ExpiredTime is null { createProposalInput.ExpiredTime = null; createProposalInput.ToAddress = SampleAddress.AddressList[0]; var transactionResult = await ParliamentAuthContractStub.CreateProposal.SendAsync(createProposalInput); transactionResult.TransactionResult.Status.ShouldBe(TransactionResultStatus.Failed); transactionResult.TransactionResult.Error.Contains("Invalid proposal.").ShouldBeTrue(); } //"Expired proposal." { createProposalInput.ExpiredTime = blockTime.AddMilliseconds(5); Thread.Sleep(10); var transactionResult = await ParliamentAuthContractStub.CreateProposal.SendAsync(createProposalInput); transactionResult.TransactionResult.Status.ShouldBe(TransactionResultStatus.Failed); } //"No registered organization." { createProposalInput.ExpiredTime = BlockTimeProvider.GetBlockTime().AddDays(1); createProposalInput.OrganizationAddress = SampleAddress.AddressList[1]; var transactionResult = await ParliamentAuthContractStub.CreateProposal.SendAsync(createProposalInput); transactionResult.TransactionResult.Status.ShouldBe(TransactionResultStatus.Failed); transactionResult.TransactionResult.Error.Contains("No registered organization.").ShouldBeTrue(); } //"Proposal already exists." { createProposalInput.OrganizationAddress = organizationAddress; var transactionResult1 = await ParliamentAuthContractStub.CreateProposal.SendAsync(createProposalInput); transactionResult1.TransactionResult.Status.ShouldBe(TransactionResultStatus.Mined); var transactionResult2 = await ParliamentAuthContractStub.CreateProposal.SendAsync(createProposalInput); transactionResult2.TransactionResult.Status.ShouldBe(TransactionResultStatus.Failed); transactionResult2.TransactionResult.Error.Contains("Proposal already exists.").ShouldBeTrue(); } //"Not authorized to propose." { var privilegeOrganizationAddress = await CreatePrivilegeOrganizationAsync(); createProposalInput.OrganizationAddress = privilegeOrganizationAddress; var transactionResult = await ParliamentAuthContractStub.CreateProposal.SendAsync(createProposalInput); transactionResult.TransactionResult.Status.ShouldBe(TransactionResultStatus.Failed); transactionResult.TransactionResult.Error.Contains("Not authorized to propose.").ShouldBeTrue(); } } [Fact] public async Task Approve_Proposal_NotFoundProposal_Test() { var transactionResult = await ParliamentAuthContractStub.Approve.SendAsync(new ApproveInput { ProposalId = Hash.FromString("Test") }); transactionResult.TransactionResult.Status.ShouldBe(TransactionResultStatus.Failed); } [Fact] public async Task Approve_Proposal_NotAuthorizedApproval_Test() { var organizationAddress = await CreateOrganizationAsync(); var proposalId = await CreateProposalAsync(DefaultSenderKeyPair, organizationAddress); ParliamentAuthContractStub = GetParliamentAuthContractTester(TesterKeyPair); var transactionResult = await ParliamentAuthContractStub.Approve.SendAsync(new ApproveInput { ProposalId = proposalId }); transactionResult.TransactionResult.Status.ShouldBe(TransactionResultStatus.Failed); transactionResult.TransactionResult.Error.Contains("Not authorized approval.").ShouldBeTrue(); } [Fact] public async Task Approve_Proposal_ExpiredTime_Test() { var organizationAddress = await CreateOrganizationAsync(); var proposalId = await CreateProposalAsync(DefaultSenderKeyPair, organizationAddress); ParliamentAuthContractStub = GetParliamentAuthContractTester(InitialMinersKeyPairs[0]); BlockTimeProvider.SetBlockTime(BlockTimeProvider.GetBlockTime().AddDays(5)); var transactionResult = await ParliamentAuthContractStub.Approve.CallAsync(new ApproveInput { ProposalId = proposalId }); transactionResult.Value.ShouldBe(false); } [Fact] public async Task Approve_Proposal_ApprovalAlreadyExists_Test() { var organizationAddress = await CreateOrganizationAsync(); var proposalId = await CreateProposalAsync(DefaultSenderKeyPair, organizationAddress); ParliamentAuthContractStub = GetParliamentAuthContractTester(InitialMinersKeyPairs[0]); var transactionResult1 = await ParliamentAuthContractStub.Approve.SendAsync(new ApproveInput {ProposalId = proposalId}); transactionResult1.TransactionResult.Status.ShouldBe(TransactionResultStatus.Mined); transactionResult1.Output.Value.ShouldBe(true); var transactionResult2 = await ParliamentAuthContractStub.Approve.SendAsync(new ApproveInput {ProposalId = proposalId}); transactionResult2.TransactionResult.Status.ShouldBe(TransactionResultStatus.Failed); transactionResult2.TransactionResult.Error.Contains("Already approved").ShouldBeTrue(); } [Fact] public async Task Release_NotEnoughWeight_Test() { var organizationAddress = await CreateOrganizationAsync(); var proposalId = await CreateProposalAsync(DefaultSenderKeyPair, organizationAddress); await TransferToOrganizationAddressAsync(organizationAddress); await ApproveAsync(InitialMinersKeyPairs[0], proposalId); ParliamentAuthContractStub = GetParliamentAuthContractTester(DefaultSenderKeyPair); var result = await ParliamentAuthContractStub.Release.SendAsync(proposalId); //Reviewer Shares < ReleaseThreshold, release failed result.TransactionResult.Status.ShouldBe(TransactionResultStatus.Failed); result.TransactionResult.Error.Contains("Not approved.").ShouldBeTrue(); } [Fact] public async Task Release_NotFound_Test() { var proposalId = Hash.FromString("test"); var result = await ParliamentAuthContractStub.Release.SendAsync(proposalId); //Proposal not found result.TransactionResult.Status.ShouldBe(TransactionResultStatus.Failed); result.TransactionResult.Error.Contains("Proposal not found.").ShouldBeTrue(); } [Fact] public async Task Release_WrongSender_Test() { var organizationAddress = await CreateOrganizationAsync(); var proposalId = await CreateProposalAsync(DefaultSenderKeyPair, organizationAddress); await TransferToOrganizationAddressAsync(organizationAddress); await ApproveAsync(InitialMinersKeyPairs[0], proposalId); await ApproveAsync(InitialMinersKeyPairs[1], proposalId); ParliamentAuthContractStub = GetParliamentAuthContractTester(TesterKeyPair); var result = await ParliamentAuthContractStub.Release.SendAsync(proposalId); result.TransactionResult.Status.ShouldBe(TransactionResultStatus.Failed); result.TransactionResult.Error.Contains("Unable to release this proposal.").ShouldBeTrue(); } [Fact] public async Task Release_Proposal_Test() { var organizationAddress = await CreateOrganizationAsync(); var proposalId = await CreateProposalAsync(DefaultSenderKeyPair, organizationAddress); await TransferToOrganizationAddressAsync(organizationAddress); await ApproveAsync(InitialMinersKeyPairs[0], proposalId); await ApproveAsync(InitialMinersKeyPairs[1], proposalId); ParliamentAuthContractStub = GetParliamentAuthContractTester(DefaultSenderKeyPair); var result = await ParliamentAuthContractStub.Release.SendAsync(proposalId); result.TransactionResult.Status.ShouldBe(TransactionResultStatus.Mined); //After release,the proposal will be deleted //var getProposal = await AssociationAuthContractStub.GetProposal.SendAsync(proposalId.Result); //getProposal.TransactionResult.Status.ShouldBe(TransactionResultStatus.Failed); //getProposal.TransactionResult.Error.Contains("Not found proposal.").ShouldBeTrue(); // Check inline transaction result var getBalance = TokenContractStub.GetBalance.CallAsync(new GetBalanceInput { Symbol = "ELF", Owner = Tester }).Result.Balance; getBalance.ShouldBe(100); } [Fact] public async Task Change_GenesisContractOwner_Test() { var contractOwner = await ParliamentAuthContractStub.GetGenesisOwnerAddress.CallAsync(new Empty()); contractOwner.ShouldBe(new Address()); var initializeParliament = await ParliamentAuthContractStub.Initialize.SendAsync(new InitializeInput { GenesisOwnerReleaseThreshold = 1, ProposerAuthorityRequired = false }); initializeParliament.TransactionResult.Status.ShouldBe(TransactionResultStatus.Mined); contractOwner = await ParliamentAuthContractStub.GetGenesisOwnerAddress.CallAsync(new Empty()); contractOwner.ShouldNotBe(new Address()); //no permission var transactionResult = await BasicContractStub.ChangeGenesisOwner.SendAsync(Tester); transactionResult.TransactionResult.Status.ShouldBe(TransactionResultStatus.Failed); transactionResult.TransactionResult.Error.ShouldContain("Unauthorized behavior"); } private async Task<Hash> CreateProposalAsync(ECKeyPair proposalKeyPair, Address organizationAddress) { var transferInput = new TransferInput() { Symbol = "ELF", Amount = 100, To = Tester, Memo = "Transfer" }; var createProposalInput = new CreateProposalInput { ContractMethodName = nameof(TokenContractStub.Transfer), ToAddress = TokenContractAddress, Params = transferInput.ToByteString(), ExpiredTime = BlockTimeProvider.GetBlockTime().AddDays(2), OrganizationAddress = organizationAddress }; ParliamentAuthContractStub = GetParliamentAuthContractTester(proposalKeyPair); var proposal = await ParliamentAuthContractStub.CreateProposal.SendAsync(createProposalInput); proposal.TransactionResult.Status.ShouldBe(TransactionResultStatus.Mined); return proposal.Output; } private async Task<Address> CreateOrganizationAsync() { var createOrganizationInput = new CreateOrganizationInput { ReleaseThreshold = 20000 / MinersCount }; var transactionResult = await ParliamentAuthContractStub.CreateOrganization.SendAsync(createOrganizationInput); transactionResult.TransactionResult.Status.ShouldBe(TransactionResultStatus.Mined); return transactionResult.Output; } private async Task<Address> CreatePrivilegeOrganizationAsync() { var createOrganizationInput = new CreateOrganizationInput { ReleaseThreshold = 20000 / MinersCount, ProposerAuthorityRequired = true, ProposerWhiteList = {Tester} }; var transactionResult = await ParliamentAuthContractStub.CreateOrganization.SendAsync(createOrganizationInput); transactionResult.TransactionResult.Status.ShouldBe(TransactionResultStatus.Mined); return transactionResult.Output; } private async Task TransferToOrganizationAddressAsync(Address to) { await TokenContractStub.Transfer.SendAsync(new TransferInput { Symbol = "ELF", Amount = 200, To = to, Memo = "transfer organization address" }); } private async Task ApproveAsync(ECKeyPair reviewer, Hash proposalId) { ParliamentAuthContractStub = GetParliamentAuthContractTester(reviewer); var transactionResult = await ParliamentAuthContractStub.Approve.SendAsync(new ApproveInput {ProposalId = proposalId}); transactionResult.TransactionResult.Status.ShouldBe(TransactionResultStatus.Mined); transactionResult.Output.Value.ShouldBe(true); } } }
48.907583
121
0.654489
[ "MIT" ]
IamWenboZhang/AElf
test/AElf.Contracts.ParliamentAuth.Tests/ParliamentAuthContractTest.cs
20,639
C#
using System; using System.Xml.Serialization; namespace Aop.Api.Domain { /// <summary> /// AlipayMarketingActivityOrdervoucherCreateModel Data Structure. /// </summary> [Serializable] public class AlipayMarketingActivityOrdervoucherCreateModel : AopObject { /// <summary> /// 活动名称。 不对用户进行展示,仅供商家在后台管理活动使用。 /// </summary> [XmlElement("activity_name")] public string ActivityName { get; set; } /// <summary> /// 商家券活动归属的商户信息。 说明: 如果该复杂对象不填。则默认为该商家券活动的归属者是调用者本人。 如果填写,则认为该商家券活动的归属者是该商户。 /// </summary> [XmlElement("belong_merchant_info")] public BelongMerchantInfo BelongMerchantInfo { get; set; } /// <summary> /// 码模式。 枚举值: MERCHANT_UPLOAD:商户上传自定义code,发券时系统随机选取上传的券code发放 /// </summary> [XmlElement("code_mode")] public string CodeMode { get; set; } /// <summary> /// 用户引导相关配置 /// </summary> [XmlElement("customer_guide")] public CustomerGuide CustomerGuide { get; set; } /// <summary> /// 外部业务单号,用作幂等控制。 幂等作用: 参数不变的情况下,再次请求返回与上一次相同的结果。 外部接入方需保证业务单号唯一。 /// </summary> [XmlElement("out_biz_no")] public string OutBizNo { get; set; } /// <summary> /// 券发放结束时间。 格式为:yyyy-MM-dd HH:mm:ss 限制: 券发放结束时间 publish_end_time 与 券发放开始时间 publish_start_time 间隔必须小于等于180天 /// </summary> [XmlElement("publish_end_time")] public string PublishEndTime { get; set; } /// <summary> /// 券发放开始时间。 格式为:yyyy-MM-dd HH:mm:ss /// </summary> [XmlElement("publish_start_time")] public string PublishStartTime { get; set; } /// <summary> /// 券展示信息 /// </summary> [XmlElement("voucher_display_info")] public VoucherDisplayInfo VoucherDisplayInfo { get; set; } /// <summary> /// 券发放规则 /// </summary> [XmlElement("voucher_send_rule")] public VoucherSendRuleDetail VoucherSendRule { get; set; } /// <summary> /// 券类型。 枚举值: FIX_VOUCHER:满减券。 /// </summary> [XmlElement("voucher_type")] public string VoucherType { get; set; } /// <summary> /// 券核销规则 /// </summary> [XmlElement("voucher_use_rule")] public VoucherUseRule VoucherUseRule { get; set; } } }
31.468354
125
0.55712
[ "Apache-2.0" ]
piaoye2019/alipay-sdk-net-all
AlipaySDKNet.Standard/Domain/AlipayMarketingActivityOrdervoucherCreateModel.cs
3,038
C#
using System; using System.Globalization; using System.Linq; using System.Reflection; namespace TimeTakenTestServer.Areas.HelpPage.ModelDescriptions { internal static class ModelNameHelper { // Modify this to provide custom model name mapping. public static string GetModelName(Type type) { ModelNameAttribute modelNameAttribute = type.GetCustomAttribute<ModelNameAttribute>(); if (modelNameAttribute != null && !String.IsNullOrEmpty(modelNameAttribute.Name)) { return modelNameAttribute.Name; } string modelName = type.Name; if (type.IsGenericType) { // Format the generic type name to something like: GenericOfAgurment1AndArgument2 Type genericType = type.GetGenericTypeDefinition(); Type[] genericArguments = type.GetGenericArguments(); string genericTypeName = genericType.Name; // Trim the generic parameter counts from the name genericTypeName = genericTypeName.Substring(0, genericTypeName.IndexOf('`')); string[] argumentTypeNames = genericArguments.Select(t => GetModelName(t)).ToArray(); modelName = String.Format(CultureInfo.InvariantCulture, "{0}Of{1}", genericTypeName, String.Join("And", argumentTypeNames)); } return modelName; } } }
40.222222
140
0.638122
[ "Apache-2.0" ]
joymon/dotnet-demos
web/iis/time-taken-field-demo/TestServer/Areas/HelpPage/ModelDescriptions/ModelNameHelper.cs
1,448
C#
using Cysharp.Threading.Tasks; namespace Mirror.Tests { public class MockComponent : NetworkBehaviour { public int cmdArg1; public string cmdArg2; [ServerRpc] public void Test(int arg1, string arg2) { cmdArg1 = arg1; cmdArg2 = arg2; } public NetworkIdentity cmdNi; [ServerRpc] public void CmdNetworkIdentity(NetworkIdentity ni) { cmdNi = ni; } public int rpcResult; [ServerRpc] public UniTask<int> GetResult() { return UniTask.FromResult(rpcResult); } public int rpcArg1; public string rpcArg2; [ClientRpc] public void RpcTest(int arg1, string arg2) { rpcArg1 = arg1; rpcArg2 = arg2; } public int targetRpcArg1; public string targetRpcArg2; public INetworkConnection targetRpcConn; [ClientRpc(target = Mirror.Client.Connection)] public void ClientConnRpcTest(INetworkConnection conn, int arg1, string arg2) { targetRpcConn = conn; targetRpcArg1 = arg1; targetRpcArg2 = arg2; } public int rpcOwnerArg1; public string rpcOwnerArg2; [ClientRpc(target = Mirror.Client.Owner)] public void RpcOwnerTest(int arg1, string arg2) { rpcOwnerArg1 = arg1; rpcOwnerArg2 = arg2; } } }
22.818182
85
0.557769
[ "MIT" ]
dragonslaya84/MirrorNG
Assets/Tests/Runtime/MockComponent.cs
1,506
C#
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) // This code is distributed under the GNU LGPL (for details please see \doc\license.txt) using System; using ICSharpCode.SharpDevelop.Dom; using NUnit.Framework; using XmlEditor.Tests.Utils; namespace XmlEditor.Tests.Folding { [TestFixture] public class MultiLineCommentFoldTestFixture { XmlFoldParserHelper helper; [SetUp] public void Init() { string xml = "<!-- first line\r\n" + "second line -->\r\n" + "<a />"; helper = new XmlFoldParserHelper(); helper.CreateParser(); helper.GetFolds(xml); } [Test] public void GetFolds_MultiLineComment_ReturnsOneFold() { int count = helper.Folds.Count; Assert.AreEqual(1, count); } [Test] public void GetFolds_MultiLineComment_FoldNameIsCommentTagsWithFirstLineOfTextBetween() { string name = helper.GetFirstFoldName(); string expectedName = "<!-- first line -->"; Assert.AreEqual(expectedName, name); } [Test] public void GetFolds_MultiLineComment_FoldRegionContainsEntireComment() { DomRegion region = helper.GetFirstFoldRegion(); int beginLine = 1; int beginColumn = 1; int endLine = 2; int endColumn = 16; DomRegion expectedRegion = new DomRegion(beginLine, beginColumn, endLine, endColumn); Assert.AreEqual(expectedRegion, region); } } }
23.949153
103
0.707006
[ "MIT" ]
Plankankul/SharpDevelop-w-Framework
src/AddIns/DisplayBindings/XmlEditor/Test/Folding/MultiLineCommentFoldTestFixture.cs
1,415
C#
/* * MIT License * * Copyright (c) 2021 [FacuFalcone] * * 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.Windows.Forms; namespace WindowsFormsAppTest { static class Program { /// <summary> /// Punto de entrada principal para la aplicación. /// </summary> [STAThread] static void Main() { //Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new FrmPrincipal()); } } }
38.487805
81
0.712294
[ "MIT" ]
caidevOficial/CSharp_UTN_LaboII
2_Modelos_Examenes/PP_2021_Hospital/Hospital.GUI/Program.cs
1,581
C#
using UnityEngine; namespace UnityAtoms.BaseAtoms { /// <summary> /// Variable of type `Vector2`. Inherits from `EquatableAtomVariable&lt;Vector2, Vector2Pair, Vector2Event, Vector2PairEvent, Vector2Vector2Function&gt;`. /// </summary> [EditorIcon("atom-icon-lush")] [CreateAssetMenu(menuName = "Unity Atoms/Variables/Vector2", fileName = "Vector2Variable")] public sealed class Vector2Variable : EquatableAtomVariable<Vector2, Vector2Pair, Vector2Event, Vector2PairEvent, Vector2Vector2Function> { /// <summary> /// Multiply variable by value. /// </summary> /// <param name="value">Value to multiple by.</param> public void MultiplyBy(float value) => Value *= value; /// <summary> /// Multiply variable by Variable value. /// </summary> /// <param name="variable">Variable with value to multiple by.</param> public void MultiplyBy(AtomBaseVariable<float> variable) => MultiplyBy(variable.Value); /// <summary> /// Divide Variable by value. /// </summary> /// <param name="value">Value to divide by.</param> public void DivideBy(float value) => Value /= value; /// <summary> /// Divide Variable by Variable value. /// </summary> /// <param name="variable">Variable value to divide by.</param> public void DivideBy(AtomBaseVariable<float> variable) => DivideBy(variable.Value); } }
39.945946
158
0.638024
[ "MIT" ]
AdamRamberg/unity-atoms
Packages/BaseAtoms/Runtime/Variables/Vector2Variable.cs
1,478
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class EnemySpawn : MonoBehaviour { public GameObject[] Enemy; public GameObject SpawnPosition; public GameObject TheCity; int index; // Start is called before the first frame update void Start() { StartCoroutine(SpawnEnemy()); } IEnumerator SpawnEnemy() { index = Random.Range(0, Enemy.Length); var EnemySpawn = Instantiate(Enemy[index], SpawnPosition.transform.position, Quaternion.identity); EnemySpawn.transform.SetParent(TheCity.transform); yield return new WaitForSeconds(30f); StartCoroutine(SpawnEnemy()); } }
27.88
106
0.69297
[ "Apache-2.0" ]
Adityanand/Bullzye
Assets/Scripts/EnemySpawn.cs
699
C#
using System; using Elide.Scintilla.Internal; namespace Elide.Scintilla.ObjectModel { public enum SciKey { Add = Sci.SCK_ADD, Back = Sci.SCK_BACK, Delete = Sci.SCK_DELETE, Divide = Sci.SCK_DIVIDE, Down = Sci.SCK_DOWN, End = Sci.SCK_END, Escape = Sci.SCK_ESCAPE, Home = Sci.SCK_HOME, Insert = Sci.SCK_INSERT, Left = Sci.SCK_LEFT, Menu = Sci.SCK_MENU, PageDown = Sci.SCK_NEXT, PageUp = Sci.SCK_PRIOR, Return = Sci.SCK_RETURN, Right = Sci.SCK_RIGHT, Rwin = Sci.SCK_RWIN, Subtract = Sci.SCK_SUBTRACT, Tab = Sci.SCK_TAB, Up = Sci.SCK_UP, Win = Sci.SCK_WIN } }
16.244898
38
0.518844
[ "MIT" ]
vorov2/ela
Elide/Elide.Scintilla/ObjectModel/SciKey.cs
798
C#
using System; using Marten.Events.Projections; using Marten.Schema; using Npgsql; using Shouldly; using Xunit; namespace Marten.Testing.Schema { public class UniqueIndexTests { private class UserCreated { public Guid UserId { get; set; } public string Email { get; set; } public string FirstName { get; set; } public string Surname { get; set; } } private class User { public Guid Id { get; set; } public string UserName { get; set; } [UniqueIndex(IndexType = UniqueIndexType.DuplicatedField)] public string Email { get; set; } [UniqueIndex(IndexName = "fullname")] public string FirstName { get; set; } [UniqueIndex(IndexName = "fullname")] public string Surname { get; set; } } private class UserViewProjection : ViewProjection<User, Guid> { public UserViewProjection() { ProjectEvent<UserCreated>(Apply); } private void Apply(User view, UserCreated @event) { view.Id = @event.UserId; view.Email = @event.Email; view.UserName = @event.Email; view.FirstName = @event.Email; view.Surname = @event.Surname; } } public IDocumentStore InitStore() { var options = new StoreOptions(); options.Connection(ConnectionSource.ConnectionString); options.Events.AddEventTypes(new[] { typeof(UserCreated) }); options.Events.InlineProjections.Add(new UserViewProjection()); options.RegisterDocumentType<User>(); return DocumentStore.For(ConnectionSource.ConnectionString); } public const string UniqueSqlState = "23505"; [Fact] public void given_two_documents_with_the_same_value_for_unique_field_with_multiple_properties_when_created_then_throws_exception() { //1. Create Events var firstDocument = new User { Id = Guid.NewGuid(), Email = "john.doe@gmail.com", FirstName = "John", Surname = "Doe" }; var secondDocument = new User { Id = Guid.NewGuid(), Email = "some.mail@outlook.com", FirstName = "John", Surname = "Doe" }; using (var store = InitStore()) { using (var session = store.OpenSession()) { //2. Save documents session.Store(firstDocument); session.Store(secondDocument); //3. Unique Exception Was thrown try { session.SaveChanges(); } catch (MartenCommandException exception) { ((PostgresException)exception.InnerException).SqlState.ShouldBe(UniqueSqlState); } } } } [Fact] public void given_two_documents_with_the_same_value_for_unique_field_with_single_property_when_created_then_throws_exception() { //1. Create Events const string email = "john.smith@mail.com"; var firstDocument = new User { Id = Guid.NewGuid(), Email = email, FirstName = "John", Surname = "Smith" }; var secondDocument = new User { Id = Guid.NewGuid(), Email = email, FirstName = "John", Surname = "Doe" }; using (var store = InitStore()) { using (var session = store.OpenSession()) { //2. Save documents session.Store(firstDocument); session.Store(secondDocument); //3. Unique Exception Was thrown try { session.SaveChanges(); } catch (MartenCommandException exception) { ((PostgresException)exception.InnerException).SqlState.ShouldBe(UniqueSqlState); } } } } [Fact] public void given_two_events_with_the_same_value_for_unique_field_with_multiple_properties_when_inline_transformation_is_applied_then_throws_exception() { //1. Create Events var firstEvent = new UserCreated { UserId = Guid.NewGuid(), Email = "john.doe@gmail.com", FirstName = "John", Surname = "Doe" }; var secondEvent = new UserCreated { UserId = Guid.NewGuid(), Email = "some.mail@outlook.com", FirstName = "John", Surname = "Doe" }; using (var store = InitStore()) { using (var session = store.OpenSession()) { //2. Publish Events session.Events.Append(firstEvent.UserId, firstEvent); session.Events.Append(secondEvent.UserId, secondEvent); //3. Unique Exception Was thrown try { session.SaveChanges(); } catch (MartenCommandException exception) { ((PostgresException)exception.InnerException).SqlState.ShouldBe(UniqueSqlState); } } } } [Fact] public void given_two_events_with_the_same_value_for_unique_field_with_single_property_when_inline_transformation_is_applied_then_throws_exception() { //1. Create Events const string email = "john.smith@mail.com"; var firstEvent = new UserCreated { UserId = Guid.NewGuid(), Email = email, FirstName = "John", Surname = "Smith" }; var secondEvent = new UserCreated { UserId = Guid.NewGuid(), Email = email, FirstName = "John", Surname = "Doe" }; using (var store = InitStore()) { using (var session = store.OpenSession()) { //2. Publish Events session.Events.Append(firstEvent.UserId, firstEvent); session.Events.Append(secondEvent.UserId, secondEvent); //3. Unique Exception Was thrown try { session.SaveChanges(); } catch (MartenCommandException exception) { ((PostgresException)exception.InnerException).SqlState.ShouldBe(UniqueSqlState); } } } } } }
38.683333
161
0.509838
[ "MIT" ]
Maximusya/marten
src/Marten.Testing/Schema/UniqueIndexTests.cs
6,965
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. /*============================================================ ** ** ** ** ** ** Purpose: Default way to access String and Object resources ** from an assembly. ** ** ===========================================================*/ namespace System.Resources { using System; using System.IO; using System.Globalization; using System.Collections; using System.Text; using System.Reflection; using System.Security; using System.Threading; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using Microsoft.Win32; using System.Collections.Generic; using System.Runtime.Versioning; using System.Diagnostics; #if FEATURE_APPX using Internal.Resources; #endif // Resource Manager exposes an assembly's resources to an application for // the correct CultureInfo. An example would be localizing text for a // user-visible message. Create a set of resource files listing a name // for a message and its value, compile them using ResGen, put them in // an appropriate place (your assembly manifest(?)), then create a Resource // Manager and query for the name of the message you want. The Resource // Manager will use CultureInfo.GetCurrentUICulture() to look // up a resource for your user's locale settings. // // Users should ideally create a resource file for every culture, or // at least a meaningful subset. The filenames will follow the naming // scheme: // // basename.culture name.resources // // The base name can be the name of your application, or depending on // the granularity desired, possibly the name of each class. The culture // name is determined from CultureInfo's Name property. // An example file name may be MyApp.en-US.resources for // MyApp's US English resources. // // ----------------- // Refactoring Notes // ----------------- // In Feb 08, began first step of refactoring ResourceManager to improve // maintainability (sd changelist 3012100). This resulted in breaking // apart the InternalGetResourceSet "big loop" so that the file-based // and manifest-based lookup was located in separate methods. // In Apr 08, continued refactoring so that file-based and manifest-based // concerns are encapsulated by separate classes. At construction, the // ResourceManager creates one of these classes based on whether the // RM will need to use file-based or manifest-based resources, and // afterwards refers to this through the interface IResourceGroveler. // // Serialization Compat: Ideally, we could have refactored further but // this would have broken serialization compat. For example, the // ResourceManager member UseManifest and UseSatelliteAssem are no // longer relevant on ResourceManager. Similarly, other members could // ideally be moved to the file-based or manifest-based classes // because they are only relevant for those types of lookup. // // Solution now / in the future: // For now, we simply use a mediator class so that we can keep these // members on ResourceManager but allow the file-based and manifest- // based classes to access/set these members in a uniform way. See // ResourceManagerMediator. // We encapsulate fallback logic in a fallback iterator class, so that // this logic isn't duplicated in several methods. // // In the future, we can also look into further factoring and better // design of IResourceGroveler interface to accommodate unused parameters // that don't make sense for either file-based or manifest-based lookup paths. // // Benefits of this refactoring: // - Makes it possible to understand what the ResourceManager does, // which is key for maintainability. // - Makes the ResourceManager more extensible by identifying and // encapsulating what varies // - Unearthed a bug that's been lurking a while in file-based // lookup paths for InternalGetResourceSet if createIfNotExists is // false. // - Reuses logic, e.g. by breaking apart the culture fallback into // the fallback iterator class, we don't have to repeat the // sometimes confusing fallback logic across multiple methods // - Fxcop violations reduced to 1/5th of original count. Most // importantly, code complexity violations disappeared. // - Finally, it got rid of dead code paths. Because the big loop was // so confusing, it masked unused chunks of code. Also, dividing // between file-based and manifest-based allowed functionaliy // unused in silverlight to fall out. // // Note: this type is integral to the construction of exception objects, // and sometimes this has to be done in low memory situtations (OOM) or // to create TypeInitializationExceptions due to failure of a static class // constructor. This type needs to be extremely careful and assume that // any type it references may have previously failed to construct, so statics // belonging to that type may not be initialized. FrameworkEventSource.Log // is one such example. // public class ResourceManager { internal class CultureNameResourceSetPair { public string lastCultureName; public ResourceSet lastResourceSet; } protected string BaseNameField; // Sets is a many-to-one table of CultureInfos mapped to ResourceSets. // Don't synchronize ResourceSets - too fine-grained a lock to be effective [Obsolete("call InternalGetResourceSet instead")] internal Hashtable ResourceSets; private Dictionary<string, ResourceSet> _resourceSets; private string moduleDir; // For assembly-ignorant directory location protected Assembly MainAssembly; // Need the assembly manifest sometimes. private Type _locationInfo; // For Assembly or type-based directory layout private Type _userResourceSet; // Which ResourceSet instance to create private CultureInfo _neutralResourcesCulture; // For perf optimizations. private CultureNameResourceSetPair _lastUsedResourceCache; private bool _ignoreCase; // Whether case matters in GetString & GetObject private bool UseManifest; // Use Assembly manifest, or grovel disk. #if RESOURCE_SATELLITE_CONFIG private static volatile Hashtable _installedSatelliteInfo; // Give the user the option // to prevent certain satellite assembly probes via a config file. // Note that config files are per-appdomain, not per-assembly nor process private static volatile bool _checkedConfigFile; // Did we read the app's config file? #endif // Whether to fall back to the main assembly or a particular // satellite for the neutral resources. private UltimateResourceFallbackLocation _fallbackLoc; // Version number of satellite assemblies to look for. May be null. private Version _satelliteContractVersion; private bool _lookedForSatelliteContractVersion; private RuntimeAssembly _callingAssembly; // Assembly who created the ResMgr. private IResourceGroveler resourceGroveler; public static readonly int MagicNumber = unchecked((int)0xBEEFCACE); // If only hex had a K... // Version number so ResMgr can get the ideal set of classes for you. // ResMgr header is: // 1) MagicNumber (little endian Int32) // 2) HeaderVersionNumber (little endian Int32) // 3) Num Bytes to skip past ResMgr header (little endian Int32) // 4) IResourceReader type name for this file (bytelength-prefixed UTF-8 String) // 5) ResourceSet type name for this file (bytelength-prefixed UTF8 String) public static readonly int HeaderVersionNumber = 1; // //It would be better if we could use _neutralCulture instead of calling //CultureInfo.InvariantCulture everywhere, but we run into problems with the .cctor. CultureInfo //initializes assembly, which initializes ResourceManager, which tries to get a CultureInfo which isn't //there yet because CultureInfo's class initializer hasn't finished. If we move SystemResMgr off of //Assembly (or at least make it an internal property) we should be able to circumvent this problem. // // private static CultureInfo _neutralCulture = null; // This is our min required ResourceSet type. private static readonly Type _minResourceSet = typeof(ResourceSet); // These Strings are used to avoid using Reflection in CreateResourceSet. // The first set are used by ResourceWriter. The second are used by // InternalResGen. internal static readonly string ResReaderTypeName = typeof(ResourceReader).FullName; internal static readonly string ResSetTypeName = typeof(RuntimeResourceSet).FullName; internal static readonly string MscorlibName = typeof(ResourceReader).Assembly.FullName; internal const string ResFileExtension = ".resources"; internal const int ResFileExtensionLength = 10; private static volatile bool s_IsAppXModel; [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod private void Init() { _callingAssembly = (RuntimeAssembly)Assembly.GetCallingAssembly(); } protected ResourceManager() { Init(); _lastUsedResourceCache = new CultureNameResourceSetPair(); ResourceManagerMediator mediator = new ResourceManagerMediator(this); resourceGroveler = new ManifestBasedResourceGroveler(mediator); } // Constructs a Resource Manager for files beginning with // baseName in the directory specified by resourceDir // or in the current directory. This Assembly-ignorant constructor is // mostly useful for testing your own ResourceSet implementation. // // A good example of a baseName might be "Strings". BaseName // should not end in ".resources". // // Note: System.Windows.Forms uses this method at design time. // private ResourceManager(string baseName, string resourceDir, Type usingResourceSet) { if (null == baseName) throw new ArgumentNullException(nameof(baseName)); if (null == resourceDir) throw new ArgumentNullException(nameof(resourceDir)); BaseNameField = baseName; moduleDir = resourceDir; _userResourceSet = usingResourceSet; #pragma warning disable 618 ResourceSets = new Hashtable(); // for backward compatibility #pragma warning restore 618 _resourceSets = new Dictionary<string, ResourceSet>(); _lastUsedResourceCache = new CultureNameResourceSetPair(); UseManifest = false; ResourceManagerMediator mediator = new ResourceManagerMediator(this); resourceGroveler = new FileBasedResourceGroveler(mediator); } [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod public ResourceManager(string baseName, Assembly assembly) { if (null == baseName) throw new ArgumentNullException(nameof(baseName)); if (null == assembly) throw new ArgumentNullException(nameof(assembly)); if (!(assembly is RuntimeAssembly)) throw new ArgumentException(SR.Argument_MustBeRuntimeAssembly); MainAssembly = assembly; BaseNameField = baseName; SetAppXConfiguration(); CommonAssemblyInit(); _callingAssembly = (RuntimeAssembly)Assembly.GetCallingAssembly(); // Special case for mscorlib - protect mscorlib's private resources. // This isn't for security reasons, but to ensure we can make // breaking changes to mscorlib's internal resources without // assuming users may have taken a dependency on them. if (assembly == typeof(object).Assembly && _callingAssembly != assembly) { _callingAssembly = null; } } [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod public ResourceManager(string baseName, Assembly assembly, Type usingResourceSet) { if (null == baseName) throw new ArgumentNullException(nameof(baseName)); if (null == assembly) throw new ArgumentNullException(nameof(assembly)); if (!(assembly is RuntimeAssembly)) throw new ArgumentException(SR.Argument_MustBeRuntimeAssembly); MainAssembly = assembly; BaseNameField = baseName; if (usingResourceSet != null && (usingResourceSet != _minResourceSet) && !(usingResourceSet.IsSubclassOf(_minResourceSet))) throw new ArgumentException(SR.Arg_ResMgrNotResSet, nameof(usingResourceSet)); _userResourceSet = usingResourceSet; CommonAssemblyInit(); _callingAssembly = (RuntimeAssembly)Assembly.GetCallingAssembly(); // Special case for mscorlib - protect mscorlib's private resources. // This isn't for security reasons, but to ensure we can make // breaking changes to mscorlib's internal resources without // assuming users may have taken a dependency on them. if (assembly == typeof(object).Assembly && _callingAssembly != assembly) _callingAssembly = null; } [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod public ResourceManager(Type resourceSource) { if (null == resourceSource) throw new ArgumentNullException(nameof(resourceSource)); if (!(resourceSource is RuntimeType)) throw new ArgumentException(SR.Argument_MustBeRuntimeType); _locationInfo = resourceSource; MainAssembly = _locationInfo.Assembly; BaseNameField = resourceSource.Name; SetAppXConfiguration(); CommonAssemblyInit(); _callingAssembly = (RuntimeAssembly)Assembly.GetCallingAssembly(); // Special case for mscorlib - protect mscorlib's private resources. if (MainAssembly == typeof(object).Assembly && _callingAssembly != MainAssembly) { _callingAssembly = null; } } // Trying to unify code as much as possible, even though having to do a // security check in each constructor prevents it. private void CommonAssemblyInit() { // Now we can use the managed resources even when using PRI's to support the APIs GetObject, GetStream...etc. UseManifest = true; _resourceSets = new Dictionary<string, ResourceSet>(); _lastUsedResourceCache = new CultureNameResourceSetPair(); _fallbackLoc = UltimateResourceFallbackLocation.MainAssembly; ResourceManagerMediator mediator = new ResourceManagerMediator(this); resourceGroveler = new ManifestBasedResourceGroveler(mediator); _neutralResourcesCulture = ManifestBasedResourceGroveler.GetNeutralResourcesLanguage(MainAssembly, ref _fallbackLoc); } // Gets the base name for the ResourceManager. public virtual string BaseName { get { return BaseNameField; } } // Whether we should ignore the capitalization of resources when calling // GetString or GetObject. public virtual bool IgnoreCase { get { return _ignoreCase; } set { _ignoreCase = value; } } // Returns the Type of the ResourceSet the ResourceManager uses // to construct ResourceSets. public virtual Type ResourceSetType { get { return (_userResourceSet == null) ? typeof(RuntimeResourceSet) : _userResourceSet; } } protected UltimateResourceFallbackLocation FallbackLocation { get { return _fallbackLoc; } set { _fallbackLoc = value; } } // Tells the ResourceManager to call Close on all ResourceSets and // release all resources. This will shrink your working set by // potentially a substantial amount in a running application. Any // future resource lookups on this ResourceManager will be as // expensive as the very first lookup, since it will need to search // for files and load resources again. // // This may be useful in some complex threading scenarios, where // creating a new ResourceManager isn't quite the correct behavior. public virtual void ReleaseAllResources() { Dictionary<string, ResourceSet> localResourceSets = _resourceSets; // If any calls to Close throw, at least leave ourselves in a // consistent state. _resourceSets = new Dictionary<string, ResourceSet>(); _lastUsedResourceCache = new CultureNameResourceSetPair(); lock (localResourceSets) { foreach ((_, ResourceSet resourceSet) in localResourceSets) { resourceSet.Close(); } } } public static ResourceManager CreateFileBasedResourceManager(string baseName, string resourceDir, Type usingResourceSet) { return new ResourceManager(baseName, resourceDir, usingResourceSet); } // Given a CultureInfo, GetResourceFileName generates the name for // the binary file for the given CultureInfo. This method uses // CultureInfo's Name property as part of the file name for all cultures // other than the invariant culture. This method does not touch the disk, // and is used only to construct what a resource file name (suitable for // passing to the ResourceReader constructor) or a manifest resource file // name should look like. // // This method can be overriden to look for a different extension, // such as ".ResX", or a completely different format for naming files. protected virtual string GetResourceFileName(CultureInfo culture) { // If this is the neutral culture, don't include the culture name. if (culture.HasInvariantCultureName) { return BaseNameField + ResFileExtension; } else { CultureInfo.VerifyCultureName(culture.Name, throwException: true); return BaseNameField + "." + culture.Name + ResFileExtension; } } // WARNING: This function must be kept in sync with ResourceFallbackManager.GetEnumerator() // Return the first ResourceSet, based on the first culture ResourceFallbackManager would return internal ResourceSet GetFirstResourceSet(CultureInfo culture) { // Logic from ResourceFallbackManager.GetEnumerator() if (_neutralResourcesCulture != null && culture.Name == _neutralResourcesCulture.Name) { culture = CultureInfo.InvariantCulture; } if (_lastUsedResourceCache != null) { lock (_lastUsedResourceCache) { if (culture.Name == _lastUsedResourceCache.lastCultureName) return _lastUsedResourceCache.lastResourceSet; } } // Look in the ResourceSet table Dictionary<string, ResourceSet> localResourceSets = _resourceSets; ResourceSet rs = null; if (localResourceSets != null) { lock (localResourceSets) { localResourceSets.TryGetValue(culture.Name, out rs); } } if (rs != null) { // update the cache with the most recent ResourceSet if (_lastUsedResourceCache != null) { lock (_lastUsedResourceCache) { _lastUsedResourceCache.lastCultureName = culture.Name; _lastUsedResourceCache.lastResourceSet = rs; } } return rs; } return null; } // Looks up a set of resources for a particular CultureInfo. This is // not useful for most users of the ResourceManager - call // GetString() or GetObject() instead. // // The parameters let you control whether the ResourceSet is created // if it hasn't yet been loaded and if parent CultureInfos should be // loaded as well for resource inheritance. // [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod public virtual ResourceSet GetResourceSet(CultureInfo culture, bool createIfNotExists, bool tryParents) { if (null == culture) throw new ArgumentNullException(nameof(culture)); Dictionary<string, ResourceSet> localResourceSets = _resourceSets; ResourceSet rs; if (localResourceSets != null) { lock (localResourceSets) { if (localResourceSets.TryGetValue(culture.Name, out rs)) return rs; } } StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; if (UseManifest && culture.HasInvariantCultureName) { string fileName = GetResourceFileName(culture); RuntimeAssembly mainAssembly = (RuntimeAssembly)MainAssembly; Stream stream = mainAssembly.GetManifestResourceStream(_locationInfo, fileName, _callingAssembly == MainAssembly, ref stackMark); if (createIfNotExists && stream != null) { rs = ((ManifestBasedResourceGroveler)resourceGroveler).CreateResourceSet(stream, MainAssembly); AddResourceSet(localResourceSets, culture.Name, ref rs); return rs; } } // Note: ideally we could plumb through the stack crawl mark here, but we must // call the virtual 3-argument InternalGetResourceSet method for compatibility. // Security-wise, we're not overly interested in protecting access to resources, // since full-trust callers can get them already and most resources are public. // Also, the JIT inliner could always inline a caller into another assembly's // method. // So if we happen to return some resources in cases where we should really be // doing a demand for member access permissions, we're not overly concerned. return InternalGetResourceSet(culture, createIfNotExists, tryParents); } // InternalGetResourceSet is a non-threadsafe method where all the logic // for getting a resource set lives. Access to it is controlled by // threadsafe methods such as GetResourceSet, GetString, & GetObject. // This will take a minimal number of locks. [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod protected virtual ResourceSet InternalGetResourceSet(CultureInfo culture, bool createIfNotExists, bool tryParents) { Debug.Assert(culture != null, "culture != null"); StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; return InternalGetResourceSet(culture, createIfNotExists, tryParents, ref stackMark); } // InternalGetResourceSet is a non-threadsafe method where all the logic // for getting a resource set lives. Access to it is controlled by // threadsafe methods such as GetResourceSet, GetString, & GetObject. // This will take a minimal number of locks. private ResourceSet InternalGetResourceSet(CultureInfo requestedCulture, bool createIfNotExists, bool tryParents, ref StackCrawlMark stackMark) { Dictionary<string, ResourceSet> localResourceSets = _resourceSets; ResourceSet rs = null; CultureInfo foundCulture = null; lock (localResourceSets) { if (localResourceSets.TryGetValue(requestedCulture.Name, out rs)) { return rs; } } ResourceFallbackManager mgr = new ResourceFallbackManager(requestedCulture, _neutralResourcesCulture, tryParents); foreach (CultureInfo currentCultureInfo in mgr) { lock (localResourceSets) { if (localResourceSets.TryGetValue(currentCultureInfo.Name, out rs)) { // we need to update the cache if we fellback if (requestedCulture != currentCultureInfo) foundCulture = currentCultureInfo; break; } } // InternalGetResourceSet will never be threadsafe. However, it must // be protected against reentrancy from the SAME THREAD. (ie, calling // GetSatelliteAssembly may send some window messages or trigger the // Assembly load event, which could fail then call back into the // ResourceManager). It's happened. rs = resourceGroveler.GrovelForResourceSet(currentCultureInfo, localResourceSets, tryParents, createIfNotExists, ref stackMark); // found a ResourceSet; we're done if (rs != null) { foundCulture = currentCultureInfo; break; } } if (rs != null && foundCulture != null) { // add entries to the cache for the cultures we have gone through // currentCultureInfo now refers to the culture that had resources. // update cultures starting from requested culture up to the culture // that had resources. foreach (CultureInfo updateCultureInfo in mgr) { AddResourceSet(localResourceSets, updateCultureInfo.Name, ref rs); // stop when we've added current or reached invariant (top of chain) if (updateCultureInfo == foundCulture) { break; } } } return rs; } // Simple helper to ease maintenance and improve readability. private static void AddResourceSet(Dictionary<string, ResourceSet> localResourceSets, string cultureName, ref ResourceSet rs) { // InternalGetResourceSet is both recursive and reentrant - // assembly load callbacks in particular are a way we can call // back into the ResourceManager in unexpectedly on the same thread. lock (localResourceSets) { // If another thread added this culture, return that. ResourceSet lostRace; if (localResourceSets.TryGetValue(cultureName, out lostRace)) { if (!object.ReferenceEquals(lostRace, rs)) { // Note: In certain cases, we can be trying to add a ResourceSet for multiple // cultures on one thread, while a second thread added another ResourceSet for one // of those cultures. If there is a race condition we must make sure our ResourceSet // isn't in our dictionary before closing it. if (!localResourceSets.ContainsValue(rs)) rs.Dispose(); rs = lostRace; } } else { localResourceSets.Add(cultureName, rs); } } } protected static Version GetSatelliteContractVersion(Assembly a) { // Ensure that the assembly reference is not null if (a == null) { throw new ArgumentNullException(nameof(a), SR.ArgumentNull_Assembly); } // Return null. The calling code will use the assembly version instead to avoid potential type // and library loads caused by CA lookup. NetCF uses the assembly version always. return null; } protected static CultureInfo GetNeutralResourcesLanguage(Assembly a) { // This method should be obsolete - replace it with the one below. // Unfortunately, we made it protected. UltimateResourceFallbackLocation ignoringUsefulData = UltimateResourceFallbackLocation.MainAssembly; CultureInfo culture = ManifestBasedResourceGroveler.GetNeutralResourcesLanguage(a, ref ignoringUsefulData); return culture; } // IGNORES VERSION internal static bool CompareNames(string asmTypeName1, string typeName2, AssemblyName asmName2) { Debug.Assert(asmTypeName1 != null, "asmTypeName1 was unexpectedly null"); // First, compare type names int comma = asmTypeName1.IndexOf(','); if (((comma == -1) ? asmTypeName1.Length : comma) != typeName2.Length) return false; // case sensitive if (string.Compare(asmTypeName1, 0, typeName2, 0, typeName2.Length, StringComparison.Ordinal) != 0) return false; if (comma == -1) return true; // Now, compare assembly display names (IGNORES VERSION AND PROCESSORARCHITECTURE) // also, for mscorlib ignores everything, since that's what the binder is going to do while (char.IsWhiteSpace(asmTypeName1[++comma])) ; // case insensitive AssemblyName an1 = new AssemblyName(asmTypeName1.Substring(comma)); if (!string.Equals(an1.Name, asmName2.Name, StringComparison.OrdinalIgnoreCase)) return false; // to match IsMscorlib() in VM if (string.Equals(an1.Name, System.CoreLib.Name, StringComparison.OrdinalIgnoreCase)) return true; if ((an1.CultureInfo != null) && (asmName2.CultureInfo != null) && #if FEATURE_USE_LCID (an1.CultureInfo.LCID != asmName2.CultureInfo.LCID) #else (an1.CultureInfo.Name != asmName2.CultureInfo.Name) #endif ) return false; byte[] pkt1 = an1.GetPublicKeyToken(); byte[] pkt2 = asmName2.GetPublicKeyToken(); if ((pkt1 != null) && (pkt2 != null)) { if (pkt1.Length != pkt2.Length) return false; for (int i = 0; i < pkt1.Length; i++) { if (pkt1[i] != pkt2[i]) return false; } } return true; } #if FEATURE_APPX private string GetStringFromPRI(string stringName, string startingCulture, string neutralResourcesCulture) { Debug.Assert(_bUsingModernResourceManagement); Debug.Assert(_WinRTResourceManager != null); Debug.Assert(_PRIonAppXInitialized); Debug.Assert(AppDomain.IsAppXModel()); if (stringName.Length == 0) return null; string resourceString = null; // Do not handle exceptions. See the comment in SetAppXConfiguration about throwing // exception types that the ResourceManager class is not documented to throw. resourceString = _WinRTResourceManager.GetString( stringName, string.IsNullOrEmpty(startingCulture) ? null : startingCulture, string.IsNullOrEmpty(neutralResourcesCulture) ? null : neutralResourcesCulture); return resourceString; } // Since we can't directly reference System.Runtime.WindowsRuntime from mscorlib, we have to get the type via reflection. // It would be better if we could just implement WindowsRuntimeResourceManager in mscorlib, but we can't, because // we can do very little with WinRT in mscorlib. internal static WindowsRuntimeResourceManagerBase GetWinRTResourceManager() { Type WinRTResourceManagerType = Type.GetType("System.Resources.WindowsRuntimeResourceManager, System.Runtime.WindowsRuntime", throwOnError: true); return (WindowsRuntimeResourceManagerBase)Activator.CreateInstance(WinRTResourceManagerType, true); } #endif private bool _bUsingModernResourceManagement; // Written only by SetAppXConfiguration #if FEATURE_APPX private WindowsRuntimeResourceManagerBase _WinRTResourceManager; // Written only by SetAppXConfiguration private bool _PRIonAppXInitialized; // Written only by SetAppXConfiguration private PRIExceptionInfo _PRIExceptionInfo; // Written only by SetAppXConfiguration // When running under AppX, the following rules apply for resource lookup: // // 1) For Framework assemblies, we always use satellite assembly based lookup. // 2) For non-FX assemblies: // // a) If the assembly lives under PLATFORM_RESOURCE_ROOTS (as specified by the host during AppDomain creation), // then we will use satellite assembly based lookup in assemblies like *.resources.dll. // // b) For any other non-FX assembly, we will use the modern resource manager with the premise that app package // contains the PRI resources. private bool ShouldUseSatelliteAssemblyResourceLookupUnderAppX(RuntimeAssembly resourcesAssembly) { bool fUseSatelliteAssemblyResourceLookupUnderAppX = typeof(object).Assembly == resourcesAssembly; if (!fUseSatelliteAssemblyResourceLookupUnderAppX) { // Check to see if the assembly is under PLATFORM_RESOURCE_ROOTS. If it is, then we should use satellite assembly lookup for it. string platformResourceRoots = (string)(AppDomain.CurrentDomain.GetData("PLATFORM_RESOURCE_ROOTS")); if ((platformResourceRoots != null) && (platformResourceRoots != string.Empty)) { string resourceAssemblyPath = resourcesAssembly.Location; // Loop through the PLATFORM_RESOURCE_ROOTS and see if the assembly is contained in it. foreach (string pathPlatformResourceRoot in platformResourceRoots.Split(Path.PathSeparator)) { if (resourceAssemblyPath.StartsWith(pathPlatformResourceRoot, StringComparison.CurrentCultureIgnoreCase)) { // Found the resource assembly to be present in one of the PLATFORM_RESOURCE_ROOT, so stop the enumeration loop. fUseSatelliteAssemblyResourceLookupUnderAppX = true; break; } } } } return fUseSatelliteAssemblyResourceLookupUnderAppX; } #endif // FEATURE_APPX // Only call SetAppXConfiguration from ResourceManager constructors, and nowhere else. // Throws MissingManifestResourceException and WinRT HResults private void SetAppXConfiguration() { Debug.Assert(_bUsingModernResourceManagement == false); // Only this function writes to this member #if FEATURE_APPX Debug.Assert(_WinRTResourceManager == null); // Only this function writes to this member Debug.Assert(_PRIonAppXInitialized == false); // Only this function writes to this member Debug.Assert(_PRIExceptionInfo == null); // Only this function writes to this member bool bUsingSatelliteAssembliesUnderAppX = false; RuntimeAssembly resourcesAssembly = (RuntimeAssembly)MainAssembly; if (resourcesAssembly == null) resourcesAssembly = _callingAssembly; if (resourcesAssembly != null) { if (resourcesAssembly != typeof(object).Assembly) // We are not loading resources for mscorlib { // Cannot load the WindowsRuntimeResourceManager when in a compilation process, since it // lives in System.Runtime.WindowsRuntime and only mscorlib may be loaded for execution. if (AppDomain.IsAppXModel()) { s_IsAppXModel = true; // If we have the type information from the ResourceManager(Type) constructor, we use it. Otherwise, we use BaseNameField. string reswFilename = _locationInfo == null ? BaseNameField : _locationInfo.FullName; // The only way this can happen is if a class inherited from ResourceManager and // did not set the BaseNameField before calling the protected ResourceManager() constructor. // For other constructors, we would already have thrown an ArgumentNullException by now. // Throwing an ArgumentNullException now is not the right thing to do because technically // ResourceManager() takes no arguments, and because it is not documented as throwing // any exceptions. Instead, let's go through the rest of the initialization with this set to // an empty string. We may in fact fail earlier for another reason, but otherwise we will // throw a MissingManifestResourceException when GetString is called indicating that a // resW filename called "" could not be found. if (reswFilename == null) reswFilename = string.Empty; WindowsRuntimeResourceManagerBase WRRM = null; bool bWRRM_Initialized = false; if (AppDomain.IsAppXDesignMode()) { WRRM = GetWinRTResourceManager(); try { PRIExceptionInfo exceptionInfo; // If the exception info is filled in, we will ignore it. bWRRM_Initialized = WRRM.Initialize(resourcesAssembly.Location, reswFilename, out exceptionInfo); bUsingSatelliteAssembliesUnderAppX = !bWRRM_Initialized; } catch (Exception e) { bUsingSatelliteAssembliesUnderAppX = true; if (e.IsTransient) throw; } } if (!bUsingSatelliteAssembliesUnderAppX) { _bUsingModernResourceManagement = !ShouldUseSatelliteAssemblyResourceLookupUnderAppX(resourcesAssembly); if (_bUsingModernResourceManagement) { // Only now are we certain that we need the PRI file. // Note that if IsAppXDesignMode is false, we haven't checked if the PRI file exists. // This is by design. We will find out in the call to WindowsRuntimeResourceManager.Initialize below. // At this point it is important NOT to set _bUsingModernResourceManagement to false // if the PRI file does not exist because we are now certain we need to load PRI // resources. We want to fail by throwing a MissingManifestResourceException // if WindowsRuntimeResourceManager.Initialize fails to locate the PRI file. We do not // want to fall back to using satellite assemblies anymore. Note that we would not throw // the MissingManifestResourceException from this function, but from GetString. See the // comment below on the reason for this. if (WRRM != null && bWRRM_Initialized) { // Reuse the one successfully created earlier _WinRTResourceManager = WRRM; _PRIonAppXInitialized = true; } else { _WinRTResourceManager = GetWinRTResourceManager(); try { _PRIonAppXInitialized = _WinRTResourceManager.Initialize(resourcesAssembly.Location, reswFilename, out _PRIExceptionInfo); // Note that _PRIExceptionInfo might be null - this is OK. // In that case we will just throw the generic // MissingManifestResource_NoPRIresources exception. // See the implementation of GetString for more details. } // We would like to be able to throw a MissingManifestResourceException here if PRI resources // could not be loaded for a recognized reason. However, the ResourceManager constructors // that call SetAppXConfiguration are not documented as throwing MissingManifestResourceException, // and since they are part of the portable profile, we cannot start throwing a new exception type // as that would break existing portable libraries. Hence we must save the exception information // now and throw the exception on the first call to GetString. catch (FileNotFoundException) { // We will throw MissingManifestResource_NoPRIresources from GetString // when we see that _PRIonAppXInitialized is false. } catch (Exception e) { // ERROR_MRM_MAP_NOT_FOUND can be thrown by the call to ResourceManager.get_AllResourceMaps // in WindowsRuntimeResourceManager.Initialize. // In this case _PRIExceptionInfo is now null and we will just throw the generic // MissingManifestResource_NoPRIresources exception. // See the implementation of GetString for more details. if (e.HResult != HResults.ERROR_MRM_MAP_NOT_FOUND) throw; // Unexpected exception code. Bubble it up to the caller. } if (!_PRIonAppXInitialized) { _bUsingModernResourceManagement = false; } // Allow all other exception types to bubble up to the caller. // Yes, this causes us to potentially throw exception types that are not documented. // Ultimately the tradeoff is the following: // -We could ignore unknown exceptions or rethrow them as inner exceptions // of exceptions that the ResourceManager class is already documented as throwing. // This would allow existing portable libraries to gracefully recover if they don't care // too much about the ResourceManager object they are using. However it could // mask potentially fatal errors that we are not aware of, such as a disk drive failing. // The alternative, which we chose, is to throw unknown exceptions. This may tear // down the process if the portable library and app don't expect this exception type. // On the other hand, this won't mask potentially fatal errors we don't know about. } } } } } } // resourcesAssembly == null should not happen but it can. See the comment on Assembly.GetCallingAssembly. // However for the sake of 100% backwards compatibility on Win7 and below, we must leave // _bUsingModernResourceManagement as false. #endif // FEATURE_APPX } // Looks up a resource value for a particular name. Looks in the // current thread's CultureInfo, and if not found, all parent CultureInfos. // Returns null if the resource wasn't found. // public virtual string GetString(string name) { return GetString(name, (CultureInfo)null); } // Looks up a resource value for a particular name. Looks in the // specified CultureInfo, and if not found, all parent CultureInfos. // Returns null if the resource wasn't found. // public virtual string GetString(string name, CultureInfo culture) { if (null == name) throw new ArgumentNullException(nameof(name)); #if FEATURE_APPX if (s_IsAppXModel) { // If the caller explictily passed in a culture that was obtained by calling CultureInfo.CurrentUICulture, // null it out, so that we re-compute it. If we use modern resource lookup, we may end up getting a "better" // match, since CultureInfo objects can't represent all the different languages the AppX resource model supports. // For classic resources, this causes us to ignore the languages list and instead use the older Win32 behavior, // which is the design choice we've made. (See the call a little later to GetCurrentUICultureNoAppX()). if (object.ReferenceEquals(culture, CultureInfo.CurrentUICulture)) { culture = null; } } if (_bUsingModernResourceManagement) { if (_PRIonAppXInitialized == false) { // Always throw if we did not fully succeed in initializing the WinRT Resource Manager. if (_PRIExceptionInfo != null && _PRIExceptionInfo.PackageSimpleName != null && _PRIExceptionInfo.ResWFile != null) throw new MissingManifestResourceException(SR.Format(SR.MissingManifestResource_ResWFileNotLoaded, _PRIExceptionInfo.ResWFile, _PRIExceptionInfo.PackageSimpleName)); throw new MissingManifestResourceException(SR.MissingManifestResource_NoPRIresources); } // Throws WinRT hresults. return GetStringFromPRI(name, culture == null ? null : culture.Name, _neutralResourcesCulture.Name); } else #endif // FEATURE_APPX { if (culture == null) { // When running inside AppX we want to ignore the languages list when trying to come up with our CurrentUICulture. // This line behaves the same way as CultureInfo.CurrentUICulture would have in .NET 4 culture = CultureInfo.CurrentUICulture; } ResourceSet last = GetFirstResourceSet(culture); if (last != null) { string value = last.GetString(name, _ignoreCase); if (value != null) return value; } // This is the CultureInfo hierarchy traversal code for resource // lookups, similar but necessarily orthogonal to the ResourceSet // lookup logic. ResourceFallbackManager mgr = new ResourceFallbackManager(culture, _neutralResourcesCulture, true); foreach (CultureInfo currentCultureInfo in mgr) { ResourceSet rs = InternalGetResourceSet(currentCultureInfo, true, true); if (rs == null) break; if (rs != last) { string value = rs.GetString(name, _ignoreCase); if (value != null) { // update last used ResourceSet if (_lastUsedResourceCache != null) { lock (_lastUsedResourceCache) { _lastUsedResourceCache.lastCultureName = currentCultureInfo.Name; _lastUsedResourceCache.lastResourceSet = rs; } } return value; } last = rs; } } } return null; } // Looks up a resource value for a particular name. Looks in the // current thread's CultureInfo, and if not found, all parent CultureInfos. // Returns null if the resource wasn't found. // public virtual object GetObject(string name) { return GetObject(name, (CultureInfo)null, true); } // Looks up a resource value for a particular name. Looks in the // specified CultureInfo, and if not found, all parent CultureInfos. // Returns null if the resource wasn't found. public virtual object GetObject(string name, CultureInfo culture) { return GetObject(name, culture, true); } private object GetObject(string name, CultureInfo culture, bool wrapUnmanagedMemStream) { if (null == name) throw new ArgumentNullException(nameof(name)); #if FEATURE_APPX if (s_IsAppXModel) { // If the caller explictily passed in a culture that was obtained by calling CultureInfo.CurrentUICulture, // null it out, so that we re-compute it based on the Win32 value and not the AppX language list value. // (See the call a little later to GetCurrentUICultureNoAppX()). if (object.ReferenceEquals(culture, CultureInfo.CurrentUICulture)) { culture = null; } } #endif if (null == culture) { // When running inside AppX we want to ignore the languages list when trying to come up with our CurrentUICulture. // This line behaves the same way as CultureInfo.CurrentUICulture would have in .NET 4 culture = CultureInfo.GetCurrentUICultureNoAppX(); } ResourceSet last = GetFirstResourceSet(culture); if (last != null) { object value = last.GetObject(name, _ignoreCase); if (value != null) { UnmanagedMemoryStream stream = value as UnmanagedMemoryStream; if (stream != null && wrapUnmanagedMemStream) return new UnmanagedMemoryStreamWrapper(stream); else return value; } } // This is the CultureInfo hierarchy traversal code for resource // lookups, similar but necessarily orthogonal to the ResourceSet // lookup logic. ResourceFallbackManager mgr = new ResourceFallbackManager(culture, _neutralResourcesCulture, true); foreach (CultureInfo currentCultureInfo in mgr) { // Note: Technically this method should be passed in a stack crawl mark that we then pass // to InternalGetResourceSet for ensuring we demand permissions to read your private resources // if you're reading resources from an assembly other than yourself. But, we must call our // three argument overload (without the stack crawl mark) for compatibility. After // consideration, we aren't worried about the security impact. ResourceSet rs = InternalGetResourceSet(currentCultureInfo, true, true); if (rs == null) break; if (rs != last) { object value = rs.GetObject(name, _ignoreCase); if (value != null) { // update the last used ResourceSet if (_lastUsedResourceCache != null) { lock (_lastUsedResourceCache) { _lastUsedResourceCache.lastCultureName = currentCultureInfo.Name; _lastUsedResourceCache.lastResourceSet = rs; } } UnmanagedMemoryStream stream = value as UnmanagedMemoryStream; if (stream != null && wrapUnmanagedMemStream) return new UnmanagedMemoryStreamWrapper(stream); else return value; } last = rs; } } return null; } public UnmanagedMemoryStream GetStream(string name) { return GetStream(name, (CultureInfo)null); } public UnmanagedMemoryStream GetStream(string name, CultureInfo culture) { object obj = GetObject(name, culture, false); UnmanagedMemoryStream ums = obj as UnmanagedMemoryStream; if (ums == null && obj != null) throw new InvalidOperationException(SR.Format(SR.InvalidOperation_ResourceNotStream_Name, name)); return ums; } #if RESOURCE_SATELLITE_CONFIG // Internal helper method - gives an end user the ability to prevent // satellite assembly probes for certain cultures via a config file. private bool TryLookingForSatellite(CultureInfo lookForCulture) { if (!_checkedConfigFile) { lock (this) { if (!_checkedConfigFile) { _checkedConfigFile = true; _installedSatelliteInfo = GetSatelliteAssembliesFromConfig(); } } } if (_installedSatelliteInfo == null) return true; string[] installedSatellites = (string[])_installedSatelliteInfo[MainAssembly.FullName]; if (installedSatellites == null) return true; // The config file told us what satellites might be installed. int pos = Array.IndexOf(installedSatellites, lookForCulture.Name); return pos >= 0; } // Note: There is one config file per appdomain. This is not // per-process nor per-assembly. private Hashtable GetSatelliteAssembliesFromConfig() { return null; } #endif // RESOURCE_SATELLITE_CONFIG internal class ResourceManagerMediator { private ResourceManager _rm; internal ResourceManagerMediator(ResourceManager rm) { if (rm == null) { throw new ArgumentNullException(nameof(rm)); } _rm = rm; } // NEEDED ONLY BY FILE-BASED internal string ModuleDir { get { return _rm.moduleDir; } } // NEEDED BOTH BY FILE-BASED AND ASSEMBLY-BASED internal Type LocationInfo { get { return _rm._locationInfo; } } internal Type UserResourceSet { get { return _rm._userResourceSet; } } internal string BaseNameField { get { return _rm.BaseNameField; } } internal CultureInfo NeutralResourcesCulture { get { return _rm._neutralResourcesCulture; } set { _rm._neutralResourcesCulture = value; } } internal string GetResourceFileName(CultureInfo culture) { return _rm.GetResourceFileName(culture); } // NEEDED ONLY BY ASSEMBLY-BASED internal bool LookedForSatelliteContractVersion { get { return _rm._lookedForSatelliteContractVersion; } set { _rm._lookedForSatelliteContractVersion = value; } } internal Version SatelliteContractVersion { get { return _rm._satelliteContractVersion; } set { _rm._satelliteContractVersion = value; } } internal Version ObtainSatelliteContractVersion(Assembly a) { return ResourceManager.GetSatelliteContractVersion(a); } internal UltimateResourceFallbackLocation FallbackLoc { get { return _rm.FallbackLocation; } set { _rm._fallbackLoc = value; } } internal RuntimeAssembly CallingAssembly { get { return _rm._callingAssembly; } } internal RuntimeAssembly MainAssembly { get { return (RuntimeAssembly)_rm.MainAssembly; } } // this is weird because we have BaseNameField accessor above, but we're sticking // with it for compat. internal string BaseName { get { return _rm.BaseName; } } #if RESOURCE_SATELLITE_CONFIG internal bool TryLookingForSatellite(CultureInfo lookForCulture) { return _rm.TryLookingForSatellite(lookForCulture); } #endif } } }
46.851795
189
0.5854
[ "MIT" ]
MSHOY/coreclr
src/System.Private.CoreLib/src/System/Resources/ResourceManager.cs
61,329
C#
// <auto-generated> // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace k8s.Models { using Microsoft.Rest; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; /// <summary> /// ClusterRoleList is a collection of ClusterRoles. Deprecated in v1.17 in /// favor of rbac.authorization.k8s.io/v1 ClusterRoles, and will no longer /// be served in v1.22. /// </summary> public partial class V1beta1ClusterRoleList { /// <summary> /// Initializes a new instance of the V1beta1ClusterRoleList class. /// </summary> public V1beta1ClusterRoleList() { CustomInit(); } /// <summary> /// Initializes a new instance of the V1beta1ClusterRoleList class. /// </summary> /// <param name="items">Items is a list of ClusterRoles</param> /// <param name="apiVersion">APIVersion defines the versioned schema of /// this representation of an object. Servers should convert recognized /// schemas to the latest internal value, and may reject unrecognized /// values. More info: /// https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources</param> /// <param name="kind">Kind is a string value representing the REST /// resource this object represents. Servers may infer this from the /// endpoint the client submits requests to. Cannot be updated. In /// CamelCase. More info: /// https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds</param> /// <param name="metadata">Standard object's metadata.</param> public V1beta1ClusterRoleList(IList<V1beta1ClusterRole> items, string apiVersion = default(string), string kind = default(string), V1ListMeta metadata = default(V1ListMeta)) { ApiVersion = apiVersion; Items = items; Kind = kind; Metadata = metadata; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// Gets or sets aPIVersion defines the versioned schema of this /// representation of an object. Servers should convert recognized /// schemas to the latest internal value, and may reject unrecognized /// values. More info: /// https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources /// </summary> [JsonProperty(PropertyName = "apiVersion")] public string ApiVersion { get; set; } /// <summary> /// Gets or sets items is a list of ClusterRoles /// </summary> [JsonProperty(PropertyName = "items")] public IList<V1beta1ClusterRole> Items { get; set; } /// <summary> /// Gets or sets kind is a string value representing the REST resource /// this object represents. Servers may infer this from the endpoint /// the client submits requests to. Cannot be updated. In CamelCase. /// More info: /// https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds /// </summary> [JsonProperty(PropertyName = "kind")] public string Kind { get; set; } /// <summary> /// Gets or sets standard object's metadata. /// </summary> [JsonProperty(PropertyName = "metadata")] public V1ListMeta Metadata { get; set; } /// <summary> /// Validate the object. /// </summary> /// <exception cref="ValidationException"> /// Thrown if validation fails /// </exception> public virtual void Validate() { if (Items == null) { throw new ValidationException(ValidationRules.CannotBeNull, "Items"); } } } }
40.716981
182
0.604032
[ "Apache-2.0" ]
AshenW0lf/csharp
src/KubernetesClient/generated/Models/V1beta1ClusterRoleList.cs
4,316
C#
namespace SIS.HTTP.Headers { public interface IHttpHeaderCollection { void AddHeader(HttpHeader header); bool ContainsHeader(string key); HttpHeader GetHeader(string key); } }
17.916667
42
0.665116
[ "Apache-2.0" ]
AJMitev/Simple-Information-Services
SIS/SIS.HTTP/Headers/IHttpHeaderCollection.cs
217
C#