content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using Klarna.Rest.Core.Model.Enum; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace Klarna.Rest.Core.Model { /// <summary> /// /// </summary> public class PaymentCustomer { /// <summary> /// ISO 8601 date. The customer date of birth /// </summary> [JsonProperty(PropertyName = "date_of_birth")] public string DateOfBirth { get; set; } /// <summary> /// The customer's title /// </summary> [JsonProperty(PropertyName = "title")] public string Title { get; set; } /// <summary> /// The customer gender /// </summary> [JsonProperty(PropertyName = "gender")] public string Gender { get; set; } /// <summary> /// Last four digits for customer social security number /// </summary> [JsonProperty(PropertyName = "last_four_ssn")] public string LastFourSsn { get; set; } /// <summary> /// The customer's national identification number /// </summary> [JsonProperty(PropertyName = "national_identification_number")] public string NationalIdentificationNumber { get; set; } /// <summary> /// Type /// </summary> [JsonProperty(PropertyName = "type")] public string Type { get; set; } /// <summary> /// VAT id /// </summary> [JsonProperty(PropertyName = "vat_id")] public string VatId { get; set; } /// <summary> /// Organization entity type /// </summary> [JsonProperty(PropertyName = "organization_registration_id")] public string OrganizationRegistrationId { get; set; } [JsonConverter(typeof(StringEnumConverter))] [JsonProperty(PropertyName = "organization_entity_type")] public PaymentCustomerOrganizationEntityType OrganizationEntityType { get; set; } } }
34.607143
89
0.584623
[ "Apache-2.0" ]
Taturevich/kco_rest_dotnet
Klarna.Rest/Klarna.Rest.Core/Model/PaymentCustomer.cs
1,940
C#
/* * Copyright 2011-2015 Numeric 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. */ using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using KPComponents.KPSecurity; using KPComponents.KPSession; using KPAttributes; using KPCore.KPSecurity; using KPEntity.ORM; using NHibernate.Criterion; using KPCore.KPException; namespace KPComponents { /// <summary> /// Page with identify Enum Generic Type /// <para>Authors: Juliano Tiago Rinaldi and /// Tiago Antonio Jacobi</para> /// </summary> public class KPPage : KPPageBase { /// <summary> /// Constructor /// </summary> /// <param name="pageEnumForm">Enum Page Form Key</param> public KPPage(Enum pageEnumForm) : base(pageEnumForm) { } protected PagePermission PagePermission { get { object o = ViewState["PagePermission"]; return o == null ? null : (PagePermission)o; } private set { ViewState["PagePermission"] = value; } } protected ComponentPermission[] ComponentsPermission { get { object o = ViewState["ComponentsPermission"]; return o == null ? null : (ComponentPermission[])o; } private set { ViewState["ComponentsPermission"] = value; } } /// <summary> /// Close Current Page /// </summary> public void ClosePageForm() { ScriptManager.RegisterClientScriptBlock(this.Page, Page.GetType(), "CloseWindow", String.Format(@"window.parent.closeWindow(""{0}"");", new System.IO.FileInfo(this.Page.Request.CurrentExecutionFilePath).Name), true); } protected override void OnLoad(EventArgs e) { base.OnLoad(e); if (!IsPostBack) { if (SecuritySession != null) { string enumName = PageEnum.ToString(); PagePermission = SecuritySession.GetPagePermission(PageEnum); ComponentsPermission = SecuritySession.GetPageComponentsPermission(PageEnum); if (PagePermission != null) { if (!PagePermission.IsPreview) { string errorPermission = String.Empty; try { FrwWindow frwWindow = FrwWindow.TryFind(PagePermission.PageId); if (frwWindow != null) { errorPermission = String.Format("Permissão Negada! Você não tem acesso a tela {0} - {1}", frwWindow.WindowTitle, frwWindow.WindowDescription); } } catch { errorPermission = "Permissão Negada!"; } throw new KPExceptionSecurity(errorPermission, PagePermission); } } } } } } }
34.385965
178
0.532143
[ "Apache-2.0" ]
NumericTechnology/Platanum.Net
KPComponents/KPPages/KPPage.cs
3,926
C#
using System; using System.Linq; using System.Numerics; using ImGuiNET; using MoonSharp.Interpreter; using Quaver.API.Enums; using Quaver.Shared.Config; using Quaver.Shared.Screens.Edit.Actions; using Quaver.Shared.Scripting; namespace Quaver.Shared.Screens.Edit.Plugins { public class EditorPlugin : LuaImGui, IEditorPlugin { /// <summary> /// </summary> private EditScreen Editor { get; } /// <summary> /// </summary> public bool IsActive { get; set; } /// <summary> /// </summary> public bool IsWindowHovered { get; set; } /// <summary> /// </summary> public string Name { get; set; } /// <summary> /// </summary> public string Author { get; set; } /// <summary> /// </summary> public string Description { get; set; } /// <summary> /// If the plugin is built into the editor /// </summary> public bool IsBuiltIn { get; set; } public string Directory { get; set; } public bool IsWorkshop { get; set; } public EditorPluginMap EditorPluginMap { get; set; } /// <inheritdoc /> /// <summary> /// </summary> /// <param name="editScreen"></param> /// <param name="name"></param> /// <param name="author"></param> /// <param name="description"></param> /// <param name="filePath"></param> /// <param name="isResource"></param> /// <param name="directory"></param> /// <param name="isWorkshop"></param> public EditorPlugin(EditScreen editScreen, string name, string author, string description, string filePath, bool isResource = false, string directory = null, bool isWorkshop = false) : base(filePath, isResource) { Editor = editScreen; Name = name; Author = author; Description = description; IsBuiltIn = isResource; Directory = directory; IsWorkshop = isWorkshop; EditorPluginUtils.EditScreen = editScreen; EditorPluginMap = new EditorPluginMap(); UserData.RegisterType<GameMode>(); UserData.RegisterType<HitSounds>(); UserData.RegisterType<TimeSignature>(); UserData.RegisterType<EditorActionType>(); } /// <inheritdoc /> /// <summary> /// </summary> public void Initialize() { } /// <inheritdoc /> /// <summary> /// </summary> public override void SetFrameState() { WorkingScript.Globals["utils"] = typeof(EditorPluginUtils); WorkingScript.Globals["game_mode"] = typeof(GameMode); WorkingScript.Globals["hitsounds"] = typeof(HitSounds); WorkingScript.Globals["time_signature"] = typeof(TimeSignature); WorkingScript.Globals["action_type"] = typeof(EditorActionType); WorkingScript.Globals["actions"] = Editor.ActionManager.PluginActionManager; var state = (EditorPluginState)State; state.SongTime = Editor.Track.Time; state.UnixTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); state.SelectedHitObjects = Editor.SelectedHitObjects.Value; state.CurrentTimingPoint = Editor.WorkingMap.GetTimingPointAt(state.SongTime); state.CurrentSnap = Editor.BeatSnap.Value; state.CurrentLayer = Editor.SelectedLayer.Value ?? Editor.DefaultLayer; state.WindowSize = new Vector2(ConfigManager.WindowWidth.Value, ConfigManager.WindowHeight.Value); EditorPluginMap.Map = Editor.WorkingMap; EditorPluginMap.Track = Editor.Track; EditorPluginMap.DefaultLayer = Editor.DefaultLayer; EditorPluginMap.SetFrameState(); WorkingScript.Globals["map"] = EditorPluginMap; base.SetFrameState(); state.PushImguiStyle(); PushDefaultStyles(); } /// <summary> /// Called after rendering the plugin to pop the default style vars /// </summary> public override void AfterRender() { ImGui.PopStyleVar(); IsWindowHovered = State.IsWindowHovered; base.AfterRender(); } /// <summary> /// To push any default styling for plugin windows /// </summary> private void PushDefaultStyles() { ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(12, 4)); } /// <inheritdoc /> /// <summary> /// </summary> /// <returns></returns> public override LuaPluginState GetStateObject() => new EditorPluginState(Options); } }
32.550336
115
0.578969
[ "MPL-2.0" ]
GreenScreen410/Quaver
Quaver.Shared/Screens/Edit/Plugins/EditorPlugin.cs
4,850
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. namespace ODataValidator.Rule { #region Namespace. using System; using System.ComponentModel.Composition; using System.Linq; using System.Net; using Newtonsoft.Json.Linq; using ODataValidator.Rule.Helper; using ODataValidator.RuleEngine; using ODataValidator.RuleEngine.Common; #endregion /// <summary> /// Class of service implemenation feature to verify . /// </summary> [Export(typeof(ExtensionRule))] public class ServiceImpl_SystemQueryOptionFilter_Substring : ServiceImplExtensionRule { /// <summary> /// Gets the service implementation feature name /// </summary> public override string Name { get { return "ServiceImpl_SystemQueryOptionFilter_Substring"; } } /// <summary> /// Gets the service implementation feature description /// </summary> public override string Description { get { return this.CategoryInfo.CategoryFullName + ",$filter(substring)"; } } /// <summary> /// Gets the service implementation feature specification in OData document /// </summary> public override string V4SpecificationSection { get { return ""; } } /// <summary> /// Gets the service implementation feature level. /// </summary> public override RequirementLevel RequirementLevel { get { return RequirementLevel.Must; } } /// <summary> /// Gets the service implementation category. /// </summary> public override ServiceImplCategory CategoryInfo { get { var parent = new ServiceImplCategory(ServiceImplCategoryName.RequestingData); parent = new ServiceImplCategory(ServiceImplCategoryName.SystemQueryOption, parent); return new ServiceImplCategory(ServiceImplCategoryName.ArithmeticOperators, parent); } } /// <summary> /// Verifies the service implementation feature. /// </summary> /// <param name="context">The Interop service context</param> /// <param name="info">out parameter to return violation information when rule does not pass</param> /// <returns>true if the service implementation feature passes; false otherwise</returns> public override bool? Verify(ServiceContext context, out ExtensionRuleViolationInfo info) { if (context == null) { throw new ArgumentNullException("context"); } bool? passed = null; info = null; var svcStatus = ServiceStatus.GetInstance(); string entityTypeShortName; var propNames = MetadataHelper.GetPropertyNames("Edm.String", out entityTypeShortName); if (null == propNames || !propNames.Any()) { return passed; } string propName = propNames[0]; var entitySetUrl = entityTypeShortName.MapEntityTypeShortNameToEntitySetURL(); string url = svcStatus.RootURL.TrimEnd('/') + "/" + entitySetUrl; var resp = WebHelper.Get(new Uri(url), string.Empty, RuleEngineSetting.Instance().DefaultMaximumPayloadSize, svcStatus.DefaultHeaders); if (null != resp && HttpStatusCode.OK == resp.StatusCode) { JObject jObj = JObject.Parse(resp.ResponsePayload); JArray jArr = jObj.GetValue(Constants.Value) as JArray; var entity = jArr.First as JObject; var propVal = entity[propName].ToString(); int startIndex = propVal.Length / 2; string subStr = propVal.Substring(startIndex); url = string.Format("{0}?$filter=substring({1}, {2}) eq '{3}'", url, propName, startIndex, subStr); resp = WebHelper.Get(new Uri(url), string.Empty, RuleEngineSetting.Instance().DefaultMaximumPayloadSize, svcStatus.DefaultHeaders); var detail = new ExtensionRuleResultDetail(this.Name, url, HttpMethod.Get, string.Empty); info = new ExtensionRuleViolationInfo(new Uri(url), string.Empty, detail); if (null != resp && HttpStatusCode.OK == resp.StatusCode) { jObj = JObject.Parse(resp.ResponsePayload); jArr = jObj.GetValue(Constants.Value) as JArray; foreach (JObject et in jArr) { passed = et[propName].ToString().Substring(startIndex) == subStr; } } else { passed = false; } } return passed; } } }
37.417266
147
0.569121
[ "MIT" ]
OData/ValidationTool
src/CodeRules/ServiceImplementation/ServiceImpl_SystemQueryOptionFilter_Substring.cs
5,203
C#
#region License // Copyright (c) 2021 Peter Šulek / ScaleHQ Solutions s.r.o. // // 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. #endregion using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using LHQ.App.Code; using LHQ.App.Model; using LHQ.App.Services.Interfaces; using LHQ.App.ViewModels.Elements; using LHQ.Utils; using LHQ.Utils.Extensions; using LHQ.Utils.Utilities; namespace LHQ.App.ViewModels { public sealed class LanguageSelectorViewModel : ViewModelBase { private readonly List<string> _languagesToExclude; private readonly bool _showAllCultures; private bool _countrySpecific; private CultureInfoItem _selectedLanguage; private ObservableCollectionExt<CultureInfoItem> _cultures; private bool _searchByCultureCode; private string _textSearchPath; public LanguageSelectorViewModel(IAppContext appContext, bool countrySpecific, bool isStartupFocused) : this(appContext, null, countrySpecific, isStartupFocused) { } public LanguageSelectorViewModel(IAppContext appContext, List<string> languagesToExclude, bool countrySpecific, bool isStartupFocused) : base(appContext, true) { TextSearchPath = "CultureDisplayName"; SearchCommand = new DelegateCommand(SearchCommandExecute); PreviewTextInputCommand = new DelegateCommand<TextCompositionEventArgs>(PreviewTextInputCommandExecute); Cultures = new ObservableCollectionExt<CultureInfoItem>(); _languagesToExclude = languagesToExclude ?? new List<string>(); _showAllCultures = false; _countrySpecific = countrySpecific; SearchByCultureCode = false; IsStartupFocused = isStartupFocused; RefreshCultures(false); } public ICommand PreviewTextInputCommand { get; } public ICommand SearchCommand { get; } public bool SearchByCultureCode { get => _searchByCultureCode; set { if (SetProperty(ref _searchByCultureCode, value)) { TextSearchPath = _searchByCultureCode ? "CultureName" : "CultureDisplayName"; RaisePropertyChanged(); RefreshCultures(true); } } } public ObservableCollectionExt<CultureInfoItem> Cultures { get => _cultures; set => SetProperty(ref _cultures, value); } public bool CountrySpecific { get => _countrySpecific; set { if (SetProperty(ref _countrySpecific, value)) { RaisePropertyChanged(); RefreshCultures(true); } } } public string TextSearchPath { get => _textSearchPath; set => SetProperty(ref _textSearchPath, value); } public CultureInfoItem SelectedLanguage { get => _selectedLanguage; set { if (SetProperty(ref _selectedLanguage, value)) { RaisePropertyChanged(); } } } public bool IsStartupFocused { get; } private static List<CultureInfoItem> LoadCultures(bool showAllCultures, List<string> languagesToExclude, bool countrySpecific, bool searchByCode) { IEnumerable<CultureInfo> allCultures = CultureCache.Instance.GetAll(); if (!showAllCultures) { bool onlyNeutral = !countrySpecific; allCultures = allCultures .Where(x => { return !x.IsGenericInvariantCulture() && languagesToExclude.All(y => y != x.Name) && (onlyNeutral && x.IsNeutralCulture || !onlyNeutral && !x.IsNeutralCulture); }); } var result = allCultures .Select(x => x.ToCultureInfoItem(searchByCode)); result = searchByCode ? result.OrderBy(x => x.CultureName) : result.OrderBy(x => x.CultureDisplayName); return result.ToList(); } private void RefreshCultures(bool backupAndRestore) { string bkpSelectedCultureName = null; string bkpSelectedParentCultureName = null; if (backupAndRestore) { bkpSelectedCultureName = SelectedLanguage?.CultureName; var parentLCID = SelectedLanguage?.Culture.Parent.LCID ?? -1; bkpSelectedParentCultureName = SelectedLanguage?.CultureParentName; if (parentLCID == 127) // 127 -> invariant culture { bkpSelectedParentCultureName = SelectedLanguage?.Culture.TextInfo.CultureName; } } Cultures = new ObservableCollectionExt<CultureInfoItem>(LoadCultures(_showAllCultures, _languagesToExclude, _countrySpecific, SearchByCultureCode)); if (backupAndRestore) { CultureInfoItem foundCulture = Cultures.SingleOrDefault(x => x.Culture.Name == bkpSelectedCultureName); if (foundCulture == null) { foundCulture = Cultures.SingleOrDefault(x => x.Culture.Name == bkpSelectedParentCultureName); } if (foundCulture == null) { foundCulture = _countrySpecific ? CultureInfoItem.EnglishUS : CultureInfoItem.English; } Select(foundCulture); } } public void Select(CultureInfoItem cultureInfoItem) { if (cultureInfoItem != null) { CultureInfoItem item = Cultures.SingleOrDefault(x => x.CultureName == cultureInfoItem.CultureName); if (item == null) { CultureInfo cultureInfo = CultureCache.Instance.GetCulture(cultureInfoItem.CultureName); if (cultureInfo?.IsNeutralCulture == false) { _countrySpecific = true; Cultures = new ObservableCollectionExt<CultureInfoItem>(LoadCultures(_showAllCultures, _languagesToExclude, _countrySpecific, SearchByCultureCode)); item = Cultures.SingleOrDefault(x => x.CultureName == cultureInfoItem.CultureName); RaisePropertyChanged(nameof(CountrySpecific)); } } if (item != null) { SelectedLanguage = item; } } } private void SearchCommandExecute(object obj) { RaisePropertyChanged(); RefreshCultures(true); } private void PreviewTextInputCommandExecute(TextCompositionEventArgs e) { if (e.Source is ComboBox comboBox) { var viewModel = (LanguageSelectorViewModel)comboBox.DataContext; var searchEdit = (TextBox)comboBox.Template.FindName("PART_EditableTextBox", comboBox); string searchText = string.Empty; int selectionStart = searchEdit.SelectionStart; if (selectionStart > 0) { searchText = searchEdit.Text.Substring(0, selectionStart) + e.Text; } bool notContainsText = viewModel.SearchByCultureCode ? !viewModel.Cultures.Any( x => x.CultureName.IndexOf(searchText, StringComparison.InvariantCultureIgnoreCase) > -1) : !viewModel.Cultures.Any( x => x.CultureDisplayName.IndexOf(searchText, StringComparison.InvariantCultureIgnoreCase) > -1); if (notContainsText) { e.Handled = true; } } } } public class ComboBoxItemTemplateSelector : DataTemplateSelector { public DataTemplate NameTemplate { get; set; } public DataTemplate CodeTemplate { get; set; } public override DataTemplate SelectTemplate(object item, DependencyObject container) { if (container is FrameworkElement fe && fe.TemplatedParent is ComboBoxItem comboBoxItem) { var parent = ItemsControl.ItemsControlFromItemContainer(comboBoxItem); if (parent is ComboBox comboBox && comboBox.DataContext is LanguageSelectorViewModel dataContext) { return dataContext.SearchByCultureCode ? CodeTemplate : NameTemplate; } } return NameTemplate; } } }
37.362637
121
0.594314
[ "MIT" ]
psulek/lhqeditor
src/App/ViewModels/LanguageSelectorViewModel.cs
10,203
C#
using System; using NetRuntimeSystem = System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.ComponentModel; using System.Reflection; using System.Collections.Generic; using System.Collections; using NetOffice; namespace NetOffice.ExcelApi { ///<summary> /// DispatchInterface Worksheets /// SupportByVersion Excel, 9,10,11,12,14,15 /// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff821537.aspx ///</summary> [SupportByVersionAttribute("Excel", 9,10,11,12,14,15)] [EntityTypeAttribute(EntityType.IsDispatchInterface)] public class Worksheets : COMObject ,IEnumerable<object> { #pragma warning disable #region Type Information private static Type _type; [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public static Type LateBindingApiWrapperType { get { if (null == _type) _type = typeof(Worksheets); return _type; } } #endregion #region Construction ///<param name="factory">current used factory core</param> ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> public Worksheets(Core factory, COMObject parentObject, object comProxy) : base(factory, parentObject, comProxy) { } ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public Worksheets(COMObject parentObject, object comProxy) : base(parentObject, comProxy) { } ///<param name="factory">current used factory core</param> ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> ///<param name="comProxyType">Type of inner wrapped COM proxy"</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public Worksheets(Core factory, COMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(factory, parentObject, comProxy, comProxyType) { } ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> ///<param name="comProxyType">Type of inner wrapped COM proxy"</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public Worksheets(COMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(parentObject, comProxy, comProxyType) { } ///<param name="replacedObject">object to replaced. replacedObject are not usable after this action</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public Worksheets(COMObject replacedObject) : base(replacedObject) { } [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public Worksheets() : base() { } /// <param name="progId">registered ProgID</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public Worksheets(string progId) : base(progId) { } #endregion #region Properties /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15 /// Get /// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff839920.aspx /// </summary> [SupportByVersionAttribute("Excel", 9,10,11,12,14,15)] public NetOffice.ExcelApi.Application Application { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "Application", paramsArray); NetOffice.ExcelApi.Application newObject = Factory.CreateKnownObjectFromComProxy(this,returnItem,NetOffice.ExcelApi.Application.LateBindingApiWrapperType) as NetOffice.ExcelApi.Application; return newObject; } } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15 /// Get /// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff821569.aspx /// </summary> [SupportByVersionAttribute("Excel", 9,10,11,12,14,15)] public NetOffice.ExcelApi.Enums.XlCreator Creator { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "Creator", paramsArray); int intReturnItem = NetRuntimeSystem.Convert.ToInt32(returnItem); return (NetOffice.ExcelApi.Enums.XlCreator)intReturnItem; } } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15 /// Get /// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff841164.aspx /// Unknown COM Proxy /// </summary> [SupportByVersionAttribute("Excel", 9,10,11,12,14,15)] public object Parent { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "Parent", paramsArray); COMObject newObject = Factory.CreateObjectFromComProxy(this,returnItem); return newObject; } } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15 /// Get /// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff834982.aspx /// </summary> [SupportByVersionAttribute("Excel", 9,10,11,12,14,15)] public Int32 Count { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "Count", paramsArray); return NetRuntimeSystem.Convert.ToInt32(returnItem); } } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15 /// Get /// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff839563.aspx /// </summary> [SupportByVersionAttribute("Excel", 9,10,11,12,14,15)] public NetOffice.ExcelApi.HPageBreaks HPageBreaks { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "HPageBreaks", paramsArray); NetOffice.ExcelApi.HPageBreaks newObject = Factory.CreateKnownObjectFromComProxy(this,returnItem,NetOffice.ExcelApi.HPageBreaks.LateBindingApiWrapperType) as NetOffice.ExcelApi.HPageBreaks; return newObject; } } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15 /// Get /// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff193529.aspx /// </summary> [SupportByVersionAttribute("Excel", 9,10,11,12,14,15)] public NetOffice.ExcelApi.VPageBreaks VPageBreaks { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "VPageBreaks", paramsArray); NetOffice.ExcelApi.VPageBreaks newObject = Factory.CreateKnownObjectFromComProxy(this,returnItem,NetOffice.ExcelApi.VPageBreaks.LateBindingApiWrapperType) as NetOffice.ExcelApi.VPageBreaks; return newObject; } } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15 /// Get/Set /// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff835903.aspx /// </summary> [SupportByVersionAttribute("Excel", 9,10,11,12,14,15)] public object Visible { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "Visible", paramsArray); if((null != returnItem) && (returnItem is MarshalByRefObject)) { COMObject newObject = Factory.CreateObjectFromComProxy(this, returnItem); return newObject; } else { return returnItem; } } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "Visible", paramsArray); } } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15 /// Get /// Unknown COM Proxy /// </summary> /// <param name="index">object Index</param> [SupportByVersionAttribute("Excel", 9,10,11,12,14,15)] [NetRuntimeSystem.Runtime.CompilerServices.IndexerName("Item")] public object this[object index] { get { object[] paramsArray = Invoker.ValidateParamsArray(index); object returnItem = Invoker.PropertyGet(this, "_Default", paramsArray); COMObject newObject = Factory.CreateObjectFromComProxy(this,returnItem); return newObject; } } #endregion #region Methods /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15 /// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff838966.aspx /// </summary> /// <param name="before">optional object Before</param> /// <param name="after">optional object After</param> /// <param name="count">optional object Count</param> /// <param name="type">optional object Type</param> [SupportByVersionAttribute("Excel", 9,10,11,12,14,15)] public object Add(object before, object after, object count, object type) { object[] paramsArray = Invoker.ValidateParamsArray(before, after, count, type); object returnItem = Invoker.MethodReturn(this, "Add", paramsArray); object newObject = Factory.CreateObjectFromComProxy(this,returnItem); return newObject; } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15 /// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff838966.aspx /// </summary> [CustomMethodAttribute] [SupportByVersionAttribute("Excel", 9,10,11,12,14,15)] public object Add() { object[] paramsArray = null; object returnItem = Invoker.MethodReturn(this, "Add", paramsArray); object newObject = Factory.CreateObjectFromComProxy(this,returnItem); return newObject; } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15 /// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff838966.aspx /// </summary> /// <param name="before">optional object Before</param> [CustomMethodAttribute] [SupportByVersionAttribute("Excel", 9,10,11,12,14,15)] public object Add(object before) { object[] paramsArray = Invoker.ValidateParamsArray(before); object returnItem = Invoker.MethodReturn(this, "Add", paramsArray); object newObject = Factory.CreateObjectFromComProxy(this,returnItem); return newObject; } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15 /// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff838966.aspx /// </summary> /// <param name="before">optional object Before</param> /// <param name="after">optional object After</param> [CustomMethodAttribute] [SupportByVersionAttribute("Excel", 9,10,11,12,14,15)] public object Add(object before, object after) { object[] paramsArray = Invoker.ValidateParamsArray(before, after); object returnItem = Invoker.MethodReturn(this, "Add", paramsArray); object newObject = Factory.CreateObjectFromComProxy(this,returnItem); return newObject; } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15 /// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff838966.aspx /// </summary> /// <param name="before">optional object Before</param> /// <param name="after">optional object After</param> /// <param name="count">optional object Count</param> [CustomMethodAttribute] [SupportByVersionAttribute("Excel", 9,10,11,12,14,15)] public object Add(object before, object after, object count) { object[] paramsArray = Invoker.ValidateParamsArray(before, after, count); object returnItem = Invoker.MethodReturn(this, "Add", paramsArray); object newObject = Factory.CreateObjectFromComProxy(this,returnItem); return newObject; } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15 /// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff193304.aspx /// </summary> /// <param name="before">optional object Before</param> /// <param name="after">optional object After</param> [SupportByVersionAttribute("Excel", 9,10,11,12,14,15)] public void Copy(object before, object after) { object[] paramsArray = Invoker.ValidateParamsArray(before, after); Invoker.Method(this, "Copy", paramsArray); } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15 /// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff193304.aspx /// </summary> [CustomMethodAttribute] [SupportByVersionAttribute("Excel", 9,10,11,12,14,15)] public void Copy() { object[] paramsArray = null; Invoker.Method(this, "Copy", paramsArray); } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15 /// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff193304.aspx /// </summary> /// <param name="before">optional object Before</param> [CustomMethodAttribute] [SupportByVersionAttribute("Excel", 9,10,11,12,14,15)] public void Copy(object before) { object[] paramsArray = Invoker.ValidateParamsArray(before); Invoker.Method(this, "Copy", paramsArray); } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15 /// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff821042.aspx /// </summary> [SupportByVersionAttribute("Excel", 9,10,11,12,14,15)] public void Delete() { object[] paramsArray = null; Invoker.Method(this, "Delete", paramsArray); } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15 /// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff838609.aspx /// </summary> /// <param name="range">NetOffice.ExcelApi.Range Range</param> /// <param name="type">optional NetOffice.ExcelApi.Enums.XlFillWith Type = -4104</param> [SupportByVersionAttribute("Excel", 9,10,11,12,14,15)] public void FillAcrossSheets(NetOffice.ExcelApi.Range range, object type) { object[] paramsArray = Invoker.ValidateParamsArray(range, type); Invoker.Method(this, "FillAcrossSheets", paramsArray); } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15 /// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff838609.aspx /// </summary> /// <param name="range">NetOffice.ExcelApi.Range Range</param> [CustomMethodAttribute] [SupportByVersionAttribute("Excel", 9,10,11,12,14,15)] public void FillAcrossSheets(NetOffice.ExcelApi.Range range) { object[] paramsArray = Invoker.ValidateParamsArray(range); Invoker.Method(this, "FillAcrossSheets", paramsArray); } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15 /// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff840429.aspx /// </summary> /// <param name="before">optional object Before</param> /// <param name="after">optional object After</param> [SupportByVersionAttribute("Excel", 9,10,11,12,14,15)] public void Move(object before, object after) { object[] paramsArray = Invoker.ValidateParamsArray(before, after); Invoker.Method(this, "Move", paramsArray); } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15 /// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff840429.aspx /// </summary> [CustomMethodAttribute] [SupportByVersionAttribute("Excel", 9,10,11,12,14,15)] public void Move() { object[] paramsArray = null; Invoker.Method(this, "Move", paramsArray); } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15 /// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff840429.aspx /// </summary> /// <param name="before">optional object Before</param> [CustomMethodAttribute] [SupportByVersionAttribute("Excel", 9,10,11,12,14,15)] public void Move(object before) { object[] paramsArray = Invoker.ValidateParamsArray(before); Invoker.Method(this, "Move", paramsArray); } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15 /// /// </summary> /// <param name="from">optional object From</param> /// <param name="to">optional object To</param> /// <param name="copies">optional object Copies</param> /// <param name="preview">optional object Preview</param> /// <param name="activePrinter">optional object ActivePrinter</param> /// <param name="printToFile">optional object PrintToFile</param> /// <param name="collate">optional object Collate</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] [SupportByVersionAttribute("Excel", 9,10,11,12,14,15)] public void _PrintOut(object from, object to, object copies, object preview, object activePrinter, object printToFile, object collate) { object[] paramsArray = Invoker.ValidateParamsArray(from, to, copies, preview, activePrinter, printToFile, collate); Invoker.Method(this, "_PrintOut", paramsArray); } /// <summary> /// SupportByVersion Excel 12, 14, 15 /// /// </summary> /// <param name="from">optional object From</param> /// <param name="to">optional object To</param> /// <param name="copies">optional object Copies</param> /// <param name="preview">optional object Preview</param> /// <param name="activePrinter">optional object ActivePrinter</param> /// <param name="printToFile">optional object PrintToFile</param> /// <param name="collate">optional object Collate</param> /// <param name="prToFileName">optional object PrToFileName</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] [SupportByVersionAttribute("Excel", 12,14,15)] public void _PrintOut(object from, object to, object copies, object preview, object activePrinter, object printToFile, object collate, object prToFileName) { object[] paramsArray = Invoker.ValidateParamsArray(from, to, copies, preview, activePrinter, printToFile, collate, prToFileName); Invoker.Method(this, "_PrintOut", paramsArray); } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15 /// /// </summary> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] [CustomMethodAttribute] [SupportByVersionAttribute("Excel", 9,10,11,12,14,15)] public void _PrintOut() { object[] paramsArray = null; Invoker.Method(this, "_PrintOut", paramsArray); } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15 /// /// </summary> /// <param name="from">optional object From</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] [CustomMethodAttribute] [SupportByVersionAttribute("Excel", 9,10,11,12,14,15)] public void _PrintOut(object from) { object[] paramsArray = Invoker.ValidateParamsArray(from); Invoker.Method(this, "_PrintOut", paramsArray); } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15 /// /// </summary> /// <param name="from">optional object From</param> /// <param name="to">optional object To</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] [CustomMethodAttribute] [SupportByVersionAttribute("Excel", 9,10,11,12,14,15)] public void _PrintOut(object from, object to) { object[] paramsArray = Invoker.ValidateParamsArray(from, to); Invoker.Method(this, "_PrintOut", paramsArray); } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15 /// /// </summary> /// <param name="from">optional object From</param> /// <param name="to">optional object To</param> /// <param name="copies">optional object Copies</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] [CustomMethodAttribute] [SupportByVersionAttribute("Excel", 9,10,11,12,14,15)] public void _PrintOut(object from, object to, object copies) { object[] paramsArray = Invoker.ValidateParamsArray(from, to, copies); Invoker.Method(this, "_PrintOut", paramsArray); } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15 /// /// </summary> /// <param name="from">optional object From</param> /// <param name="to">optional object To</param> /// <param name="copies">optional object Copies</param> /// <param name="preview">optional object Preview</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] [CustomMethodAttribute] [SupportByVersionAttribute("Excel", 9,10,11,12,14,15)] public void _PrintOut(object from, object to, object copies, object preview) { object[] paramsArray = Invoker.ValidateParamsArray(from, to, copies, preview); Invoker.Method(this, "_PrintOut", paramsArray); } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15 /// /// </summary> /// <param name="from">optional object From</param> /// <param name="to">optional object To</param> /// <param name="copies">optional object Copies</param> /// <param name="preview">optional object Preview</param> /// <param name="activePrinter">optional object ActivePrinter</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] [CustomMethodAttribute] [SupportByVersionAttribute("Excel", 9,10,11,12,14,15)] public void _PrintOut(object from, object to, object copies, object preview, object activePrinter) { object[] paramsArray = Invoker.ValidateParamsArray(from, to, copies, preview, activePrinter); Invoker.Method(this, "_PrintOut", paramsArray); } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15 /// /// </summary> /// <param name="from">optional object From</param> /// <param name="to">optional object To</param> /// <param name="copies">optional object Copies</param> /// <param name="preview">optional object Preview</param> /// <param name="activePrinter">optional object ActivePrinter</param> /// <param name="printToFile">optional object PrintToFile</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] [CustomMethodAttribute] [SupportByVersionAttribute("Excel", 9,10,11,12,14,15)] public void _PrintOut(object from, object to, object copies, object preview, object activePrinter, object printToFile) { object[] paramsArray = Invoker.ValidateParamsArray(from, to, copies, preview, activePrinter, printToFile); Invoker.Method(this, "_PrintOut", paramsArray); } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15 /// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff839246.aspx /// </summary> /// <param name="enableChanges">optional object EnableChanges</param> [SupportByVersionAttribute("Excel", 9,10,11,12,14,15)] public void PrintPreview(object enableChanges) { object[] paramsArray = Invoker.ValidateParamsArray(enableChanges); Invoker.Method(this, "PrintPreview", paramsArray); } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15 /// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff839246.aspx /// </summary> [CustomMethodAttribute] [SupportByVersionAttribute("Excel", 9,10,11,12,14,15)] public void PrintPreview() { object[] paramsArray = null; Invoker.Method(this, "PrintPreview", paramsArray); } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15 /// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff841056.aspx /// </summary> /// <param name="replace">optional object Replace</param> [SupportByVersionAttribute("Excel", 9,10,11,12,14,15)] public void Select(object replace) { object[] paramsArray = Invoker.ValidateParamsArray(replace); Invoker.Method(this, "Select", paramsArray); } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15 /// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff841056.aspx /// </summary> [CustomMethodAttribute] [SupportByVersionAttribute("Excel", 9,10,11,12,14,15)] public void Select() { object[] paramsArray = null; Invoker.Method(this, "Select", paramsArray); } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15 /// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff840355.aspx /// </summary> /// <param name="from">optional object From</param> /// <param name="to">optional object To</param> /// <param name="copies">optional object Copies</param> /// <param name="preview">optional object Preview</param> /// <param name="activePrinter">optional object ActivePrinter</param> /// <param name="printToFile">optional object PrintToFile</param> /// <param name="collate">optional object Collate</param> /// <param name="prToFileName">optional object PrToFileName</param> [SupportByVersionAttribute("Excel", 9,10,11,12,14,15)] public void PrintOut(object from, object to, object copies, object preview, object activePrinter, object printToFile, object collate, object prToFileName) { object[] paramsArray = Invoker.ValidateParamsArray(from, to, copies, preview, activePrinter, printToFile, collate, prToFileName); Invoker.Method(this, "PrintOut", paramsArray); } /// <summary> /// SupportByVersion Excel 12, 14, 15 /// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff840355.aspx /// </summary> /// <param name="from">optional object From</param> /// <param name="to">optional object To</param> /// <param name="copies">optional object Copies</param> /// <param name="preview">optional object Preview</param> /// <param name="activePrinter">optional object ActivePrinter</param> /// <param name="printToFile">optional object PrintToFile</param> /// <param name="collate">optional object Collate</param> /// <param name="prToFileName">optional object PrToFileName</param> /// <param name="ignorePrintAreas">optional object IgnorePrintAreas</param> [SupportByVersionAttribute("Excel", 12,14,15)] public void PrintOut(object from, object to, object copies, object preview, object activePrinter, object printToFile, object collate, object prToFileName, object ignorePrintAreas) { object[] paramsArray = Invoker.ValidateParamsArray(from, to, copies, preview, activePrinter, printToFile, collate, prToFileName, ignorePrintAreas); Invoker.Method(this, "PrintOut", paramsArray); } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15 /// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff840355.aspx /// </summary> [CustomMethodAttribute] [SupportByVersionAttribute("Excel", 9,10,11,12,14,15)] public void PrintOut() { object[] paramsArray = null; Invoker.Method(this, "PrintOut", paramsArray); } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15 /// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff840355.aspx /// </summary> /// <param name="from">optional object From</param> [CustomMethodAttribute] [SupportByVersionAttribute("Excel", 9,10,11,12,14,15)] public void PrintOut(object from) { object[] paramsArray = Invoker.ValidateParamsArray(from); Invoker.Method(this, "PrintOut", paramsArray); } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15 /// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff840355.aspx /// </summary> /// <param name="from">optional object From</param> /// <param name="to">optional object To</param> [CustomMethodAttribute] [SupportByVersionAttribute("Excel", 9,10,11,12,14,15)] public void PrintOut(object from, object to) { object[] paramsArray = Invoker.ValidateParamsArray(from, to); Invoker.Method(this, "PrintOut", paramsArray); } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15 /// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff840355.aspx /// </summary> /// <param name="from">optional object From</param> /// <param name="to">optional object To</param> /// <param name="copies">optional object Copies</param> [CustomMethodAttribute] [SupportByVersionAttribute("Excel", 9,10,11,12,14,15)] public void PrintOut(object from, object to, object copies) { object[] paramsArray = Invoker.ValidateParamsArray(from, to, copies); Invoker.Method(this, "PrintOut", paramsArray); } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15 /// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff840355.aspx /// </summary> /// <param name="from">optional object From</param> /// <param name="to">optional object To</param> /// <param name="copies">optional object Copies</param> /// <param name="preview">optional object Preview</param> [CustomMethodAttribute] [SupportByVersionAttribute("Excel", 9,10,11,12,14,15)] public void PrintOut(object from, object to, object copies, object preview) { object[] paramsArray = Invoker.ValidateParamsArray(from, to, copies, preview); Invoker.Method(this, "PrintOut", paramsArray); } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15 /// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff840355.aspx /// </summary> /// <param name="from">optional object From</param> /// <param name="to">optional object To</param> /// <param name="copies">optional object Copies</param> /// <param name="preview">optional object Preview</param> /// <param name="activePrinter">optional object ActivePrinter</param> [CustomMethodAttribute] [SupportByVersionAttribute("Excel", 9,10,11,12,14,15)] public void PrintOut(object from, object to, object copies, object preview, object activePrinter) { object[] paramsArray = Invoker.ValidateParamsArray(from, to, copies, preview, activePrinter); Invoker.Method(this, "PrintOut", paramsArray); } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15 /// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff840355.aspx /// </summary> /// <param name="from">optional object From</param> /// <param name="to">optional object To</param> /// <param name="copies">optional object Copies</param> /// <param name="preview">optional object Preview</param> /// <param name="activePrinter">optional object ActivePrinter</param> /// <param name="printToFile">optional object PrintToFile</param> [CustomMethodAttribute] [SupportByVersionAttribute("Excel", 9,10,11,12,14,15)] public void PrintOut(object from, object to, object copies, object preview, object activePrinter, object printToFile) { object[] paramsArray = Invoker.ValidateParamsArray(from, to, copies, preview, activePrinter, printToFile); Invoker.Method(this, "PrintOut", paramsArray); } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15 /// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff840355.aspx /// </summary> /// <param name="from">optional object From</param> /// <param name="to">optional object To</param> /// <param name="copies">optional object Copies</param> /// <param name="preview">optional object Preview</param> /// <param name="activePrinter">optional object ActivePrinter</param> /// <param name="printToFile">optional object PrintToFile</param> /// <param name="collate">optional object Collate</param> [CustomMethodAttribute] [SupportByVersionAttribute("Excel", 9,10,11,12,14,15)] public void PrintOut(object from, object to, object copies, object preview, object activePrinter, object printToFile, object collate) { object[] paramsArray = Invoker.ValidateParamsArray(from, to, copies, preview, activePrinter, printToFile, collate); Invoker.Method(this, "PrintOut", paramsArray); } /// <summary> /// SupportByVersion Excel 12, 14, 15 /// /// </summary> /// <param name="from">optional object From</param> /// <param name="to">optional object To</param> /// <param name="copies">optional object Copies</param> /// <param name="preview">optional object Preview</param> /// <param name="activePrinter">optional object ActivePrinter</param> /// <param name="printToFile">optional object PrintToFile</param> /// <param name="collate">optional object Collate</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] [SupportByVersionAttribute("Excel", 12,14,15)] public void __PrintOut(object from, object to, object copies, object preview, object activePrinter, object printToFile, object collate) { object[] paramsArray = Invoker.ValidateParamsArray(from, to, copies, preview, activePrinter, printToFile, collate); Invoker.Method(this, "__PrintOut", paramsArray); } /// <summary> /// SupportByVersion Excel 12, 14, 15 /// /// </summary> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] [CustomMethodAttribute] [SupportByVersionAttribute("Excel", 12,14,15)] public void __PrintOut() { object[] paramsArray = null; Invoker.Method(this, "__PrintOut", paramsArray); } /// <summary> /// SupportByVersion Excel 12, 14, 15 /// /// </summary> /// <param name="from">optional object From</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] [CustomMethodAttribute] [SupportByVersionAttribute("Excel", 12,14,15)] public void __PrintOut(object from) { object[] paramsArray = Invoker.ValidateParamsArray(from); Invoker.Method(this, "__PrintOut", paramsArray); } /// <summary> /// SupportByVersion Excel 12, 14, 15 /// /// </summary> /// <param name="from">optional object From</param> /// <param name="to">optional object To</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] [CustomMethodAttribute] [SupportByVersionAttribute("Excel", 12,14,15)] public void __PrintOut(object from, object to) { object[] paramsArray = Invoker.ValidateParamsArray(from, to); Invoker.Method(this, "__PrintOut", paramsArray); } /// <summary> /// SupportByVersion Excel 12, 14, 15 /// /// </summary> /// <param name="from">optional object From</param> /// <param name="to">optional object To</param> /// <param name="copies">optional object Copies</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] [CustomMethodAttribute] [SupportByVersionAttribute("Excel", 12,14,15)] public void __PrintOut(object from, object to, object copies) { object[] paramsArray = Invoker.ValidateParamsArray(from, to, copies); Invoker.Method(this, "__PrintOut", paramsArray); } /// <summary> /// SupportByVersion Excel 12, 14, 15 /// /// </summary> /// <param name="from">optional object From</param> /// <param name="to">optional object To</param> /// <param name="copies">optional object Copies</param> /// <param name="preview">optional object Preview</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] [CustomMethodAttribute] [SupportByVersionAttribute("Excel", 12,14,15)] public void __PrintOut(object from, object to, object copies, object preview) { object[] paramsArray = Invoker.ValidateParamsArray(from, to, copies, preview); Invoker.Method(this, "__PrintOut", paramsArray); } /// <summary> /// SupportByVersion Excel 12, 14, 15 /// /// </summary> /// <param name="from">optional object From</param> /// <param name="to">optional object To</param> /// <param name="copies">optional object Copies</param> /// <param name="preview">optional object Preview</param> /// <param name="activePrinter">optional object ActivePrinter</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] [CustomMethodAttribute] [SupportByVersionAttribute("Excel", 12,14,15)] public void __PrintOut(object from, object to, object copies, object preview, object activePrinter) { object[] paramsArray = Invoker.ValidateParamsArray(from, to, copies, preview, activePrinter); Invoker.Method(this, "__PrintOut", paramsArray); } /// <summary> /// SupportByVersion Excel 12, 14, 15 /// /// </summary> /// <param name="from">optional object From</param> /// <param name="to">optional object To</param> /// <param name="copies">optional object Copies</param> /// <param name="preview">optional object Preview</param> /// <param name="activePrinter">optional object ActivePrinter</param> /// <param name="printToFile">optional object PrintToFile</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] [CustomMethodAttribute] [SupportByVersionAttribute("Excel", 12,14,15)] public void __PrintOut(object from, object to, object copies, object preview, object activePrinter, object printToFile) { object[] paramsArray = Invoker.ValidateParamsArray(from, to, copies, preview, activePrinter, printToFile); Invoker.Method(this, "__PrintOut", paramsArray); } /// <summary> /// SupportByVersion Excel 15 /// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/jj229051.aspx /// </summary> /// <param name="before">optional object Before</param> /// <param name="after">optional object After</param> /// <param name="count">optional object Count</param> /// <param name="newLayout">optional object NewLayout</param> [SupportByVersionAttribute("Excel", 15)] public object Add2(object before, object after, object count, object newLayout) { object[] paramsArray = Invoker.ValidateParamsArray(before, after, count, newLayout); object returnItem = Invoker.MethodReturn(this, "Add2", paramsArray); object newObject = Factory.CreateObjectFromComProxy(this,returnItem); return newObject; } /// <summary> /// SupportByVersion Excel 15 /// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/jj229051.aspx /// </summary> [CustomMethodAttribute] [SupportByVersionAttribute("Excel", 15)] public object Add2() { object[] paramsArray = null; object returnItem = Invoker.MethodReturn(this, "Add2", paramsArray); object newObject = Factory.CreateObjectFromComProxy(this,returnItem); return newObject; } /// <summary> /// SupportByVersion Excel 15 /// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/jj229051.aspx /// </summary> /// <param name="before">optional object Before</param> [CustomMethodAttribute] [SupportByVersionAttribute("Excel", 15)] public object Add2(object before) { object[] paramsArray = Invoker.ValidateParamsArray(before); object returnItem = Invoker.MethodReturn(this, "Add2", paramsArray); object newObject = Factory.CreateObjectFromComProxy(this,returnItem); return newObject; } /// <summary> /// SupportByVersion Excel 15 /// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/jj229051.aspx /// </summary> /// <param name="before">optional object Before</param> /// <param name="after">optional object After</param> [CustomMethodAttribute] [SupportByVersionAttribute("Excel", 15)] public object Add2(object before, object after) { object[] paramsArray = Invoker.ValidateParamsArray(before, after); object returnItem = Invoker.MethodReturn(this, "Add2", paramsArray); object newObject = Factory.CreateObjectFromComProxy(this,returnItem); return newObject; } /// <summary> /// SupportByVersion Excel 15 /// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/jj229051.aspx /// </summary> /// <param name="before">optional object Before</param> /// <param name="after">optional object After</param> /// <param name="count">optional object Count</param> [CustomMethodAttribute] [SupportByVersionAttribute("Excel", 15)] public object Add2(object before, object after, object count) { object[] paramsArray = Invoker.ValidateParamsArray(before, after, count); object returnItem = Invoker.MethodReturn(this, "Add2", paramsArray); object newObject = Factory.CreateObjectFromComProxy(this,returnItem); return newObject; } #endregion #region IEnumerable<object> Member /// <summary> /// SupportByVersionAttribute Excel, 9,10,11,12,14,15 /// </summary> [SupportByVersionAttribute("Excel", 9,10,11,12,14,15)] public IEnumerator<object> GetEnumerator() { NetRuntimeSystem.Collections.IEnumerable innerEnumerator = (this as NetRuntimeSystem.Collections.IEnumerable); foreach (object item in innerEnumerator) yield return item; } #endregion #region IEnumerable Members /// <summary> /// SupportByVersionAttribute Excel, 9,10,11,12,14,15 /// </summary> [SupportByVersionAttribute("Excel", 9,10,11,12,14,15)] IEnumerator NetRuntimeSystem.Collections.IEnumerable.GetEnumerator() { return NetOffice.Utils.GetProxyEnumeratorAsProperty(this); } #endregion #pragma warning restore } }
39.989474
194
0.68542
[ "MIT" ]
NetOffice/NetOffice
Source/Excel/DispatchInterfaces/Worksheets.cs
41,789
C#
// *********************************************************************** // Copyright (c) 2017 Charlie Poole, Rob Prouse // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** using System; using System.Collections.Generic; using System.Reflection; using System.Text; using NUnit.Engine; namespace NUnit.Common { internal static class ExceptionHelper { /// <summary> /// Builds up a message, using the Message field of the specified exception /// as well as any InnerExceptions. /// </summary> /// <param name="exception">The exception.</param> /// <returns>A combined message string.</returns> public static string BuildMessage(Exception exception) { var sb = new StringBuilder(); sb.AppendFormat("{0} : ", exception.GetType()); sb.Append(GetExceptionMessage(exception)); foreach (Exception inner in FlattenExceptionHierarchy(exception)) { sb.Append(Environment.NewLine); sb.Append(" ----> "); sb.AppendFormat("{0} : ", inner.GetType()); sb.Append(GetExceptionMessage(inner)); } return sb.ToString(); } /// <summary> /// Builds up a message, using the Message field of the specified exception /// as well as any InnerExceptions. /// </summary> /// <param name="exception">The exception.</param> /// <returns>A combined stack trace.</returns> public static string BuildMessageAndStackTrace(Exception exception) { var sb = new StringBuilder("--"); sb.AppendLine(exception.GetType().Name); sb.AppendLine(GetExceptionMessage(exception)); sb.AppendLine(GetSafeStackTrace(exception)); foreach (Exception inner in FlattenExceptionHierarchy(exception)) { sb.AppendLine("--"); sb.AppendLine(inner.GetType().Name); sb.AppendLine(GetExceptionMessage(inner)); sb.AppendLine(GetSafeStackTrace(inner)); } return sb.ToString(); } /// <summary> /// Gets the stack trace of the exception. If no stack trace /// is provided, returns "No stack trace available". /// </summary> /// <param name="exception">The exception.</param> /// <returns>A string representation of the stack trace.</returns> private static string GetSafeStackTrace(Exception exception) { try { return exception.StackTrace; } catch (Exception) { return "No stack trace available"; } } private static List<Exception> FlattenExceptionHierarchy(Exception exception) { var result = new List<Exception>(); var unloadException = exception as NUnitEngineUnloadException; if (unloadException?.AggregatedExceptions != null) { result.AddRange(unloadException.AggregatedExceptions); foreach (var aggregatedException in unloadException.AggregatedExceptions) result.AddRange(FlattenExceptionHierarchy(aggregatedException)); } var reflectionException = exception as ReflectionTypeLoadException; if (reflectionException != null) { result.AddRange(reflectionException.LoaderExceptions); foreach (var innerException in reflectionException.LoaderExceptions) result.AddRange(FlattenExceptionHierarchy(innerException)); } if (exception.InnerException != null) { result.Add(exception.InnerException); result.AddRange(FlattenExceptionHierarchy(exception.InnerException)); } return result; } private static string GetExceptionMessage(Exception ex) { if (string.IsNullOrEmpty(ex.Message)) { // Special handling for Mono 5.0, which returns an empty message var fnfEx = ex as System.IO.FileNotFoundException; return fnfEx != null ? "Could not load assembly. File not found: " + fnfEx.FileName : "No message provided"; } return ex.Message; } } }
38.655172
89
0.594826
[ "MIT" ]
Fan270/nunit-console
src/NUnitEngine/nunit.engine/Internal/ExceptionHelper.cs
5,607
C#
using CoreGraphics; using Foundation; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Reactive.Linq; using Toggl.Core.UI.ViewModels; using Toggl.iOS.Views; using Toggl.Shared; using UIKit; using static System.Math; namespace Toggl.iOS.ViewSources { public sealed class ColorSelectionCollectionViewSource : ReloadCollectionViewSource<SelectableColorViewModel>, IUICollectionViewDelegateFlowLayout { public IObservable<Color> ColorSelected => Observable .FromEventPattern<SelectableColorViewModel>(e => OnItemTapped += e, e => OnItemTapped -= e) .Select(e => e.EventArgs.Color); public ColorSelectionCollectionViewSource(IObservable<IEnumerable<SelectableColorViewModel>> colors) : base(ImmutableList<SelectableColorViewModel>.Empty, configureCell) { } public void SetNewColors(IEnumerable<SelectableColorViewModel> colors) { items = colors.ToImmutableList(); } [Export("collectionView:layout:sizeForItemAtIndexPath:")] public CGSize GetSizeForItem( UICollectionView collectionView, UICollectionViewLayout layout, NSIndexPath indexPath) => new CGSize(Floor(collectionView.Frame.Width / 5), 36); [Export("collectionView:layout:minimumLineSpacingForSectionAtIndex:")] public nfloat GetMinimumLineSpacingForSection( UICollectionView collectionView, UICollectionViewLayout layout, nint section) => 12; [Export("collectionView:layout:minimumInteritemSpacingForSectionAtIndex:")] public nfloat GetMinimumInteritemSpacingForSection( UICollectionView collectionView, UICollectionViewLayout layout, nint section) => 0; [Export("collectionView:layout:insetForSectionAtIndex:")] public UIEdgeInsets GetInsetForSection( UICollectionView collectionView, UICollectionViewLayout layout, nint section) => new UIEdgeInsets(0, 0, 0, 0); private static UICollectionViewCell configureCell(ReloadCollectionViewSource<SelectableColorViewModel> source, UICollectionView collectionView, NSIndexPath indexPath, SelectableColorViewModel colorViewModel) { var cell = collectionView.DequeueReusableCell(ColorSelectionViewCell.Identifier, indexPath) as ColorSelectionViewCell; cell.Item = colorViewModel; return cell; } } }
41.295082
150
0.717348
[ "BSD-3-Clause" ]
MULXCODE/mobileapp
Toggl.iOS/ViewSources/ColorSelectionCollectionViewSource.cs
2,521
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. namespace Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801 { using Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.PowerShell; /// <summary> /// A PowerShell PSTypeConverter to support converting to an instance of <see cref="WebAppInstanceCollection" /> /// </summary> public partial class WebAppInstanceCollectionTypeConverter : global::System.Management.Automation.PSTypeConverter { /// <summary> /// Determines if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" /> /// parameter. /// </summary> /// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param> /// <param name="destinationType">the <see cref="System.Type" /> to convert to</param> /// <returns> /// <c>true</c> if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" /> /// parameter, otherwise <c>false</c>. /// </returns> public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); /// <summary> /// Determines if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="WebAppInstanceCollection" /// type/>. /// </summary> /// <param name="sourceValue">the <see cref="System.Object" /> instance to check if it can be converted to the <see cref="WebAppInstanceCollection" /// /> type.</param> /// <returns> /// <c>true</c> if the instance could be converted to a <see cref="WebAppInstanceCollection" /> type, otherwise <c>false</c> /// </returns> public static bool CanConvertFrom(dynamic sourceValue) { if (null == sourceValue) { return true; } global::System.Type type = sourceValue.GetType(); if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) { // we say yest to PSObjects return true; } if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) { // we say yest to Hashtables/dictionaries return true; } try { if (null != sourceValue.ToJsonString()) { return true; } } catch { // Not one of our objects } try { string text = sourceValue.ToString()?.Trim(); return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonType.Object; } catch { // Doesn't look like it can be treated as JSON } return false; } /// <summary> /// Determines if the <see cref="sourceValue" /> parameter can be converted to the <see cref="destinationType" /> parameter /// </summary> /// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param> /// <param name="destinationType">the <see cref="System.Type" /> to convert to</param> /// <returns> /// <c>true</c> if the converter can convert the <see cref="sourceValue" /> parameter to the <see cref="destinationType" /> /// parameter, otherwise <c>false</c> /// </returns> public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; /// <summary> /// Converts the <see cref="sourceValue" /> parameter to the <see cref="destinationType" /> parameter using <see cref="formatProvider" /// /> and <see cref="ignoreCase" /> /// </summary> /// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param> /// <param name="destinationType">the <see cref="System.Type" /> to convert to</param> /// <param name="formatProvider">not used by this TypeConverter.</param> /// <param name="ignoreCase">when set to <c>true</c>, will ignore the case when converting.</param> /// <returns> /// an instance of <see cref="WebAppInstanceCollection" />, or <c>null</c> if there is no suitable conversion. /// </returns> public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); /// <summary> /// Converts the <see cref="sourceValue" /> parameter to the <see cref="destinationType" /> parameter using <see cref="formatProvider" /// /> and <see cref="ignoreCase" /> /// </summary> /// <param name="sourceValue">the value to convert into an instance of <see cref="WebAppInstanceCollection" />.</param> /// <returns> /// an instance of <see cref="WebAppInstanceCollection" />, or <c>null</c> if there is no suitable conversion. /// </returns> public static Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IWebAppInstanceCollection ConvertFrom(dynamic sourceValue) { if (null == sourceValue) { return null; } global::System.Type type = sourceValue.GetType(); if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IWebAppInstanceCollection).IsAssignableFrom(type)) { return sourceValue; } try { return WebAppInstanceCollection.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; } catch { // Unable to use JSON pattern } if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) { return WebAppInstanceCollection.DeserializeFromPSObject(sourceValue); } if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) { return WebAppInstanceCollection.DeserializeFromDictionary(sourceValue); } return null; } /// <summary>NotImplemented -- this will return <c>null</c></summary> /// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param> /// <param name="destinationType">the <see cref="System.Type" /> to convert to</param> /// <param name="formatProvider">not used by this TypeConverter.</param> /// <param name="ignoreCase">when set to <c>true</c>, will ignore the case when converting.</param> /// <returns>will always return <c>null</c>.</returns> public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; } }
52.428571
249
0.595173
[ "MIT" ]
AlanFlorance/azure-powershell
src/Functions/generated/api/Models/Api20190801/WebAppInstanceCollection.TypeConverter.cs
7,561
C#
using System; namespace SelfLinqDemo.Model { public class User { public User() { Id = Guid.NewGuid(); BasicInfo = new UserBasicInfo(); } public Guid Id { get; set; } public UserBasicInfo BasicInfo { get; set; } } }
16.388889
52
0.515254
[ "MIT" ]
huruiyi/CSharpExample
CSharpExample/LinqDemo/SelfLinqDemo/Model/User.cs
297
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace rokWebsite.Models { public class Perfomance { [Key] public int Id { get; set; } //below is for base datas [Required(ErrorMessage = "T4 kill base is required.")] [Display(Name = "T4 kill base", Description = "T4 kill base")] [RegularExpression(@"-?\d+(?:\.\d+)?", ErrorMessage = "Please enter valid minimum price")] [Range(0, double.MaxValue, ErrorMessage = "Please enter valid minimum price")] public double T4killsBase { get; set; } [Required(ErrorMessage = "T5 kill base is required.")] [Display(Name = "T5 kill base", Description = "T5 kill base")] [RegularExpression(@"-?\d+(?:\.\d+)?", ErrorMessage = "Please enter valid minimum price")] [Range(0, double.MaxValue, ErrorMessage = "Please enter valid minimum price")] public double T5killsBase { get; set; } [Required(ErrorMessage = "T4 deaths base is required.")] [Display(Name = "T4 deaths base", Description = "T4 deaths base")] [RegularExpression(@"-?\d+(?:\.\d+)?", ErrorMessage = "Please enter valid minimum price")] [Range(0, double.MaxValue, ErrorMessage = "Please enter valid minimum price")] public double T4deathsBase { get; set; } [Required(ErrorMessage = "T5 deaths base is required.")] [Display(Name = "T5 deaths base", Description = "T5 deaths base")] [RegularExpression(@"-?\d+(?:\.\d+)?", ErrorMessage = "Please enter valid minimum price")] [Range(0, double.MaxValue, ErrorMessage = "Please enter valid minimum price")] public double T5deathsBase { get; set; } [Required(ErrorMessage = "Rss Support base is required.")] [Display(Name = "Rss Support base", Description = "Rss Support base")] [RegularExpression(@"-?\d+(?:\.\d+)?", ErrorMessage = "Please enter valid minimum price")] [Range(0, double.MaxValue, ErrorMessage = "Please enter valid minimum price")] public double RssSupportBase { get; set; } //below is for current datas [Required(ErrorMessage = "T4 kill current is required.")] [Display(Name = "T4 kill current", Description = "T4 kill current")] [RegularExpression(@"-?\d+(?:\.\d+)?", ErrorMessage = "Please enter valid minimum price")] [Range(0, double.MaxValue, ErrorMessage = "Please enter valid minimum price")] public double T4killsCurrent { get; set; } [Required(ErrorMessage = "T5 kill current is required.")] [Display(Name = "T5 kill current", Description = "T5 kill current")] [RegularExpression(@"-?\d+(?:\.\d+)?", ErrorMessage = "Please enter valid minimum price")] [Range(0, double.MaxValue, ErrorMessage = "Please enter valid minimum price")] public double T5killsCurrent { get; set; } [Required(ErrorMessage = "T4 deaths current is required.")] [Display(Name = "T4 deaths current", Description = "T4 deaths current")] [RegularExpression(@"-?\d+(?:\.\d+)?", ErrorMessage = "Please enter valid minimum price")] [Range(0, double.MaxValue, ErrorMessage = "Please enter valid minimum price")] public double T4deathsCurrent { get; set; } [Required(ErrorMessage = "T5 deaths current is required.")] [Display(Name = "T5 deaths current", Description = "T5 deaths current")] [RegularExpression(@"-?\d+(?:\.\d+)?", ErrorMessage = "Please enter valid minimum price")] [Range(0, double.MaxValue, ErrorMessage = "Please enter valid minimum price")] public double T5deathsCurrent { get; set; } [Required(ErrorMessage = "Rss Support current is required.")] [Display(Name = "Rss Support current", Description = "Rss Support current")] [RegularExpression(@"-?\d+(?:\.\d+)?", ErrorMessage = "Please enter valid minimum price")] [Range(0, double.MaxValue, ErrorMessage = "Please enter valid minimum price")] public double RssSupportCurrent { get; set; } } }
47.227273
98
0.636429
[ "MIT" ]
behluluysal/asp-net-core-5-training
rokWebsite/Models/Perfomance.cs
4,158
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.Network.V20160330.Outputs { /// <summary> /// PublicIPAddress resource /// </summary> [OutputType] public sealed class PublicIPAddressResponse { /// <summary> /// Gets or sets FQDN of the DNS record associated with the public IP address /// </summary> public readonly Outputs.PublicIPAddressDnsSettingsResponse? DnsSettings; /// <summary> /// Gets a unique read-only string that changes whenever the resource is updated /// </summary> public readonly string? Etag; /// <summary> /// Resource Id /// </summary> public readonly string? Id; /// <summary> /// Gets or sets the idle timeout of the public IP address /// </summary> public readonly int? IdleTimeoutInMinutes; public readonly string? IpAddress; /// <summary> /// IPConfiguration /// </summary> public readonly Outputs.IPConfigurationResponse? IpConfiguration; /// <summary> /// Resource location /// </summary> public readonly string? Location; /// <summary> /// Resource name /// </summary> public readonly string Name; /// <summary> /// Gets or sets Provisioning state of the PublicIP resource Updating/Deleting/Failed /// </summary> public readonly string? ProvisioningState; /// <summary> /// Gets or sets PublicIP address version (IPv4/IPv6) /// </summary> public readonly string? PublicIPAddressVersion; /// <summary> /// Gets or sets PublicIP allocation method (Static/Dynamic) /// </summary> public readonly string? PublicIPAllocationMethod; /// <summary> /// Gets or sets resource GUID property of the PublicIP resource /// </summary> public readonly string? ResourceGuid; /// <summary> /// Resource tags /// </summary> public readonly ImmutableDictionary<string, string>? Tags; /// <summary> /// Resource type /// </summary> public readonly string Type; [OutputConstructor] private PublicIPAddressResponse( Outputs.PublicIPAddressDnsSettingsResponse? dnsSettings, string? etag, string? id, int? idleTimeoutInMinutes, string? ipAddress, Outputs.IPConfigurationResponse? ipConfiguration, string? location, string name, string? provisioningState, string? publicIPAddressVersion, string? publicIPAllocationMethod, string? resourceGuid, ImmutableDictionary<string, string>? tags, string type) { DnsSettings = dnsSettings; Etag = etag; Id = id; IdleTimeoutInMinutes = idleTimeoutInMinutes; IpAddress = ipAddress; IpConfiguration = ipConfiguration; Location = location; Name = name; ProvisioningState = provisioningState; PublicIPAddressVersion = publicIPAddressVersion; PublicIPAllocationMethod = publicIPAllocationMethod; ResourceGuid = resourceGuid; Tags = tags; Type = type; } } }
30.916667
93
0.591105
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/Network/V20160330/Outputs/PublicIPAddressResponse.cs
3,710
C#
//////////////////////////////////////////////////////////////////////////////// //NUnit tests for "EF Core Provider for LCPI OLE DB" // IBProvider and Contributors. 02.05.2021. using System; using System.Data; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using Microsoft.EntityFrameworkCore; using NUnit.Framework; using xdb=lcpi.data.oledb; namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D1.Query.Operators.SET_001.GreaterThanOrEqual.Complete.NullableDouble.NullableInt64{ //////////////////////////////////////////////////////////////////////////////// using T_DATA1 =System.Nullable<System.Double>; using T_DATA2 =System.Nullable<System.Int64>; //////////////////////////////////////////////////////////////////////////////// //class TestSet_504__param__04__NN public static class TestSet_504__param__04__NN { private const string c_NameOf__TABLE ="DUAL"; private sealed class MyContext:TestBaseDbContext { [Table(c_NameOf__TABLE)] public sealed class TEST_RECORD { [Key] [Column("ID")] public System.Int32? TEST_ID { get; set; } };//class TEST_RECORD //---------------------------------------------------------------------- public DbSet<TEST_RECORD> testTable { get; set; } //---------------------------------------------------------------------- public MyContext(xdb.OleDbTransaction tr) :base(tr) { }//MyContext };//class MyContext //----------------------------------------------------------------------- [Test] public static void Test_001() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { T_DATA1 vv1=null; T_DATA2 vv2=null; var recs=db.testTable.Where(r => vv1 /*OP{*/ >= /*}OP*/ vv2); foreach(var r in recs) { TestServices.ThrowSelectedRow(); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("d","ID").EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL() .T("WHERE NULL")); }//using db tr.Commit(); }//using tr }//using cn }//Test_001 //----------------------------------------------------------------------- [Test] public static void Test_002() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { T_DATA1 vv1=null; T_DATA2 vv2=null; var recs=db.testTable.Where(r => !(vv1 /*OP{*/ >= /*}OP*/ vv2)); foreach(var r in recs) { TestServices.ThrowSelectedRow(); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("d","ID").EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL() .T("WHERE NULL")); }//using db tr.Commit(); }//using tr }//using cn }//Test_002 };//class TestSet_504__param__04__NN //////////////////////////////////////////////////////////////////////////////// }//namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D1.Query.Operators.SET_001.GreaterThanOrEqual.Complete.NullableDouble.NullableInt64
28.241667
154
0.539982
[ "MIT" ]
ibprovider/Lcpi.EFCore.LcpiOleDb
Tests/General/Source/Work/DBMS/Firebird/V03_0_0/D1/Query/Operators/SET_001/GreaterThanOrEqual/Complete/NullableDouble/NullableInt64/TestSet_504__param__04__NN.cs
3,391
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using TeleSharp.TL; namespace TeleSharp.TL { [TLObject(-1063525281)] public class TLMessage : TLAbsMessage { public override int Constructor { get { return -1063525281; } } public int Flags { get; set; } public bool Out { get; set; } public bool Mentioned { get; set; } public bool MediaUnread { get; set; } public bool Silent { get; set; } public bool Post { get; set; } public int Id { get; set; } public int? FromId { get; set; } public TLAbsPeer ToId { get; set; } public TLMessageFwdHeader FwdFrom { get; set; } public int? ViaBotId { get; set; } public int? ReplyToMsgId { get; set; } public int Date { get; set; } public string Message { get; set; } public TLAbsMessageMedia Media { get; set; } public TLAbsReplyMarkup ReplyMarkup { get; set; } public TLVector<TLAbsMessageEntity> Entities { get; set; } public int? Views { get; set; } public int? EditDate { get; set; } public void ComputeFlags() { this.Flags = 0; this.Flags = this.Out ? (this.Flags | 2) : (this.Flags & ~2); this.Flags = this.Mentioned ? (this.Flags | 16) : (this.Flags & ~16); this.Flags = this.MediaUnread ? (this.Flags | 32) : (this.Flags & ~32); this.Flags = this.Silent ? (this.Flags | 8192) : (this.Flags & ~8192); this.Flags = this.Post ? (this.Flags | 16384) : (this.Flags & ~16384); this.Flags = this.FromId != null ? (this.Flags | 256) : (this.Flags & ~256); this.Flags = this.FwdFrom != null ? (this.Flags | 4) : (this.Flags & ~4); this.Flags = this.ViaBotId != null ? (this.Flags | 2048) : (this.Flags & ~2048); this.Flags = this.ReplyToMsgId != null ? (this.Flags | 8) : (this.Flags & ~8); this.Flags = this.Media != null ? (this.Flags | 512) : (this.Flags & ~512); this.Flags = this.ReplyMarkup != null ? (this.Flags | 64) : (this.Flags & ~64); this.Flags = this.Entities != null ? (this.Flags | 128) : (this.Flags & ~128); this.Flags = this.Views != null ? (this.Flags | 1024) : (this.Flags & ~1024); this.Flags = this.EditDate != null ? (this.Flags | 32768) : (this.Flags & ~32768); } public override void DeserializeBody(BinaryReader br) { this.Flags = br.ReadInt32(); this.Out = (this.Flags & 2) != 0; this.Mentioned = (this.Flags & 16) != 0; this.MediaUnread = (this.Flags & 32) != 0; this.Silent = (this.Flags & 8192) != 0; this.Post = (this.Flags & 16384) != 0; this.Id = br.ReadInt32(); if ((this.Flags & 256) != 0) { this.FromId = br.ReadInt32(); } else { this.FromId = null; } this.ToId = (TLAbsPeer)ObjectUtils.DeserializeObject(br); if ((this.Flags & 4) != 0) { this.FwdFrom = (TLMessageFwdHeader)ObjectUtils.DeserializeObject(br); } else { this.FwdFrom = null; } if ((this.Flags & 2048) != 0) { this.ViaBotId = br.ReadInt32(); } else { this.ViaBotId = null; } if ((this.Flags & 8) != 0) { this.ReplyToMsgId = br.ReadInt32(); } else { this.ReplyToMsgId = null; } this.Date = br.ReadInt32(); this.Message = StringUtil.Deserialize(br); if ((this.Flags & 512) != 0) { this.Media = (TLAbsMessageMedia)ObjectUtils.DeserializeObject(br); } else { this.Media = null; } if ((this.Flags & 64) != 0) { this.ReplyMarkup = (TLAbsReplyMarkup)ObjectUtils.DeserializeObject(br); } else { this.ReplyMarkup = null; } if ((this.Flags & 128) != 0) { this.Entities = (TLVector<TLAbsMessageEntity>)ObjectUtils.DeserializeVector<TLAbsMessageEntity>(br); } else { this.Entities = null; } if ((this.Flags & 1024) != 0) { this.Views = br.ReadInt32(); } else { this.Views = null; } if ((this.Flags & 32768) != 0) { this.EditDate = br.ReadInt32(); } else { this.EditDate = null; } } public override void SerializeBody(BinaryWriter bw) { bw.Write(this.Constructor); this.ComputeFlags(); bw.Write(this.Flags); bw.Write(this.Id); if ((this.Flags & 256) != 0) { bw.Write(this.FromId.Value); } ObjectUtils.SerializeObject(this.ToId, bw); if ((this.Flags & 4) != 0) { ObjectUtils.SerializeObject(this.FwdFrom, bw); } if ((this.Flags & 2048) != 0) { bw.Write(this.ViaBotId.Value); } if ((this.Flags & 8) != 0) { bw.Write(this.ReplyToMsgId.Value); } bw.Write(this.Date); StringUtil.Serialize(this.Message, bw); if ((this.Flags & 512) != 0) { ObjectUtils.SerializeObject(this.Media, bw); } if ((this.Flags & 64) != 0) { ObjectUtils.SerializeObject(this.ReplyMarkup, bw); } if ((this.Flags & 128) != 0) { ObjectUtils.SerializeObject(this.Entities, bw); } if ((this.Flags & 1024) != 0) { bw.Write(this.Views.Value); } if ((this.Flags & 32768) != 0) { bw.Write(this.EditDate.Value); } } } }
30.502304
116
0.454903
[ "MIT" ]
slctr/Men.Telegram.ClientApi
Men.Telegram.ClientApi/TL/TL/TLMessage.cs
6,619
C#
//Copyright 2017 Open Science, Engineering, Research and Development Information Systems Open, LLC. (OSRS Open) // 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 Osrs.Data; using Osrs.Runtime; using System; namespace Osrs.Oncor.WellKnown.Vegetation { public sealed class VegPlotType : IIdentifiableEntity<CompoundIdentity>, IDescribable, IEquatable<VegPlotType> { public CompoundIdentity Identity { get; } private string name; public string Name { get { return this.name; } set { if (!string.IsNullOrEmpty(value)) this.name = value; } } public string Description { get; set; } public VegPlotType(CompoundIdentity id, string name) : this(id, name, null) { } public VegPlotType(CompoundIdentity id, string name, string description) { MethodContract.NotNullOrEmpty(id, nameof(id)); MethodContract.NotNullOrEmpty(name, nameof(name)); this.Identity = id; this.name = name; this.Description = description; } public bool Equals(IIdentifiableEntity<CompoundIdentity> other) { return this.Equals(other as VegPlotType); } public bool Equals(VegPlotType other) { if (other != null) return this.Identity.Equals(other.Identity); return false; } } }
31.578125
114
0.626917
[ "Apache-2.0" ]
OSRS/Oncor_Base
Osrs.Oncor.WellKnown.Vegetation/Osrs.Oncor.WellKnown.Vegetation/VegPlotType.cs
2,023
C#
using System.Collections.Generic; using BenchmarkDotNet.Attributes; namespace JsonWebToken.Performance { [Config(typeof(DefaultCoreConfig))] [BenchmarkCategory("CI-CD")] public class WriteCompressedTokenBenchmark : WriteCompressedToken { public override IEnumerable<string> GetPayloads() { yield return "JWE DEF 6 claims"; yield return "JWE DEF 16 claims"; } } }
27
69
0.675926
[ "MIT" ]
signature-opensource/Jwt
perf/Sandbox/WriteCompressedTokenBenchmark.cs
434
C#
using System; using System.Collections.Generic; using System.Threading.Tasks; using BabyTracker.Models; using BabyTracker.Services; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using Mjml.AspNetCore; using Quartz; using Razor.Templating.Core; using SendGrid; using SendGrid.Helpers.Mail; [DisallowConcurrentExecution] public class MemoriesJob : IJob { private readonly ILogger<MemoriesJob> _logger; private readonly ISqLiteService _sqLiteService; private readonly IConfiguration _configuration; private readonly ISendGridClient _sendGridClient; private readonly IMemoriesService _memoriesService; public MemoriesJob(ILogger<MemoriesJob> logger, ISqLiteService sqLiteService, IConfiguration configuration, ISendGridClient sendGridClient, IMemoriesService memoriesService) { _logger = logger; _sqLiteService = sqLiteService; _configuration = configuration; _sendGridClient = sendGridClient; _memoriesService = memoriesService; } public async Task Execute(IJobExecutionContext context) { var babyNames = _configuration["MEMORIES_NAMES"].Split(";"); foreach (var babyName in babyNames) { var memories = _sqLiteService.GetMemoriesFromDb(DateTime.Now, babyName); _logger.LogInformation($"Found {memories.Count} memories for {babyName}"); if (memories.Count > 0) { await SendEmail(memories, babyName); } } } private async Task<Response> SendEmail(List<EntryModel> memories, string babyName) { var msg = new SendGridMessage() { From = new EmailAddress(_configuration["MEMORIES_FROM_EMAIL"], _configuration["MEMORIES_FROM_NAME"]), Subject = $"BabyTracker - Memories {DateTime.Now.ToString("yyyy-MM-dd")}" }; var mjml = await _memoriesService.GetMJML(memories, babyName); var html = await _memoriesService.GetHTML(mjml); msg.AddContent(MimeType.Html, html); var recipients = _configuration[$"MEMORIES_{babyName.ToUpper()}_TO"].Split(";"); foreach (var recipient in recipients) { msg.AddTo(new EmailAddress(recipient)); } return await _sendGridClient.SendEmailAsync(msg).ConfigureAwait(false); } }
32.821918
113
0.686144
[ "MIT" ]
sboulema/BabyTracker
BabyTracker/Jobs/MemoriesJob.cs
2,396
C#
using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Windows; // 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("Hirakanji")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Hirakanji")] [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)] //In order to begin building localizable applications, set //<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file //inside a <PropertyGroup>. For example, if you are using US english //in your source files, set the <UICulture> to en-US. Then uncomment //the NeutralResourceLanguage attribute below. Update the "en-US" in //the line below to match the UICulture setting in the project file. //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] [assembly: ThemeInfo( ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located //(used if a resource is not found in the page, // or application resource dictionaries) ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located //(used if a resource is not found in the page, // app, or any theme specific resource dictionaries) )] // 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")]
39.714286
96
0.754047
[ "MIT" ]
Grawul/Hirakata
Hirakanji/Properties/AssemblyInfo.cs
2,227
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace Northwind.Dal.Models { [Table("ProductReview", Schema = "Production")] public partial class ProductReview { [Key] [Column("ProductReviewID")] public int ProductReviewId { get; set; } [Column("ProductID")] public int ProductId { get; set; } [Required] [StringLength(50)] public string ReviewerName { get; set; } [Column(TypeName = "datetime")] public DateTime ReviewDate { get; set; } [Required] [StringLength(50)] public string EmailAddress { get; set; } public int Rating { get; set; } [StringLength(3850)] public string Comments { get; set; } [Column(TypeName = "datetime")] public DateTime ModifiedDate { get; set; } [ForeignKey(nameof(ProductId))] [InverseProperty("ProductReview")] public virtual Product Product { get; set; } } }
30.8
52
0.621521
[ "BSD-3-Clause", "MIT" ]
MalikWaseemJaved/presentations
.NETCore/WhatsNewInDotNetCore3/Northwind.DAL/Models/ProductReview.cs
1,080
C#
// <auto-generated /> using System; using DIGNDB.App.SmitteStop.DAL.Context; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; namespace DIGNDB.App.SmitteStop.DAL.Migrations { [DbContext(typeof(DigNDB_SmittestopContext))] [Migration("20210311123914_FixLithuaniaTranslations")] partial class FixLithuaniaTranslations { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "3.1.7") .HasAnnotation("Relational:MaxIdentifierLength", 128) .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("DIGNDB.App.SmitteStop.Domain.Db.ApplicationStatistics", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime>("EntryDate") .HasColumnType("datetime2"); b.Property<int>("PositiveResultsLast7Days") .HasColumnType("int"); b.Property<int>("PositiveTestsResultsTotal") .HasColumnType("int"); b.Property<int>("TotalSmittestopDownloads") .HasColumnType("int"); b.HasKey("Id"); b.ToTable("ApplicationStatistics"); }); modelBuilder.Entity("DIGNDB.App.SmitteStop.Domain.Db.Country", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("Code") .HasColumnType("nvarchar(2)") .HasMaxLength(2); b.Property<bool>("PullingFromGatewayEnabled") .HasColumnType("bit"); b.Property<bool>("VisitedCountriesEnabled") .HasColumnType("bit"); b.HasKey("Id"); b.ToTable("Country"); b.HasData( new { Id = 1L, Code = "AT", PullingFromGatewayEnabled = true, VisitedCountriesEnabled = true }, new { Id = 2L, Code = "BE", PullingFromGatewayEnabled = true, VisitedCountriesEnabled = true }, new { Id = 3L, Code = "BG", PullingFromGatewayEnabled = true, VisitedCountriesEnabled = true }, new { Id = 4L, Code = "HR", PullingFromGatewayEnabled = true, VisitedCountriesEnabled = true }, new { Id = 5L, Code = "CY", PullingFromGatewayEnabled = true, VisitedCountriesEnabled = true }, new { Id = 6L, Code = "CZ", PullingFromGatewayEnabled = true, VisitedCountriesEnabled = true }, new { Id = 8L, Code = "EE", PullingFromGatewayEnabled = true, VisitedCountriesEnabled = true }, new { Id = 9L, Code = "FI", PullingFromGatewayEnabled = true, VisitedCountriesEnabled = true }, new { Id = 10L, Code = "FR", PullingFromGatewayEnabled = true, VisitedCountriesEnabled = true }, new { Id = 11L, Code = "DE", PullingFromGatewayEnabled = true, VisitedCountriesEnabled = true }, new { Id = 12L, Code = "GR", PullingFromGatewayEnabled = true, VisitedCountriesEnabled = true }, new { Id = 13L, Code = "HU", PullingFromGatewayEnabled = true, VisitedCountriesEnabled = true }, new { Id = 14L, Code = "IE", PullingFromGatewayEnabled = true, VisitedCountriesEnabled = true }, new { Id = 15L, Code = "IT", PullingFromGatewayEnabled = true, VisitedCountriesEnabled = true }, new { Id = 16L, Code = "LV", PullingFromGatewayEnabled = true, VisitedCountriesEnabled = true }, new { Id = 17L, Code = "LT", PullingFromGatewayEnabled = true, VisitedCountriesEnabled = true }, new { Id = 18L, Code = "LU", PullingFromGatewayEnabled = true, VisitedCountriesEnabled = true }, new { Id = 19L, Code = "MT", PullingFromGatewayEnabled = true, VisitedCountriesEnabled = true }, new { Id = 20L, Code = "NL", PullingFromGatewayEnabled = true, VisitedCountriesEnabled = true }, new { Id = 21L, Code = "PL", PullingFromGatewayEnabled = true, VisitedCountriesEnabled = true }, new { Id = 22L, Code = "PT", PullingFromGatewayEnabled = true, VisitedCountriesEnabled = true }, new { Id = 23L, Code = "RO", PullingFromGatewayEnabled = true, VisitedCountriesEnabled = true }, new { Id = 24L, Code = "SK", PullingFromGatewayEnabled = true, VisitedCountriesEnabled = true }, new { Id = 25L, Code = "SI", PullingFromGatewayEnabled = true, VisitedCountriesEnabled = true }, new { Id = 26L, Code = "ES", PullingFromGatewayEnabled = true, VisitedCountriesEnabled = true }, new { Id = 27L, Code = "SE", PullingFromGatewayEnabled = true, VisitedCountriesEnabled = true }, new { Id = 7L, Code = "DK", PullingFromGatewayEnabled = true, VisitedCountriesEnabled = true }, new { Id = 29L, Code = "NO", PullingFromGatewayEnabled = false, VisitedCountriesEnabled = false }, new { Id = 28L, Code = "EN", PullingFromGatewayEnabled = false, VisitedCountriesEnabled = false }, new { Id = 30L, Code = "IS", PullingFromGatewayEnabled = true, VisitedCountriesEnabled = true }, new { Id = 31L, Code = "LI", PullingFromGatewayEnabled = true, VisitedCountriesEnabled = true }, new { Id = 32L, Code = "CH", PullingFromGatewayEnabled = true, VisitedCountriesEnabled = true }, new { Id = 33L, Code = "NB", PullingFromGatewayEnabled = false, VisitedCountriesEnabled = false }, new { Id = 34L, Code = "NN", PullingFromGatewayEnabled = false, VisitedCountriesEnabled = false }, new { Id = 35L, Code = "AR", PullingFromGatewayEnabled = false, VisitedCountriesEnabled = false }, new { Id = 36L, Code = "SO", PullingFromGatewayEnabled = false, VisitedCountriesEnabled = false }, new { Id = 37L, Code = "TI", PullingFromGatewayEnabled = false, VisitedCountriesEnabled = false }, new { Id = 38L, Code = "UR", PullingFromGatewayEnabled = false, VisitedCountriesEnabled = false }); }); modelBuilder.Entity("DIGNDB.App.SmitteStop.Domain.Db.CovidStatistics", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int>("ConfirmedCasesToday") .HasColumnType("int"); b.Property<int>("ConfirmedCasesTotal") .HasColumnType("int"); b.Property<DateTime>("Date") .HasColumnType("datetime2"); b.Property<int>("IcuAdmittedToday") .HasColumnType("int"); b.Property<int>("PatientsAdmittedToday") .HasColumnType("int"); b.Property<int>("TestsConductedToday") .HasColumnType("int"); b.Property<int>("TestsConductedTotal") .HasColumnType("int"); b.Property<double>("VaccinatedFirstDoseToday") .HasColumnType("float"); b.Property<double>("VaccinatedFirstDoseTotal") .HasColumnType("float"); b.Property<double>("VaccinatedSecondDoseToday") .HasColumnType("float"); b.Property<double>("VaccinatedSecondDoseTotal") .HasColumnType("float"); b.HasKey("Id"); b.ToTable("CovidStatistics"); }); modelBuilder.Entity("DIGNDB.App.SmitteStop.Domain.Db.JwtToken", b => { b.Property<string>("Id") .HasColumnType("nvarchar(450)"); b.Property<DateTime>("ExpirationTime") .HasColumnType("datetime2"); b.HasKey("Id"); b.ToTable("JwtToken"); }); modelBuilder.Entity("DIGNDB.App.SmitteStop.Domain.Db.Setting", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("Key") .IsRequired() .HasColumnType("nvarchar(96)") .HasMaxLength(96); b.Property<string>("Value") .HasColumnType("nvarchar(max)"); b.HasKey("Id"); b.ToTable("Setting"); }); modelBuilder.Entity("DIGNDB.App.SmitteStop.Domain.Db.TemporaryExposureKey", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnName("ID") .HasColumnType("uniqueidentifier") .HasDefaultValueSql("(newid())"); b.Property<DateTime>("CreatedOn") .HasColumnType("datetime"); b.Property<int?>("DaysSinceOnsetOfSymptoms") .HasColumnType("int"); b.Property<byte[]>("KeyData") .IsRequired() .HasColumnType("varbinary(255)") .HasMaxLength(255); b.Property<int>("KeySource") .HasColumnType("int"); b.Property<long>("OriginId") .HasColumnType("bigint"); b.Property<int>("ReportType") .HasColumnType("int"); b.Property<long>("RollingPeriod") .HasColumnType("bigint"); b.Property<long>("RollingStartNumber") .HasColumnType("bigint"); b.Property<bool>("SharingConsentGiven") .HasColumnType("bit"); b.Property<int>("TransmissionRiskLevel") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("KeyData") .IsUnique(); b.HasIndex("OriginId"); b.ToTable("TemporaryExposureKey"); }); modelBuilder.Entity("DIGNDB.App.SmitteStop.Domain.Db.TemporaryExposureKeyCountry", b => { b.Property<Guid>("TemporaryExposureKeyId") .HasColumnType("uniqueidentifier"); b.Property<long>("CountryId") .HasColumnType("bigint"); b.HasKey("TemporaryExposureKeyId", "CountryId"); b.HasIndex("CountryId"); b.ToTable("TemporaryExposureKeyCountry"); }); modelBuilder.Entity("DIGNDB.App.SmitteStop.Domain.Db.Translation", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<long>("EntityId") .HasColumnType("bigint"); b.Property<string>("EntityName") .HasColumnType("nvarchar(96)") .HasMaxLength(96); b.Property<long?>("LanguageCountryId") .HasColumnType("bigint"); b.Property<string>("Value") .HasColumnType("nvarchar(96)") .HasMaxLength(96); b.HasKey("Id"); b.HasIndex("LanguageCountryId"); b.ToTable("Translation"); b.HasData( new { Id = 1L, EntityId = 1L, EntityName = "Country", LanguageCountryId = 28L, Value = "Austria" }, new { Id = 2L, EntityId = 2L, EntityName = "Country", LanguageCountryId = 28L, Value = "Belgium" }, new { Id = 3L, EntityId = 3L, EntityName = "Country", LanguageCountryId = 28L, Value = "Bulgaria" }, new { Id = 4L, EntityId = 4L, EntityName = "Country", LanguageCountryId = 28L, Value = "Croatia" }, new { Id = 5L, EntityId = 5L, EntityName = "Country", LanguageCountryId = 28L, Value = "Cyprus" }, new { Id = 6L, EntityId = 6L, EntityName = "Country", LanguageCountryId = 28L, Value = "Czech Republic" }, new { Id = 7L, EntityId = 7L, EntityName = "Country", LanguageCountryId = 28L, Value = "Denmark" }, new { Id = 8L, EntityId = 8L, EntityName = "Country", LanguageCountryId = 28L, Value = "Estonia" }, new { Id = 9L, EntityId = 9L, EntityName = "Country", LanguageCountryId = 28L, Value = "Finland" }, new { Id = 10L, EntityId = 10L, EntityName = "Country", LanguageCountryId = 28L, Value = "France" }, new { Id = 11L, EntityId = 11L, EntityName = "Country", LanguageCountryId = 28L, Value = "Germany" }, new { Id = 12L, EntityId = 12L, EntityName = "Country", LanguageCountryId = 28L, Value = "Greece" }, new { Id = 13L, EntityId = 13L, EntityName = "Country", LanguageCountryId = 28L, Value = "Hungary" }, new { Id = 14L, EntityId = 14L, EntityName = "Country", LanguageCountryId = 28L, Value = "Ireland" }, new { Id = 15L, EntityId = 15L, EntityName = "Country", LanguageCountryId = 28L, Value = "Italy" }, new { Id = 16L, EntityId = 16L, EntityName = "Country", LanguageCountryId = 28L, Value = "Latvia" }, new { Id = 17L, EntityId = 17L, EntityName = "Country", LanguageCountryId = 28L, Value = "Lithuania" }, new { Id = 18L, EntityId = 18L, EntityName = "Country", LanguageCountryId = 28L, Value = "Luxembourg" }, new { Id = 19L, EntityId = 19L, EntityName = "Country", LanguageCountryId = 28L, Value = "Malta" }, new { Id = 20L, EntityId = 20L, EntityName = "Country", LanguageCountryId = 28L, Value = "Netherlands" }, new { Id = 21L, EntityId = 21L, EntityName = "Country", LanguageCountryId = 28L, Value = "Poland" }, new { Id = 22L, EntityId = 22L, EntityName = "Country", LanguageCountryId = 28L, Value = "Portugal" }, new { Id = 23L, EntityId = 23L, EntityName = "Country", LanguageCountryId = 28L, Value = "Romania" }, new { Id = 24L, EntityId = 24L, EntityName = "Country", LanguageCountryId = 28L, Value = "Slovakia" }, new { Id = 25L, EntityId = 25L, EntityName = "Country", LanguageCountryId = 28L, Value = "Slovenia" }, new { Id = 26L, EntityId = 26L, EntityName = "Country", LanguageCountryId = 28L, Value = "Spain" }, new { Id = 27L, EntityId = 27L, EntityName = "Country", LanguageCountryId = 28L, Value = "Sweden" }, new { Id = 28L, EntityId = 30L, EntityName = "Country", LanguageCountryId = 28L, Value = "Iceland" }, new { Id = 29L, EntityId = 31L, EntityName = "Country", LanguageCountryId = 28L, Value = "Liechtenstein" }, new { Id = 30L, EntityId = 32L, EntityName = "Country", LanguageCountryId = 28L, Value = "Switzerland" }, new { Id = 31L, EntityId = 1L, EntityName = "Country", LanguageCountryId = 33L, Value = "Østerrike" }, new { Id = 32L, EntityId = 2L, EntityName = "Country", LanguageCountryId = 33L, Value = "Belgia" }, new { Id = 33L, EntityId = 3L, EntityName = "Country", LanguageCountryId = 33L, Value = "Bulgaria" }, new { Id = 34L, EntityId = 4L, EntityName = "Country", LanguageCountryId = 33L, Value = "Kroatia" }, new { Id = 35L, EntityId = 5L, EntityName = "Country", LanguageCountryId = 33L, Value = "Kypros" }, new { Id = 36L, EntityId = 6L, EntityName = "Country", LanguageCountryId = 33L, Value = "Tsjekkia" }, new { Id = 37L, EntityId = 7L, EntityName = "Country", LanguageCountryId = 33L, Value = "Danmark" }, new { Id = 38L, EntityId = 8L, EntityName = "Country", LanguageCountryId = 33L, Value = "Estland" }, new { Id = 39L, EntityId = 9L, EntityName = "Country", LanguageCountryId = 33L, Value = "Finland" }, new { Id = 40L, EntityId = 10L, EntityName = "Country", LanguageCountryId = 33L, Value = "Frankrike" }, new { Id = 41L, EntityId = 11L, EntityName = "Country", LanguageCountryId = 33L, Value = "Tyskland" }, new { Id = 42L, EntityId = 12L, EntityName = "Country", LanguageCountryId = 33L, Value = "Hellas" }, new { Id = 43L, EntityId = 13L, EntityName = "Country", LanguageCountryId = 33L, Value = "Ungarn" }, new { Id = 44L, EntityId = 14L, EntityName = "Country", LanguageCountryId = 33L, Value = "Irland" }, new { Id = 45L, EntityId = 15L, EntityName = "Country", LanguageCountryId = 33L, Value = "Italia" }, new { Id = 46L, EntityId = 16L, EntityName = "Country", LanguageCountryId = 33L, Value = "Latvia" }, new { Id = 47L, EntityId = 17L, EntityName = "Country", LanguageCountryId = 33L, Value = "Litauen" }, new { Id = 48L, EntityId = 18L, EntityName = "Country", LanguageCountryId = 33L, Value = "Luxembourg" }, new { Id = 49L, EntityId = 19L, EntityName = "Country", LanguageCountryId = 33L, Value = "Malta" }, new { Id = 50L, EntityId = 20L, EntityName = "Country", LanguageCountryId = 33L, Value = "Nederland" }, new { Id = 51L, EntityId = 21L, EntityName = "Country", LanguageCountryId = 33L, Value = "Polen" }, new { Id = 52L, EntityId = 22L, EntityName = "Country", LanguageCountryId = 33L, Value = "Portugal" }, new { Id = 53L, EntityId = 23L, EntityName = "Country", LanguageCountryId = 33L, Value = "Romania" }, new { Id = 54L, EntityId = 24L, EntityName = "Country", LanguageCountryId = 33L, Value = "Slovakia" }, new { Id = 55L, EntityId = 25L, EntityName = "Country", LanguageCountryId = 33L, Value = "Slovenia" }, new { Id = 56L, EntityId = 26L, EntityName = "Country", LanguageCountryId = 33L, Value = "Spania" }, new { Id = 57L, EntityId = 27L, EntityName = "Country", LanguageCountryId = 33L, Value = "Sverige" }, new { Id = 58L, EntityId = 30L, EntityName = "Country", LanguageCountryId = 33L, Value = "Island" }, new { Id = 59L, EntityId = 31L, EntityName = "Country", LanguageCountryId = 33L, Value = "Liechtenstein" }, new { Id = 60L, EntityId = 32L, EntityName = "Country", LanguageCountryId = 33L, Value = "Sveits" }, new { Id = 61L, EntityId = 1L, EntityName = "Country", LanguageCountryId = 34L, Value = "Austerrike" }, new { Id = 62L, EntityId = 2L, EntityName = "Country", LanguageCountryId = 34L, Value = "Belgia" }, new { Id = 63L, EntityId = 3L, EntityName = "Country", LanguageCountryId = 34L, Value = "Bulgaria" }, new { Id = 64L, EntityId = 4L, EntityName = "Country", LanguageCountryId = 34L, Value = "Kroatia" }, new { Id = 65L, EntityId = 5L, EntityName = "Country", LanguageCountryId = 34L, Value = "Kypros" }, new { Id = 66L, EntityId = 6L, EntityName = "Country", LanguageCountryId = 34L, Value = "Tsjekkia" }, new { Id = 67L, EntityId = 7L, EntityName = "Country", LanguageCountryId = 34L, Value = "Danmark" }, new { Id = 68L, EntityId = 8L, EntityName = "Country", LanguageCountryId = 34L, Value = "Estland" }, new { Id = 69L, EntityId = 9L, EntityName = "Country", LanguageCountryId = 34L, Value = "Finland" }, new { Id = 70L, EntityId = 10L, EntityName = "Country", LanguageCountryId = 34L, Value = "Frankrike" }, new { Id = 71L, EntityId = 11L, EntityName = "Country", LanguageCountryId = 34L, Value = "Tyskland" }, new { Id = 72L, EntityId = 12L, EntityName = "Country", LanguageCountryId = 34L, Value = "Hellas" }, new { Id = 73L, EntityId = 13L, EntityName = "Country", LanguageCountryId = 34L, Value = "Ungarn" }, new { Id = 74L, EntityId = 14L, EntityName = "Country", LanguageCountryId = 34L, Value = "Irland" }, new { Id = 75L, EntityId = 15L, EntityName = "Country", LanguageCountryId = 34L, Value = "Italia" }, new { Id = 76L, EntityId = 16L, EntityName = "Country", LanguageCountryId = 34L, Value = "Latvia" }, new { Id = 77L, EntityId = 17L, EntityName = "Country", LanguageCountryId = 34L, Value = "Litauen" }, new { Id = 78L, EntityId = 18L, EntityName = "Country", LanguageCountryId = 34L, Value = "Luxembourg" }, new { Id = 79L, EntityId = 19L, EntityName = "Country", LanguageCountryId = 34L, Value = "Malta" }, new { Id = 80L, EntityId = 20L, EntityName = "Country", LanguageCountryId = 34L, Value = "Nederland" }, new { Id = 81L, EntityId = 21L, EntityName = "Country", LanguageCountryId = 34L, Value = "Polen" }, new { Id = 82L, EntityId = 22L, EntityName = "Country", LanguageCountryId = 34L, Value = "Portugal" }, new { Id = 83L, EntityId = 23L, EntityName = "Country", LanguageCountryId = 34L, Value = "Romania" }, new { Id = 84L, EntityId = 24L, EntityName = "Country", LanguageCountryId = 34L, Value = "Slovakia" }, new { Id = 85L, EntityId = 25L, EntityName = "Country", LanguageCountryId = 34L, Value = "Slovenia" }, new { Id = 86L, EntityId = 26L, EntityName = "Country", LanguageCountryId = 34L, Value = "Spania" }, new { Id = 87L, EntityId = 27L, EntityName = "Country", LanguageCountryId = 34L, Value = "Sverige" }, new { Id = 88L, EntityId = 30L, EntityName = "Country", LanguageCountryId = 34L, Value = "Island" }, new { Id = 89L, EntityId = 31L, EntityName = "Country", LanguageCountryId = 34L, Value = "Liechtenstein" }, new { Id = 90L, EntityId = 32L, EntityName = "Country", LanguageCountryId = 34L, Value = "Sveits" }, new { Id = 91L, EntityId = 1L, EntityName = "Country", LanguageCountryId = 35L, Value = "النمسا" }, new { Id = 92L, EntityId = 2L, EntityName = "Country", LanguageCountryId = 35L, Value = "بلجیکا" }, new { Id = 93L, EntityId = 3L, EntityName = "Country", LanguageCountryId = 35L, Value = "بلغاریا" }, new { Id = 94L, EntityId = 4L, EntityName = "Country", LanguageCountryId = 35L, Value = "کرواتیا" }, new { Id = 95L, EntityId = 5L, EntityName = "Country", LanguageCountryId = 35L, Value = "قبرص" }, new { Id = 96L, EntityId = 6L, EntityName = "Country", LanguageCountryId = 35L, Value = "تشیکیا" }, new { Id = 97L, EntityId = 7L, EntityName = "Country", LanguageCountryId = 35L, Value = "دانمارك" }, new { Id = 98L, EntityId = 8L, EntityName = "Country", LanguageCountryId = 35L, Value = "استونیا" }, new { Id = 99L, EntityId = 9L, EntityName = "Country", LanguageCountryId = 35L, Value = "فنلندة" }, new { Id = 100L, EntityId = 10L, EntityName = "Country", LanguageCountryId = 35L, Value = "فرنسا" }, new { Id = 101L, EntityId = 11L, EntityName = "Country", LanguageCountryId = 35L, Value = "ألمانیا" }, new { Id = 102L, EntityId = 12L, EntityName = "Country", LanguageCountryId = 35L, Value = "الیونان" }, new { Id = 103L, EntityId = 13L, EntityName = "Country", LanguageCountryId = 35L, Value = "هنغاریا (المجر)" }, new { Id = 104L, EntityId = 14L, EntityName = "Country", LanguageCountryId = 35L, Value = "ایرلندا" }, new { Id = 105L, EntityId = 15L, EntityName = "Country", LanguageCountryId = 35L, Value = "إیطالیا" }, new { Id = 106L, EntityId = 16L, EntityName = "Country", LanguageCountryId = 35L, Value = "لاتفیا" }, new { Id = 107L, EntityId = 17L, EntityName = "Country", LanguageCountryId = 35L, Value = "لیتوانیا" }, new { Id = 108L, EntityId = 18L, EntityName = "Country", LanguageCountryId = 35L, Value = "لکسمبورج" }, new { Id = 109L, EntityId = 19L, EntityName = "Country", LanguageCountryId = 35L, Value = "مالطا" }, new { Id = 110L, EntityId = 20L, EntityName = "Country", LanguageCountryId = 35L, Value = "هولندا" }, new { Id = 111L, EntityId = 21L, EntityName = "Country", LanguageCountryId = 35L, Value = "(بولندا) بولونیا " }, new { Id = 112L, EntityId = 22L, EntityName = "Country", LanguageCountryId = 35L, Value = "برتغال" }, new { Id = 113L, EntityId = 23L, EntityName = "Country", LanguageCountryId = 35L, Value = "رومانیا" }, new { Id = 114L, EntityId = 24L, EntityName = "Country", LanguageCountryId = 35L, Value = "سلوفاکیا" }, new { Id = 115L, EntityId = 25L, EntityName = "Country", LanguageCountryId = 35L, Value = "سلوفینیا" }, new { Id = 116L, EntityId = 26L, EntityName = "Country", LanguageCountryId = 35L, Value = "اسبانیا" }, new { Id = 117L, EntityId = 27L, EntityName = "Country", LanguageCountryId = 35L, Value = "السوید" }, new { Id = 118L, EntityId = 30L, EntityName = "Country", LanguageCountryId = 35L, Value = "ایسلندة" }, new { Id = 119L, EntityId = 31L, EntityName = "Country", LanguageCountryId = 35L, Value = "لشتنشتاین" }, new { Id = 120L, EntityId = 32L, EntityName = "Country", LanguageCountryId = 35L, Value = "سویسرا" }, new { Id = 121L, EntityId = 1L, EntityName = "Country", LanguageCountryId = 21L, Value = "Austria" }, new { Id = 122L, EntityId = 2L, EntityName = "Country", LanguageCountryId = 21L, Value = "Belgia" }, new { Id = 123L, EntityId = 3L, EntityName = "Country", LanguageCountryId = 21L, Value = "Bułgaria" }, new { Id = 124L, EntityId = 4L, EntityName = "Country", LanguageCountryId = 21L, Value = "Chorwacja" }, new { Id = 125L, EntityId = 5L, EntityName = "Country", LanguageCountryId = 21L, Value = "Cypr" }, new { Id = 126L, EntityId = 6L, EntityName = "Country", LanguageCountryId = 21L, Value = "Czechy" }, new { Id = 127L, EntityId = 7L, EntityName = "Country", LanguageCountryId = 21L, Value = "Dania`" }, new { Id = 128L, EntityId = 8L, EntityName = "Country", LanguageCountryId = 21L, Value = "Estonia" }, new { Id = 129L, EntityId = 9L, EntityName = "Country", LanguageCountryId = 21L, Value = "Finlandia" }, new { Id = 130L, EntityId = 10L, EntityName = "Country", LanguageCountryId = 21L, Value = "Francja" }, new { Id = 131L, EntityId = 11L, EntityName = "Country", LanguageCountryId = 21L, Value = "Niemcy" }, new { Id = 132L, EntityId = 12L, EntityName = "Country", LanguageCountryId = 21L, Value = "Grecja" }, new { Id = 133L, EntityId = 13L, EntityName = "Country", LanguageCountryId = 21L, Value = "Węgry" }, new { Id = 134L, EntityId = 14L, EntityName = "Country", LanguageCountryId = 21L, Value = "Irlandia" }, new { Id = 135L, EntityId = 15L, EntityName = "Country", LanguageCountryId = 21L, Value = "Włochy" }, new { Id = 136L, EntityId = 16L, EntityName = "Country", LanguageCountryId = 21L, Value = "Łotwa" }, new { Id = 137L, EntityId = 17L, EntityName = "Country", LanguageCountryId = 21L, Value = "Litwa" }, new { Id = 138L, EntityId = 18L, EntityName = "Country", LanguageCountryId = 21L, Value = "Luksemburg" }, new { Id = 139L, EntityId = 19L, EntityName = "Country", LanguageCountryId = 21L, Value = "Malta" }, new { Id = 140L, EntityId = 20L, EntityName = "Country", LanguageCountryId = 21L, Value = "Holandia" }, new { Id = 141L, EntityId = 21L, EntityName = "Country", LanguageCountryId = 21L, Value = "Polska" }, new { Id = 142L, EntityId = 22L, EntityName = "Country", LanguageCountryId = 21L, Value = "Portugalia" }, new { Id = 143L, EntityId = 23L, EntityName = "Country", LanguageCountryId = 21L, Value = "Rumunia" }, new { Id = 144L, EntityId = 24L, EntityName = "Country", LanguageCountryId = 21L, Value = "Słowacja" }, new { Id = 145L, EntityId = 25L, EntityName = "Country", LanguageCountryId = 21L, Value = "Słowenia" }, new { Id = 146L, EntityId = 26L, EntityName = "Country", LanguageCountryId = 21L, Value = "Hiszpania" }, new { Id = 147L, EntityId = 27L, EntityName = "Country", LanguageCountryId = 21L, Value = "Szwecja" }, new { Id = 148L, EntityId = 30L, EntityName = "Country", LanguageCountryId = 21L, Value = "Islandia" }, new { Id = 149L, EntityId = 31L, EntityName = "Country", LanguageCountryId = 21L, Value = "Lichtenstein" }, new { Id = 150L, EntityId = 32L, EntityName = "Country", LanguageCountryId = 21L, Value = "Szwajcaria" }, new { Id = 151L, EntityId = 1L, EntityName = "Country", LanguageCountryId = 36L, Value = "Awstriya" }, new { Id = 152L, EntityId = 2L, EntityName = "Country", LanguageCountryId = 36L, Value = "Beljim" }, new { Id = 153L, EntityId = 3L, EntityName = "Country", LanguageCountryId = 36L, Value = "Bulgaariya" }, new { Id = 154L, EntityId = 4L, EntityName = "Country", LanguageCountryId = 36L, Value = "Kuruweeshiya" }, new { Id = 155L, EntityId = 5L, EntityName = "Country", LanguageCountryId = 36L, Value = "Sayberes" }, new { Id = 156L, EntityId = 6L, EntityName = "Country", LanguageCountryId = 36L, Value = "Jeekiya" }, new { Id = 157L, EntityId = 7L, EntityName = "Country", LanguageCountryId = 36L, Value = "Denmark" }, new { Id = 158L, EntityId = 8L, EntityName = "Country", LanguageCountryId = 36L, Value = "Estooniya" }, new { Id = 159L, EntityId = 9L, EntityName = "Country", LanguageCountryId = 36L, Value = "Finland" }, new { Id = 160L, EntityId = 10L, EntityName = "Country", LanguageCountryId = 36L, Value = "Faransiiska" }, new { Id = 161L, EntityId = 11L, EntityName = "Country", LanguageCountryId = 36L, Value = "Jarmalka" }, new { Id = 162L, EntityId = 12L, EntityName = "Country", LanguageCountryId = 36L, Value = "Giriiga" }, new { Id = 163L, EntityId = 13L, EntityName = "Country", LanguageCountryId = 36L, Value = "Hangari" }, new { Id = 164L, EntityId = 14L, EntityName = "Country", LanguageCountryId = 36L, Value = "Irland" }, new { Id = 165L, EntityId = 15L, EntityName = "Country", LanguageCountryId = 36L, Value = "Talyaaniga" }, new { Id = 166L, EntityId = 16L, EntityName = "Country", LanguageCountryId = 36L, Value = "Latfiya" }, new { Id = 167L, EntityId = 17L, EntityName = "Country", LanguageCountryId = 36L, Value = "Litweyniya" }, new { Id = 168L, EntityId = 18L, EntityName = "Country", LanguageCountryId = 36L, Value = "Luksemburg" }, new { Id = 169L, EntityId = 19L, EntityName = "Country", LanguageCountryId = 36L, Value = "Malta" }, new { Id = 170L, EntityId = 20L, EntityName = "Country", LanguageCountryId = 36L, Value = "Holland" }, new { Id = 171L, EntityId = 21L, EntityName = "Country", LanguageCountryId = 36L, Value = "Booland" }, new { Id = 172L, EntityId = 22L, EntityName = "Country", LanguageCountryId = 36L, Value = "Burtuqaal" }, new { Id = 173L, EntityId = 23L, EntityName = "Country", LanguageCountryId = 36L, Value = "Romaaniya" }, new { Id = 174L, EntityId = 24L, EntityName = "Country", LanguageCountryId = 36L, Value = "Islofaakiya" }, new { Id = 175L, EntityId = 25L, EntityName = "Country", LanguageCountryId = 36L, Value = "Islofeeniya" }, new { Id = 176L, EntityId = 26L, EntityName = "Country", LanguageCountryId = 36L, Value = "Isbaaniya" }, new { Id = 177L, EntityId = 27L, EntityName = "Country", LanguageCountryId = 36L, Value = "Iswiidhan" }, new { Id = 178L, EntityId = 30L, EntityName = "Country", LanguageCountryId = 36L, Value = "Island" }, new { Id = 179L, EntityId = 31L, EntityName = "Country", LanguageCountryId = 36L, Value = "Liechtenstein" }, new { Id = 180L, EntityId = 32L, EntityName = "Country", LanguageCountryId = 36L, Value = "Iswiserland" }, new { Id = 181L, EntityId = 1L, EntityName = "Country", LanguageCountryId = 37L, Value = "ኣውስትርያ" }, new { Id = 182L, EntityId = 2L, EntityName = "Country", LanguageCountryId = 37L, Value = "በልጁም" }, new { Id = 183L, EntityId = 3L, EntityName = "Country", LanguageCountryId = 37L, Value = "ቡልጋርያ" }, new { Id = 184L, EntityId = 4L, EntityName = "Country", LanguageCountryId = 37L, Value = "ክሮኣሽያ" }, new { Id = 185L, EntityId = 5L, EntityName = "Country", LanguageCountryId = 37L, Value = "ቂፕሮስ" }, new { Id = 186L, EntityId = 6L, EntityName = "Country", LanguageCountryId = 37L, Value = "ቸክ ረፓብሊክ" }, new { Id = 187L, EntityId = 7L, EntityName = "Country", LanguageCountryId = 37L, Value = "ዴኒማርክ" }, new { Id = 188L, EntityId = 8L, EntityName = "Country", LanguageCountryId = 37L, Value = "ኤስትላንድ" }, new { Id = 189L, EntityId = 9L, EntityName = "Country", LanguageCountryId = 37L, Value = "ፊንላንድ" }, new { Id = 190L, EntityId = 10L, EntityName = "Country", LanguageCountryId = 37L, Value = "ፈረንሳ" }, new { Id = 191L, EntityId = 11L, EntityName = "Country", LanguageCountryId = 37L, Value = "ጀርመን" }, new { Id = 192L, EntityId = 12L, EntityName = "Country", LanguageCountryId = 37L, Value = "ግሪኽ" }, new { Id = 193L, EntityId = 13L, EntityName = "Country", LanguageCountryId = 37L, Value = "ሃንጋሪ" }, new { Id = 194L, EntityId = 14L, EntityName = "Country", LanguageCountryId = 37L, Value = "ኣይርላንድ" }, new { Id = 195L, EntityId = 15L, EntityName = "Country", LanguageCountryId = 37L, Value = "ጥልያን" }, new { Id = 196L, EntityId = 16L, EntityName = "Country", LanguageCountryId = 37L, Value = "ላትቭያ" }, new { Id = 197L, EntityId = 17L, EntityName = "Country", LanguageCountryId = 37L, Value = "ሊታወን" }, new { Id = 198L, EntityId = 18L, EntityName = "Country", LanguageCountryId = 37L, Value = "ላክሰንበርግ" }, new { Id = 199L, EntityId = 19L, EntityName = "Country", LanguageCountryId = 37L, Value = "ማልታ" }, new { Id = 200L, EntityId = 20L, EntityName = "Country", LanguageCountryId = 37L, Value = "ሆላንድ" }, new { Id = 201L, EntityId = 21L, EntityName = "Country", LanguageCountryId = 37L, Value = "ፖላንድ" }, new { Id = 202L, EntityId = 22L, EntityName = "Country", LanguageCountryId = 37L, Value = "ፖርቱጓል" }, new { Id = 203L, EntityId = 23L, EntityName = "Country", LanguageCountryId = 37L, Value = "ሩማንያ" }, new { Id = 204L, EntityId = 24L, EntityName = "Country", LanguageCountryId = 37L, Value = "ስሎቫክያ" }, new { Id = 205L, EntityId = 25L, EntityName = "Country", LanguageCountryId = 37L, Value = "ስሎቬንያ" }, new { Id = 206L, EntityId = 26L, EntityName = "Country", LanguageCountryId = 37L, Value = "ስጳኛ" }, new { Id = 207L, EntityId = 27L, EntityName = "Country", LanguageCountryId = 37L, Value = "ሽዊደን" }, new { Id = 208L, EntityId = 30L, EntityName = "Country", LanguageCountryId = 37L, Value = "ኣይስላንድ" }, new { Id = 209L, EntityId = 31L, EntityName = "Country", LanguageCountryId = 37L, Value = "ሊሽተንስታይን" }, new { Id = 210L, EntityId = 32L, EntityName = "Country", LanguageCountryId = 37L, Value = "ስዊዘርላንድ" }, new { Id = 211L, EntityId = 1L, EntityName = "Country", LanguageCountryId = 38L, Value = "آسٹریا" }, new { Id = 212L, EntityId = 2L, EntityName = "Country", LanguageCountryId = 38L, Value = "بیلجیئم" }, new { Id = 213L, EntityId = 3L, EntityName = "Country", LanguageCountryId = 38L, Value = "بلغاریہ" }, new { Id = 214L, EntityId = 4L, EntityName = "Country", LanguageCountryId = 38L, Value = "کرویشیا" }, new { Id = 215L, EntityId = 5L, EntityName = "Country", LanguageCountryId = 38L, Value = "قبرص" }, new { Id = 216L, EntityId = 6L, EntityName = "Country", LanguageCountryId = 38L, Value = "چیک ریپبلک" }, new { Id = 217L, EntityId = 7L, EntityName = "Country", LanguageCountryId = 38L, Value = "ڈنمارک" }, new { Id = 218L, EntityId = 8L, EntityName = "Country", LanguageCountryId = 38L, Value = "ایسٹونیا" }, new { Id = 219L, EntityId = 9L, EntityName = "Country", LanguageCountryId = 38L, Value = "فن لینڈ" }, new { Id = 220L, EntityId = 10L, EntityName = "Country", LanguageCountryId = 38L, Value = "فرانس" }, new { Id = 221L, EntityId = 11L, EntityName = "Country", LanguageCountryId = 38L, Value = "جرمنی" }, new { Id = 222L, EntityId = 12L, EntityName = "Country", LanguageCountryId = 38L, Value = "یونان" }, new { Id = 223L, EntityId = 13L, EntityName = "Country", LanguageCountryId = 38L, Value = "ہنگری" }, new { Id = 224L, EntityId = 14L, EntityName = "Country", LanguageCountryId = 38L, Value = "آئرلینڈ" }, new { Id = 225L, EntityId = 15L, EntityName = "Country", LanguageCountryId = 38L, Value = "اٹلی" }, new { Id = 226L, EntityId = 16L, EntityName = "Country", LanguageCountryId = 38L, Value = "لیٹویا" }, new { Id = 227L, EntityId = 17L, EntityName = "Country", LanguageCountryId = 38L, Value = "لتھوئینیا" }, new { Id = 228L, EntityId = 18L, EntityName = "Country", LanguageCountryId = 38L, Value = "لکسمبرگ" }, new { Id = 229L, EntityId = 19L, EntityName = "Country", LanguageCountryId = 38L, Value = "مالٹا" }, new { Id = 230L, EntityId = 20L, EntityName = "Country", LanguageCountryId = 38L, Value = "ہالینڈ" }, new { Id = 231L, EntityId = 21L, EntityName = "Country", LanguageCountryId = 38L, Value = "پولینڈ" }, new { Id = 232L, EntityId = 22L, EntityName = "Country", LanguageCountryId = 38L, Value = "پرتگال" }, new { Id = 233L, EntityId = 23L, EntityName = "Country", LanguageCountryId = 38L, Value = "رومانیہ" }, new { Id = 234L, EntityId = 24L, EntityName = "Country", LanguageCountryId = 38L, Value = "سلوواکیہ" }, new { Id = 235L, EntityId = 25L, EntityName = "Country", LanguageCountryId = 38L, Value = "سلووینیا" }, new { Id = 236L, EntityId = 26L, EntityName = "Country", LanguageCountryId = 38L, Value = "سپین" }, new { Id = 237L, EntityId = 27L, EntityName = "Country", LanguageCountryId = 38L, Value = "سویڈن" }, new { Id = 238L, EntityId = 30L, EntityName = "Country", LanguageCountryId = 38L, Value = "آئس لینڈ" }, new { Id = 239L, EntityId = 31L, EntityName = "Country", LanguageCountryId = 38L, Value = "لیختنستائین" }, new { Id = 240L, EntityId = 32L, EntityName = "Country", LanguageCountryId = 38L, Value = "سوئٹزرلینڈ" }, new { Id = 241L, EntityId = 1L, EntityName = "Country", LanguageCountryId = 17L, Value = "Austrija" }, new { Id = 242L, EntityId = 2L, EntityName = "Country", LanguageCountryId = 17L, Value = "Belgija" }, new { Id = 243L, EntityId = 3L, EntityName = "Country", LanguageCountryId = 17L, Value = "Bulgarija" }, new { Id = 244L, EntityId = 4L, EntityName = "Country", LanguageCountryId = 17L, Value = "Kroatija" }, new { Id = 245L, EntityId = 5L, EntityName = "Country", LanguageCountryId = 17L, Value = "Kipras" }, new { Id = 246L, EntityId = 6L, EntityName = "Country", LanguageCountryId = 17L, Value = "Čekijos Respublika" }, new { Id = 247L, EntityId = 7L, EntityName = "Country", LanguageCountryId = 17L, Value = "Danija" }, new { Id = 248L, EntityId = 8L, EntityName = "Country", LanguageCountryId = 17L, Value = "Estija" }, new { Id = 249L, EntityId = 9L, EntityName = "Country", LanguageCountryId = 17L, Value = "Suomija" }, new { Id = 250L, EntityId = 10L, EntityName = "Country", LanguageCountryId = 17L, Value = "Prancūzija" }, new { Id = 251L, EntityId = 11L, EntityName = "Country", LanguageCountryId = 17L, Value = "Vokietija" }, new { Id = 252L, EntityId = 12L, EntityName = "Country", LanguageCountryId = 17L, Value = "Graikija" }, new { Id = 253L, EntityId = 13L, EntityName = "Country", LanguageCountryId = 17L, Value = "Vengrija" }, new { Id = 254L, EntityId = 14L, EntityName = "Country", LanguageCountryId = 17L, Value = "Airija" }, new { Id = 255L, EntityId = 15L, EntityName = "Country", LanguageCountryId = 17L, Value = "Italija" }, new { Id = 256L, EntityId = 16L, EntityName = "Country", LanguageCountryId = 17L, Value = "Latvija" }, new { Id = 257L, EntityId = 17L, EntityName = "Country", LanguageCountryId = 17L, Value = "Lietuva" }, new { Id = 258L, EntityId = 18L, EntityName = "Country", LanguageCountryId = 17L, Value = "Liuksemburgas" }, new { Id = 259L, EntityId = 19L, EntityName = "Country", LanguageCountryId = 17L, Value = "Malta" }, new { Id = 260L, EntityId = 20L, EntityName = "Country", LanguageCountryId = 17L, Value = "Nyderlandai" }, new { Id = 261L, EntityId = 21L, EntityName = "Country", LanguageCountryId = 17L, Value = "Lenkija" }, new { Id = 262L, EntityId = 22L, EntityName = "Country", LanguageCountryId = 17L, Value = "Portugalija" }, new { Id = 263L, EntityId = 23L, EntityName = "Country", LanguageCountryId = 17L, Value = "Rumunija" }, new { Id = 264L, EntityId = 24L, EntityName = "Country", LanguageCountryId = 17L, Value = "Slovakija" }, new { Id = 265L, EntityId = 25L, EntityName = "Country", LanguageCountryId = 17L, Value = "Slovėnija" }, new { Id = 266L, EntityId = 26L, EntityName = "Country", LanguageCountryId = 17L, Value = "Ispanija" }, new { Id = 267L, EntityId = 27L, EntityName = "Country", LanguageCountryId = 17L, Value = "Švedija" }, new { Id = 268L, EntityId = 30L, EntityName = "Country", LanguageCountryId = 17L, Value = "Islandija" }, new { Id = 269L, EntityId = 31L, EntityName = "Country", LanguageCountryId = 17L, Value = "Lichtenšteinas" }, new { Id = 270L, EntityId = 32L, EntityName = "Country", LanguageCountryId = 17L, Value = "Šveicarija " }); }); modelBuilder.Entity("DIGNDB.App.SmitteStop.Domain.Db.TemporaryExposureKey", b => { b.HasOne("DIGNDB.App.SmitteStop.Domain.Db.Country", "Origin") .WithMany() .HasForeignKey("OriginId") .OnDelete(DeleteBehavior.NoAction) .IsRequired(); }); modelBuilder.Entity("DIGNDB.App.SmitteStop.Domain.Db.TemporaryExposureKeyCountry", b => { b.HasOne("DIGNDB.App.SmitteStop.Domain.Db.Country", "Country") .WithMany("TemporaryExposureKeyCountries") .HasForeignKey("CountryId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("DIGNDB.App.SmitteStop.Domain.Db.TemporaryExposureKey", "TemporaryExposureKey") .WithMany("VisitedCountries") .HasForeignKey("TemporaryExposureKeyId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("DIGNDB.App.SmitteStop.Domain.Db.Translation", b => { b.HasOne("DIGNDB.App.SmitteStop.Domain.Db.Country", "LanguageCountry") .WithMany("EntityTranslations") .HasForeignKey("LanguageCountryId"); }); #pragma warning restore 612, 618 } } }
40.219224
126
0.241072
[ "MIT" ]
folkehelseinstituttet/Fhi.Smittestopp.Backend
DIGNDB.App.SmitteStop.DAL/Migrations/20210311123914_FixLithuaniaTranslations.Designer.cs
109,505
C#
using System.Collections.Generic; using System.Collections.ObjectModel; namespace WebAPIRoute.Areas.HelpPage.ModelDescriptions { public class EnumTypeModelDescription : ModelDescription { public EnumTypeModelDescription() { Values = new Collection<EnumValueDescription>(); } public Collection<EnumValueDescription> Values { get; private set; } } }
27
76
0.708642
[ "MIT" ]
aline0liveira/GitC
WebAPIRoute/Areas/HelpPage/ModelDescriptions/EnumTypeModelDescription.cs
405
C#
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.Aws.WafV2.Inputs { public sealed class WebAclRuleStatementManagedRuleGroupStatementScopeDownStatementNotStatementStatementNotStatementStatementSqliMatchStatementFieldToMatchBodyGetArgs : Pulumi.ResourceArgs { public WebAclRuleStatementManagedRuleGroupStatementScopeDownStatementNotStatementStatementNotStatementStatementSqliMatchStatementFieldToMatchBodyGetArgs() { } } }
37.05
191
0.805668
[ "ECL-2.0", "Apache-2.0" ]
RafalSumislawski/pulumi-aws
sdk/dotnet/WafV2/Inputs/WebAclRuleStatementManagedRuleGroupStatementScopeDownStatementNotStatementStatementNotStatementStatementSqliMatchStatementFieldToMatchBodyGetArgs.cs
741
C#
using System; namespace TotalDischargeExternalProcessor { public class Option { public string Key { get; set; } public string Description { get; set; } public Action<string> Setter { get; set; } public Func<string> Getter { get; set; } public string UsageText() { if (string.IsNullOrEmpty(Key) && string.IsNullOrEmpty(Description)) return string.Empty; // Omits a blank line var key = string.IsNullOrEmpty(Key) ? SeparatorLine : "-" + Key.PadRight(KeyWidth); var defaultValue = Getter != null ? Getter() : string.Empty; if (!string.IsNullOrEmpty(defaultValue)) defaultValue = $" [default: {defaultValue}]"; return $"{key} {Description}{defaultValue}"; } private const int KeyWidth = 24; private static readonly string SeparatorLine = string.Empty.PadRight(KeyWidth + 1, '='); } }
31.096774
96
0.595436
[ "Apache-2.0" ]
AquaticInformatics/Examples
TimeSeries/PublicApis/SdkExamples/TotalDischargeExternalProcessor/Option.cs
966
C#
using System.Collections.Generic; using System.Collections.ObjectModel; namespace Nanoblog.AppCore.Extensions { public static class EnumerableExtensions { public static ObservableCollection<T> ToObservable<T>(this IEnumerable<T> list) { return new ObservableCollection<T>(list); } } }
23.928571
87
0.695522
[ "MIT" ]
Harry09/nanoblog
Frontend/dotnet/Nanoblog.AppCore/Extensions/EnumerableExtensions.cs
337
C#
using System; using System.IO; using System.Linq; using System.Threading.Tasks; namespace TextCaseChanger { class Program { public delegate string FormatString(string rawString); static void Main(string[] args) { Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("Text Case Changer by Shahrukh Yousafzai"); Console.ForegroundColor = ConsoleColor.White; string FilePath = ""; string[] lines = {""}; while (true) { Console.ForegroundColor = ConsoleColor.White; try { Console.Write("Enter text file path: "); FilePath = Console.ReadLine(); lines = File.ReadAllLines(FilePath); } catch { Console.ForegroundColor = ConsoleColor.Red; Console.Write("Error, No readable file found"); return; } Console.ForegroundColor = ConsoleColor.Red; Console.Write("Select an option: \n"); Console.ForegroundColor = ConsoleColor.White; Console.Write("0) Change to sentence case\n"); Console.Write("1) change to lower case\n"); Console.Write("2) CHANGE TO UPPER CASE\n"); Console.Write("3) Change To Capitalized Case\n"); Console.Write("4) Change to Title Case\n"); int Option; Console.Write("Your Option: "); Option = int.Parse(Console.ReadLine()); if (Option == 0) { for (int i = 0; i < lines.Length; i++) { lines[i] = ConvertToSentenceCase(lines[i]); } string SavePath = AppDomain.CurrentDomain.BaseDirectory + Path.GetFileNameWithoutExtension(FilePath) + "_sentencecased" + Path.GetExtension(FilePath); File.WriteAllLines(SavePath, lines); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("Case converted file have been saved to " + SavePath); } else if (Option == 1) { for (int i = 0; i < lines.Length; i++) { lines[i] = ConvertToLowerCase(lines[i]); } string SavePath = AppDomain.CurrentDomain.BaseDirectory + Path.GetFileNameWithoutExtension(FilePath) + "_lowercased" + Path.GetExtension(FilePath); File.WriteAllLines(SavePath, lines); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("Case converted file have been saved to " + SavePath); } else if (Option == 2) { for (int i = 0; i < lines.Length; i++) { lines[i] = ConvertToUpperCase(lines[i]); } string SavePath = AppDomain.CurrentDomain.BaseDirectory + Path.GetFileNameWithoutExtension(FilePath) + "_uppercased" + Path.GetExtension(FilePath); File.WriteAllLines(SavePath, lines); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("Case converted file have been saved to " + SavePath); } else if (Option == 3) { for (int i = 0; i < lines.Length; i++) { lines[i] = ConvertToCapitalizedCase(lines[i]); } string SavePath = AppDomain.CurrentDomain.BaseDirectory + Path.GetFileNameWithoutExtension(FilePath) + "_capitalizedcased" + Path.GetExtension(FilePath); File.WriteAllLines(SavePath, lines); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("Case converted file have been saved to " + SavePath); } else if (Option == 4) { for (int i = 0; i < lines.Length; i++) { lines[i] = ConvertToTitleCase(lines[i]); } string SavePath = AppDomain.CurrentDomain.BaseDirectory + Path.GetFileNameWithoutExtension(FilePath) + "_titlecased" + Path.GetExtension(FilePath); File.WriteAllLines(SavePath, lines); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("Case converted file have been saved to " + SavePath); } } } static string ConvertToSentenceCase(string strParagraph) { FormatString format = RemoveSpace; string formatted = RemoveSpace(strParagraph); FormatString split = Split; var finalString = Split(formatted); return finalString; } static string ConvertToUpperCase(string Text) { var ConvertedString = Text.ToUpper(); return ConvertedString; } static string ConvertToTitleCase(string Text) { var ConvertedString = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(Text); return ConvertedString; } static string ConvertToLowerCase(string Text) { var ConvertedString = Text.ToLower(); return ConvertedString; } static string ConvertToCapitalizedCase(string Text) { var ConvertedString = System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(Text.ToLower()); return ConvertedString; } public static string RemoveSpace(string fullString) { return fullString.Trim(); } public static string Split(string fullString) { var strArr = fullString.Split(new char[] { '.' }); var newStrArr = strArr; foreach (var item in strArr) for (int iCount = 0; iCount < strArr.Count(); iCount++) { strArr[iCount] = strArr[iCount].Insert(0, strArr[iCount][0].ToString().ToUpper()); strArr[iCount] = strArr[iCount].Remove(1, 1); } return string.Join(".", strArr); } } }
34.547739
175
0.500218
[ "MIT" ]
SRKYousafzaiPK/TextCaseChanger
Source/TextCaseChanger/Program.cs
6,877
C#
//---------------------------------------------------------------------------------------------------------- // X-PostProcessing Library // Copyright (C) 2020 QianMo. All rights reserved. // Licensed under the MIT 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 //---------------------------------------------------------------------------------------------------------- using System; using UnityEngine; using UnityEngine.Rendering; using UnityEngine.Rendering.PostProcessing; namespace XPostProcessing { [Serializable] [PostProcess(typeof(EdgeDetectionScharrRenderer), PostProcessEvent.AfterStack, "X-PostProcessing/EdgeDetection/EdgeDetectionScharr")] public class EdgeDetectionScharr : PostProcessEffectSettings { [Range(0.05f, 5.0f)] public FloatParameter edgeWidth = new FloatParameter { value = 0.3f }; [ColorUsageAttribute(true, true, 0f, 20f, 0.125f, 3f)] public ColorParameter edgeColor = new ColorParameter { value = new Color(0.0f, 0.0f, 0.0f, 1) }; [Range(0.0f, 1.0f)] public FloatParameter backgroundFade = new FloatParameter { value = 1f }; [ColorUsageAttribute(true, true, 0f, 20f, 0.125f, 3f)] public ColorParameter backgroundColor = new ColorParameter { value = new Color(1.0f, 1.0f, 1.0f, 1) }; } public sealed class EdgeDetectionScharrRenderer : PostProcessEffectRenderer<EdgeDetectionScharr> { private const string PROFILER_TAG = "X-EdgeDetectionScharr"; private Shader shader; public override void Init() { shader = Shader.Find("Hidden/X-PostProcessing/EdgeDetectionScharr"); } public override void Release() { base.Release(); } static class ShaderIDs { internal static readonly int Params = Shader.PropertyToID("_Params"); internal static readonly int EdgeColor = Shader.PropertyToID("_EdgeColor"); internal static readonly int BackgroundColor = Shader.PropertyToID("_BackgroundColor"); } public override void Render(PostProcessRenderContext context) { CommandBuffer cmd = context.command; PropertySheet sheet = context.propertySheets.Get(shader); cmd.BeginSample(PROFILER_TAG); sheet.properties.SetVector(ShaderIDs.Params, new Vector2(settings.edgeWidth, settings.backgroundFade)); sheet.properties.SetColor(ShaderIDs.EdgeColor, settings.edgeColor); sheet.properties.SetColor(ShaderIDs.BackgroundColor, settings.backgroundColor); cmd.BlitFullscreenTriangle(context.source, context.destination, sheet, 0); cmd.EndSample(PROFILER_TAG); } } }
36.679487
137
0.627753
[ "MIT" ]
walklook/X-PostProcessing-Library
Assets/X-PostProcessing/Effects/EdgeDetectionScharr/EdgeDetectionScharr.cs
2,861
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; using System.Runtime.InteropServices; using System.Drawing; using Autodesk.AutoCAD.ApplicationServices; using Autodesk.AutoCAD.DatabaseServices; using Autodesk.AutoCAD.EditorInput; using Autodesk.AutoCAD.Runtime; using Autodesk.AutoCAD.Geometry; using Autodesk.AutoCAD.Windows; using Autodesk.AutoCAD.Customization; namespace DWGLib { class LoadMenu { const string CUIPATH = "./gui/ui.cuix"; Editor ed; string mainCui; CustomizationSection cs; PartialCuiFileCollection pcfc; public LoadMenu() { Menu mainMenu = Autodesk.AutoCAD.ApplicationServices.Application.MenuBar as Menu; MenuItem item1 = new MenuItem("Hudson"); mainMenu.MenuItems.Add(item1); } protected void InitializeRibbonMenu() { if (!pcfc.Contains(CUIPATH)) { } } protected void LoadCUI() { } protected void CreateNormalMenu() { } } }
23.235294
93
0.631224
[ "MIT" ]
DmytroMat/DWGLib
Class/Menu.cs
1,187
C#
using CKAN.Versioning; namespace CKAN { public abstract class BaseGameComparator : IGameComparator { public BaseGameComparator() { } public virtual bool Compatible(GameVersionCriteria gameVersionCriteria, CkanModule module) { if (gameVersionCriteria.Versions.Count == 0) { return true; } foreach (GameVersion gameVersion in gameVersionCriteria.Versions) { if (SingleVersionsCompatible (gameVersion, module)) { return true; } } return false; } public abstract bool SingleVersionsCompatible(GameVersion gameVersionCriteria, CkanModule module); } }
27.5
106
0.576623
[ "MIT" ]
050644zf/CKAN
Core/Types/GameComparator/BaseGameComparator.cs
772
C#
using System; using System.Linq; using System.Net.Http; using System.Threading.Tasks; using System.Xml; using System.Xml.Linq; using System.Xml.XPath; using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; namespace GSS.Authentication.CAS.AspNetCore { public class CasSingleSignOutMiddleware { private const string RequestContentType = "application/x-www-form-urlencoded"; private static readonly XmlNamespaceManager _xmlNamespaceManager = InitializeXmlNamespaceManager(); private readonly ITicketStore _store; private readonly ILogger<CasSingleSignOutMiddleware> _logger; private readonly RequestDelegate _next; public CasSingleSignOutMiddleware(RequestDelegate next, ITicketStore store, ILogger<CasSingleSignOutMiddleware> logger) { _next = next; _store = store; _logger = logger; } public async Task Invoke(HttpContext context) { if (context?.Request.Method.Equals(HttpMethod.Post.Method, StringComparison.OrdinalIgnoreCase) == true && string.Equals(context.Request.ContentType, RequestContentType, StringComparison.OrdinalIgnoreCase)) { var formData = await context.Request.ReadFormAsync(context.RequestAborted).ConfigureAwait(false); if (formData.ContainsKey("logoutRequest")){ var logOutRequest = formData.First(x => x.Key == "logoutRequest").Value[0]; if (!string.IsNullOrEmpty(logOutRequest)) { _logger.LogDebug($"logoutRequest: {logOutRequest}"); var serviceTicket = ExtractSingleSignOutTicketFromSamlResponse(logOutRequest); if (!string.IsNullOrEmpty(serviceTicket)) { _logger.LogInformation($"remove serviceTicket: {serviceTicket} ..."); await _store.RemoveAsync(serviceTicket).ConfigureAwait(false); } } } } await _next.Invoke(context).ConfigureAwait(false); } private static string ExtractSingleSignOutTicketFromSamlResponse(string text) { try { var doc = XDocument.Parse(text); var nav = doc.CreateNavigator(); /* <samlp:LogoutRequest xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol" xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion" ID="[RANDOM ID]" Version="2.0" IssueInstant="[CURRENT DATE/TIME]"> <saml:NameID>@NOT_USED@</saml:NameID> <samlp:SessionIndex>[SESSION IDENTIFIER]</samlp:SessionIndex> </samlp:LogoutRequest> */ var node = nav.SelectSingleNode("samlp:LogoutRequest/samlp:SessionIndex/text()", _xmlNamespaceManager); if (node != null) { return node.Value; } } catch (XmlException) { //logoutRequest was not xml } return string.Empty; } private static XmlNamespaceManager InitializeXmlNamespaceManager() { var namespaceManager = new XmlNamespaceManager(new NameTable()); namespaceManager.AddNamespace("samlp", "urn:oasis:names:tc:SAML:2.0:protocol"); return namespaceManager; } } }
40.788889
127
0.586489
[ "MIT" ]
iesoftwaredeveloper/GSS.Authentication.CAS
src/GSS.Authentication.CAS.AspNetCore/CasSingleSignOutMiddleware.cs
3,671
C#
using Fusee.Base.Common; using Fusee.Base.Core; using Fusee.Base.Imp.Desktop; using Fusee.Engine.Common; using Fusee.Engine.Core; using Fusee.Engine.Core.Scene; using Fusee.Serialization; using System.IO; using System.Reflection; using System.Threading.Tasks; namespace Fusee.Examples.GeometryEditing.Desktop { public class MeshingAround { public static void Main() { // Inject Fusee.Engine.Base InjectMe dependencies IO.IOImp = new Fusee.Base.Imp.Desktop.IOImp(); var fap = new Fusee.Base.Imp.Desktop.FileAssetProvider("Assets"); fap.RegisterTypeHandler( new AssetHandler { ReturnedType = typeof(Font), DecoderAsync = async (string id, object storage) => { if (!Path.GetExtension(id).Contains("ttf", System.StringComparison.OrdinalIgnoreCase)) return null; return await Task.FromResult(new Font { _fontImp = new FontImp((Stream)storage) }); }, Decoder = (string id, object storage) => { if (!Path.GetExtension(id).Contains("ttf", System.StringComparison.OrdinalIgnoreCase)) return null; return new Font { _fontImp = new FontImp((Stream)storage) }; }, Checker = id => Path.GetExtension(id).Contains("ttf", System.StringComparison.OrdinalIgnoreCase) }); fap.RegisterTypeHandler( new AssetHandler { ReturnedType = typeof(SceneContainer), DecoderAsync = async (string id, object storage) => { if (!Path.GetExtension(id).Contains("fus", System.StringComparison.OrdinalIgnoreCase)) return null; return await FusSceneConverter.ConvertFromAsync(ProtoBuf.Serializer.Deserialize<FusFile>((Stream)storage), id); }, Decoder = (string id, object storage) => { if (!Path.GetExtension(id).Contains("fus", System.StringComparison.OrdinalIgnoreCase)) return null; return FusSceneConverter.ConvertFrom(ProtoBuf.Serializer.Deserialize<FusFile>((Stream)storage), id); }, Checker = id => Path.GetExtension(id).Contains("fus", System.StringComparison.OrdinalIgnoreCase) }); AssetStorage.RegisterProvider(fap); var app = new Core.GeometryEditing(); // Inject Fusee.Engine InjectMe dependencies (hard coded) System.Drawing.Icon appIcon = System.Drawing.Icon.ExtractAssociatedIcon(Assembly.GetExecutingAssembly().Location); app.CanvasImplementor = new Fusee.Engine.Imp.Graphics.Desktop.RenderCanvasImp(appIcon); app.ContextImplementor = new Fusee.Engine.Imp.Graphics.Desktop.RenderContextImp(app.CanvasImplementor); Input.AddDriverImp(new Fusee.Engine.Imp.Graphics.Desktop.RenderCanvasInputDriverImp(app.CanvasImplementor)); Input.AddDriverImp(new Fusee.Engine.Imp.Graphics.Desktop.WindowsTouchInputDriverImp(app.CanvasImplementor)); // app.InputImplementor = new Fusee.Engine.Imp.Graphics.Desktop.InputImp(app.CanvasImplementor); // app.InputDriverImplementor = new Fusee.Engine.Imp.Input.Desktop.InputDriverImp(); // app.VideoManagerImplementor = ImpFactory.CreateIVideoManagerImp(); app.InitApp(); // Start the app app.Run(); } } }
49.2
135
0.60542
[ "BSD-2-Clause", "MIT" ]
ASPePeX/Fusee
Examples/Complete/GeometryEditing/Desktop/Main.cs
3,692
C#
using System; using System.Collections.Generic; using System.Linq; using GraphQL.Conversion; using GraphQL.Introspection; namespace GraphQL.Types { public class GraphTypesLookup { private readonly IDictionary<string, IGraphType> _types = new Dictionary<string, IGraphType>(); private readonly object _lock = new object(); public GraphTypesLookup() { AddType<StringGraphType>(); AddType<BooleanGraphType>(); AddType<FloatGraphType>(); AddType<IntGraphType>(); AddType<IdGraphType>(); AddType<DateGraphType>(); AddType<DateTimeGraphType>(); AddType<DateTimeOffsetGraphType>(); AddType<TimeSpanSecondsGraphType>(); AddType<TimeSpanMillisecondsGraphType>(); AddType<DecimalGraphType>(); AddType<__Schema>(); AddType<__Type>(); AddType<__Directive>(); AddType<__Field>(); AddType<__EnumValue>(); AddType<__InputValue>(); AddType<__TypeKind>(); } public static GraphTypesLookup Create( IEnumerable<IGraphType> types, IEnumerable<DirectiveGraphType> directives, Func<Type, IGraphType> resolveType, IFieldNameConverter fieldNameConverter) { var lookup = new GraphTypesLookup(); lookup.FieldNameConverter = fieldNameConverter ?? new CamelCaseFieldNameConverter(); var ctx = new TypeCollectionContext(resolveType, (name, graphType, context) => { if (lookup[name] == null) { lookup.AddType(graphType, context); } }); foreach (var type in types) { lookup.AddType(type, ctx); } var introspectionType = typeof(SchemaIntrospection); lookup.HandleField(introspectionType, SchemaIntrospection.SchemaMeta, ctx); lookup.HandleField(introspectionType, SchemaIntrospection.TypeMeta, ctx); lookup.HandleField(introspectionType, SchemaIntrospection.TypeNameMeta, ctx); foreach (var directive in directives) { if (directive.Arguments == null) continue; foreach (var arg in directive.Arguments) { if (arg.ResolvedType != null) { arg.ResolvedType = lookup.ConvertTypeReference(directive, arg.ResolvedType); } else { arg.ResolvedType = lookup.BuildNamedType(arg.Type, ctx.ResolveType); } } } lookup.ApplyTypeReferences(); return lookup; } public IFieldNameConverter FieldNameConverter { get; set; } = new CamelCaseFieldNameConverter(); public void Clear() { lock (_lock) { _types.Clear(); } } public IEnumerable<IGraphType> All() { lock (_lock) { return _types.Values.ToList(); } } public IGraphType this[string typeName] { get { if (string.IsNullOrWhiteSpace(typeName)) { throw new ArgumentOutOfRangeException(nameof(typeName), "A type name is required to lookup."); } IGraphType type; var name = typeName.TrimGraphQLTypes(); lock (_lock) { _types.TryGetValue(name, out type); } return type; } set { lock (_lock) { _types[typeName.TrimGraphQLTypes()] = value; } } } public IGraphType this[Type type] { get { lock (_lock) { var result = _types.FirstOrDefault(x => x.Value.GetType() == type); return result.Value; } } } public void AddType<TType>() where TType : IGraphType, new() { var context = new TypeCollectionContext( type => { return BuildNamedType(type, t => (IGraphType)Activator.CreateInstance(t)); }, (name, type, ctx) => { var trimmed = name.TrimGraphQLTypes(); lock (_lock) { _types[trimmed] = type; } ctx?.AddType(trimmed, type, null); }); AddType<TType>(context); } private IGraphType BuildNamedType(Type type, Func<Type, IGraphType> resolver) { return type.BuildNamedType(t => this[t] ?? resolver(t)); } public void AddType<TType>(TypeCollectionContext context) where TType : IGraphType { var type = typeof(TType).GetNamedType(); var instance = context.ResolveType(type); AddType(instance, context); } public void AddType(IGraphType type, TypeCollectionContext context) { if (type == null || type is GraphQLTypeReference) { return; } if (type is NonNullGraphType || type is ListGraphType) { throw new ExecutionError("Only add root types."); } var name = type.CollectTypes(context).TrimGraphQLTypes(); lock (_lock) { _types[name] = type; } if (type is IComplexGraphType complexType) { foreach (var field in complexType.Fields) { HandleField(type.GetType(), field, context); } } if (type is IObjectGraphType obj) { foreach (var objectInterface in obj.Interfaces) { AddTypeIfNotRegistered(objectInterface, context); if (this[objectInterface] is IInterfaceGraphType interfaceInstance) { obj.AddResolvedInterface(interfaceInstance); interfaceInstance.AddPossibleType(obj); if (interfaceInstance.ResolveType == null && obj.IsTypeOf == null) { throw new ExecutionError(( "Interface type {0} does not provide a \"resolveType\" function " + "and possible Type \"{1}\" does not provide a \"isTypeOf\" function. " + "There is no way to resolve this possible type during execution.") .ToFormat(interfaceInstance.Name, obj.Name)); } } } } if (type is UnionGraphType union) { if (!union.Types.Any() && !union.PossibleTypes.Any()) { throw new ExecutionError("Must provide types for Union {0}.".ToFormat(union)); } foreach (var unionedType in union.PossibleTypes) { AddTypeIfNotRegistered(unionedType, context); if (union.ResolveType == null && unionedType.IsTypeOf == null) { throw new ExecutionError(( "Union type {0} does not provide a \"resolveType\" function" + "and possible Type \"{1}\" does not provide a \"isTypeOf\" function. " + "There is no way to resolve this possible type during execution.") .ToFormat(union.Name, unionedType.Name)); } } foreach (var unionedType in union.Types) { AddTypeIfNotRegistered(unionedType, context); var objType = this[unionedType] as IObjectGraphType; if (union.ResolveType == null && objType != null && objType.IsTypeOf == null) { throw new ExecutionError(( "Union type {0} does not provide a \"resolveType\" function" + "and possible Type \"{1}\" does not provide a \"isTypeOf\" function. " + "There is no way to resolve this possible type during execution.") .ToFormat(union.Name, objType.Name)); } union.AddPossibleType(objType); } } } private void HandleField(Type parentType, FieldType field, TypeCollectionContext context) { field.Name = FieldNameConverter.NameFor(field.Name, parentType); if (field.ResolvedType == null) { AddTypeIfNotRegistered(field.Type, context); field.ResolvedType = BuildNamedType(field.Type, context.ResolveType); } else { AddTypeIfNotRegistered(field.ResolvedType, context); } if (field.Arguments == null) return; foreach (var arg in field.Arguments) { arg.Name = FieldNameConverter.NameFor(arg.Name, null); if (arg.ResolvedType != null) { AddTypeIfNotRegistered(arg.ResolvedType, context); return; } AddTypeIfNotRegistered(arg.Type, context); arg.ResolvedType = BuildNamedType(arg.Type, context.ResolveType); } } private void AddTypeIfNotRegistered(Type type, TypeCollectionContext context) { var namedType = type.GetNamedType(); var foundType = this[namedType]; if (foundType == null) { AddType(context.ResolveType(namedType), context); } } private void AddTypeIfNotRegistered(IGraphType type, TypeCollectionContext context) { var namedType = type.GetNamedType(); var foundType = this[namedType.Name]; if(foundType == null) { AddType(namedType, context); } } public void ApplyTypeReferences() { foreach (var type in _types.Values.ToList()) { ApplyTypeReference(type); } } public void ApplyTypeReference(IGraphType type) { if (type is IComplexGraphType complexType) { foreach (var field in complexType.Fields) { field.ResolvedType = ConvertTypeReference(type, field.ResolvedType); if (field.Arguments == null) continue; foreach (var arg in field.Arguments) { arg.ResolvedType = ConvertTypeReference(type, arg.ResolvedType); } } } if (type is IObjectGraphType objectType) { objectType.ResolvedInterfaces = objectType .ResolvedInterfaces .Select(i => { var interfaceType = ConvertTypeReference(objectType, i) as IInterfaceGraphType; if (objectType.IsTypeOf == null && interfaceType.ResolveType == null) { throw new ExecutionError(( "Interface type {0} does not provide a \"resolveType\" function " + "and possible Type \"{1}\" does not provide a \"isTypeOf\" function. " + "There is no way to resolve this possible type during execution.") .ToFormat(interfaceType.Name, objectType.Name)); } interfaceType.AddPossibleType(objectType); return interfaceType; }) .ToList(); } if (type is UnionGraphType union) { union.PossibleTypes = union .PossibleTypes .Select(t => { var unionType = ConvertTypeReference(union, t) as IObjectGraphType; if (union.ResolveType == null && unionType != null && unionType.IsTypeOf == null) { throw new ExecutionError(( "Union type {0} does not provide a \"resolveType\" function" + "and possible Type \"{1}\" does not provide a \"isTypeOf\" function. " + "There is no way to resolve this possible type during execution.") .ToFormat(union.Name, unionType.Name)); } return unionType; }) .ToList(); } } private IGraphType ConvertTypeReference(INamedType parentType, IGraphType type) { if (type is NonNullGraphType nonNull) { nonNull.ResolvedType = ConvertTypeReference(parentType, nonNull.ResolvedType); return nonNull; } if (type is ListGraphType list) { list.ResolvedType = ConvertTypeReference(parentType, list.ResolvedType); return list; } var reference = type as GraphQLTypeReference; var result = reference == null ? type : this[reference.TypeName]; if (reference != null && result == null) { throw new ExecutionError($"Unable to resolve reference to type '{reference.TypeName}' on '{parentType.Name}'"); } return result; } } }
34.880952
127
0.478635
[ "MIT" ]
BobbyDigitalStudios/graphql-dotnet
src/GraphQL/Types/GraphTypesLookup.cs
14,650
C#
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="JsonActionResultWithCors.cs" company=""> // // </copyright> // <summary> // The json action result with cors. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace ConsoleWebServer.Framework.Actions { using System.Collections.Generic; using ConsoleWebServer.Framework.Http; /// <summary> /// The json action result with cors. /// </summary> public class JsonActionResultWithCors : JsonActionResult { /// <summary> /// Initializes a new instance of the <see cref="JsonActionResultWithCors"/> class. /// </summary> /// <param name="request"> /// The request. /// </param> /// <param name="model"> /// The model. /// </param> /// <param name="corsSettings"> /// The cors settings. /// </param> public JsonActionResultWithCors(IHttpRequest request, object model, string corsSettings) : base(request, model) { this.ResponseHeaders.Add(new KeyValuePair<string, string>("Access-Control-Allow-Origin", corsSettings)); } } }
35.052632
119
0.486486
[ "MIT" ]
atanas-georgiev/TelerikAcademy
10.High-Quality-Code/Exams/High-Quality-Code-Exam-15-10-2015/ConsoleWebServer/ConsoleWebServer.Framework/Actions/JsonActionResultWithCors.cs
1,332
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated from a template. // // Manual changes to this file may cause unexpected behavior in your application. // Manual changes to this file will be overwritten if the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace ACTransit.Entities.Training { using System; using System.Collections.Generic; public partial class CourseType { public CourseType() { this.Courses = new HashSet<Course>(); this.Instructors = new HashSet<Instructor>(); this.Topics = new HashSet<Topic>(); } public long CourseTypeId { get; set; } public string Name { get; set; } public string Description { get; set; } public int SortOrder { get; set; } public bool IsActive { get; set; } public string AddUserId { get; set; } public System.DateTime AddDateTime { get; set; } public string UpdUserId { get; set; } public Nullable<System.DateTime> UpdDateTime { get; set; } public virtual ICollection<Course> Courses { get; set; } public virtual ICollection<Instructor> Instructors { get; set; } public virtual ICollection<Topic> Topics { get; set; } } }
36.615385
85
0.553221
[ "MIT" ]
actransitorg/ACTransit.Training
ACTransit.Entities/Entities.Training/CourseType.cs
1,428
C#
using BungieSharper.Client; using System; using System.Collections.Generic; using System.Net.Http; using System.Text.Json; using System.Threading; using System.Threading.Tasks; namespace BungieSharper.Endpoints { public partial class Endpoints { /// <summary> /// Returns a list of all available group avatars for the signed-in user. /// </summary> /// <param name="authToken">The OAuth access token to authenticate the request with.</param> /// <param name="cancelToken">The <see cref="CancellationToken" /> to observe.</param> public Task<Dictionary<int, string>> GroupV2_GetAvailableAvatars(string? authToken = null, CancellationToken cancelToken = default) { return _apiAccessor.ApiRequestAsync<Dictionary<int, string>>( new Uri($"GroupV2/GetAvailableAvatars/", UriKind.Relative), null, HttpMethod.Get, authToken, cancelToken ); } /// <inheritdoc cref="GroupV2_GetAvailableAvatars(string?, CancellationToken)" /> /// <typeparam name="T">The custom type to deserialize to.</typeparam> public Task<T> GroupV2_GetAvailableAvatars<T>(string? authToken = null, CancellationToken cancelToken = default) { return _apiAccessor.ApiRequestAsync<T>( new Uri($"GroupV2/GetAvailableAvatars/", UriKind.Relative), null, HttpMethod.Get, authToken, cancelToken ); } /// <summary> /// Returns a list of all available group themes. /// </summary> /// <param name="authToken">The OAuth access token to authenticate the request with.</param> /// <param name="cancelToken">The <see cref="CancellationToken" /> to observe.</param> public Task<IEnumerable<Entities.Config.GroupTheme>> GroupV2_GetAvailableThemes(string? authToken = null, CancellationToken cancelToken = default) { return _apiAccessor.ApiRequestAsync<IEnumerable<Entities.Config.GroupTheme>>( new Uri($"GroupV2/GetAvailableThemes/", UriKind.Relative), null, HttpMethod.Get, authToken, cancelToken ); } /// <inheritdoc cref="GroupV2_GetAvailableThemes(string?, CancellationToken)" /> /// <typeparam name="T">The custom type to deserialize to.</typeparam> public Task<T> GroupV2_GetAvailableThemes<T>(string? authToken = null, CancellationToken cancelToken = default) { return _apiAccessor.ApiRequestAsync<T>( new Uri($"GroupV2/GetAvailableThemes/", UriKind.Relative), null, HttpMethod.Get, authToken, cancelToken ); } /// <summary> /// Gets the state of the user's clan invite preferences for a particular membership type - true if they wish to be invited to clans, false otherwise. /// Requires OAuth2 scope(s): ReadUserData /// </summary> /// <param name="mType">The Destiny membership type of the account we wish to access settings.</param> /// <param name="authToken">The OAuth access token to authenticate the request with.</param> /// <param name="cancelToken">The <see cref="CancellationToken" /> to observe.</param> public Task<bool> GroupV2_GetUserClanInviteSetting(Entities.BungieMembershipType mType, string? authToken = null, CancellationToken cancelToken = default) { return _apiAccessor.ApiRequestAsync<bool>( new Uri($"GroupV2/GetUserClanInviteSetting/{mType}/", UriKind.Relative), null, HttpMethod.Get, authToken, cancelToken ); } /// <inheritdoc cref="GroupV2_GetUserClanInviteSetting(Entities.BungieMembershipType, string?, CancellationToken)" /> /// <typeparam name="T">The custom type to deserialize to.</typeparam> public Task<T> GroupV2_GetUserClanInviteSetting<T>(Entities.BungieMembershipType mType, string? authToken = null, CancellationToken cancelToken = default) { return _apiAccessor.ApiRequestAsync<T>( new Uri($"GroupV2/GetUserClanInviteSetting/{mType}/", UriKind.Relative), null, HttpMethod.Get, authToken, cancelToken ); } /// <summary> /// Gets groups recommended for you based on the groups to whom those you follow belong. /// Requires OAuth2 scope(s): ReadGroups /// </summary> /// <param name="createDateRange">Requested range in which to pull recommended groups</param> /// <param name="groupType">Type of groups requested</param> /// <param name="authToken">The OAuth access token to authenticate the request with.</param> /// <param name="cancelToken">The <see cref="CancellationToken" /> to observe.</param> public Task<IEnumerable<Entities.GroupsV2.GroupV2Card>> GroupV2_GetRecommendedGroups(Entities.GroupsV2.GroupDateRange createDateRange, Entities.GroupsV2.GroupType groupType, string? authToken = null, CancellationToken cancelToken = default) { return _apiAccessor.ApiRequestAsync<IEnumerable<Entities.GroupsV2.GroupV2Card>>( new Uri($"GroupV2/Recommended/{groupType}/{createDateRange}/", UriKind.Relative), null, HttpMethod.Post, authToken, cancelToken ); } /// <inheritdoc cref="GroupV2_GetRecommendedGroups(Entities.GroupsV2.GroupDateRange, Entities.GroupsV2.GroupType, string?, CancellationToken)" /> /// <typeparam name="T">The custom type to deserialize to.</typeparam> public Task<T> GroupV2_GetRecommendedGroups<T>(Entities.GroupsV2.GroupDateRange createDateRange, Entities.GroupsV2.GroupType groupType, string? authToken = null, CancellationToken cancelToken = default) { return _apiAccessor.ApiRequestAsync<T>( new Uri($"GroupV2/Recommended/{groupType}/{createDateRange}/", UriKind.Relative), null, HttpMethod.Post, authToken, cancelToken ); } /// <summary> /// Search for Groups. /// </summary> /// <param name="authToken">The OAuth access token to authenticate the request with.</param> /// <param name="cancelToken">The <see cref="CancellationToken" /> to observe.</param> public Task<Entities.GroupsV2.GroupSearchResponse> GroupV2_GroupSearch(Entities.GroupsV2.GroupQuery requestBody, string? authToken = null, CancellationToken cancelToken = default) { return _apiAccessor.ApiRequestAsync<Entities.GroupsV2.GroupSearchResponse>( new Uri($"GroupV2/Search/", UriKind.Relative), new StringContent(JsonSerializer.Serialize(requestBody), System.Text.Encoding.UTF8, "application/json"), HttpMethod.Post, authToken, cancelToken ); } /// <inheritdoc cref="GroupV2_GroupSearch(Entities.GroupsV2.GroupQuery, string?, CancellationToken)" /> /// <typeparam name="T">The custom type to deserialize to.</typeparam> public Task<T> GroupV2_GroupSearch<T>(Entities.GroupsV2.GroupQuery requestBody, string? authToken = null, CancellationToken cancelToken = default) { return _apiAccessor.ApiRequestAsync<T>( new Uri($"GroupV2/Search/", UriKind.Relative), new StringContent(JsonSerializer.Serialize(requestBody), System.Text.Encoding.UTF8, "application/json"), HttpMethod.Post, authToken, cancelToken ); } /// <summary> /// Get information about a specific group of the given ID. /// </summary> /// <param name="groupId">Requested group's id.</param> /// <param name="authToken">The OAuth access token to authenticate the request with.</param> /// <param name="cancelToken">The <see cref="CancellationToken" /> to observe.</param> public Task<Entities.GroupsV2.GroupResponse> GroupV2_GetGroup(long groupId, string? authToken = null, CancellationToken cancelToken = default) { return _apiAccessor.ApiRequestAsync<Entities.GroupsV2.GroupResponse>( new Uri($"GroupV2/{groupId}/", UriKind.Relative), null, HttpMethod.Get, authToken, cancelToken ); } /// <inheritdoc cref="GroupV2_GetGroup(long, string?, CancellationToken)" /> /// <typeparam name="T">The custom type to deserialize to.</typeparam> public Task<T> GroupV2_GetGroup<T>(long groupId, string? authToken = null, CancellationToken cancelToken = default) { return _apiAccessor.ApiRequestAsync<T>( new Uri($"GroupV2/{groupId}/", UriKind.Relative), null, HttpMethod.Get, authToken, cancelToken ); } /// <summary> /// Get information about a specific group with the given name and type. /// </summary> /// <param name="groupName">Exact name of the group to find.</param> /// <param name="groupType">Type of group to find.</param> /// <param name="authToken">The OAuth access token to authenticate the request with.</param> /// <param name="cancelToken">The <see cref="CancellationToken" /> to observe.</param> public Task<Entities.GroupsV2.GroupResponse> GroupV2_GetGroupByName(string groupName, Entities.GroupsV2.GroupType groupType, string? authToken = null, CancellationToken cancelToken = default) { return _apiAccessor.ApiRequestAsync<Entities.GroupsV2.GroupResponse>( new Uri($"GroupV2/Name/{Uri.EscapeDataString(groupName)}/{groupType}/", UriKind.Relative), null, HttpMethod.Get, authToken, cancelToken ); } /// <inheritdoc cref="GroupV2_GetGroupByName(string, Entities.GroupsV2.GroupType, string?, CancellationToken)" /> /// <typeparam name="T">The custom type to deserialize to.</typeparam> public Task<T> GroupV2_GetGroupByName<T>(string groupName, Entities.GroupsV2.GroupType groupType, string? authToken = null, CancellationToken cancelToken = default) { return _apiAccessor.ApiRequestAsync<T>( new Uri($"GroupV2/Name/{Uri.EscapeDataString(groupName)}/{groupType}/", UriKind.Relative), null, HttpMethod.Get, authToken, cancelToken ); } /// <summary> /// Get information about a specific group with the given name and type. The POST version. /// </summary> /// <param name="authToken">The OAuth access token to authenticate the request with.</param> /// <param name="cancelToken">The <see cref="CancellationToken" /> to observe.</param> public Task<Entities.GroupsV2.GroupResponse> GroupV2_GetGroupByNameV2(Entities.GroupsV2.GroupNameSearchRequest requestBody, string? authToken = null, CancellationToken cancelToken = default) { return _apiAccessor.ApiRequestAsync<Entities.GroupsV2.GroupResponse>( new Uri($"GroupV2/NameV2/", UriKind.Relative), new StringContent(JsonSerializer.Serialize(requestBody), System.Text.Encoding.UTF8, "application/json"), HttpMethod.Post, authToken, cancelToken ); } /// <inheritdoc cref="GroupV2_GetGroupByNameV2(Entities.GroupsV2.GroupNameSearchRequest, string?, CancellationToken)" /> /// <typeparam name="T">The custom type to deserialize to.</typeparam> public Task<T> GroupV2_GetGroupByNameV2<T>(Entities.GroupsV2.GroupNameSearchRequest requestBody, string? authToken = null, CancellationToken cancelToken = default) { return _apiAccessor.ApiRequestAsync<T>( new Uri($"GroupV2/NameV2/", UriKind.Relative), new StringContent(JsonSerializer.Serialize(requestBody), System.Text.Encoding.UTF8, "application/json"), HttpMethod.Post, authToken, cancelToken ); } /// <summary> /// Gets a list of available optional conversation channels and their settings. /// </summary> /// <param name="groupId">Requested group's id.</param> /// <param name="authToken">The OAuth access token to authenticate the request with.</param> /// <param name="cancelToken">The <see cref="CancellationToken" /> to observe.</param> public Task<IEnumerable<Entities.GroupsV2.GroupOptionalConversation>> GroupV2_GetGroupOptionalConversations(long groupId, string? authToken = null, CancellationToken cancelToken = default) { return _apiAccessor.ApiRequestAsync<IEnumerable<Entities.GroupsV2.GroupOptionalConversation>>( new Uri($"GroupV2/{groupId}/OptionalConversations/", UriKind.Relative), null, HttpMethod.Get, authToken, cancelToken ); } /// <inheritdoc cref="GroupV2_GetGroupOptionalConversations(long, string?, CancellationToken)" /> /// <typeparam name="T">The custom type to deserialize to.</typeparam> public Task<T> GroupV2_GetGroupOptionalConversations<T>(long groupId, string? authToken = null, CancellationToken cancelToken = default) { return _apiAccessor.ApiRequestAsync<T>( new Uri($"GroupV2/{groupId}/OptionalConversations/", UriKind.Relative), null, HttpMethod.Get, authToken, cancelToken ); } /// <summary> /// Edit an existing group. You must have suitable permissions in the group to perform this operation. This latest revision will only edit the fields you pass in - pass null for properties you want to leave unaltered. /// Requires OAuth2 scope(s): AdminGroups /// </summary> /// <param name="groupId">Group ID of the group to edit.</param> /// <param name="authToken">The OAuth access token to authenticate the request with.</param> /// <param name="cancelToken">The <see cref="CancellationToken" /> to observe.</param> public Task<int> GroupV2_EditGroup(long groupId, Entities.GroupsV2.GroupEditAction requestBody, string? authToken = null, CancellationToken cancelToken = default) { return _apiAccessor.ApiRequestAsync<int>( new Uri($"GroupV2/{groupId}/Edit/", UriKind.Relative), new StringContent(JsonSerializer.Serialize(requestBody), System.Text.Encoding.UTF8, "application/json"), HttpMethod.Post, authToken, cancelToken ); } /// <inheritdoc cref="GroupV2_EditGroup(long, Entities.GroupsV2.GroupEditAction, string?, CancellationToken)" /> /// <typeparam name="T">The custom type to deserialize to.</typeparam> public Task<T> GroupV2_EditGroup<T>(long groupId, Entities.GroupsV2.GroupEditAction requestBody, string? authToken = null, CancellationToken cancelToken = default) { return _apiAccessor.ApiRequestAsync<T>( new Uri($"GroupV2/{groupId}/Edit/", UriKind.Relative), new StringContent(JsonSerializer.Serialize(requestBody), System.Text.Encoding.UTF8, "application/json"), HttpMethod.Post, authToken, cancelToken ); } /// <summary> /// Edit an existing group's clan banner. You must have suitable permissions in the group to perform this operation. All fields are required. /// Requires OAuth2 scope(s): AdminGroups /// </summary> /// <param name="groupId">Group ID of the group to edit.</param> /// <param name="authToken">The OAuth access token to authenticate the request with.</param> /// <param name="cancelToken">The <see cref="CancellationToken" /> to observe.</param> public Task<int> GroupV2_EditClanBanner(long groupId, Entities.GroupsV2.ClanBanner requestBody, string? authToken = null, CancellationToken cancelToken = default) { return _apiAccessor.ApiRequestAsync<int>( new Uri($"GroupV2/{groupId}/EditClanBanner/", UriKind.Relative), new StringContent(JsonSerializer.Serialize(requestBody), System.Text.Encoding.UTF8, "application/json"), HttpMethod.Post, authToken, cancelToken ); } /// <inheritdoc cref="GroupV2_EditClanBanner(long, Entities.GroupsV2.ClanBanner, string?, CancellationToken)" /> /// <typeparam name="T">The custom type to deserialize to.</typeparam> public Task<T> GroupV2_EditClanBanner<T>(long groupId, Entities.GroupsV2.ClanBanner requestBody, string? authToken = null, CancellationToken cancelToken = default) { return _apiAccessor.ApiRequestAsync<T>( new Uri($"GroupV2/{groupId}/EditClanBanner/", UriKind.Relative), new StringContent(JsonSerializer.Serialize(requestBody), System.Text.Encoding.UTF8, "application/json"), HttpMethod.Post, authToken, cancelToken ); } /// <summary> /// Edit group options only available to a founder. You must have suitable permissions in the group to perform this operation. /// Requires OAuth2 scope(s): AdminGroups /// </summary> /// <param name="groupId">Group ID of the group to edit.</param> /// <param name="authToken">The OAuth access token to authenticate the request with.</param> /// <param name="cancelToken">The <see cref="CancellationToken" /> to observe.</param> public Task<int> GroupV2_EditFounderOptions(long groupId, Entities.GroupsV2.GroupOptionsEditAction requestBody, string? authToken = null, CancellationToken cancelToken = default) { return _apiAccessor.ApiRequestAsync<int>( new Uri($"GroupV2/{groupId}/EditFounderOptions/", UriKind.Relative), new StringContent(JsonSerializer.Serialize(requestBody), System.Text.Encoding.UTF8, "application/json"), HttpMethod.Post, authToken, cancelToken ); } /// <inheritdoc cref="GroupV2_EditFounderOptions(long, Entities.GroupsV2.GroupOptionsEditAction, string?, CancellationToken)" /> /// <typeparam name="T">The custom type to deserialize to.</typeparam> public Task<T> GroupV2_EditFounderOptions<T>(long groupId, Entities.GroupsV2.GroupOptionsEditAction requestBody, string? authToken = null, CancellationToken cancelToken = default) { return _apiAccessor.ApiRequestAsync<T>( new Uri($"GroupV2/{groupId}/EditFounderOptions/", UriKind.Relative), new StringContent(JsonSerializer.Serialize(requestBody), System.Text.Encoding.UTF8, "application/json"), HttpMethod.Post, authToken, cancelToken ); } /// <summary> /// Add a new optional conversation/chat channel. Requires admin permissions to the group. /// Requires OAuth2 scope(s): AdminGroups /// </summary> /// <param name="groupId">Group ID of the group to edit.</param> /// <param name="authToken">The OAuth access token to authenticate the request with.</param> /// <param name="cancelToken">The <see cref="CancellationToken" /> to observe.</param> public Task<long> GroupV2_AddOptionalConversation(long groupId, Entities.GroupsV2.GroupOptionalConversationAddRequest requestBody, string? authToken = null, CancellationToken cancelToken = default) { return _apiAccessor.ApiRequestAsync<long>( new Uri($"GroupV2/{groupId}/OptionalConversations/Add/", UriKind.Relative), new StringContent(JsonSerializer.Serialize(requestBody), System.Text.Encoding.UTF8, "application/json"), HttpMethod.Post, authToken, cancelToken ); } /// <inheritdoc cref="GroupV2_AddOptionalConversation(long, Entities.GroupsV2.GroupOptionalConversationAddRequest, string?, CancellationToken)" /> /// <typeparam name="T">The custom type to deserialize to.</typeparam> public Task<T> GroupV2_AddOptionalConversation<T>(long groupId, Entities.GroupsV2.GroupOptionalConversationAddRequest requestBody, string? authToken = null, CancellationToken cancelToken = default) { return _apiAccessor.ApiRequestAsync<T>( new Uri($"GroupV2/{groupId}/OptionalConversations/Add/", UriKind.Relative), new StringContent(JsonSerializer.Serialize(requestBody), System.Text.Encoding.UTF8, "application/json"), HttpMethod.Post, authToken, cancelToken ); } /// <summary> /// Edit the settings of an optional conversation/chat channel. Requires admin permissions to the group. /// Requires OAuth2 scope(s): AdminGroups /// </summary> /// <param name="conversationId">Conversation Id of the channel being edited.</param> /// <param name="groupId">Group ID of the group to edit.</param> /// <param name="authToken">The OAuth access token to authenticate the request with.</param> /// <param name="cancelToken">The <see cref="CancellationToken" /> to observe.</param> public Task<long> GroupV2_EditOptionalConversation(long conversationId, long groupId, Entities.GroupsV2.GroupOptionalConversationEditRequest requestBody, string? authToken = null, CancellationToken cancelToken = default) { return _apiAccessor.ApiRequestAsync<long>( new Uri($"GroupV2/{groupId}/OptionalConversations/Edit/{conversationId}/", UriKind.Relative), new StringContent(JsonSerializer.Serialize(requestBody), System.Text.Encoding.UTF8, "application/json"), HttpMethod.Post, authToken, cancelToken ); } /// <inheritdoc cref="GroupV2_EditOptionalConversation(long, long, Entities.GroupsV2.GroupOptionalConversationEditRequest, string?, CancellationToken)" /> /// <typeparam name="T">The custom type to deserialize to.</typeparam> public Task<T> GroupV2_EditOptionalConversation<T>(long conversationId, long groupId, Entities.GroupsV2.GroupOptionalConversationEditRequest requestBody, string? authToken = null, CancellationToken cancelToken = default) { return _apiAccessor.ApiRequestAsync<T>( new Uri($"GroupV2/{groupId}/OptionalConversations/Edit/{conversationId}/", UriKind.Relative), new StringContent(JsonSerializer.Serialize(requestBody), System.Text.Encoding.UTF8, "application/json"), HttpMethod.Post, authToken, cancelToken ); } /// <summary> /// Get the list of members in a given group. /// </summary> /// <param name="currentpage">Page number (starting with 1). Each page has a fixed size of 50 items per page.</param> /// <param name="groupId">The ID of the group.</param> /// <param name="memberType">Filter out other member types. Use None for all members.</param> /// <param name="nameSearch">The name fragment upon which a search should be executed for members with matching display or unique names.</param> /// <param name="authToken">The OAuth access token to authenticate the request with.</param> /// <param name="cancelToken">The <see cref="CancellationToken" /> to observe.</param> public Task<Entities.SearchResultOfGroupMember> GroupV2_GetMembersOfGroup(int currentpage, long groupId, Entities.GroupsV2.RuntimeGroupMemberType? memberType = null, string? nameSearch = null, string? authToken = null, CancellationToken cancelToken = default) { return _apiAccessor.ApiRequestAsync<Entities.SearchResultOfGroupMember>( new Uri($"GroupV2/{groupId}/Members/" + HttpRequestGenerator.MakeQuerystring(memberType != null ? $"memberType={memberType}" : null, nameSearch != null ? $"nameSearch={Uri.EscapeDataString(nameSearch)}" : null), UriKind.Relative), null, HttpMethod.Get, authToken, cancelToken ); } /// <inheritdoc cref="GroupV2_GetMembersOfGroup(int, long, Entities.GroupsV2.RuntimeGroupMemberType?, string?, string?, CancellationToken)" /> /// <typeparam name="T">The custom type to deserialize to.</typeparam> public Task<T> GroupV2_GetMembersOfGroup<T>(int currentpage, long groupId, Entities.GroupsV2.RuntimeGroupMemberType? memberType = null, string? nameSearch = null, string? authToken = null, CancellationToken cancelToken = default) { return _apiAccessor.ApiRequestAsync<T>( new Uri($"GroupV2/{groupId}/Members/" + HttpRequestGenerator.MakeQuerystring(memberType != null ? $"memberType={memberType}" : null, nameSearch != null ? $"nameSearch={Uri.EscapeDataString(nameSearch)}" : null), UriKind.Relative), null, HttpMethod.Get, authToken, cancelToken ); } /// <summary> /// Get the list of members in a given group who are of admin level or higher. /// </summary> /// <param name="currentpage">Page number (starting with 1). Each page has a fixed size of 50 items per page.</param> /// <param name="groupId">The ID of the group.</param> /// <param name="authToken">The OAuth access token to authenticate the request with.</param> /// <param name="cancelToken">The <see cref="CancellationToken" /> to observe.</param> public Task<Entities.SearchResultOfGroupMember> GroupV2_GetAdminsAndFounderOfGroup(int currentpage, long groupId, string? authToken = null, CancellationToken cancelToken = default) { return _apiAccessor.ApiRequestAsync<Entities.SearchResultOfGroupMember>( new Uri($"GroupV2/{groupId}/AdminsAndFounder/", UriKind.Relative), null, HttpMethod.Get, authToken, cancelToken ); } /// <inheritdoc cref="GroupV2_GetAdminsAndFounderOfGroup(int, long, string?, CancellationToken)" /> /// <typeparam name="T">The custom type to deserialize to.</typeparam> public Task<T> GroupV2_GetAdminsAndFounderOfGroup<T>(int currentpage, long groupId, string? authToken = null, CancellationToken cancelToken = default) { return _apiAccessor.ApiRequestAsync<T>( new Uri($"GroupV2/{groupId}/AdminsAndFounder/", UriKind.Relative), null, HttpMethod.Get, authToken, cancelToken ); } /// <summary> /// Edit the membership type of a given member. You must have suitable permissions in the group to perform this operation. /// Requires OAuth2 scope(s): AdminGroups /// </summary> /// <param name="groupId">ID of the group to which the member belongs.</param> /// <param name="membershipId">Membership ID to modify.</param> /// <param name="membershipType">Membership type of the provide membership ID.</param> /// <param name="memberType">New membertype for the specified member.</param> /// <param name="authToken">The OAuth access token to authenticate the request with.</param> /// <param name="cancelToken">The <see cref="CancellationToken" /> to observe.</param> public Task<int> GroupV2_EditGroupMembership(long groupId, long membershipId, Entities.BungieMembershipType membershipType, Entities.GroupsV2.RuntimeGroupMemberType memberType, string? authToken = null, CancellationToken cancelToken = default) { return _apiAccessor.ApiRequestAsync<int>( new Uri($"GroupV2/{groupId}/Members/{membershipType}/{membershipId}/SetMembershipType/{memberType}/", UriKind.Relative), null, HttpMethod.Post, authToken, cancelToken ); } /// <inheritdoc cref="GroupV2_EditGroupMembership(long, long, Entities.BungieMembershipType, Entities.GroupsV2.RuntimeGroupMemberType, string?, CancellationToken)" /> /// <typeparam name="T">The custom type to deserialize to.</typeparam> public Task<T> GroupV2_EditGroupMembership<T>(long groupId, long membershipId, Entities.BungieMembershipType membershipType, Entities.GroupsV2.RuntimeGroupMemberType memberType, string? authToken = null, CancellationToken cancelToken = default) { return _apiAccessor.ApiRequestAsync<T>( new Uri($"GroupV2/{groupId}/Members/{membershipType}/{membershipId}/SetMembershipType/{memberType}/", UriKind.Relative), null, HttpMethod.Post, authToken, cancelToken ); } /// <summary> /// Kick a member from the given group, forcing them to reapply if they wish to re-join the group. You must have suitable permissions in the group to perform this operation. /// Requires OAuth2 scope(s): AdminGroups /// </summary> /// <param name="groupId">Group ID to kick the user from.</param> /// <param name="membershipId">Membership ID to kick.</param> /// <param name="membershipType">Membership type of the provided membership ID.</param> /// <param name="authToken">The OAuth access token to authenticate the request with.</param> /// <param name="cancelToken">The <see cref="CancellationToken" /> to observe.</param> public Task<Entities.GroupsV2.GroupMemberLeaveResult> GroupV2_KickMember(long groupId, long membershipId, Entities.BungieMembershipType membershipType, string? authToken = null, CancellationToken cancelToken = default) { return _apiAccessor.ApiRequestAsync<Entities.GroupsV2.GroupMemberLeaveResult>( new Uri($"GroupV2/{groupId}/Members/{membershipType}/{membershipId}/Kick/", UriKind.Relative), null, HttpMethod.Post, authToken, cancelToken ); } /// <inheritdoc cref="GroupV2_KickMember(long, long, Entities.BungieMembershipType, string?, CancellationToken)" /> /// <typeparam name="T">The custom type to deserialize to.</typeparam> public Task<T> GroupV2_KickMember<T>(long groupId, long membershipId, Entities.BungieMembershipType membershipType, string? authToken = null, CancellationToken cancelToken = default) { return _apiAccessor.ApiRequestAsync<T>( new Uri($"GroupV2/{groupId}/Members/{membershipType}/{membershipId}/Kick/", UriKind.Relative), null, HttpMethod.Post, authToken, cancelToken ); } /// <summary> /// Bans the requested member from the requested group for the specified period of time. /// Requires OAuth2 scope(s): AdminGroups /// </summary> /// <param name="groupId">Group ID that has the member to ban.</param> /// <param name="membershipId">Membership ID of the member to ban from the group.</param> /// <param name="membershipType">Membership type of the provided membership ID.</param> /// <param name="authToken">The OAuth access token to authenticate the request with.</param> /// <param name="cancelToken">The <see cref="CancellationToken" /> to observe.</param> public Task<int> GroupV2_BanMember(long groupId, long membershipId, Entities.BungieMembershipType membershipType, Entities.GroupsV2.GroupBanRequest requestBody, string? authToken = null, CancellationToken cancelToken = default) { return _apiAccessor.ApiRequestAsync<int>( new Uri($"GroupV2/{groupId}/Members/{membershipType}/{membershipId}/Ban/", UriKind.Relative), new StringContent(JsonSerializer.Serialize(requestBody), System.Text.Encoding.UTF8, "application/json"), HttpMethod.Post, authToken, cancelToken ); } /// <inheritdoc cref="GroupV2_BanMember(long, long, Entities.BungieMembershipType, Entities.GroupsV2.GroupBanRequest, string?, CancellationToken)" /> /// <typeparam name="T">The custom type to deserialize to.</typeparam> public Task<T> GroupV2_BanMember<T>(long groupId, long membershipId, Entities.BungieMembershipType membershipType, Entities.GroupsV2.GroupBanRequest requestBody, string? authToken = null, CancellationToken cancelToken = default) { return _apiAccessor.ApiRequestAsync<T>( new Uri($"GroupV2/{groupId}/Members/{membershipType}/{membershipId}/Ban/", UriKind.Relative), new StringContent(JsonSerializer.Serialize(requestBody), System.Text.Encoding.UTF8, "application/json"), HttpMethod.Post, authToken, cancelToken ); } /// <summary> /// Unbans the requested member, allowing them to re-apply for membership. /// Requires OAuth2 scope(s): AdminGroups /// </summary> /// <param name="membershipId">Membership ID of the member to unban from the group</param> /// <param name="membershipType">Membership type of the provided membership ID.</param> /// <param name="authToken">The OAuth access token to authenticate the request with.</param> /// <param name="cancelToken">The <see cref="CancellationToken" /> to observe.</param> public Task<int> GroupV2_UnbanMember(long groupId, long membershipId, Entities.BungieMembershipType membershipType, string? authToken = null, CancellationToken cancelToken = default) { return _apiAccessor.ApiRequestAsync<int>( new Uri($"GroupV2/{groupId}/Members/{membershipType}/{membershipId}/Unban/", UriKind.Relative), null, HttpMethod.Post, authToken, cancelToken ); } /// <inheritdoc cref="GroupV2_UnbanMember(long, long, Entities.BungieMembershipType, string?, CancellationToken)" /> /// <typeparam name="T">The custom type to deserialize to.</typeparam> public Task<T> GroupV2_UnbanMember<T>(long groupId, long membershipId, Entities.BungieMembershipType membershipType, string? authToken = null, CancellationToken cancelToken = default) { return _apiAccessor.ApiRequestAsync<T>( new Uri($"GroupV2/{groupId}/Members/{membershipType}/{membershipId}/Unban/", UriKind.Relative), null, HttpMethod.Post, authToken, cancelToken ); } /// <summary> /// Get the list of banned members in a given group. Only accessible to group Admins and above. Not applicable to all groups. Check group features. /// Requires OAuth2 scope(s): AdminGroups /// </summary> /// <param name="currentpage">Page number (starting with 1). Each page has a fixed size of 50 entries.</param> /// <param name="groupId">Group ID whose banned members you are fetching</param> /// <param name="authToken">The OAuth access token to authenticate the request with.</param> /// <param name="cancelToken">The <see cref="CancellationToken" /> to observe.</param> public Task<Entities.SearchResultOfGroupBan> GroupV2_GetBannedMembersOfGroup(int currentpage, long groupId, string? authToken = null, CancellationToken cancelToken = default) { return _apiAccessor.ApiRequestAsync<Entities.SearchResultOfGroupBan>( new Uri($"GroupV2/{groupId}/Banned/", UriKind.Relative), null, HttpMethod.Get, authToken, cancelToken ); } /// <inheritdoc cref="GroupV2_GetBannedMembersOfGroup(int, long, string?, CancellationToken)" /> /// <typeparam name="T">The custom type to deserialize to.</typeparam> public Task<T> GroupV2_GetBannedMembersOfGroup<T>(int currentpage, long groupId, string? authToken = null, CancellationToken cancelToken = default) { return _apiAccessor.ApiRequestAsync<T>( new Uri($"GroupV2/{groupId}/Banned/", UriKind.Relative), null, HttpMethod.Get, authToken, cancelToken ); } /// <summary> /// An administrative method to allow the founder of a group or clan to give up their position to another admin permanently. /// </summary> /// <param name="founderIdNew">The new founder for this group. Must already be a group admin.</param> /// <param name="groupId">The target group id.</param> /// <param name="membershipType">Membership type of the provided founderIdNew.</param> /// <param name="authToken">The OAuth access token to authenticate the request with.</param> /// <param name="cancelToken">The <see cref="CancellationToken" /> to observe.</param> public Task<bool> GroupV2_AbdicateFoundership(long founderIdNew, long groupId, Entities.BungieMembershipType membershipType, string? authToken = null, CancellationToken cancelToken = default) { return _apiAccessor.ApiRequestAsync<bool>( new Uri($"GroupV2/{groupId}/Admin/AbdicateFoundership/{membershipType}/{founderIdNew}/", UriKind.Relative), null, HttpMethod.Post, authToken, cancelToken ); } /// <inheritdoc cref="GroupV2_AbdicateFoundership(long, long, Entities.BungieMembershipType, string?, CancellationToken)" /> /// <typeparam name="T">The custom type to deserialize to.</typeparam> public Task<T> GroupV2_AbdicateFoundership<T>(long founderIdNew, long groupId, Entities.BungieMembershipType membershipType, string? authToken = null, CancellationToken cancelToken = default) { return _apiAccessor.ApiRequestAsync<T>( new Uri($"GroupV2/{groupId}/Admin/AbdicateFoundership/{membershipType}/{founderIdNew}/", UriKind.Relative), null, HttpMethod.Post, authToken, cancelToken ); } /// <summary> /// Get the list of users who are awaiting a decision on their application to join a given group. Modified to include application info. /// Requires OAuth2 scope(s): AdminGroups /// </summary> /// <param name="currentpage">Page number (starting with 1). Each page has a fixed size of 50 items per page.</param> /// <param name="groupId">ID of the group.</param> /// <param name="authToken">The OAuth access token to authenticate the request with.</param> /// <param name="cancelToken">The <see cref="CancellationToken" /> to observe.</param> public Task<Entities.SearchResultOfGroupMemberApplication> GroupV2_GetPendingMemberships(int currentpage, long groupId, string? authToken = null, CancellationToken cancelToken = default) { return _apiAccessor.ApiRequestAsync<Entities.SearchResultOfGroupMemberApplication>( new Uri($"GroupV2/{groupId}/Members/Pending/", UriKind.Relative), null, HttpMethod.Get, authToken, cancelToken ); } /// <inheritdoc cref="GroupV2_GetPendingMemberships(int, long, string?, CancellationToken)" /> /// <typeparam name="T">The custom type to deserialize to.</typeparam> public Task<T> GroupV2_GetPendingMemberships<T>(int currentpage, long groupId, string? authToken = null, CancellationToken cancelToken = default) { return _apiAccessor.ApiRequestAsync<T>( new Uri($"GroupV2/{groupId}/Members/Pending/", UriKind.Relative), null, HttpMethod.Get, authToken, cancelToken ); } /// <summary> /// Get the list of users who have been invited into the group. /// Requires OAuth2 scope(s): AdminGroups /// </summary> /// <param name="currentpage">Page number (starting with 1). Each page has a fixed size of 50 items per page.</param> /// <param name="groupId">ID of the group.</param> /// <param name="authToken">The OAuth access token to authenticate the request with.</param> /// <param name="cancelToken">The <see cref="CancellationToken" /> to observe.</param> public Task<Entities.SearchResultOfGroupMemberApplication> GroupV2_GetInvitedIndividuals(int currentpage, long groupId, string? authToken = null, CancellationToken cancelToken = default) { return _apiAccessor.ApiRequestAsync<Entities.SearchResultOfGroupMemberApplication>( new Uri($"GroupV2/{groupId}/Members/InvitedIndividuals/", UriKind.Relative), null, HttpMethod.Get, authToken, cancelToken ); } /// <inheritdoc cref="GroupV2_GetInvitedIndividuals(int, long, string?, CancellationToken)" /> /// <typeparam name="T">The custom type to deserialize to.</typeparam> public Task<T> GroupV2_GetInvitedIndividuals<T>(int currentpage, long groupId, string? authToken = null, CancellationToken cancelToken = default) { return _apiAccessor.ApiRequestAsync<T>( new Uri($"GroupV2/{groupId}/Members/InvitedIndividuals/", UriKind.Relative), null, HttpMethod.Get, authToken, cancelToken ); } /// <summary> /// Approve all of the pending users for the given group. /// Requires OAuth2 scope(s): AdminGroups /// </summary> /// <param name="groupId">ID of the group.</param> /// <param name="authToken">The OAuth access token to authenticate the request with.</param> /// <param name="cancelToken">The <see cref="CancellationToken" /> to observe.</param> public Task<IEnumerable<Entities.Entities.EntityActionResult>> GroupV2_ApproveAllPending(long groupId, Entities.GroupsV2.GroupApplicationRequest requestBody, string? authToken = null, CancellationToken cancelToken = default) { return _apiAccessor.ApiRequestAsync<IEnumerable<Entities.Entities.EntityActionResult>>( new Uri($"GroupV2/{groupId}/Members/ApproveAll/", UriKind.Relative), new StringContent(JsonSerializer.Serialize(requestBody), System.Text.Encoding.UTF8, "application/json"), HttpMethod.Post, authToken, cancelToken ); } /// <inheritdoc cref="GroupV2_ApproveAllPending(long, Entities.GroupsV2.GroupApplicationRequest, string?, CancellationToken)" /> /// <typeparam name="T">The custom type to deserialize to.</typeparam> public Task<T> GroupV2_ApproveAllPending<T>(long groupId, Entities.GroupsV2.GroupApplicationRequest requestBody, string? authToken = null, CancellationToken cancelToken = default) { return _apiAccessor.ApiRequestAsync<T>( new Uri($"GroupV2/{groupId}/Members/ApproveAll/", UriKind.Relative), new StringContent(JsonSerializer.Serialize(requestBody), System.Text.Encoding.UTF8, "application/json"), HttpMethod.Post, authToken, cancelToken ); } /// <summary> /// Deny all of the pending users for the given group. /// Requires OAuth2 scope(s): AdminGroups /// </summary> /// <param name="groupId">ID of the group.</param> /// <param name="authToken">The OAuth access token to authenticate the request with.</param> /// <param name="cancelToken">The <see cref="CancellationToken" /> to observe.</param> public Task<IEnumerable<Entities.Entities.EntityActionResult>> GroupV2_DenyAllPending(long groupId, Entities.GroupsV2.GroupApplicationRequest requestBody, string? authToken = null, CancellationToken cancelToken = default) { return _apiAccessor.ApiRequestAsync<IEnumerable<Entities.Entities.EntityActionResult>>( new Uri($"GroupV2/{groupId}/Members/DenyAll/", UriKind.Relative), new StringContent(JsonSerializer.Serialize(requestBody), System.Text.Encoding.UTF8, "application/json"), HttpMethod.Post, authToken, cancelToken ); } /// <inheritdoc cref="GroupV2_DenyAllPending(long, Entities.GroupsV2.GroupApplicationRequest, string?, CancellationToken)" /> /// <typeparam name="T">The custom type to deserialize to.</typeparam> public Task<T> GroupV2_DenyAllPending<T>(long groupId, Entities.GroupsV2.GroupApplicationRequest requestBody, string? authToken = null, CancellationToken cancelToken = default) { return _apiAccessor.ApiRequestAsync<T>( new Uri($"GroupV2/{groupId}/Members/DenyAll/", UriKind.Relative), new StringContent(JsonSerializer.Serialize(requestBody), System.Text.Encoding.UTF8, "application/json"), HttpMethod.Post, authToken, cancelToken ); } /// <summary> /// Approve all of the pending users for the given group. /// Requires OAuth2 scope(s): AdminGroups /// </summary> /// <param name="groupId">ID of the group.</param> /// <param name="authToken">The OAuth access token to authenticate the request with.</param> /// <param name="cancelToken">The <see cref="CancellationToken" /> to observe.</param> public Task<IEnumerable<Entities.Entities.EntityActionResult>> GroupV2_ApprovePendingForList(long groupId, Entities.GroupsV2.GroupApplicationListRequest requestBody, string? authToken = null, CancellationToken cancelToken = default) { return _apiAccessor.ApiRequestAsync<IEnumerable<Entities.Entities.EntityActionResult>>( new Uri($"GroupV2/{groupId}/Members/ApproveList/", UriKind.Relative), new StringContent(JsonSerializer.Serialize(requestBody), System.Text.Encoding.UTF8, "application/json"), HttpMethod.Post, authToken, cancelToken ); } /// <inheritdoc cref="GroupV2_ApprovePendingForList(long, Entities.GroupsV2.GroupApplicationListRequest, string?, CancellationToken)" /> /// <typeparam name="T">The custom type to deserialize to.</typeparam> public Task<T> GroupV2_ApprovePendingForList<T>(long groupId, Entities.GroupsV2.GroupApplicationListRequest requestBody, string? authToken = null, CancellationToken cancelToken = default) { return _apiAccessor.ApiRequestAsync<T>( new Uri($"GroupV2/{groupId}/Members/ApproveList/", UriKind.Relative), new StringContent(JsonSerializer.Serialize(requestBody), System.Text.Encoding.UTF8, "application/json"), HttpMethod.Post, authToken, cancelToken ); } /// <summary> /// Approve the given membershipId to join the group/clan as long as they have applied. /// Requires OAuth2 scope(s): AdminGroups /// </summary> /// <param name="groupId">ID of the group.</param> /// <param name="membershipId">The membership id being approved.</param> /// <param name="membershipType">Membership type of the supplied membership ID.</param> /// <param name="authToken">The OAuth access token to authenticate the request with.</param> /// <param name="cancelToken">The <see cref="CancellationToken" /> to observe.</param> public Task<bool> GroupV2_ApprovePending(long groupId, long membershipId, Entities.BungieMembershipType membershipType, Entities.GroupsV2.GroupApplicationRequest requestBody, string? authToken = null, CancellationToken cancelToken = default) { return _apiAccessor.ApiRequestAsync<bool>( new Uri($"GroupV2/{groupId}/Members/Approve/{membershipType}/{membershipId}/", UriKind.Relative), new StringContent(JsonSerializer.Serialize(requestBody), System.Text.Encoding.UTF8, "application/json"), HttpMethod.Post, authToken, cancelToken ); } /// <inheritdoc cref="GroupV2_ApprovePending(long, long, Entities.BungieMembershipType, Entities.GroupsV2.GroupApplicationRequest, string?, CancellationToken)" /> /// <typeparam name="T">The custom type to deserialize to.</typeparam> public Task<T> GroupV2_ApprovePending<T>(long groupId, long membershipId, Entities.BungieMembershipType membershipType, Entities.GroupsV2.GroupApplicationRequest requestBody, string? authToken = null, CancellationToken cancelToken = default) { return _apiAccessor.ApiRequestAsync<T>( new Uri($"GroupV2/{groupId}/Members/Approve/{membershipType}/{membershipId}/", UriKind.Relative), new StringContent(JsonSerializer.Serialize(requestBody), System.Text.Encoding.UTF8, "application/json"), HttpMethod.Post, authToken, cancelToken ); } /// <summary> /// Deny all of the pending users for the given group that match the passed-in . /// Requires OAuth2 scope(s): AdminGroups /// </summary> /// <param name="groupId">ID of the group.</param> /// <param name="authToken">The OAuth access token to authenticate the request with.</param> /// <param name="cancelToken">The <see cref="CancellationToken" /> to observe.</param> public Task<IEnumerable<Entities.Entities.EntityActionResult>> GroupV2_DenyPendingForList(long groupId, Entities.GroupsV2.GroupApplicationListRequest requestBody, string? authToken = null, CancellationToken cancelToken = default) { return _apiAccessor.ApiRequestAsync<IEnumerable<Entities.Entities.EntityActionResult>>( new Uri($"GroupV2/{groupId}/Members/DenyList/", UriKind.Relative), new StringContent(JsonSerializer.Serialize(requestBody), System.Text.Encoding.UTF8, "application/json"), HttpMethod.Post, authToken, cancelToken ); } /// <inheritdoc cref="GroupV2_DenyPendingForList(long, Entities.GroupsV2.GroupApplicationListRequest, string?, CancellationToken)" /> /// <typeparam name="T">The custom type to deserialize to.</typeparam> public Task<T> GroupV2_DenyPendingForList<T>(long groupId, Entities.GroupsV2.GroupApplicationListRequest requestBody, string? authToken = null, CancellationToken cancelToken = default) { return _apiAccessor.ApiRequestAsync<T>( new Uri($"GroupV2/{groupId}/Members/DenyList/", UriKind.Relative), new StringContent(JsonSerializer.Serialize(requestBody), System.Text.Encoding.UTF8, "application/json"), HttpMethod.Post, authToken, cancelToken ); } /// <summary> /// Get information about the groups that a given member has joined. /// </summary> /// <param name="filter">Filter apply to list of joined groups.</param> /// <param name="groupType">Type of group the supplied member founded.</param> /// <param name="membershipId">Membership ID to for which to find founded groups.</param> /// <param name="membershipType">Membership type of the supplied membership ID.</param> /// <param name="authToken">The OAuth access token to authenticate the request with.</param> /// <param name="cancelToken">The <see cref="CancellationToken" /> to observe.</param> public Task<Entities.GroupsV2.GetGroupsForMemberResponse> GroupV2_GetGroupsForMember(Entities.GroupsV2.GroupsForMemberFilter filter, Entities.GroupsV2.GroupType groupType, long membershipId, Entities.BungieMembershipType membershipType, string? authToken = null, CancellationToken cancelToken = default) { return _apiAccessor.ApiRequestAsync<Entities.GroupsV2.GetGroupsForMemberResponse>( new Uri($"GroupV2/User/{membershipType}/{membershipId}/{filter}/{groupType}/", UriKind.Relative), null, HttpMethod.Get, authToken, cancelToken ); } /// <inheritdoc cref="GroupV2_GetGroupsForMember(Entities.GroupsV2.GroupsForMemberFilter, Entities.GroupsV2.GroupType, long, Entities.BungieMembershipType, string?, CancellationToken)" /> /// <typeparam name="T">The custom type to deserialize to.</typeparam> public Task<T> GroupV2_GetGroupsForMember<T>(Entities.GroupsV2.GroupsForMemberFilter filter, Entities.GroupsV2.GroupType groupType, long membershipId, Entities.BungieMembershipType membershipType, string? authToken = null, CancellationToken cancelToken = default) { return _apiAccessor.ApiRequestAsync<T>( new Uri($"GroupV2/User/{membershipType}/{membershipId}/{filter}/{groupType}/", UriKind.Relative), null, HttpMethod.Get, authToken, cancelToken ); } /// <summary> /// Allows a founder to manually recover a group they can see in game but not on bungie.net /// </summary> /// <param name="groupType">Type of group the supplied member founded.</param> /// <param name="membershipId">Membership ID to for which to find founded groups.</param> /// <param name="membershipType">Membership type of the supplied membership ID.</param> /// <param name="authToken">The OAuth access token to authenticate the request with.</param> /// <param name="cancelToken">The <see cref="CancellationToken" /> to observe.</param> public Task<Entities.GroupsV2.GroupMembershipSearchResponse> GroupV2_RecoverGroupForFounder(Entities.GroupsV2.GroupType groupType, long membershipId, Entities.BungieMembershipType membershipType, string? authToken = null, CancellationToken cancelToken = default) { return _apiAccessor.ApiRequestAsync<Entities.GroupsV2.GroupMembershipSearchResponse>( new Uri($"GroupV2/Recover/{membershipType}/{membershipId}/{groupType}/", UriKind.Relative), null, HttpMethod.Get, authToken, cancelToken ); } /// <inheritdoc cref="GroupV2_RecoverGroupForFounder(Entities.GroupsV2.GroupType, long, Entities.BungieMembershipType, string?, CancellationToken)" /> /// <typeparam name="T">The custom type to deserialize to.</typeparam> public Task<T> GroupV2_RecoverGroupForFounder<T>(Entities.GroupsV2.GroupType groupType, long membershipId, Entities.BungieMembershipType membershipType, string? authToken = null, CancellationToken cancelToken = default) { return _apiAccessor.ApiRequestAsync<T>( new Uri($"GroupV2/Recover/{membershipType}/{membershipId}/{groupType}/", UriKind.Relative), null, HttpMethod.Get, authToken, cancelToken ); } /// <summary> /// Get information about the groups that a given member has applied to or been invited to. /// </summary> /// <param name="filter">Filter apply to list of potential joined groups.</param> /// <param name="groupType">Type of group the supplied member applied.</param> /// <param name="membershipId">Membership ID to for which to find applied groups.</param> /// <param name="membershipType">Membership type of the supplied membership ID.</param> /// <param name="authToken">The OAuth access token to authenticate the request with.</param> /// <param name="cancelToken">The <see cref="CancellationToken" /> to observe.</param> public Task<Entities.GroupsV2.GroupPotentialMembershipSearchResponse> GroupV2_GetPotentialGroupsForMember(Entities.GroupsV2.GroupPotentialMemberStatus filter, Entities.GroupsV2.GroupType groupType, long membershipId, Entities.BungieMembershipType membershipType, string? authToken = null, CancellationToken cancelToken = default) { return _apiAccessor.ApiRequestAsync<Entities.GroupsV2.GroupPotentialMembershipSearchResponse>( new Uri($"GroupV2/User/Potential/{membershipType}/{membershipId}/{filter}/{groupType}/", UriKind.Relative), null, HttpMethod.Get, authToken, cancelToken ); } /// <inheritdoc cref="GroupV2_GetPotentialGroupsForMember(Entities.GroupsV2.GroupPotentialMemberStatus, Entities.GroupsV2.GroupType, long, Entities.BungieMembershipType, string?, CancellationToken)" /> /// <typeparam name="T">The custom type to deserialize to.</typeparam> public Task<T> GroupV2_GetPotentialGroupsForMember<T>(Entities.GroupsV2.GroupPotentialMemberStatus filter, Entities.GroupsV2.GroupType groupType, long membershipId, Entities.BungieMembershipType membershipType, string? authToken = null, CancellationToken cancelToken = default) { return _apiAccessor.ApiRequestAsync<T>( new Uri($"GroupV2/User/Potential/{membershipType}/{membershipId}/{filter}/{groupType}/", UriKind.Relative), null, HttpMethod.Get, authToken, cancelToken ); } /// <summary> /// Invite a user to join this group. /// Requires OAuth2 scope(s): AdminGroups /// </summary> /// <param name="groupId">ID of the group you would like to join.</param> /// <param name="membershipId">Membership id of the account being invited.</param> /// <param name="membershipType">MembershipType of the account being invited.</param> /// <param name="authToken">The OAuth access token to authenticate the request with.</param> /// <param name="cancelToken">The <see cref="CancellationToken" /> to observe.</param> public Task<Entities.GroupsV2.GroupApplicationResponse> GroupV2_IndividualGroupInvite(long groupId, long membershipId, Entities.BungieMembershipType membershipType, Entities.GroupsV2.GroupApplicationRequest requestBody, string? authToken = null, CancellationToken cancelToken = default) { return _apiAccessor.ApiRequestAsync<Entities.GroupsV2.GroupApplicationResponse>( new Uri($"GroupV2/{groupId}/Members/IndividualInvite/{membershipType}/{membershipId}/", UriKind.Relative), new StringContent(JsonSerializer.Serialize(requestBody), System.Text.Encoding.UTF8, "application/json"), HttpMethod.Post, authToken, cancelToken ); } /// <inheritdoc cref="GroupV2_IndividualGroupInvite(long, long, Entities.BungieMembershipType, Entities.GroupsV2.GroupApplicationRequest, string?, CancellationToken)" /> /// <typeparam name="T">The custom type to deserialize to.</typeparam> public Task<T> GroupV2_IndividualGroupInvite<T>(long groupId, long membershipId, Entities.BungieMembershipType membershipType, Entities.GroupsV2.GroupApplicationRequest requestBody, string? authToken = null, CancellationToken cancelToken = default) { return _apiAccessor.ApiRequestAsync<T>( new Uri($"GroupV2/{groupId}/Members/IndividualInvite/{membershipType}/{membershipId}/", UriKind.Relative), new StringContent(JsonSerializer.Serialize(requestBody), System.Text.Encoding.UTF8, "application/json"), HttpMethod.Post, authToken, cancelToken ); } /// <summary> /// Cancels a pending invitation to join a group. /// Requires OAuth2 scope(s): AdminGroups /// </summary> /// <param name="groupId">ID of the group you would like to join.</param> /// <param name="membershipId">Membership id of the account being cancelled.</param> /// <param name="membershipType">MembershipType of the account being cancelled.</param> /// <param name="authToken">The OAuth access token to authenticate the request with.</param> /// <param name="cancelToken">The <see cref="CancellationToken" /> to observe.</param> public Task<Entities.GroupsV2.GroupApplicationResponse> GroupV2_IndividualGroupInviteCancel(long groupId, long membershipId, Entities.BungieMembershipType membershipType, string? authToken = null, CancellationToken cancelToken = default) { return _apiAccessor.ApiRequestAsync<Entities.GroupsV2.GroupApplicationResponse>( new Uri($"GroupV2/{groupId}/Members/IndividualInviteCancel/{membershipType}/{membershipId}/", UriKind.Relative), null, HttpMethod.Post, authToken, cancelToken ); } /// <inheritdoc cref="GroupV2_IndividualGroupInviteCancel(long, long, Entities.BungieMembershipType, string?, CancellationToken)" /> /// <typeparam name="T">The custom type to deserialize to.</typeparam> public Task<T> GroupV2_IndividualGroupInviteCancel<T>(long groupId, long membershipId, Entities.BungieMembershipType membershipType, string? authToken = null, CancellationToken cancelToken = default) { return _apiAccessor.ApiRequestAsync<T>( new Uri($"GroupV2/{groupId}/Members/IndividualInviteCancel/{membershipType}/{membershipId}/", UriKind.Relative), null, HttpMethod.Post, authToken, cancelToken ); } } }
68.894318
337
0.675112
[ "MIT", "BSD-3-Clause" ]
ashakoor/BungieSharp
BungieSharper/Endpoints/GroupV2.cs
60,629
C#
using Abp.Application.Services.Dto; using Abp.AutoMapper; using DevPP.MultiTenancy; namespace DevPP.Sessions.Dto { [AutoMapFrom(typeof(Tenant))] public class TenantLoginInfoDto : EntityDto { public string TenancyName { get; set; } public string Name { get; set; } } }
20.2
47
0.683168
[ "MIT" ]
ThinkAcademy-BR/DevPP
aspnet-core/src/DevPP.Application/Sessions/Dto/TenantLoginInfoDto.cs
305
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // 有关程序集的一般信息由以下 // 控制。更改这些特性值可修改 // 与程序集关联的信息。 [assembly: AssemblyTitle("Ch10_Exercise02")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Ch10_Exercise02")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] //将 ComVisible 设置为 false 将使此程序集中的类型 //对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型, //请将此类型的 ComVisible 特性设置为 true。 [assembly: ComVisible(false)] // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID [assembly: Guid("09e09e2c-ae14-4990-ac72-35b849914068")] // 程序集的版本信息由下列四个值组成: // // 主版本 // 次版本 // 生成号 // 修订号 // //可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值, // 方法是按如下所示使用“*”: : // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
25.702703
56
0.716088
[ "MIT" ]
tianfengs/AbpPractice
C# 6 and .net core/Chapter10/Ch10_Exercise02/Properties/AssemblyInfo.cs
1,302
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using Microsoft.Build.Framework; using Microsoft.Build.Tasks.Deployment.ManifestUtilities; namespace Microsoft.Build.Tasks { /// <summary> /// Formats a url by canonicalizing it (i.e. " " -> "%20") and transforming "localhost" to "machinename". /// </summary> public sealed class FormatUrl : TaskExtension { public string InputUrl { get; set; } [Output] public string OutputUrl { get; set; } public override bool Execute() { #if RUNTIME_TYPE_NETCORE Log.LogErrorFromResources("TaskRequiresFrameworkFailure", nameof(FormatUrl)); return false; #else OutputUrl = InputUrl != null ? PathUtil.Format(InputUrl) : String.Empty; return true; #endif } } }
29.28125
109
0.65635
[ "MIT" ]
0xced/msbuild
src/Tasks/FormatUrl.cs
939
C#
using Abp.Application.Services; using Abp.Application.Services.Dto; using Abp.Domain.Repositories; using BlazorProject.Backend.Cargos.Dto; using BlazorProject.Backend.Entities; using System.Collections.Generic; using System.Threading.Tasks; namespace BlazorProject.Backend.Cargos { public class CargoService : ApplicationService, ICargoService { private readonly IRepository<Cargo> _cargoRepository; public CargoService(IRepository<Cargo> cargoRepository) { _cargoRepository = cargoRepository; } public async Task<ListResultDto<CargoListDto>> GetCargos() { var cargos = await _cargoRepository.GetAllListAsync(); return new ListResultDto<CargoListDto> ( ObjectMapper.Map<List<CargoListDto>>(cargos) ); } } }
29.448276
66
0.685012
[ "MIT" ]
274188A/BlazorProjectASPBoilerplateBackend
aspnet-core/src/BlazorProject.Backend.Application/Cargos/CargoService.cs
856
C#
using System; using System.Threading.Tasks; using AirView.Api.Core; using AirView.Api.Core.Hateoas; using AirView.Application; using AirView.Application.Core; using AirView.Application.Core.Exceptions; using AirView.Domain; using AirView.Persistence.Core; using AirView.Shared.Railways; using AutoMapper; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; namespace AirView.Api.Flights { [Route("api/flights")] [ApiController] public class FlightsController : ControllerBase { private readonly ICommandSender _commandSender; private readonly IMapper _mapper; private readonly IQueryableRepository<FlightProjection> _queryableRepository; public FlightsController(ICommandSender commandSender, IMapper mapper, IQueryableRepository<FlightProjection> queryableRepository) { _commandSender = commandSender; _mapper = mapper; _queryableRepository = queryableRepository; } [HttpGet("{id}", Name = "find")] public async Task<IActionResult> Find(Guid id) => (await _queryableRepository.TryFindAsync(id)) .Do(AddLinks) .Map<FlightProjection, IActionResult>(Ok) .Reduce(NotFound); [HttpGet(Name = "query")] public async Task<IActionResult> Query(int limit = 50, int offset = 0) { var query = _queryableRepository.Query().Paginate(limit, offset); var dto = await query.ToCollectionDtoAsync(await _queryableRepository.Query().CountAsync()); AddLinks(dto, query); return Ok(dto); } [HttpPost(Name = "register")] public async Task<IActionResult> Register([FromBody] RegisterFlightDto dto) => (await _commandSender.SendAsync(_mapper.Map<RegisterFlightCommand>(dto))) .Map(id => Accepted(Url.RouteUrl("find", new {id})) as IActionResult) .ReduceOrThrow(); [HttpPut("{id}/schedule", Name = "schedule")] public async Task<IActionResult> Schedule(Guid id, [FromBody] ScheduleFlightDto dto) { var flightId = id; var command = _mapper.Map<ScheduleFlightCommand>( dto, opt => opt.Items[nameof(ScheduleFlightCommand.Id)] = flightId); return (await _commandSender.SendAsync(command)) .Map(() => Accepted(Url.RouteUrl("find", new {id})) as IActionResult) .Reduce<EntityNotFoundCommandException<ScheduleFlightCommand>>(_ => NotFound()) .ReduceOrThrow(); } [HttpDelete("{id}", Name = "unregister")] public async Task<IActionResult> Unregister(Guid id) => (await _commandSender.SendAsync(new UnregisterFlightCommand(id))) .Map(() => Accepted(Url.RouteUrl("find", new {id})) as IActionResult) .Reduce<EntityNotFoundCommandException<UnregisterFlightCommand>>(_ => NotFound()) .ReduceOrThrow(); private void AddLinks(FlightProjection dto) { dto.AddLink("self", new LinkDto(Url.RouteUrl("find", new {dto.Id}))); dto.AddLink("schedule", new LinkDto(Url.RouteUrl("schedule", new {dto.Id}))); dto.AddLink("unregister", new LinkDto(Url.RouteUrl("unregister", new {dto.Id}))); } private void AddLinks(CollectionDto<FlightProjection> dto, IPagedQueryable<FlightProjection> query) { dto.AddLink("self", new LinkDto(RouteUrl("query", query))); if (query.HasPreviousPage()) { dto.AddLink("first", new LinkDto(RouteUrl("query", query.FirstPage()))); dto.AddLink("prev", new LinkDto(RouteUrl("query", query.PreviousPage()))); } if (query.HasNextPage(dto.TotalCount)) { dto.AddLink("next", new LinkDto(RouteUrl("query", query.NextPage(dto.TotalCount)))); dto.AddLink("last", new LinkDto(RouteUrl("query", query.LastPage(dto.TotalCount)))); } dto.AddLink("find", new LinkDto($"{Url.RouteUrl("query")}/{{id}}") {Templated = true}); dto.AddLink("register", new LinkDto(Url.RouteUrl("register"))); foreach (var value in dto.Values) AddLinks(value); } private string RouteUrl<T>(string routeName, IPagedQueryable<T> queryable) => Url.RouteUrl(routeName, new {limit = queryable.Limit, offset = queryable.Offset}); } }
42.018692
107
0.63056
[ "MIT" ]
softframe/airview
src/AirView.Api/Flights/FlightsController.cs
4,498
C#
// Copyright (c) Lex Li. All rights reserved. // // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections; using System.Collections.Generic; using System.Windows.Forms; namespace Microsoft.Web.Management.Client.Win32 { public class SortableListView : UserControl { public SortableListView( List<ColumnHeader> columnHeaders ) { } public void AddItems( List<ListViewItem> itemsList ) { } protected override void Dispose( bool disposing ) { } protected virtual IComparer GetItemComparer( ColumnHeader sortColumn, SortOrder sortOrder ) { return null; } public void SetItems( List<ListViewItem> itemsList ) { } public void ShowSortColumn( ColumnHeader column, SortOrder sortOrder ) { } protected void Sort() { } public void Sort( ColumnHeader column, SortOrder sortOrder ) { } public ListView ListView { get; } public ColumnHeader SortColumn { get; } public SortOrder SortOrder { get; } } }
22.566667
101
0.550222
[ "MIT" ]
68681395/JexusManager
Microsoft.Web.Management/Client/Win32/SortableListView.cs
1,354
C#
#region License // Copyright (c) 2011, ClearCanvas Inc. // All rights reserved. // http://www.clearcanvas.ca // // This software is licensed under the Open Software License v3.0. // For the complete license, see http://www.clearcanvas.ca/OSLv3.0 #endregion using ClearCanvas.Common.Statistics; namespace ClearCanvas.ImageServer.Services.Streaming.HeaderStreaming { internal class HeaderStreamingStatistics : StatisticsSet { #region Constructors public HeaderStreamingStatistics() : base("HeaderStreaming") { AddField(new Statistics<string>("Client")); AddField(new Statistics<string>("StudyInstanceUid")); AddField(new TimeSpanStatistics("ProcessTime")); } #endregion Constructors #region Public Properties public TimeSpanStatistics ProcessTime { get { return this["ProcessTime"] as TimeSpanStatistics; } } #endregion Public Properties } }
26.615385
70
0.641618
[ "Apache-2.0" ]
SNBnani/Xian
ImageServer/Services/Streaming/HeaderStreaming/HeaderStreamingStatistics.cs
1,038
C#
using System; using GovUk.Education.ExploreEducationStatistics.Content.Model; namespace GovUk.Education.ExploreEducationStatistics.Admin.ViewModels { public class CommentViewModel { public Guid Id { get; set; } public string Content { get; set; } public DateTime Created { get; set; } public User CreatedBy { get; set; } public DateTime? Updated { get; set; } public DateTime? Resolved { get; set; } public User ResolvedBy { get; set; } } }
30
69
0.656863
[ "MIT" ]
dfe-analytical-services/explore-education-statistics
src/GovUk.Education.ExploreEducationStatistics.Admin/ViewModels/CommentViewModel.cs
510
C#
// Copyright 2007-2018 Chris Patterson, Dru Sellers, Travis Smith, et. al. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. namespace MassTransit.AmazonSqsTransport.Topology.Configuration.Configurators { using AmazonSqsTransport.Configuration; using Entities; public class QueueConfigurator : EntityConfigurator, IQueueConfigurator, Queue { public QueueConfigurator(string queueName, bool durable = true, bool autoDelete = false) : base(queueName, durable, autoDelete) { } public QueueConfigurator(Queue source) : base(source.EntityName, source.Durable, source.AutoDelete) { } public bool Lazy { get; set; } } }
35.666667
97
0.675234
[ "Apache-2.0" ]
JakubSurfer/MassTransit
src/MassTransit.AmazonSqsTransport/Topology/Configuration/Configurators/QueueConfigurator.cs
1,284
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Diagnostics.ContractsLight; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using BuildXL.Cache.ContentStore.Distributed.Sessions; using BuildXL.Cache.ContentStore.Hashing; using BuildXL.Cache.ContentStore.Interfaces.FileSystem; using BuildXL.Cache.ContentStore.Interfaces.Results; using BuildXL.Cache.ContentStore.Interfaces.Tracing; using BuildXL.Cache.ContentStore.Tracing; using BuildXL.Cache.ContentStore.Tracing.Internal; using BuildXL.Cache.ContentStore.UtilitiesCore; using BuildXL.Cache.ContentStore.Utils; using BuildXL.Utilities.Tasks; using BuildXL.Utilities.Tracing; using static BuildXL.Cache.ContentStore.Distributed.Stores.DistributedContentStoreSettings; namespace BuildXL.Cache.ContentStore.Distributed.Stores { /// <summary> /// Handles copies from remote locations to a local store /// </summary> /// <typeparam name="T">The content locations being stored.</typeparam> public class DistributedContentCopier<T> : StartupShutdownSlimBase, IDistributedContentCopier where T : PathBase { // Gate to control the maximum number of simultaneously active IO operations. private readonly SemaphoreSlim _ioGate; // Gate to control the maximum number of simultaneously active proactive copies. private readonly SemaphoreSlim _proactiveCopyIoGate; private readonly IReadOnlyList<TimeSpan> _retryIntervals; private readonly TimeSpan _timeoutForPoractiveCopies; private readonly DisposableDirectory _tempFolderForCopies; private readonly IFileCopier<T> _remoteFileCopier; private readonly ICopyRequester _copyRequester; private readonly IFileExistenceChecker<T> _remoteFileExistenceChecker; private readonly IPathTransformer<T> _pathTransformer; private readonly IContentLocationStore _contentLocationStore; private readonly DistributedContentStoreSettings _settings; private readonly IAbsFileSystem _fileSystem; private readonly Dictionary<HashType, IContentHasher> _hashers; private readonly CounterCollection<DistributedContentCopierCounters> _counters = new CounterCollection<DistributedContentCopierCounters>(); private readonly AbsolutePath _workingDirectory; /// <inheritdoc /> protected override Tracer Tracer { get; } = new Tracer(nameof(DistributedContentCopier<T>)); /// <nodoc /> public int CurrentIoGateCount => _ioGate.CurrentCount; /// <nodoc /> public DistributedContentCopier( AbsolutePath workingDirectory, DistributedContentStoreSettings settings, IAbsFileSystem fileSystem, IFileCopier<T> fileCopier, IFileExistenceChecker<T> fileExistenceChecker, ICopyRequester copyRequester, IPathTransformer<T> pathTransformer, IContentLocationStore contentLocationStore) { Contract.Requires(settings != null); Contract.Requires(settings.ParallelHashingFileSizeBoundary >= -1); _settings = settings; _tempFolderForCopies = new DisposableDirectory(fileSystem, workingDirectory / "Temp"); _remoteFileCopier = fileCopier; _remoteFileExistenceChecker = fileExistenceChecker; _copyRequester = copyRequester; _contentLocationStore = contentLocationStore; _pathTransformer = pathTransformer; _fileSystem = fileSystem; _workingDirectory = _tempFolderForCopies.Path; // TODO: Use hashers from IContentStoreInternal instead? _hashers = HashInfoLookup.CreateAll(); _ioGate = new SemaphoreSlim(_settings.MaxConcurrentCopyOperations); _proactiveCopyIoGate = new SemaphoreSlim(_settings.MaxConcurrentProactiveCopyOperations); _retryIntervals = settings.RetryIntervalForCopies; _timeoutForPoractiveCopies = settings.TimeoutForProactiveCopies; } /// <inheritdoc /> protected override Task<BoolResult> StartupCoreAsync(OperationContext context) { if (_settings.CleanRandomFilesAtRoot) { foreach (var file in _fileSystem.EnumerateFiles(_workingDirectory.Parent, EnumerateOptions.None)) { if (IsRandomFile(file.FullPath)) { Tracer.Debug(context, $"Deleting random file {file.FullPath} at root."); _fileSystem.DeleteFile(file.FullPath); } } } return base.StartupCoreAsync(context); } private bool IsRandomFile(AbsolutePath file) { var fileName = file.GetFileName(); return fileName.StartsWith("random-", StringComparison.OrdinalIgnoreCase); } /// <inheritdoc /> protected override Task<BoolResult> ShutdownCoreAsync(OperationContext context) { _tempFolderForCopies.Dispose(); return base.ShutdownCoreAsync(context); } /// <inheritdoc /> public async Task<PutResult> TryCopyAndPutAsync( OperationContext operationContext, ContentHashWithSizeAndLocations hashInfo, Func<(CopyFileResult copyResult, AbsolutePath tempLocation, int attemptCount), Task<PutResult>> handleCopyAsync, Action<IReadOnlyList<MachineLocation>> handleBadLocations = null) { var cts = operationContext.Token; try { PutResult putResult = null; var badContentLocations = new HashSet<MachineLocation>(); var missingContentLocations = new HashSet<MachineLocation>(); int attemptCount = 0; while (attemptCount < _retryIntervals.Count && (putResult == null || !putResult)) { bool retry; (putResult, retry) = await WalkLocationsAndCopyAndPutAsync( operationContext, _workingDirectory, hashInfo, badContentLocations, missingContentLocations, attemptCount, handleCopyAsync); if (putResult || operationContext.Token.IsCancellationRequested) { break; } if (missingContentLocations.Count == hashInfo.Locations.Count) { Tracer.Warning(operationContext, $"{AttemptTracePrefix(attemptCount)} All replicas {hashInfo.Locations.Count} are reported missing. Not retrying for hash {hashInfo.ContentHash.ToShortString()}."); break; } if (!retry) { Tracer.Warning(operationContext, $"{AttemptTracePrefix(attemptCount)} Cannot place {hashInfo.ContentHash.ToShortString()} due to error: {putResult.ErrorMessage}. Not retrying for hash {hashInfo.ContentHash.ToShortString()}."); break; } attemptCount++; if (attemptCount < _retryIntervals.Count) { long waitTicks = _retryIntervals[attemptCount].Ticks; // Randomize the wait delay to `[0.5 * delay, 1.5 * delay)` TimeSpan waitDelay = TimeSpan.FromTicks((long)((waitTicks / 2) + (waitTicks * ThreadSafeRandom.Generator.NextDouble()))); // Log with the original attempt count Tracer.Warning(operationContext, $"{AttemptTracePrefix(attemptCount - 1)} All replicas {hashInfo.Locations.Count} failed. Retrying for hash {hashInfo.ContentHash.ToShortString()} in {waitDelay.TotalMilliseconds}ms..."); await Task.Delay(waitDelay, cts); } else { break; } } // now that retries are exhausted, combine the missing and bad locations. badContentLocations.UnionWith(missingContentLocations); if (badContentLocations.Any()) { // This will go away when LLS is the only content location store handleBadLocations?.Invoke(badContentLocations.ToList()); } if (!putResult.Succeeded) { traceCopyFailed(operationContext); } else { Tracer.TrackMetric(operationContext, "RemoteBytesCount", putResult.ContentSize); _counters[DistributedContentCopierCounters.RemoteBytes].Add(putResult.ContentSize); _counters[DistributedContentCopierCounters.RemoteFilesCopied].Increment(); } return putResult; } catch (Exception ex) { traceCopyFailed(operationContext); if (cts.IsCancellationRequested) { return CreateCanceledPutResult(); } return new ErrorResult(ex).AsResult<PutResult>(); } void traceCopyFailed(Context c) { Tracer.TrackMetric(c, "RemoteCopyFileFailed", 1); _counters[DistributedContentCopierCounters.RemoteFilesFailedCopy].Increment(); } } /// <summary> /// Requests another machine to copy from the current machine. /// </summary> public Task<BoolResult> RequestCopyFileAsync(OperationContext context, ContentHash hash, MachineLocation targetLocation) { context.TraceDebug("Waiting on IOGate for RequestCopyFileAsync: " + $"ContentHash={hash.ToShortString()} " + $"TargetLocation=[{targetLocation}] " + $"IOGate.OccupiedCount={_settings.MaxConcurrentProactiveCopyOperations - _proactiveCopyIoGate.CurrentCount} "); return _proactiveCopyIoGate.GatedOperationAsync(ts => { var cts = new CancellationTokenSource(); cts.CancelAfter(_timeoutForPoractiveCopies); var innerContext = context.CreateNested(cts.Token); return context.PerformOperationAsync( Tracer, operation: () => { return _copyRequester.RequestCopyFileAsync(innerContext, hash, targetLocation); }, traceOperationStarted: false, extraEndMessage: result => $"ContentHash={hash.ToShortString()} " + $"TargetLocation=[{targetLocation}] " + $"IOGate.OccupiedCount={_settings.MaxConcurrentProactiveCopyOperations - _proactiveCopyIoGate.CurrentCount} " + $"IOGate.Wait={ts.TotalMilliseconds}ms." + $"Timeout={cts.Token.IsCancellationRequested}" ); }, context.Token); } private PutResult CreateCanceledPutResult() => new ErrorResult("The operation was canceled").AsResult<PutResult>(); /// <nodoc /> private async Task<(PutResult result, bool retry)> WalkLocationsAndCopyAndPutAsync( OperationContext context, AbsolutePath workingFolder, ContentHashWithSizeAndLocations hashInfo, HashSet<MachineLocation> badContentLocations, HashSet<MachineLocation> missingContentLocations, int attemptCount, Func<(CopyFileResult copyResult, AbsolutePath tempLocation, int attemptCount), Task<PutResult>> handleCopyAsync) { var cts = context.Token; // before each retry, clear the list of bad locations so we can retry them all. // this helps isolate transient network errors. badContentLocations.Clear(); string lastErrorMessage = null; foreach (MachineLocation location in hashInfo.Locations) { // if the file is explicitly reported missing by the remote, don't bother retrying. if (missingContentLocations.Contains(location)) { continue; } var sourcePath = _pathTransformer.GeneratePath(hashInfo.ContentHash, location.Data); var tempLocation = AbsolutePath.CreateRandomFileName(workingFolder); (PutResult result, bool retry) reportCancellationRequested() { Tracer.Debug( context, $"{AttemptTracePrefix(attemptCount)} Could not copy file with hash {hashInfo.ContentHash.ToShortString()} to temp path {tempLocation} because cancellation was requested."); return (result: CreateCanceledPutResult(), retry: false); } // Both Puts will attempt to Move the file into the cache. If the Put is successful, then the temporary file // does not need to be deleted. If anything else goes wrong, then the temporary file must be removed. bool deleteTempFile = true; try { if (cts.IsCancellationRequested) { return reportCancellationRequested(); } // Gate entrance to both the copy logic and the logging which surrounds it CopyFileResult copyFileResult = null; try { copyFileResult = await _ioGate.GatedOperationAsync(ts => context.PerformOperationAsync( Tracer, async () => { return await TaskUtilities.AwaitWithProgressReporting( task: CopyFileAsync(context, sourcePath, tempLocation, hashInfo, cts), period: TimeSpan.FromMinutes(5), action: timeSpan => Tracer.Debug(context, $"{Tracer.Name}.RemoteCopyFile from[{location}]) via stream in progress {(int)timeSpan.TotalSeconds}s."), reportImmediately: false, reportAtEnd: false); }, traceOperationStarted: false, traceOperationFinished: true, // _ioGate.CurrentCount returns the number of free slots, but we need to print the number of occupied slots instead. extraEndMessage: (result) => $"contentHash=[{hashInfo.ContentHash.ToShortString()}] " + $"from=[{sourcePath}] " + $"size=[{result.Size ?? hashInfo.Size}] " + $"trusted={_settings.UseTrustedHash} " + (result.TimeSpentHashing.HasValue ? $"timeSpentHashing={result.TimeSpentHashing.Value.TotalMilliseconds}ms " : string.Empty) + $"IOGate.OccupiedCount={_settings.MaxConcurrentCopyOperations - _ioGate.CurrentCount} " + $"IOGate.Wait={ts.TotalMilliseconds}ms.", caller: "RemoteCopyFile", counter: _counters[DistributedContentCopierCounters.RemoteCopyFile]), cts); if (copyFileResult.TimeSpentHashing.HasValue) { Tracer.TrackMetric(context, "CopyHashingTimeMs", (long)copyFileResult.TimeSpentHashing.Value.TotalMilliseconds); } } catch (Exception e) when (e is OperationCanceledException) { // Handles both OperationCanceledException and TaskCanceledException (TaskCanceledException derives from OperationCanceledException) return reportCancellationRequested(); } if (cts.IsCancellationRequested) { return reportCancellationRequested(); } if (copyFileResult != null) { switch (copyFileResult.Code) { case CopyFileResult.ResultCode.Success: _contentLocationStore.ReportReputation(location, MachineReputation.Good); break; case CopyFileResult.ResultCode.FileNotFoundError: lastErrorMessage = $"Could not copy file with hash {hashInfo.ContentHash.ToShortString()} from path {sourcePath} to path {tempLocation} due to an error with the sourcepath: {copyFileResult}"; Tracer.Warning( context, $"{AttemptTracePrefix(attemptCount)} {lastErrorMessage} Trying another replica."); missingContentLocations.Add(location); _contentLocationStore.ReportReputation(location, MachineReputation.Missing); break; case CopyFileResult.ResultCode.SourcePathError: lastErrorMessage = $"Could not copy file with hash {hashInfo.ContentHash.ToShortString()} from path {sourcePath} to path {tempLocation} due to an error with the sourcepath: {copyFileResult}"; Tracer.Warning( context, $"{AttemptTracePrefix(attemptCount)} {lastErrorMessage} Trying another replica."); _contentLocationStore.ReportReputation(location, MachineReputation.Bad); badContentLocations.Add(location); break; case CopyFileResult.ResultCode.DestinationPathError: lastErrorMessage = $"Could not copy file with hash {hashInfo.ContentHash.ToShortString()} from path {sourcePath} to temp path {tempLocation} due to an error with the destination path: {copyFileResult}"; Tracer.Warning( context, $"{AttemptTracePrefix(attemptCount)} {lastErrorMessage} Not trying another replica."); return (result: new ErrorResult(copyFileResult).AsResult<PutResult>(), retry: true); case CopyFileResult.ResultCode.CopyTimeoutError: lastErrorMessage = $"Could not copy file with hash {hashInfo.ContentHash.ToShortString()} from path {sourcePath} to path {tempLocation} due to copy timeout: {copyFileResult}"; Tracer.Warning( context, $"{AttemptTracePrefix(attemptCount)} {lastErrorMessage} Trying another replica."); _contentLocationStore.ReportReputation(location, MachineReputation.Timeout); break; case CopyFileResult.ResultCode.CopyBandwidthTimeoutError: lastErrorMessage = $"Could not copy file with hash {hashInfo.ContentHash.ToShortString()} from path {sourcePath} to path {tempLocation} due to insufficient bandwidth timeout: {copyFileResult}"; Tracer.Warning( context, $"{AttemptTracePrefix(attemptCount)} {lastErrorMessage} Trying another replica."); _contentLocationStore.ReportReputation(location, MachineReputation.Timeout); break; case CopyFileResult.ResultCode.InvalidHash: lastErrorMessage = $"Could not copy file with hash {hashInfo.ContentHash.ToShortString()} from path {sourcePath} to path {tempLocation} due to invalid hash: {copyFileResult}"; Tracer.Warning( context, $"{AttemptTracePrefix(attemptCount)} {lastErrorMessage} {copyFileResult}"); break; case CopyFileResult.ResultCode.Unknown: lastErrorMessage = $"Could not copy file with hash {hashInfo.ContentHash.ToShortString()} from path {sourcePath} to temp path {tempLocation} due to an internal error: {copyFileResult}"; Tracer.Warning( context, $"{AttemptTracePrefix(attemptCount)} {lastErrorMessage} Not trying another replica."); _contentLocationStore.ReportReputation(location, MachineReputation.Bad); break; default: lastErrorMessage = $"File copier result code {copyFileResult.Code} is not recognized"; return (result: new ErrorResult(copyFileResult, $"{AttemptTracePrefix(attemptCount)} {lastErrorMessage}").AsResult<PutResult>(), retry: true); } if (copyFileResult.Succeeded) { // The copy succeeded, but it is possible that the resulting size doesn't match an expected one. if (hashInfo.Size != -1 && copyFileResult.Size != null && hashInfo.Size != copyFileResult.Size.Value) { lastErrorMessage = $"Contenthash {hashInfo.ContentHash.ToShortString()} at location {location} has content size {copyFileResult.Size.Value} mismatch from {hashInfo.Size}"; Tracer.Warning( context, $"{AttemptTracePrefix(attemptCount)} {lastErrorMessage} Trying another replica."); // Not tracking the source as a machine with bad reputation, because it is possible that we provided the wrong size. continue; } PutResult putResult = await handleCopyAsync((copyFileResult, tempLocation, attemptCount)); if (putResult.Succeeded) { // The put succeeded, but this doesn't necessarily mean that we put the content we intended. Check the content hash // to ensure it's what is expected. This should only go wrong for a small portion of non-trusted puts. if (putResult.ContentHash != hashInfo.ContentHash) { lastErrorMessage = $"Contenthash at location {location} has contenthash {putResult.ContentHash.ToShortString()} mismatch from {hashInfo.ContentHash.ToShortString()}"; // If PutFileAsync re-hashed the file, then it could have found a content hash which differs from the expected content hash. // If this happens, we should fail this copy and move to the next location. Tracer.Warning( context, $"{AttemptTracePrefix(attemptCount)} {lastErrorMessage}"); badContentLocations.Add(location); continue; } // Don't delete the temporary file! It no longer exists after the Put moved it into the cache deleteTempFile = false; // Successful case return (result: putResult, retry: false); } else if (putResult.IsCancelled) { return reportCancellationRequested(); } else { // Nothing is known about the put's failure. Give up on all locations, do not retry. // An example of a failure requiring this: Failed to reserve space for content var errorMessage = $"Put file for content hash {hashInfo.ContentHash.ToShortString()} failed with error {putResult.ErrorMessage} "; Tracer.Warning( context, $"{AttemptTracePrefix(attemptCount)} {errorMessage} diagnostics {putResult.Diagnostics}"); return (result: putResult, retry: false); } } } } finally { if (deleteTempFile) { _fileSystem.DeleteFile(tempLocation); } } } if (lastErrorMessage != null) { lastErrorMessage = ". " + lastErrorMessage; } return (new PutResult(hashInfo.ContentHash, $"Unable to copy file{lastErrorMessage}"), retry: true); } private async Task<CopyFileResult> CopyFileAsync( Context context, T location, AbsolutePath tempDestinationPath, ContentHashWithSizeAndLocations hashInfo, CancellationToken cts) { try { // Only use trusted hash for files greater than _trustedHashFileSizeBoundary. Over a few weeks of data collection, smaller files appear to copy and put faster using the untrusted variant. if (_settings.UseTrustedHash && hashInfo.Size >= _settings.TrustedHashFileSizeBoundary) { // If we know that the file is large, then hash concurrently from the start bool hashEntireFileConcurrently = _settings.ParallelHashingFileSizeBoundary >= 0 && hashInfo.Size > _settings.ParallelHashingFileSizeBoundary; int bufferSize = GetBufferSize(hashInfo); // Since this is the only place where we hash the file during trusted copies, we attempt to get access to the bytes here, // to avoid an additional IO operation later. In case that the file is bigger than the ContentLocationStore permits or blobs // aren't supported, disposing the FileStream twice does not throw or cause issues. using (Stream fileStream = await _fileSystem.OpenAsync(tempDestinationPath, FileAccess.Write, FileMode.Create, FileShare.Read | FileShare.Delete, FileOptions.SequentialScan, bufferSize)) using (Stream possiblyRecordingStream = _contentLocationStore.AreBlobsSupported && hashInfo.Size <= _contentLocationStore.MaxBlobSize && hashInfo.Size >= 0 ? (Stream)new RecordingStream(fileStream, hashInfo.Size) : fileStream) using (HashingStream hashingStream = _hashers[hashInfo.ContentHash.HashType].CreateWriteHashingStream(possiblyRecordingStream, hashEntireFileConcurrently ? 1 : _settings.ParallelHashingFileSizeBoundary)) { var copyFileResult = await _remoteFileCopier.CopyToAsync(location, hashingStream, hashInfo.Size, cts); copyFileResult.TimeSpentHashing = hashingStream.TimeSpentHashing; if (copyFileResult.Succeeded) { var foundHash = hashingStream.GetContentHash(); if (foundHash != hashInfo.ContentHash) { return new CopyFileResult(CopyFileResult.ResultCode.InvalidHash, $"{nameof(CopyFileAsync)} unsuccessful with different hash. Found {foundHash.ToShortString()}, expected {hashInfo.ContentHash.ToShortString()}. Found size {hashingStream.Length}, expected size {hashInfo.Size}."); } // Expose the bytes that were copied, so that small files can be put into the ContentLocationStore even when trusted copy is done if (possiblyRecordingStream is RecordingStream recordingStream) { copyFileResult.BytesFromTrustedCopy = recordingStream.RecordedBytes; } return copyFileResult; } else { // This result will be logged in the caller return copyFileResult; } } } else { return await _remoteFileCopier.CopyFileAsync(location, tempDestinationPath, hashInfo.Size, overwrite: true, cancellationToken: cts); } } catch (Exception ex) when (ex is UnauthorizedAccessException || ex is InvalidOperationException || ex is IOException) { // Auth errors are considered errors with the destination. // Since FSServer now returns HTTP based exceptions for web, IO failures must be local file paths. return new CopyFileResult(CopyFileResult.ResultCode.DestinationPathError, ex, ex.ToString()); } catch (Exception ex) { // any other exceptions are assumed to be bad remote files. return new CopyFileResult(CopyFileResult.ResultCode.SourcePathError, ex, ex.ToString()); } } private static int GetBufferSize(ContentHashWithSizeAndLocations hashInfo) { // For "small" files we use "small buffer size" // For files in [small, large) range we use file.Size // For "large" files we use "large buffer size". var size = hashInfo.Size; if (size <= DefaultSmallBufferSize) { return DefaultSmallBufferSize; } else if (size >= DefaultLargeBufferSize) { return DefaultLargeBufferSize; } else { return (int)size; } } private string AttemptTracePrefix(int attemptCount) { return $"Attempt #{attemptCount}:"; } // This class is used in this type to pass results out of the VerifyRemote method. internal class VerifyResult { public ContentHash Hash { get; set; } public IReadOnlyList<MachineLocation> Present { get; set; } public IReadOnlyList<MachineLocation> Absent { get; set; } public IReadOnlyList<MachineLocation> Unknown { get; set; } } // Given a content record set, check all the locations and determine, for each location, whether the file is actually // present, actually absent, or if its presence or absence cannot be determined in the alloted time. // The CheckFileExistsAsync method that is called in this implementation may be doing more complicated stuff (retries, queuing, // throttling, its own timeout) than we want or expect; we should dig into this. internal async Task<VerifyResult> VerifyAsync(Context context, ContentHashWithSizeAndLocations remote, CancellationToken cancel) { Contract.Requires(remote != null); Task<FileExistenceResult>[] verifications = new Task<FileExistenceResult>[remote.Locations.Count]; using (var timeoutCancelSource = CancellationTokenSource.CreateLinkedTokenSource(cancel)) { for (int i = 0; i < verifications.Length; i++) { T location = _pathTransformer.GeneratePath(remote.ContentHash, remote.Locations[i].Data); var verification = Task.Run(async () => await GatedCheckFileExistenceAsync(location, timeoutCancelSource.Token)); verifications[i] = verification; } // Spend up to the timeout doing as many verification as we can. timeoutCancelSource.CancelAfter(VerifyTimeout); // In order to await the end of the verifications and still not throw an exception if verification were canceled (or faulted internally), we // use the trick of awaiting a WhenAny, which never throws but instead always runs to completion when the argument tasks complete. #pragma warning disable EPC13 // Suspiciously unobserved result. await Task.WhenAny(Task.WhenAll(verifications)); #pragma warning restore EPC13 // Suspiciously unobserved result. } // Read out the results of the file existence checks var present = new List<MachineLocation>(); var absent = new List<MachineLocation>(); var unknown = new List<MachineLocation>(); for (int i = 0; i < verifications.Length; i++) { var location = remote.Locations[i]; Task<FileExistenceResult> verification = verifications[i]; Contract.Assert(verification.IsCompleted); if (verification.IsCanceled && !cancel.IsCancellationRequested) { Tracer.Info(context, $"During verification, hash {remote.ContentHash.ToShortString()} timed out for location {location}."); unknown.Add(location); } else if (verification.IsFaulted) { Tracer.Info(context, $"During verification, hash {remote.ContentHash.ToShortString()} encountered the error {verification.Exception} while verifying location {location}."); unknown.Add(location); } else { FileExistenceResult result = await verification; if (result.Code == FileExistenceResult.ResultCode.FileExists) { present.Add(location); } else if (result.Code == FileExistenceResult.ResultCode.FileNotFound) { Tracer.Info(context, $"During verification, hash {remote.ContentHash.ToShortString()} was not found at location {location}."); absent.Add(location); } else { unknown.Add(location); } } } return new VerifyResult() { Hash = remote.ContentHash, Present = present, Absent = absent, Unknown = unknown }; } /// <summary> /// This gated method attempts to limit the number of simultaneous off-machine file IO. /// It's not clear whether this is really a good idea, since usually IO thread management is best left to the scheduler. /// But if there is a truly enormous amount of external IO, it's not clear that they will all be scheduled in a way /// that will minimize timeouts, so we will try this gate. /// </summary> private Task<FileExistenceResult> GatedCheckFileExistenceAsync(T path, CancellationToken token) { return _ioGate.GatedOperationAsync( (_) => _remoteFileExistenceChecker.CheckFileExistsAsync(path, Timeout.InfiniteTimeSpan, token), token); } /// <nodoc /> public CounterSet GetCounters() => _counters.ToCounterSet(); private enum DistributedContentCopierCounters { /// <nodoc /> [CounterType(CounterType.Stopwatch)] RemoteCopyFile, /// <nodoc /> RemoteBytes, /// <nodoc /> RemoteFilesCopied, /// <nodoc /> RemoteFilesFailedCopy } } }
54.18529
310
0.549505
[ "MIT" ]
nayanshah/BuildXL
Public/Src/Cache/ContentStore/Distributed/Stores/DistributedContentCopier.cs
38,309
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Threading.Tasks; using Azure.Core.TestFramework; using Azure.ResourceManager.Storage.Models; using Azure.ResourceManager.Storage.Tests.Helpers; using NUnit.Framework; namespace Azure.ResourceManager.Storage.Tests.Tests { [RunFrequency(RunTestFrequency.Manually)] public class StorageAccountTests : StorageTestsManagementClientBase { public StorageAccountTests(bool isAsync) : base(isAsync) { } [SetUp] public void ClearChallengeCacheforRecord() { if (Mode == RecordedTestMode.Record || Mode == RecordedTestMode.Playback) { Initialize(); } } [TearDown] public async Task CleanupResourceGroup() { await CleanupResourceGroupsAsync(); } [RecordedTest] public async Task StorageAccountCreateTest() { string rgname = await CreateResourceGroupAsync(); string accountName = Recording.GenerateAssetName("sto"); string accountName1 = Recording.GenerateAssetName("sto"); StorageAccount account = await _CreateStorageAccountAsync(rgname, accountName); VerifyAccountProperties(account, true); //Make sure a second create returns immediately account = await _CreateStorageAccountAsync(rgname, accountName); VerifyAccountProperties(account, true); //Create storage account with only required params account = await _CreateStorageAccountAsync(rgname, accountName1); VerifyAccountProperties(account, false); } [RecordedTest] public async Task StorageAccountCreateWithEncryptionTest() { //Create resource group string rgname = await CreateResourceGroupAsync(); string accountName = Recording.GenerateAssetName("sto"); //Create storage account StorageAccountCreateParameters parameters = GetDefaultStorageAccountParameters(); parameters.Encryption = new Encryption(KeySource.MicrosoftStorage) { Services = new EncryptionServices { Blob = new EncryptionService { Enabled = true }, File = new EncryptionService { Enabled = true } } }; StorageAccount account = await _CreateStorageAccountAsync(rgname, accountName, parameters); VerifyAccountProperties(account, true); //Verify encryption settings Assert.NotNull(account.Encryption); Assert.NotNull(account.Encryption.Services.Blob); Assert.True(account.Encryption.Services.Blob.Enabled); Assert.NotNull(account.Encryption.Services.Blob.LastEnabledTime); Assert.NotNull(account.Encryption.Services.File); Assert.NotNull(account.Encryption.Services.File.Enabled); Assert.NotNull(account.Encryption.Services.File.LastEnabledTime); if (null != account.Encryption.Services.Table) { if (account.Encryption.Services.Table.Enabled.HasValue) { Assert.False(account.Encryption.Services.Table.LastEnabledTime.HasValue); } } if (null != account.Encryption.Services.Queue) { if (account.Encryption.Services.Queue.Enabled.HasValue) { Assert.False(account.Encryption.Services.Queue.LastEnabledTime.HasValue); } } } [RecordedTest] public async Task StorageAccountCreateWithAccessTierTest() { //Create resource group string rgname = await CreateResourceGroupAsync(); string accountName = Recording.GenerateAssetName("sto"); string accountName1 = Recording.GenerateAssetName("sto"); //Create storage account StorageAccountCreateParameters parameters = GetDefaultStorageAccountParameters(kind: Kind.BlobStorage); parameters.AccessTier = AccessTier.Hot; StorageAccount account = await _CreateStorageAccountAsync(rgname, accountName, parameters); VerifyAccountProperties(account, false); Assert.AreEqual(AccessTier.Hot, account.AccessTier); Assert.AreEqual(Kind.BlobStorage, account.Kind); //Create storage account with cool parameters = GetDefaultStorageAccountParameters(kind: Kind.BlobStorage); parameters.AccessTier = AccessTier.Cool; account = await _CreateStorageAccountAsync(rgname, accountName1, parameters); VerifyAccountProperties(account, false); Assert.AreEqual(AccessTier.Cool, account.AccessTier); Assert.AreEqual(Kind.BlobStorage, account.Kind); } [RecordedTest] public async Task StorageAccountBeginCreateTest() { //Create resource group string rgname = await CreateResourceGroupAsync(); string accountName = Recording.GenerateAssetName("sto"); //Create storage account await _CreateStorageAccountAsync(rgname, accountName); } [RecordedTest] public async Task StorageAccountDeleteTest() { //Create resource group string rgname = await CreateResourceGroupAsync(); //Delete an account which does not exist await DeleteStorageAccountAsync(rgname, "missingaccount"); //Create storage account string accountName = await CreateStorageAccount(AccountsClient, rgname, Recording); //Delete an account await DeleteStorageAccountAsync(rgname, accountName); //Delete an account which was just deleted await DeleteStorageAccountAsync(rgname, accountName); } [RecordedTest] public async Task StorageAccountGetStandardTest() { //Create resource group string rgname = await CreateResourceGroupAsync(); string accountName = Recording.GenerateAssetName("sto"); string accountName1 = Recording.GenerateAssetName("sto"); string accountName2 = Recording.GenerateAssetName("sto"); string accountName3 = Recording.GenerateAssetName("sto"); // Create and get a LRS storage account StorageAccountCreateParameters parameters = GetDefaultStorageAccountParameters(sku: new Sku(SkuName.StandardLRS)); await _CreateStorageAccountAsync(rgname, accountName, parameters); StorageAccount account = await WaitToGetAccountSuccessfullyAsync(rgname, accountName); VerifyAccountProperties(account, false); // Create and get a GRS storage account parameters = GetDefaultStorageAccountParameters(sku: new Sku(SkuName.StandardGRS)); await _CreateStorageAccountAsync(rgname, accountName1, parameters); account = await WaitToGetAccountSuccessfullyAsync(rgname, accountName1); VerifyAccountProperties(account, true); // Create and get a RAGRS storage account parameters = GetDefaultStorageAccountParameters(sku: new Sku(SkuName.StandardRagrs)); await _CreateStorageAccountAsync(rgname, accountName2, parameters); account = await WaitToGetAccountSuccessfullyAsync(rgname, accountName2); VerifyAccountProperties(account, false); // Create and get a ZRS storage account parameters = GetDefaultStorageAccountParameters(sku: new Sku(SkuName.StandardZRS)); await _CreateStorageAccountAsync(rgname, accountName3, parameters); account = await WaitToGetAccountSuccessfullyAsync(rgname, accountName3); VerifyAccountProperties(account, false); } [RecordedTest] public async Task StorageAccountGetBlobTest() { //Create resource group string rgname = await CreateResourceGroupAsync(); string accountName = Recording.GenerateAssetName("sto"); string accountName1 = Recording.GenerateAssetName("sto"); string accountName2 = Recording.GenerateAssetName("sto"); // Create and get a blob LRS storage account StorageAccountCreateParameters parameters = GetDefaultStorageAccountParameters(sku: new Sku(SkuName.StandardLRS), kind: Kind.BlobStorage); parameters.AccessTier = AccessTier.Hot; await _CreateStorageAccountAsync(rgname, accountName, parameters); StorageAccount account = await WaitToGetAccountSuccessfullyAsync(rgname, accountName); VerifyAccountProperties(account, false); // Create and get a blob GRS storage account parameters = GetDefaultStorageAccountParameters(sku: new Sku(SkuName.StandardGRS), kind: Kind.BlobStorage); parameters.AccessTier = AccessTier.Hot; await _CreateStorageAccountAsync(rgname, accountName1, parameters); account = await WaitToGetAccountSuccessfullyAsync(rgname, accountName1); VerifyAccountProperties(account, false); // Create and get a blob RAGRS storage account parameters = GetDefaultStorageAccountParameters(sku: new Sku(SkuName.StandardRagrs), kind: Kind.BlobStorage); parameters.AccessTier = AccessTier.Hot; await _CreateStorageAccountAsync(rgname, accountName2, parameters); account = await WaitToGetAccountSuccessfullyAsync(rgname, accountName2); VerifyAccountProperties(account, false); } [RecordedTest] public async Task StorageAccountGetPremiumTest() { //Create resource group string rgname = await CreateResourceGroupAsync(); string accountName = Recording.GenerateAssetName("sto"); // Create and get a Premium LRS storage account StorageAccountCreateParameters parameters = GetDefaultStorageAccountParameters(sku: new Sku(SkuName.StandardLRS), kind: Kind.BlobStorage); parameters.AccessTier = AccessTier.Hot; await _CreateStorageAccountAsync(rgname, accountName, parameters); StorageAccount account = await WaitToGetAccountSuccessfullyAsync(rgname, accountName); VerifyAccountProperties(account, false); } [RecordedTest] public async Task StorageAccountListByResourceGroupTest() { //Create resource group string rgname = await CreateResourceGroupAsync(); //List by resource group AsyncPageable<StorageAccount> accountlistAP = AccountsClient.ListByResourceGroupAsync(rgname); List<StorageAccount> accountlist = await accountlistAP.ToEnumerableAsync(); Assert.False(accountlist.Any()); // Create storage accounts string accountName1 = await CreateStorageAccount(AccountsClient, rgname, Recording); string accountName2 = await CreateStorageAccount(AccountsClient, rgname, Recording); accountlistAP = AccountsClient.ListByResourceGroupAsync(rgname); accountlist = await accountlistAP.ToEnumerableAsync(); Assert.AreEqual(2, accountlist.Count()); foreach (StorageAccount account in accountlist) { VerifyAccountProperties(account, true); } } [RecordedTest] public async Task StorageAccountListWithEncryptionTest() { //Create resource group string rgname = await CreateResourceGroupAsync(); string accountName = Recording.GenerateAssetName("sto"); // Create storage account StorageAccountCreateParameters parameters = GetDefaultStorageAccountParameters(); parameters.Encryption = new Encryption(KeySource.MicrosoftStorage) { Services = new EncryptionServices { Blob = new EncryptionService { Enabled = true }, File = new EncryptionService { Enabled = true } } }; await _CreateStorageAccountAsync(rgname, accountName, parameters); // List account and verify AsyncPageable<StorageAccount> accounts = AccountsClient.ListByResourceGroupAsync(rgname); List<StorageAccount> accountlist = await accounts.ToEnumerableAsync(); Assert.AreEqual(1, accountlist.Count()); StorageAccount account = accountlist.ToArray()[0]; VerifyAccountProperties(account, true); Assert.NotNull(account.Encryption); Assert.NotNull(account.Encryption.Services.Blob); Assert.True(account.Encryption.Services.Blob.Enabled); Assert.NotNull(account.Encryption.Services.Blob.LastEnabledTime); Assert.NotNull(account.Encryption.Services.File); Assert.True(account.Encryption.Services.File.Enabled); Assert.NotNull(account.Encryption.Services.File.LastEnabledTime); if (null != account.Encryption.Services.Table) { if (account.Encryption.Services.Table.Enabled.HasValue) { Assert.False(account.Encryption.Services.Table.LastEnabledTime.HasValue); } } if (null != account.Encryption.Services.Queue) { if (account.Encryption.Services.Queue.Enabled.HasValue) { Assert.False(account.Encryption.Services.Queue.LastEnabledTime.HasValue); } } } [RecordedTest] public async Task StorageAccountListBySubscriptionTest() { // Create resource group and storage account string rgname1 = await CreateResourceGroupAsync(); string accountName1 = await CreateStorageAccount(AccountsClient, rgname1, Recording); // Create different resource group and storage account string rgname2 = await CreateResourceGroupAsync(); string accountName2 = await CreateStorageAccount(AccountsClient, rgname2, Recording); AsyncPageable<StorageAccount> accountlist = AccountsClient.ListAsync(); List<StorageAccount> accountlists = accountlist.ToEnumerableAsync().Result; StorageAccount account1 = accountlists.First( t => StringComparer.OrdinalIgnoreCase.Equals(t.Name, accountName1)); VerifyAccountProperties(account1, true); StorageAccount account2 = accountlists.First( t => StringComparer.OrdinalIgnoreCase.Equals(t.Name, accountName2)); VerifyAccountProperties(account2, true); } [RecordedTest] public async Task StorageAccountListKeysTest() { //Create resource group string rgname = await CreateResourceGroupAsync(); // Create storage account string accountName = await CreateStorageAccount(AccountsClient, rgname, Recording); // List keys Response<StorageAccountListKeysResult> keys = await AccountsClient.ListKeysAsync(rgname, accountName); Assert.NotNull(keys); // Validate Key1 StorageAccountKey key1 = keys.Value.Keys.First( t => StringComparer.OrdinalIgnoreCase.Equals(t.KeyName, "key1")); Assert.NotNull(key1); Assert.AreEqual(KeyPermission.Full, key1.Permissions); Assert.NotNull(key1.Value); // Validate Key2 StorageAccountKey key2 = keys.Value.Keys.First( t => StringComparer.OrdinalIgnoreCase.Equals(t.KeyName, "key2")); Assert.NotNull(key2); Assert.AreEqual(KeyPermission.Full, key2.Permissions); Assert.NotNull(key2.Value); } [RecordedTest] public async Task StorageAccountRegenerateKeyTest() { //Create resource group string rgname = await CreateResourceGroupAsync(); // Create storage account string accountName = await CreateStorageAccount(AccountsClient, rgname, Recording); // List keys Response<StorageAccountListKeysResult> keys = await AccountsClient.ListKeysAsync(rgname, accountName); Assert.NotNull(keys); StorageAccountKey key2 = keys.Value.Keys.First( t => StringComparer.OrdinalIgnoreCase.Equals(t.KeyName, "key2")); Assert.NotNull(key2); // Regenerate keys and verify that keys change StorageAccountRegenerateKeyParameters keyParameters = new StorageAccountRegenerateKeyParameters("key2"); Response<StorageAccountListKeysResult> regenKeys = await AccountsClient.RegenerateKeyAsync(rgname, accountName, keyParameters); StorageAccountKey key2Regen = regenKeys.Value.Keys.First( t => StringComparer.OrdinalIgnoreCase.Equals(t.KeyName, "key2")); Assert.NotNull(key2Regen); // Validate key was regenerated Assert.AreNotEqual(key2.Value, key2Regen.Value); } [RecordedTest] public async Task StorageAccountRevokeUserDelegationKeysTest() { //Create resource group string rgname = await CreateResourceGroupAsync(); // Create storage account string accountName = await CreateStorageAccount(AccountsClient, rgname, Recording); // Revoke User DelegationKeys await AccountsClient.RevokeUserDelegationKeysAsync(rgname, accountName); } [RecordedTest] public async Task StorageAccountCheckNameTest() { //Create resource group string rgname = await CreateResourceGroupAsync(); string accountName = Recording.GenerateAssetName("sto"); // Check valid name StorageAccountCheckNameAvailabilityParameters storageAccountCheckNameAvailabilityParameters = new StorageAccountCheckNameAvailabilityParameters(accountName); Response<CheckNameAvailabilityResult> checkNameRequest = await AccountsClient.CheckNameAvailabilityAsync(storageAccountCheckNameAvailabilityParameters); Assert.True(checkNameRequest.Value.NameAvailable); Assert.Null(checkNameRequest.Value.Reason); Assert.Null(checkNameRequest.Value.Message); // Check invalid name storageAccountCheckNameAvailabilityParameters = new StorageAccountCheckNameAvailabilityParameters("CAPS"); checkNameRequest = await AccountsClient.CheckNameAvailabilityAsync(storageAccountCheckNameAvailabilityParameters); Assert.False(checkNameRequest.Value.NameAvailable); Assert.AreEqual(Reason.AccountNameInvalid, checkNameRequest.Value.Reason); Assert.AreEqual("CAPS is not a valid storage account name. Storage account name must be between 3 and 24 " + "characters in length and use numbers and lower-case letters only.", checkNameRequest.Value.Message); // Check name of account that already exists string accountName1 = await CreateStorageAccount(AccountsClient, rgname, Recording); storageAccountCheckNameAvailabilityParameters = new StorageAccountCheckNameAvailabilityParameters(accountName1); checkNameRequest = await AccountsClient.CheckNameAvailabilityAsync(storageAccountCheckNameAvailabilityParameters); Assert.False(checkNameRequest.Value.NameAvailable); Assert.AreEqual(Reason.AlreadyExists, checkNameRequest.Value.Reason); Assert.AreEqual("The storage account named " + accountName1 + " is already taken.", checkNameRequest.Value.Message); } [RecordedTest] public async Task StorageAccountUpdateWithCreateTest() { //Create resource group string rgname = await CreateResourceGroupAsync(); // Create storage account string accountName = await CreateStorageAccount(AccountsClient, rgname, Recording); // Update storage account type StorageAccountCreateParameters parameters = GetDefaultStorageAccountParameters(sku: new Sku(SkuName.StandardLRS)); StorageAccount account = await _CreateStorageAccountAsync(rgname, accountName, parameters); Assert.AreEqual(SkuName.StandardLRS, account.Sku.Name); // Validate Response<StorageAccount> accountProerties = await WaitToGetAccountSuccessfullyAsync(rgname, accountName); Assert.AreEqual(SkuName.StandardLRS, accountProerties.Value.Sku.Name); // Update storage tags // Update storage tags parameters.Tags.Clear(); parameters.Tags.Add("key3", "value3"); parameters.Tags.Add("key4", "value4"); parameters.Tags.Add("key5", "value6"); account = await _CreateStorageAccountAsync(rgname, accountName, parameters); Assert.AreEqual(account.Tags.Count, parameters.Tags.Count); // Validate accountProerties = await WaitToGetAccountSuccessfullyAsync(rgname, accountName); Assert.AreEqual(accountProerties.Value.Tags.Count, parameters.Tags.Count); // Update storage encryption parameters.Encryption = new Encryption(KeySource.MicrosoftStorage) { Services = new EncryptionServices { Blob = new EncryptionService { Enabled = true }, File = new EncryptionService { Enabled = true } } }; account = await _CreateStorageAccountAsync(rgname, accountName, parameters); Assert.NotNull(account.Encryption); // Validate accountProerties = await WaitToGetAccountSuccessfullyAsync(rgname, accountName); Assert.NotNull(accountProerties.Value.Encryption); Assert.NotNull(accountProerties.Value.Encryption.Services.Blob); Assert.True(accountProerties.Value.Encryption.Services.Blob.Enabled); Assert.NotNull(accountProerties.Value.Encryption.Services.Blob.LastEnabledTime); Assert.NotNull(accountProerties.Value.Encryption.Services.File); Assert.True(accountProerties.Value.Encryption.Services.File.Enabled); Assert.NotNull(accountProerties.Value.Encryption.Services.File.LastEnabledTime); if (null != accountProerties.Value.Encryption.Services.Table) { if (accountProerties.Value.Encryption.Services.Table.Enabled.HasValue) { Assert.False(accountProerties.Value.Encryption.Services.Table.LastEnabledTime.HasValue); } } if (null != accountProerties.Value.Encryption.Services.Queue) { if (accountProerties.Value.Encryption.Services.Queue.Enabled.HasValue) { Assert.False(accountProerties.Value.Encryption.Services.Queue.LastEnabledTime.HasValue); } } // Update storage custom domains parameters = GetDefaultStorageAccountParameters(); parameters.CustomDomain = new CustomDomain("foo.example.com") { UseSubDomainName = true }; try { await AccountsClient.StartCreateAsync(rgname, accountName, parameters); Assert.True(false, "This request should fail with the below code."); } catch (RequestFailedException ex) { Assert.AreEqual((int)HttpStatusCode.Conflict, ex.Status); Assert.True(ex.Message != null && ex.Message.Contains("The custom domain name could not be verified. CNAME mapping from foo.example.com to")); } } [RecordedTest] public async Task StorageAccountUpdateTest() { //Create resource group string rgname = await CreateResourceGroupAsync(); // Create storage account string accountName = await CreateStorageAccount(AccountsClient, rgname, Recording); // Update storage account type StorageAccountUpdateParameters parameters = new StorageAccountUpdateParameters() { Sku = new Sku(SkuName.StandardLRS), }; StorageAccount account = await UpdateStorageAccountAsync(rgname, accountName, parameters); Assert.AreEqual(SkuName.StandardLRS, account.Sku.Name); // Validate Response<StorageAccount> accountProerties = await WaitToGetAccountSuccessfullyAsync(rgname, accountName); Assert.AreEqual(SkuName.StandardLRS, accountProerties.Value.Sku.Name); // Update storage tags parameters.Tags.Clear(); parameters.Tags.Add("key3", "value3"); parameters.Tags.Add("key4", "value4"); parameters.Tags.Add("key5", "value6"); account = await UpdateStorageAccountAsync(rgname, accountName, parameters); Assert.AreEqual(account.Tags.Count, parameters.Tags.Count); // Validate accountProerties = await WaitToGetAccountSuccessfullyAsync(rgname, accountName); Assert.AreEqual(accountProerties.Value.Tags.Count, parameters.Tags.Count); // Update storage encryption parameters.Encryption = new Encryption(KeySource.MicrosoftStorage) { Services = new EncryptionServices { Blob = new EncryptionService { Enabled = true }, File = new EncryptionService { Enabled = true } } }; account = await UpdateStorageAccountAsync(rgname, accountName, parameters); Assert.NotNull(account.Encryption); // Validate accountProerties = await WaitToGetAccountSuccessfullyAsync(rgname, accountName); Assert.NotNull(accountProerties.Value.Encryption); Assert.NotNull(accountProerties.Value.Encryption.Services.Blob); Assert.True(accountProerties.Value.Encryption.Services.Blob.Enabled); Assert.NotNull(accountProerties.Value.Encryption.Services.Blob.LastEnabledTime); Assert.NotNull(accountProerties.Value.Encryption.Services.File); Assert.True(accountProerties.Value.Encryption.Services.File.Enabled); Assert.NotNull(accountProerties.Value.Encryption.Services.File.LastEnabledTime); if (null != accountProerties.Value.Encryption.Services.Table) { if (accountProerties.Value.Encryption.Services.Table.Enabled.HasValue) { Assert.False(accountProerties.Value.Encryption.Services.Table.LastEnabledTime.HasValue); } } if (null != accountProerties.Value.Encryption.Services.Queue) { if (accountProerties.Value.Encryption.Services.Queue.Enabled.HasValue) { Assert.False(accountProerties.Value.Encryption.Services.Queue.LastEnabledTime.HasValue); } } // Update storage custom domains parameters = new StorageAccountUpdateParameters { CustomDomain = new CustomDomain("foo.example.com") { UseSubDomainName = true } }; try { await UpdateStorageAccountAsync(rgname, accountName, parameters); Assert.True(false, "This request should fail with the below code."); } catch (RequestFailedException ex) { Assert.AreEqual((int)HttpStatusCode.Conflict, ex.Status); Assert.True(ex.Message != null && ex.Message.Contains("The custom domain name could not be verified. CNAME mapping from foo.example.com to")); } } [RecordedTest] public async Task StorageAccountUpdateMultipleTest() { //Create resource group string rgname = await CreateResourceGroupAsync(); // Create storage account string accountName = await CreateStorageAccount(AccountsClient, rgname, Recording); // Update storage account type StorageAccountUpdateParameters parameters = new StorageAccountUpdateParameters() { Sku = new Sku(SkuName.StandardLRS), Tags = { { "key3", "value3" }, { "key4", "value4" }, { "key5", "value6" } } }; StorageAccount account = await UpdateStorageAccountAsync(rgname, accountName, parameters); Assert.AreEqual(SkuName.StandardLRS, account.Sku.Name); Assert.AreEqual(account.Tags.Count, parameters.Tags.Count); // Validate Response<StorageAccount> accountProerties = await WaitToGetAccountSuccessfullyAsync(rgname, accountName); Assert.AreEqual(SkuName.StandardLRS, accountProerties.Value.Sku.Name); Assert.AreEqual(accountProerties.Value.Tags.Count, parameters.Tags.Count); } [RecordedTest] public async Task StorageAccountLocationUsageTest() { // Query usage string Location = DefaultLocation; AsyncPageable<Usage> usages = UsagesClient.ListByLocationAsync(Location); List<Usage> usagelist = await usages.ToEnumerableAsync(); Assert.AreEqual(1, usagelist.Count()); Assert.AreEqual(UsageUnit.Count, usagelist.First().Unit); Assert.NotNull(usagelist.First().CurrentValue); Assert.AreEqual(250, usagelist.First().Limit); Assert.NotNull(usagelist.First().Name); Assert.AreEqual("StorageAccounts", usagelist.First().Name.Value); Assert.AreEqual("Storage Accounts", usagelist.First().Name.LocalizedValue); } [RecordedTest] [Ignore("Track2: The function of 'ResourceProviderOperationDetails' is not found in trach2 Management.Resource")] public void StorageAccountGetOperationsTest() { //var handler = new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }; //using (MockContext context = MockContext.Start(this.GetType())) //{ // var resourcesClient = GetResourceManagementClient(context, handler); // var ops = resourcesClient.ResourceProviderOperationDetails.List("Microsoft.Storage", "2015-06-15"); // Assert.True(ops.Count() > 1); //} } [RecordedTest] public async Task StorageAccountListAccountSASTest() { //Create resource group string rgname = await CreateResourceGroupAsync(); string accountName = Recording.GenerateAssetName("sto"); // Create storage account await _CreateStorageAccountAsync(rgname, accountName); AccountSasParameters accountSasParameters = new AccountSasParameters(services: "bftq", resourceTypes: "sco", permissions: "rdwlacup", sharedAccessExpiryTime: Recording.UtcNow.AddHours(1)) { Protocols = HttpProtocol.HttpsHttp, SharedAccessStartTime = Recording.UtcNow, KeyToSign = "key1" }; Response<ListAccountSasResponse> result = await AccountsClient.ListAccountSASAsync(rgname, accountName, accountSasParameters); AccountSasParameters resultCredentials = ParseAccountSASToken(result.Value.AccountSasToken); Assert.AreEqual(accountSasParameters.Services, resultCredentials.Services); Assert.AreEqual(accountSasParameters.ResourceTypes, resultCredentials.ResourceTypes); Assert.AreEqual(accountSasParameters.Permissions, resultCredentials.Permissions); Assert.AreEqual(accountSasParameters.Protocols, resultCredentials.Protocols); Assert.NotNull(accountSasParameters.SharedAccessStartTime); Assert.NotNull(accountSasParameters.SharedAccessExpiryTime); } [RecordedTest] public async Task StorageAccountListAccountSASWithDefaultProperties() { //Create resource group string rgname = await CreateResourceGroupAsync(); string accountName = Recording.GenerateAssetName("sto"); // Create storage account await _CreateStorageAccountAsync(rgname, accountName); // Test for default values of sas credentials. AccountSasParameters accountSasParameters = new AccountSasParameters(services: "b", resourceTypes: "sco", permissions: "rl", sharedAccessExpiryTime: Recording.UtcNow.AddHours(1)); Response<ListAccountSasResponse> result = await AccountsClient.ListAccountSASAsync(rgname, accountName, accountSasParameters); AccountSasParameters resultCredentials = ParseAccountSASToken(result.Value.AccountSasToken); Assert.AreEqual(accountSasParameters.Services, resultCredentials.Services); Assert.AreEqual(accountSasParameters.ResourceTypes, resultCredentials.ResourceTypes); Assert.AreEqual(accountSasParameters.Permissions, resultCredentials.Permissions); Assert.NotNull(accountSasParameters.SharedAccessExpiryTime); } [RecordedTest] public async Task StorageAccountListAccountSASWithMissingProperties() { //Create resource group string rgname = await CreateResourceGroupAsync(); string accountName = Recording.GenerateAssetName("sto"); // Create storage account await _CreateStorageAccountAsync(rgname, accountName); // Test for default values of sas credentials. AccountSasParameters accountSasParameters = new AccountSasParameters(services: "b", resourceTypes: "sco", permissions: "rl", sharedAccessExpiryTime: Recording.UtcNow.AddHours(-1)); try { Response<ListAccountSasResponse> result = await AccountsClient.ListAccountSASAsync(rgname, accountName, accountSasParameters); AccountSasParameters resultCredentials = ParseAccountSASToken(result.Value.AccountSasToken); } catch (Exception ex) { Assert.True(ex.Message != null && ex.Message.Contains("Values for request parameters are invalid: signedExpiry.")); return; } throw new Exception("AccountSasToken shouldn't be returned without SharedAccessExpiryTime"); } [RecordedTest] public async Task StorageAccountListServiceSASTest() { //Create resource group string rgname = await CreateResourceGroupAsync(); string accountName = Recording.GenerateAssetName("sto"); // Create storage account await _CreateStorageAccountAsync(rgname, accountName); string canonicalizedResourceParameter = "/blob/" + accountName + "/music"; ServiceSasParameters serviceSasParameters = new ServiceSasParameters(canonicalizedResource: canonicalizedResourceParameter) { Resource = "c", Permissions = "rdwlacup", Protocols = HttpProtocol.HttpsHttp, SharedAccessStartTime = Recording.UtcNow, SharedAccessExpiryTime = Recording.UtcNow.AddHours(1), KeyToSign = "key1" }; Task<Response<ListServiceSasResponse>> result = AccountsClient.ListServiceSASAsync(rgname, accountName, serviceSasParameters); ServiceSasParameters resultCredentials = ParseServiceSASToken(result.Result.Value.ServiceSasToken, canonicalizedResourceParameter); Assert.AreEqual(serviceSasParameters.Resource, resultCredentials.Resource); Assert.AreEqual(serviceSasParameters.Permissions, resultCredentials.Permissions); Assert.AreEqual(serviceSasParameters.Protocols, resultCredentials.Protocols); Assert.NotNull(serviceSasParameters.SharedAccessStartTime); Assert.NotNull(serviceSasParameters.SharedAccessExpiryTime); } [RecordedTest] public async Task StorageAccountListServiceSASWithDefaultProperties() { //Create resource group string rgname = await CreateResourceGroupAsync(); string accountName = Recording.GenerateAssetName("sto"); // Create storage account await _CreateStorageAccountAsync(rgname, accountName); // Test for default values of sas credentials. string canonicalizedResourceParameter = "/blob/" + accountName + "/music"; ServiceSasParameters serviceSasParameters = new ServiceSasParameters(canonicalizedResource: canonicalizedResourceParameter) { Resource = "c", Permissions = "rl", SharedAccessExpiryTime = Recording.UtcNow.AddHours(1), }; Response<ListServiceSasResponse> result = await AccountsClient.ListServiceSASAsync(rgname, accountName, serviceSasParameters); ServiceSasParameters resultCredentials = ParseServiceSASToken(result.Value.ServiceSasToken, canonicalizedResourceParameter); Assert.AreEqual(serviceSasParameters.Resource, resultCredentials.Resource); Assert.AreEqual(serviceSasParameters.Permissions, resultCredentials.Permissions); Assert.NotNull(serviceSasParameters.SharedAccessExpiryTime); } [RecordedTest] public async Task StorageAccountListServiceSASWithMissingProperties() { //Create resource group string rgname = await CreateResourceGroupAsync(); string accountName = Recording.GenerateAssetName("sto"); // Create storage account await _CreateStorageAccountAsync(rgname, accountName); // Test for default values of sas credentials. string canonicalizedResourceParameter = "/blob/" + accountName + "/music"; ServiceSasParameters serviceSasParameters = new ServiceSasParameters(canonicalizedResource: canonicalizedResourceParameter) { Resource = "b", Permissions = "rl" }; try { Response<ListServiceSasResponse> result = await AccountsClient.ListServiceSASAsync(rgname, accountName, serviceSasParameters); ServiceSasParameters resultCredentials = ParseServiceSASToken(result.Value.ServiceSasToken, canonicalizedResourceParameter); } catch (RequestFailedException ex) { Assert.True(ex.Message != null && ex.Message.Contains("Values for request parameters are invalid: signedExpiry.")); return; } throw new Exception("AccountSasToken shouldn't be returned without SharedAccessExpiryTime"); } [RecordedTest] public async Task StorageAccountUpdateEncryptionTest() { //Create resource group string rgname = await CreateResourceGroupAsync(); // Create storage account string accountName = await CreateStorageAccount(AccountsClient, rgname, Recording); // Update storage account type StorageAccountUpdateParameters parameters = new StorageAccountUpdateParameters { Sku = new Sku(SkuName.StandardLRS) }; StorageAccount account = await UpdateStorageAccountAsync(rgname, accountName, parameters); Assert.AreEqual(SkuName.StandardLRS, account.Sku.Name); // Validate account = await WaitToGetAccountSuccessfullyAsync(rgname, accountName); Assert.AreEqual(SkuName.StandardLRS, account.Sku.Name); // Update storage tags parameters = new StorageAccountUpdateParameters { Tags = { {"key3","value3"}, {"key4","value4"}, {"key5","value6"} } }; account = await UpdateStorageAccountAsync(rgname, accountName, parameters); Assert.AreEqual(account.Tags.Count, parameters.Tags.Count); // Validate account = await WaitToGetAccountSuccessfullyAsync(rgname, accountName); Assert.AreEqual(account.Tags.Count, parameters.Tags.Count); // 1. Update storage encryption parameters = new StorageAccountUpdateParameters { Encryption = new Encryption(keySource: KeySource.MicrosoftStorage) { Services = new EncryptionServices { Blob = new EncryptionService { Enabled = true }, File = new EncryptionService { Enabled = true } } } }; account = await UpdateStorageAccountAsync(rgname, accountName, parameters); Assert.NotNull(account.Encryption); // Validate account = await WaitToGetAccountSuccessfullyAsync(rgname, accountName); Assert.NotNull(account.Encryption); Assert.NotNull(account.Encryption.Services.Blob); Assert.True(account.Encryption.Services.Blob.Enabled); Assert.NotNull(account.Encryption.Services.Blob.LastEnabledTime); Assert.NotNull(account.Encryption.Services.File); Assert.True(account.Encryption.Services.File.Enabled); Assert.NotNull(account.Encryption.Services.File.LastEnabledTime); // 2. Restore storage encryption parameters = new StorageAccountUpdateParameters { Encryption = new Encryption(keySource: KeySource.MicrosoftStorage) { Services = new EncryptionServices { Blob = new EncryptionService { Enabled = true }, File = new EncryptionService { Enabled = true } } } }; account = await UpdateStorageAccountAsync(rgname, accountName, parameters); Assert.NotNull(account.Encryption); // Validate account = await WaitToGetAccountSuccessfullyAsync(rgname, accountName); Assert.NotNull(account.Encryption); Assert.NotNull(account.Encryption.Services.Blob); Assert.True(account.Encryption.Services.Blob.Enabled); Assert.NotNull(account.Encryption.Services.Blob.LastEnabledTime); Assert.NotNull(account.Encryption.Services.File); Assert.True(account.Encryption.Services.File.Enabled); Assert.NotNull(account.Encryption.Services.File.LastEnabledTime); // 3. Remove file encryption service field. parameters = new StorageAccountUpdateParameters { Encryption = new Encryption(keySource: KeySource.MicrosoftStorage) { Services = new EncryptionServices { Blob = new EncryptionService { Enabled = true } } } }; account = await UpdateStorageAccountAsync(rgname, accountName, parameters); Assert.NotNull(account.Encryption); // Validate account = await WaitToGetAccountSuccessfullyAsync(rgname, accountName); Assert.NotNull(account.Encryption); Assert.NotNull(account.Encryption.Services.Blob); Assert.True(account.Encryption.Services.Blob.Enabled); Assert.NotNull(account.Encryption.Services.Blob.LastEnabledTime); Assert.NotNull(account.Encryption.Services.File); Assert.True(account.Encryption.Services.File.Enabled); Assert.NotNull(account.Encryption.Services.File.LastEnabledTime); } [RecordedTest] public async Task StorageAccountUpdateWithHttpsOnlyTest() { //Create resource group string rgname = await CreateResourceGroupAsync(); string accountName = Recording.GenerateAssetName("sto"); // Create storage account with hot StorageAccountCreateParameters parameters = GetDefaultStorageAccountParameters(); parameters.EnableHttpsTrafficOnly = false; StorageAccount account = await _CreateStorageAccountAsync(rgname, accountName, parameters); VerifyAccountProperties(account, false); Assert.False(account.EnableHttpsTrafficOnly); //Update storage account StorageAccountUpdateParameters parameter = new StorageAccountUpdateParameters { EnableHttpsTrafficOnly = true }; account = await UpdateStorageAccountAsync(rgname, accountName, parameter); VerifyAccountProperties(account, false); Assert.True(account.EnableHttpsTrafficOnly); //Update storage account parameter = new StorageAccountUpdateParameters { EnableHttpsTrafficOnly = false }; account = await UpdateStorageAccountAsync(rgname, accountName, parameter); VerifyAccountProperties(account, false); Assert.False(account.EnableHttpsTrafficOnly); } [RecordedTest] public async Task StorageAccountCreateWithHttpsOnlyTest() { //Create resource group string rgname = await CreateResourceGroupAsync(); string accountName = Recording.GenerateAssetName("sto"); string accountName1 = Recording.GenerateAssetName("sto"); // Create storage account with hot StorageAccountCreateParameters parameters = GetDefaultStorageAccountParameters(); parameters.EnableHttpsTrafficOnly = true; StorageAccount account = await _CreateStorageAccountAsync(rgname, accountName, parameters); VerifyAccountProperties(account, false); Assert.True(account.EnableHttpsTrafficOnly); // Create storage account with cool parameters.EnableHttpsTrafficOnly = false; account = await _CreateStorageAccountAsync(rgname, accountName1, parameters); VerifyAccountProperties(account, false); Assert.False(account.EnableHttpsTrafficOnly); } [RecordedTest] [Ignore("Track2: Need KeyVaultManagementClient")] public void StorageAccountCMKTest() { //var handler = new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }; //using (MockContext context = MockContext.Start(this.GetType())) //{ // var resourcesClient = GetResourceManagementClient(context, handler); // var storageMgmtClient = GetStorageManagementClient(context, handler); // var keyVaultMgmtClient = GetKeyVaultManagementClient(context, handler); // var keyVaultClient = CreateKeyVaultClient(); // string accountName = TestUtilities.GenerateName("sto"); // var rgname = CreateResourceGroup(resourcesClient); // string vaultName = TestUtilities.GenerateName("keyvault"); // string keyName = TestUtilities.GenerateName("keyvaultkey"); // var parameters = GetDefaultStorageAccountParameters(); // parameters.Location = "centraluseuap"; // parameters.Identity = new Identity { }; // var account = storageMgmtClient.StorageAccounts.Create(rgname, accountName, parameters); // VerifyAccountProperties(account, false); // Assert.NotNull(account.Identity); // var accessPolicies = new List<Microsoft.Azure.Management.KeyVault.Models.AccessPolicyEntry>(); // accessPolicies.Add(new Microsoft.Azure.Management.KeyVault.Models.AccessPolicyEntry // { // TenantId = System.Guid.Parse(account.Identity.TenantId), // ObjectId = account.Identity.PrincipalId, // Permissions = new Microsoft.Azure.Management.KeyVault.Models.Permissions(new List<string> { "wrapkey", "unwrapkey" }) // }); // string servicePrincipalObjectId = GetServicePrincipalObjectId(); // accessPolicies.Add(new Microsoft.Azure.Management.KeyVault.Models.AccessPolicyEntry // { // TenantId = System.Guid.Parse(account.Identity.TenantId), // ObjectId = servicePrincipalObjectId, // Permissions = new Microsoft.Azure.Management.KeyVault.Models.Permissions(new List<string> { "all" }) // }); // var keyVault = keyVaultMgmtClient.Vaults.CreateOrUpdate(rgname, vaultName, new Microsoft.Azure.Management.KeyVault.Models.VaultCreateOrUpdateParameters // { // Location = account.Location, // Properties = new Microsoft.Azure.Management.KeyVault.Models.VaultProperties // { // TenantId = System.Guid.Parse(account.Identity.TenantId), // AccessPolicies = accessPolicies, // Sku = new Microsoft.Azure.Management.KeyVault.Models.Sku(Microsoft.Azure.Management.KeyVault.Models.SkuName.Standard), // EnabledForDiskEncryption = false, // EnabledForDeployment = false, // EnabledForTemplateDeployment = false // } // }); // var keyVaultKey = keyVaultClient.CreateKeyAsync(keyVault.Properties.VaultUri, keyName, JsonWebKeyType.Rsa, 2048, // JsonWebKeyOperation.AllOperations, new Microsoft.Azure.KeyVault.Models.KeyAttributes()).GetAwaiter().GetResult(); // // Enable encryption. // var updateParameters = new StorageAccountUpdateParameters // { // Encryption = new Encryption // { // Services = new EncryptionServices { Blob = new EncryptionService { Enabled = true }, File = new EncryptionService { Enabled = true } }, // KeySource = "Microsoft.Keyvault", // KeyVaultProperties = // new KeyVaultProperties // { // KeyName = keyVaultKey.KeyIdentifier.Name, // KeyVaultUri = keyVault.Properties.VaultUri, // KeyVersion = keyVaultKey.KeyIdentifier.Version // } // } // }; // account = storageMgmtClient.StorageAccounts.Update(rgname, accountName, updateParameters); // VerifyAccountProperties(account, false); // Assert.NotNull(account.Encryption); // Assert.True(account.Encryption.Services.Blob.Enabled); // Assert.True(account.Encryption.Services.File.Enabled); // Assert.Equal("Microsoft.Keyvault", account.Encryption.KeySource); // // Disable Encryption. // updateParameters = new StorageAccountUpdateParameters // { // Encryption = new Encryption // { // Services = new EncryptionServices { Blob = new EncryptionService { Enabled = true }, File = new EncryptionService { Enabled = true } }, // KeySource = "Microsoft.Storage" // } // }; // account = storageMgmtClient.StorageAccounts.Update(rgname, accountName, updateParameters); // VerifyAccountProperties(account, false); // Assert.NotNull(account.Encryption); // Assert.True(account.Encryption.Services.Blob.Enabled); // Assert.True(account.Encryption.Services.File.Enabled); // Assert.Equal("Microsoft.Storage", account.Encryption.KeySource); // updateParameters = new StorageAccountUpdateParameters // { // Encryption = new Encryption // { // Services = new EncryptionServices { Blob = new EncryptionService { Enabled = false }, File = new EncryptionService { Enabled = false } }, // KeySource = KeySource.MicrosoftStorage // } // }; // account = storageMgmtClient.StorageAccounts.Update(rgname, accountName, updateParameters); // VerifyAccountProperties(account, false); // Assert.Null(account.Encryption); //} } [RecordedTest] [Ignore("Track2: The constructor of OperationDisplay is internal")] public void StorageAccountOperationsTest() { //var handler = new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }; //using (MockContext context = MockContext.Start(this.GetType())) //{ // var resourcesClient = GetResourceManagementClient(context, handler); // var storageMgmtClient = GetStorageManagementClient(context, handler); // var keyVaultMgmtClient = GetKeyVaultManagementClient(context, handler); // // Create storage account with hot // string accountName = TestUtilities.GenerateName("sto"); // var rgname = CreateResourceGroup(resourcesClient); // var ops = storageMgmtClient.Operations.List(); // var op1 = new Operation // { // Name = "Microsoft.Storage/storageAccounts/write", // Display = new OperationDisplay // { // Provider = "Microsoft Storage", // Resource = "Storage Accounts", // Operation = "Create/Update Storage Account" // } // }; // var op2 = new Operation // { // Name = "Microsoft.Storage/storageAccounts/delete", // Display = new OperationDisplay // { // Provider = "Microsoft Storage", // Resource = "Storage Accounts", // Operation = "Delete Storage Account" // } // }; // bool exists1 = false; // bool exists2 = false; // Assert.NotNull(ops); // Assert.NotNull(ops.GetEnumerator()); // var operation = ops.GetEnumerator(); // while (operation.MoveNext()) // { // if (operation.Current.ToString().Equals(op1.ToString())) // { // exists1 = true; // } // if (operation.Current.ToString().Equals(op2.ToString())) // { // exists2 = true; // } // } // Assert.True(exists1); // Assert.True(exists2); //} } [RecordedTest] public async Task StorageAccountVnetACLTest() { //Create resource group string rgname = await CreateResourceGroupAsync(); string accountName = Recording.GenerateAssetName("sto"); // Create storage account with Vnet StorageAccountCreateParameters parameters = GetDefaultStorageAccountParameters(); parameters.NetworkRuleSet = new NetworkRuleSet(defaultAction: DefaultAction.Deny) { Bypass = @"Logging,AzureServices", IpRules = { new IPRule(iPAddressOrRange: "23.45.67.90") } }; await _CreateStorageAccountAsync(rgname, accountName, parameters); StorageAccount account = await WaitToGetAccountSuccessfullyAsync(rgname, accountName); // Verify the vnet rule properties. Assert.NotNull(account.NetworkRuleSet); Assert.AreEqual(@"Logging, AzureServices", account.NetworkRuleSet.Bypass.ToString()); Assert.AreEqual(DefaultAction.Deny, account.NetworkRuleSet.DefaultAction); Assert.IsEmpty(account.NetworkRuleSet.VirtualNetworkRules); Assert.NotNull(account.NetworkRuleSet.IpRules); Assert.IsNotEmpty(account.NetworkRuleSet.IpRules); Assert.AreEqual("23.45.67.90", account.NetworkRuleSet.IpRules[0].IPAddressOrRange); Assert.AreEqual(DefaultAction.Allow.ToString(), account.NetworkRuleSet.IpRules[0].Action); // Update Vnet StorageAccountUpdateParameters updateParameters = new StorageAccountUpdateParameters { NetworkRuleSet = new NetworkRuleSet(defaultAction: DefaultAction.Deny) { Bypass = @"Logging, Metrics", IpRules ={ new IPRule(iPAddressOrRange:"23.45.67.91") { Action = DefaultAction.Allow.ToString() }, new IPRule(iPAddressOrRange:"23.45.67.92") }, } }; await UpdateStorageAccountAsync(rgname, accountName, updateParameters); account = await WaitToGetAccountSuccessfullyAsync(rgname, accountName); Assert.NotNull(account.NetworkRuleSet); Assert.AreEqual(@"Logging, Metrics", account.NetworkRuleSet.Bypass.ToString()); Assert.AreEqual(DefaultAction.Deny, account.NetworkRuleSet.DefaultAction); Assert.IsEmpty(account.NetworkRuleSet.VirtualNetworkRules); Assert.NotNull(account.NetworkRuleSet.IpRules); Assert.IsNotEmpty(account.NetworkRuleSet.IpRules); Assert.AreEqual("23.45.67.91", account.NetworkRuleSet.IpRules[0].IPAddressOrRange); Assert.AreEqual(DefaultAction.Allow.ToString(), account.NetworkRuleSet.IpRules[0].Action); Assert.AreEqual("23.45.67.92", account.NetworkRuleSet.IpRules[1].IPAddressOrRange); Assert.AreEqual(DefaultAction.Allow.ToString(), account.NetworkRuleSet.IpRules[1].Action); // Delete vnet. updateParameters = new StorageAccountUpdateParameters { NetworkRuleSet = new NetworkRuleSet(DefaultAction.Allow) }; await UpdateStorageAccountAsync(rgname, accountName, updateParameters); account = await WaitToGetAccountSuccessfullyAsync(rgname, accountName); Assert.NotNull(account.NetworkRuleSet); Assert.AreEqual(@"Logging, Metrics", account.NetworkRuleSet.Bypass.ToString()); Assert.AreEqual(DefaultAction.Allow, account.NetworkRuleSet.DefaultAction); } [RecordedTest] public void StorageSKUListTest() { AsyncPageable<SkuInformation> skulist = SkusClient.ListAsync(); Assert.NotNull(skulist); Task<List<SkuInformation>> skuListTask = skulist.ToEnumerableAsync(); Assert.AreEqual(@"storageAccounts", skuListTask.Result.ElementAt(0).ResourceType); Assert.NotNull(skuListTask.Result.ElementAt(0).Name); Assert.True(skuListTask.Result.ElementAt(0).Name.GetType() == SkuName.PremiumLRS.GetType()); Assert.True(skuListTask.Result.ElementAt(0).Name.Equals(SkuName.PremiumLRS) || skuListTask.Result.ElementAt(0).Name.Equals(SkuName.StandardGRS) || skuListTask.Result.ElementAt(0).Name.Equals(SkuName.StandardLRS) || skuListTask.Result.ElementAt(0).Name.Equals(SkuName.StandardRagrs) || skuListTask.Result.ElementAt(0).Name.Equals(SkuName.StandardZRS)); Assert.NotNull(skuListTask.Result.ElementAt(0).Kind); Assert.True(skuListTask.Result.ElementAt(0).Kind.Equals(Kind.BlobStorage) || skuListTask.Result.ElementAt(0).Kind.Equals(Kind.Storage) || skuListTask.Result.ElementAt(0).Kind.Equals(Kind.StorageV2)); } [RecordedTest] public async Task StorageAccountCreateWithStorageV2() { //Create resource group string rgname = await CreateResourceGroupAsync(); string accountName = Recording.GenerateAssetName("sto"); // Create storage account with StorageV2 Sku sku = new Sku(SkuName.StandardGRS); StorageAccountCreateParameters parameters = new StorageAccountCreateParameters(sku: sku, kind: Kind.StorageV2, location: DefaultLocation); StorageAccount account = await _CreateStorageAccountAsync(rgname, accountName, parameters); VerifyAccountProperties(account, false); Assert.NotNull(account.PrimaryEndpoints.Web); Assert.AreEqual(Kind.StorageV2, account.Kind); } [RecordedTest] public async Task StorageAccountUpdateKindStorageV2() { //Create resource group string rgname = await CreateResourceGroupAsync(); // Create storage account string accountName = await CreateStorageAccount(AccountsClient, rgname, Recording); // Update storage account type StorageAccountUpdateParameters parameters = new StorageAccountUpdateParameters { Kind = Kind.StorageV2, EnableHttpsTrafficOnly = true }; StorageAccount account = await UpdateStorageAccountAsync(rgname, accountName, parameters); Assert.AreEqual(Kind.StorageV2, account.Kind); Assert.True(account.EnableHttpsTrafficOnly); Assert.NotNull(account.PrimaryEndpoints.Web); // Validate account = await WaitToGetAccountSuccessfullyAsync(rgname, accountName); Assert.AreEqual(Kind.StorageV2, account.Kind); Assert.True(account.EnableHttpsTrafficOnly); Assert.NotNull(account.PrimaryEndpoints.Web); } [RecordedTest] public async Task StorageAccountSetGetDeleteManagementPolicy() { //Create resource group string rgname = await CreateResourceGroupAsync(); string accountName = Recording.GenerateAssetName("sto"); // Create storage account Sku sku = new Sku(SkuName.StandardGRS); StorageAccountCreateParameters parameters = new StorageAccountCreateParameters(sku: sku, kind: Kind.StorageV2, location: "westus"); await _CreateStorageAccountAsync(rgname, accountName, parameters); List<ManagementPolicyRule> rules = new List<ManagementPolicyRule>(); ManagementPolicyAction Actions = new ManagementPolicyAction() { BaseBlob = new ManagementPolicyBaseBlob() { Delete = new DateAfterModification(300), TierToArchive = new DateAfterModification(90), TierToCool = new DateAfterModification(1000), }, Snapshot = new ManagementPolicySnapShot() { Delete = new DateAfterCreation(100) } }; ManagementPolicyDefinition Definition = new ManagementPolicyDefinition(Actions) { Filters = new ManagementPolicyFilter(new List<string>() { "blockBlob" }) { PrefixMatch = { "olcmtestcontainer", "testblob" } } }; ManagementPolicyRule rule1 = new ManagementPolicyRule("olcmtest", RuleType.Lifecycle, Definition) { Enabled = true }; rules.Add(rule1); ManagementPolicyAction Actions2 = new ManagementPolicyAction() { BaseBlob = new ManagementPolicyBaseBlob() { Delete = new DateAfterModification(1000), }, }; ManagementPolicyDefinition Definition2 = new ManagementPolicyDefinition(Actions2) { Filters = new ManagementPolicyFilter(new List<string>() { "blockBlob" }) }; ManagementPolicyRule rule2 = new ManagementPolicyRule("olcmtest2", RuleType.Lifecycle, Definition2) { Enabled = false }; rules.Add(rule2); ManagementPolicyAction Actions3 = new ManagementPolicyAction() { Snapshot = new ManagementPolicySnapShot() { Delete = new DateAfterCreation(200) } }; ManagementPolicyDefinition Definition3 = new ManagementPolicyDefinition(Actions3) { Filters = new ManagementPolicyFilter(new List<string>() { "blockBlob" }) }; ManagementPolicyRule rule3 = new ManagementPolicyRule("olcmtest3", RuleType.Lifecycle, Definition3); rules.Add(rule3); //Set Management Policies ManagementPolicySchema policyToSet = new ManagementPolicySchema(rules); ManagementPolicy managementPolicy = new ManagementPolicy() { Policy = policyToSet }; Response<ManagementPolicy> policy = await ManagementPoliciesClient.CreateOrUpdateAsync(rgname, accountName, ManagementPolicyName.Default, managementPolicy); CompareStorageAccountManagementPolicyProperty(policyToSet, policy.Value.Policy); //Get Management Policies policy = await ManagementPoliciesClient.GetAsync(rgname, accountName, ManagementPolicyName.Default); CompareStorageAccountManagementPolicyProperty(policyToSet, policy.Value.Policy); //Delete Management Policies, and check policy not exist await ManagementPoliciesClient.DeleteAsync(rgname, accountName, ManagementPolicyName.Default); bool dataPolicyExist = true; try { policy = await ManagementPoliciesClient.GetAsync(rgname, accountName, ManagementPolicyName.Default); } catch (RequestFailedException cloudException) { Assert.AreEqual((int)HttpStatusCode.NotFound, cloudException.Status); dataPolicyExist = false; } Assert.False(dataPolicyExist); //Delete not exist Management Policies will not fail await ManagementPoliciesClient.DeleteAsync(rgname, accountName, ManagementPolicyName.Default); } private static void CompareStorageAccountManagementPolicyProperty(ManagementPolicySchema policy1, ManagementPolicySchema policy2) { Assert.AreEqual(policy1.Rules.Count, policy2.Rules.Count); foreach (ManagementPolicyRule rule1 in policy1.Rules) { bool ruleFound = false; foreach (ManagementPolicyRule rule2 in policy2.Rules) { if (rule1.Name == rule2.Name) { ruleFound = true; Assert.AreEqual(rule1.Enabled is null ? true : rule1.Enabled, rule2.Enabled); if (rule1.Definition.Filters != null || rule2.Definition.Filters != null) { Assert.AreEqual(rule1.Definition.Filters.BlobTypes, rule2.Definition.Filters.BlobTypes); Assert.AreEqual(rule1.Definition.Filters.PrefixMatch, rule2.Definition.Filters.PrefixMatch); } if (rule1.Definition.Actions.BaseBlob != null || rule2.Definition.Actions.BaseBlob != null) { CompareDateAfterModification(rule1.Definition.Actions.BaseBlob.TierToCool, rule2.Definition.Actions.BaseBlob.TierToCool); CompareDateAfterModification(rule1.Definition.Actions.BaseBlob.TierToArchive, rule2.Definition.Actions.BaseBlob.TierToArchive); CompareDateAfterModification(rule1.Definition.Actions.BaseBlob.Delete, rule2.Definition.Actions.BaseBlob.Delete); } if (rule1.Definition.Actions.Snapshot != null || rule2.Definition.Actions.Snapshot != null) { CompareDateAfterCreation(rule1.Definition.Actions.Snapshot.Delete, rule1.Definition.Actions.Snapshot.Delete); } break; } } Assert.True(ruleFound, string.Format("The set rule {0} should be found in the output.", rule1.Name)); } } private static void CompareDateAfterModification(DateAfterModification date1, DateAfterModification date2) { if ((date1 is null) && (date2 is null)) { return; } Assert.AreEqual(date1.DaysAfterModificationGreaterThan, date2.DaysAfterModificationGreaterThan); } private static void CompareDateAfterCreation(DateAfterCreation date1, DateAfterCreation date2) { if ((date1 is null) && (date2 is null)) { return; } Assert.AreEqual(date1.DaysAfterCreationGreaterThan, date2.DaysAfterCreationGreaterThan); } [RecordedTest] public async Task StorageAccountCreateGetdfs() { //Create resource group string rgname = await CreateResourceGroupAsync(); string accountName = Recording.GenerateAssetName("sto"); // Create storage account Sku sku = new Sku(SkuName.StandardGRS); StorageAccountCreateParameters parameters = new StorageAccountCreateParameters(sku: sku, kind: Kind.StorageV2, location: DefaultRGLocation) { IsHnsEnabled = true }; StorageAccount account = await _CreateStorageAccountAsync(rgname, accountName, parameters); Assert.True(account.IsHnsEnabled = true); Assert.NotNull(account.PrimaryEndpoints.Dfs); // Validate account = await WaitToGetAccountSuccessfullyAsync(rgname, accountName); Assert.True(account.IsHnsEnabled = true); Assert.NotNull(account.PrimaryEndpoints.Dfs); } [RecordedTest] public async Task StorageAccountCreateWithFileStorage() { //Create resource group string rgname = await CreateResourceGroupAsync(); string accountName = Recording.GenerateAssetName("sto"); // Create storage account with StorageV2 Sku sku = new Sku(SkuName.PremiumLRS); StorageAccountCreateParameters parameters = new StorageAccountCreateParameters(sku: sku, kind: Kind.FileStorage, location: "centraluseuap"); StorageAccount account = await _CreateStorageAccountAsync(rgname, accountName, parameters); VerifyAccountProperties(account, false); Assert.AreEqual(Kind.FileStorage, account.Kind); Assert.AreEqual(SkuName.PremiumLRS, account.Sku.Name); } [RecordedTest] public async Task StorageAccountCreateWithBlockBlobStorage() { //Create resource group string rgname = await CreateResourceGroupAsync(); string accountName = Recording.GenerateAssetName("sto"); // Create storage account with StorageV2 Sku sku = new Sku(SkuName.PremiumLRS); StorageAccountCreateParameters parameters = new StorageAccountCreateParameters(sku: sku, kind: Kind.BlockBlobStorage, location: "centraluseuap"); StorageAccount account = await _CreateStorageAccountAsync(rgname, accountName, parameters); VerifyAccountProperties(account, false); Assert.AreEqual(Kind.BlockBlobStorage, account.Kind); Assert.AreEqual(SkuName.PremiumLRS, account.Sku.Name); } [RecordedTest] [Ignore("Track2: Unable to locate active AAD DS for AAD tenant Id *************** associated with the storage account.")] public async Task StorageAccountCreateSetGetFileAadIntegration() { //Create resource group string rgname = await CreateResourceGroupAsync(); string accountName = Recording.GenerateAssetName("sto"); // Create storage account Sku sku = new Sku(SkuName.StandardGRS); StorageAccountCreateParameters parameters = new StorageAccountCreateParameters(sku: sku, kind: Kind.StorageV2, location: DefaultLocation) { AzureFilesIdentityBasedAuthentication = new AzureFilesIdentityBasedAuthentication(DirectoryServiceOptions.Aadds) }; StorageAccount account = await _CreateStorageAccountAsync(rgname, accountName, parameters); Assert.AreEqual(DirectoryServiceOptions.Aadds, account.AzureFilesIdentityBasedAuthentication.DirectoryServiceOptions); // Validate account = await WaitToGetAccountSuccessfullyAsync(rgname, accountName); Assert.AreEqual(DirectoryServiceOptions.Aadds, account.AzureFilesIdentityBasedAuthentication.DirectoryServiceOptions); // Update storage account StorageAccountUpdateParameters updateParameters = new StorageAccountUpdateParameters { AzureFilesIdentityBasedAuthentication = new AzureFilesIdentityBasedAuthentication(DirectoryServiceOptions.None), EnableHttpsTrafficOnly = true }; account = await UpdateStorageAccountAsync(rgname, accountName, updateParameters); Assert.AreEqual(DirectoryServiceOptions.None, account.AzureFilesIdentityBasedAuthentication.DirectoryServiceOptions); // Validate account = await WaitToGetAccountSuccessfullyAsync(rgname, accountName); Assert.AreEqual(DirectoryServiceOptions.None, account.AzureFilesIdentityBasedAuthentication.DirectoryServiceOptions); } [RecordedTest] [Ignore("Track2: Last sync time is unavailable for account sto218")] public async Task StorageAccountFailOver() { //Create resource group string rgname = await CreateResourceGroupAsync(); string accountName = Recording.GenerateAssetName("sto"); // Create storage account Sku sku = new Sku(SkuName.StandardRagrs); StorageAccountCreateParameters parameters = new StorageAccountCreateParameters(sku: sku, kind: Kind.StorageV2, location: DefaultLocation); _ = await _CreateStorageAccountAsync(rgname, accountName, parameters); // Wait for account ready to failover and Validate StorageAccount account; string location; int i = 100; do { account = await AccountsClient.GetPropertiesAsync(rgname, accountName, expand: StorageAccountExpand.GeoReplicationStats); Assert.AreEqual(SkuName.StandardRagrs, account.Sku.Name); Assert.Null(account.FailoverInProgress); location = account.SecondaryLocation; //Don't need sleep when playback, or Unit test will be very slow. Need sleep when record. if (Mode == RecordedTestMode.Record) { System.Threading.Thread.Sleep(10000); } } while ((account.GeoReplicationStats.CanFailover != true) && (i-- > 0)); // Failover storage account Operation<Response> failoverWait = await AccountsClient.StartFailoverAsync(rgname, accountName); await WaitForCompletionAsync(failoverWait); // Validate account = await WaitToGetAccountSuccessfullyAsync(rgname, accountName); Assert.AreEqual(SkuName.StandardLRS, account.Sku.Name); Assert.AreEqual(location, account.PrimaryLocation); } [RecordedTest] public async Task StorageAccountGetLastSyncTime() { //Create resource group string rgname = await CreateResourceGroupAsync(); string accountName = Recording.GenerateAssetName("sto"); // Create storage account Sku sku = new Sku(SkuName.StandardRagrs); StorageAccountCreateParameters parameters = new StorageAccountCreateParameters(sku: sku, kind: Kind.StorageV2, location: "eastus2"); StorageAccount account = await _CreateStorageAccountAsync(rgname, accountName, parameters); Assert.AreEqual(SkuName.StandardRagrs, account.Sku.Name); Assert.Null(account.GeoReplicationStats); account = await WaitToGetAccountSuccessfullyAsync(rgname, accountName); Assert.Null(account.GeoReplicationStats); account = await AccountsClient.GetPropertiesAsync(rgname, accountName, StorageAccountExpand.GeoReplicationStats); Assert.NotNull(account.GeoReplicationStats); Assert.NotNull(account.GeoReplicationStats.Status); Assert.NotNull(account.GeoReplicationStats.LastSyncTime); Assert.NotNull(account.GeoReplicationStats.CanFailover); } [RecordedTest] public async Task StorageAccountLargeFileSharesStateTest() { //Create resource group string rgname = await CreateResourceGroupAsync(); string accountName = Recording.GenerateAssetName("sto"); // Create storage account Sku sku = new Sku(SkuName.StandardLRS); StorageAccountCreateParameters parameters = new StorageAccountCreateParameters(sku: sku, kind: Kind.StorageV2, location: "westeurope") { LargeFileSharesState = LargeFileSharesState.Enabled }; StorageAccount account = await _CreateStorageAccountAsync(rgname, accountName, parameters); Assert.AreEqual(SkuName.StandardLRS, account.Sku.Name); Assert.AreEqual(LargeFileSharesState.Enabled, account.LargeFileSharesState); // Validate account = await WaitToGetAccountSuccessfullyAsync(rgname, accountName); Assert.AreEqual(SkuName.StandardLRS, account.Sku.Name); Assert.AreEqual(LargeFileSharesState.Enabled, account.LargeFileSharesState); } [RecordedTest] public async Task StorageAccountPrivateEndpointTest() { //Create resource group string rgname = await CreateResourceGroupAsync(); string accountName = Recording.GenerateAssetName("sto"); // Create storage account Sku sku = new Sku(SkuName.StandardLRS); StorageAccountCreateParameters parameters = new StorageAccountCreateParameters(sku: sku, kind: Kind.StorageV2, location: "westeurope") { LargeFileSharesState = LargeFileSharesState.Enabled }; StorageAccount account = await _CreateStorageAccountAsync(rgname, accountName, parameters); Assert.AreEqual(SkuName.StandardLRS, account.Sku.Name); account = await WaitToGetAccountSuccessfullyAsync(rgname, accountName); IReadOnlyList<PrivateEndpointConnection> pes = account.PrivateEndpointConnections; foreach (PrivateEndpointConnection pe in pes) { //Get from account await PrivateEndpointConnectionsClient.GetAsync(rgname, accountName, pe.Name); // Prepare data for set PrivateEndpoint endpoint = new PrivateEndpoint(); PrivateEndpointConnection connection = new PrivateEndpointConnection() { PrivateEndpoint = endpoint, PrivateLinkServiceConnectionState = new PrivateLinkServiceConnectionState() { ActionRequired = "None", Description = "123", Status = "Approved" } }; if (pe.PrivateLinkServiceConnectionState.Status != "Rejected") { //Set approve connection.PrivateLinkServiceConnectionState.Status = "Approved"; PrivateEndpointConnection pe3 = await PrivateEndpointConnectionsClient.PutAsync(rgname, accountName, pe.Name, pe); Assert.AreEqual("Approved", pe3.PrivateLinkServiceConnectionState.Status); //Validate approve by get pe3 = await PrivateEndpointConnectionsClient.GetAsync(rgname, accountName, pe.Name); Assert.AreEqual("Approved", pe3.PrivateLinkServiceConnectionState.Status); } if (pe.PrivateLinkServiceConnectionState.Status == "Rejected") { //Set reject connection.PrivateLinkServiceConnectionState.Status = "Rejected"; PrivateEndpointConnection pe4 = await PrivateEndpointConnectionsClient.PutAsync(rgname, accountName, pe.Name, pe); Assert.AreEqual("Rejected", pe4.PrivateLinkServiceConnectionState.Status); //Validate reject by get pe4 = await PrivateEndpointConnectionsClient.GetAsync(rgname, accountName, pe.Name); Assert.AreEqual("Rejected", pe4.PrivateLinkServiceConnectionState.Status); } } } [RecordedTest] public async Task StorageAccountPrivateLinkTest() { //Create resource group string rgname = await CreateResourceGroupAsync(); string accountName = Recording.GenerateAssetName("sto"); // Create storage account Sku sku = new Sku(SkuName.StandardLRS); StorageAccountCreateParameters parameters = new StorageAccountCreateParameters(sku: sku, kind: Kind.StorageV2, location: "westus") { LargeFileSharesState = LargeFileSharesState.Enabled }; await _CreateStorageAccountAsync(rgname, accountName, parameters); // Get private link resource Response<PrivateLinkResourceListResult> result = await PrivateLinkResourcesClient.ListByStorageAccountAsync(rgname, accountName); // Validate Assert.True(result.Value.Value.Count > 0); } [RecordedTest] public async Task StorageAccountCreateWithTableQueueEcryptionKeyTypeTest() { //Create resource group string rgname = await CreateResourceGroupAsync(); string accountName = Recording.GenerateAssetName("sto"); // Create storage account Sku sku = new Sku(SkuName.StandardLRS); StorageAccountCreateParameters parameters = new StorageAccountCreateParameters(sku: sku, kind: Kind.StorageV2, location: "East US 2 EUAP") { Encryption = new Encryption(keySource: KeySource.MicrosoftStorage) { Services = new EncryptionServices { Queue = new EncryptionService { KeyType = KeyType.Account }, Table = new EncryptionService { KeyType = KeyType.Account }, } } }; StorageAccount account = await _CreateStorageAccountAsync(rgname, accountName, parameters); // Verify encryption settings Assert.NotNull(account.Encryption); Assert.NotNull(account.Encryption.Services.Blob); Assert.True(account.Encryption.Services.Blob.Enabled); Assert.AreEqual(KeyType.Account, account.Encryption.Services.Blob.KeyType); Assert.NotNull(account.Encryption.Services.Blob.LastEnabledTime); Assert.NotNull(account.Encryption.Services.File); Assert.True(account.Encryption.Services.File.Enabled); Assert.AreEqual(KeyType.Account, account.Encryption.Services.Blob.KeyType); Assert.NotNull(account.Encryption.Services.File.LastEnabledTime); Assert.NotNull(account.Encryption.Services.Queue); Assert.AreEqual(KeyType.Account, account.Encryption.Services.Queue.KeyType); Assert.True(account.Encryption.Services.Queue.Enabled); Assert.NotNull(account.Encryption.Services.Queue.LastEnabledTime); Assert.NotNull(account.Encryption.Services.Table); Assert.AreEqual(KeyType.Account, account.Encryption.Services.Table.KeyType); Assert.True(account.Encryption.Services.Table.Enabled); Assert.NotNull(account.Encryption.Services.Table.LastEnabledTime); } [RecordedTest] public async Task EcryptionScopeTest() { //Create resource group string rgname = await CreateResourceGroupAsync(); string accountName = Recording.GenerateAssetName("sto"); // Create storage account Sku sku = new Sku(SkuName.StandardLRS); StorageAccountCreateParameters parameters = new StorageAccountCreateParameters(sku: sku, kind: Kind.StorageV2, location: "East US 2 EUAP"); await _CreateStorageAccountAsync(rgname, accountName, parameters); //Create EcryptionScope EncryptionScope EncryptionScope = new EncryptionScope() { Source = EncryptionScopeSource.MicrosoftStorage, State = EncryptionScopeState.Disabled }; EncryptionScope es = await EncryptionScopesClient.PutAsync(rgname, accountName, "testscope", EncryptionScope); Assert.AreEqual("testscope", es.Name); Assert.AreEqual(EncryptionScopeState.Disabled, es.State); Assert.AreEqual(EncryptionScopeSource.MicrosoftStorage, es.Source); // Get EcryptionScope es = await EncryptionScopesClient.GetAsync(rgname, accountName, "testscope"); Assert.AreEqual("testscope", es.Name); Assert.AreEqual(EncryptionScopeState.Disabled, es.State); Assert.AreEqual(EncryptionScopeSource.MicrosoftStorage, es.Source); // Patch EcryptionScope es.State = EncryptionScopeState.Enabled; es = await EncryptionScopesClient.PatchAsync(rgname, accountName, "testscope", es); Assert.AreEqual("testscope", es.Name); Assert.AreEqual(EncryptionScopeState.Enabled, es.State); Assert.AreEqual(EncryptionScopeSource.MicrosoftStorage, es.Source); //List EcryptionScope AsyncPageable<EncryptionScope> ess = EncryptionScopesClient.ListAsync(rgname, accountName); Task<List<EncryptionScope>> essList = ess.ToEnumerableAsync(); es = essList.Result.First(); Assert.AreEqual("testscope", es.Name); Assert.AreEqual(EncryptionScopeState.Enabled, es.State); Assert.AreEqual(EncryptionScopeSource.MicrosoftStorage, es.Source); } private async Task<string> CreateResourceGroupAsync() { return await CreateResourceGroup(ResourceGroupsClient, Recording); } private async Task<StorageAccount> _CreateStorageAccountAsync(string resourceGroupName, string accountName, StorageAccountCreateParameters parameters = null) { StorageAccountCreateParameters saParameters = parameters ?? GetDefaultStorageAccountParameters(); Operation<StorageAccount> accountsResponse = await AccountsClient.StartCreateAsync(resourceGroupName, accountName, saParameters); StorageAccount account = (await WaitForCompletionAsync(accountsResponse)).Value; return account; } private async Task<Response<StorageAccount>> WaitToGetAccountSuccessfullyAsync(string resourceGroupName, string accountName) { return await AccountsClient.GetPropertiesAsync(resourceGroupName, accountName); } private async Task<Response<StorageAccount>> UpdateStorageAccountAsync(string resourceGroupName, string accountName, StorageAccountUpdateParameters parameters) { return await AccountsClient.UpdateAsync(resourceGroupName, accountName, parameters); } private async Task<Response> DeleteStorageAccountAsync(string resourceGroupName, string accountName) { return await AccountsClient.DeleteAsync(resourceGroupName, accountName); } } }
49.153762
211
0.635891
[ "MIT" ]
AME-Redmond/azure-sdk-for-net
sdk/storage/Azure.ResourceManager.Storage/tests/Tests/StorageAccountTests.cs
89,511
C#
using System.IO; using System.Runtime.Serialization; using GameEstate.Red.Formats.Red.CR2W.Reflection; using FastMember; using static GameEstate.Red.Formats.Red.Records.Enums; namespace GameEstate.Red.Formats.Red.Types { [DataContract(Namespace = "")] [REDMeta] public class BTTaskForceFinisherDef : IBehTreeTaskDefinition { [Ordinal(1)] [RED("belowHealthPercent")] public CFloat BelowHealthPercent { get; set;} [Ordinal(2)] [RED("whenAlone")] public CBool WhenAlone { get; set;} [Ordinal(3)] [RED("leftStanceFinisherAnimName")] public CName LeftStanceFinisherAnimName { get; set;} [Ordinal(4)] [RED("rightStanceFinisherAnimName")] public CName RightStanceFinisherAnimName { get; set;} [Ordinal(5)] [RED("shouldCheckForFinisherDLC")] public CBool ShouldCheckForFinisherDLC { get; set;} [Ordinal(6)] [RED("hasFinisherDLC")] public CBool HasFinisherDLC { get; set;} public BTTaskForceFinisherDef(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name){ } public static new CVariable Create(CR2WFile cr2w, CVariable parent, string name) => new BTTaskForceFinisherDef(cr2w, parent, name); public override void Read(BinaryReader file, uint size) => base.Read(file, size); public override void Write(BinaryWriter file) => base.Write(file); } }
38.2
134
0.73074
[ "MIT" ]
bclnet/GameEstate
src/Estates/Red/GameEstate.Red.Format/Red/W3/RTTIConvert/BTTaskForceFinisherDef.cs
1,337
C#
using System; namespace softaware.Sitemap { public sealed class LocalizedSitemapNode { public LocalizedSitemapNode(string language, SitemapNode node) { this.Language = language ?? throw new ArgumentNullException(nameof(language)); this.Node = node ?? throw new ArgumentNullException(nameof(node)); } public LocalizedSitemapNode(string language, string url) : this(language, new SitemapNode(url)) { } public string Language { get; set; } public SitemapNode Node { get; set; } } }
27.590909
90
0.614498
[ "MIT" ]
softawaregmbh/library-sitemap
src/softaware.Sitemap/LocalizedSitemapNode.cs
609
C#
// Copyright (c) Josef Pihrt. All rights reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; using Orang.Expressions; using Orang.FileSystem; using static Orang.Logger; namespace Orang.CommandLine { internal static class ParseHelpers { public static bool TryParseFileProperties( IEnumerable<string> values, string optionName, out FilePropertyFilter filter) { filter = null; Func<long, bool> sizePredicate = null; Func<DateTime, bool> creationTimePredicate = null; Func<DateTime, bool> modifiedTimePredicate = null; foreach (string value in values) { try { Expression expression = Expression.Parse(value); if (OptionValues.FileProperty_Size.IsKeyOrShortKey(expression.Identifier)) { if (expression.Kind == ExpressionKind.DecrementExpression) { WriteError($"Option '{OptionNames.GetHelpText(optionName)}' has invalid expression '{value}'."); return false; } sizePredicate = PredicateHelpers.GetLongPredicate(expression); } else if (OptionValues.FileProperty_CreationTime.IsKeyOrShortKey(expression.Identifier)) { creationTimePredicate = PredicateHelpers.GetDateTimePredicate(expression); } else if (OptionValues.FileProperty_ModifiedTime.IsKeyOrShortKey(expression.Identifier)) { modifiedTimePredicate = PredicateHelpers.GetDateTimePredicate(expression); } else { WriteParseError(value, optionName, OptionValueProviders.FilePropertiesProvider); return false; } } catch (ArgumentException) { WriteError($"Option '{OptionNames.GetHelpText(optionName)}' has invalid expression '{value}'."); return false; } } filter = new FilePropertyFilter( sizePredicate: sizePredicate, creationTimePredicate: creationTimePredicate, modifiedTimePredicate: modifiedTimePredicate); return true; } public static bool TryParseSortOptions( IEnumerable<string> values, string optionName, out SortOptions sortOptions) { sortOptions = null; int maxCount = 0; List<string> options = null; if (!values.Any()) return true; foreach (string value in values) { int index = value.IndexOf('='); if (index >= 0) { string key = value.Substring(0, index); string value2 = value.Substring(index + 1); if (OptionValues.MaxCount.IsKeyOrShortKey(key)) { if (!TryParseCount(value2, out maxCount, value)) return false; } else { WriteParseError(value, optionName, OptionValueProviders.SortFlagsProvider); return false; } } else { (options ?? (options = new List<string>())).Add(value); } } if (!TryParseAsEnumValues(options, optionName, out ImmutableArray<SortFlags> flags, provider: OptionValueProviders.SortFlagsProvider)) return false; SortDirection direction = (flags.Contains(SortFlags.Descending)) ? SortDirection.Descending : SortDirection.Ascending; List<SortDescriptor> descriptors = null; foreach (SortFlags flag in flags) { switch (flag) { case SortFlags.Name: { AddDescriptor(SortProperty.Name, direction); break; } case SortFlags.CreationTime: { AddDescriptor(SortProperty.CreationTime, direction); break; } case SortFlags.ModifiedTime: { AddDescriptor(SortProperty.ModifiedTime, direction); break; } case SortFlags.Size: { AddDescriptor(SortProperty.Size, direction); break; } case SortFlags.None: case SortFlags.Ascending: case SortFlags.Descending: { break; } default: { throw new InvalidOperationException($"Unknown enum value '{flag}'."); } } } if (descriptors != null) { sortOptions = new SortOptions(descriptors.ToImmutableArray(), maxCount: maxCount); } else { sortOptions = new SortOptions(ImmutableArray.Create(new SortDescriptor(SortProperty.Name, SortDirection.Ascending)), maxCount: maxCount); } return true; void AddDescriptor(SortProperty p, SortDirection d) { (descriptors ?? (descriptors = new List<SortDescriptor>())).Add(new SortDescriptor(p, d)); } } public static bool TryParseModifyOptions( IEnumerable<string> values, string optionName, out ModifyOptions modifyOptions, out bool aggregateOnly) { modifyOptions = null; aggregateOnly = false; var sortProperty = ValueSortProperty.None; List<string> options = null; foreach (string value in values) { int index = value.IndexOf('='); if (index >= 0) { string key = value.Substring(0, index); string value2 = value.Substring(index + 1); if (OptionValues.SortBy.IsKeyOrShortKey(key)) { if (!TryParseAsEnum(value2, optionName, out sortProperty, provider: OptionValueProviders.ValueSortPropertyProvider)) return false; } else { string helpText = OptionValueProviders.ModifyFlagsProvider.GetHelpText(); WriteError($"Option '{OptionNames.GetHelpText(optionName)}' has invalid value '{value}'. Allowed values: {helpText}."); return false; } } else { (options ?? (options = new List<string>())).Add(value); } } var modifyFlags = ModifyFlags.None; if (options != null && !TryParseAsEnumFlags(options, optionName, out modifyFlags, provider: OptionValueProviders.ModifyFlagsProvider)) { return false; } if ((modifyFlags & ModifyFlags.ExceptIntersect) == ModifyFlags.ExceptIntersect) { WriteError($"Values '{OptionValues.ModifyFlags_Except.HelpValue}' and '{OptionValues.ModifyFlags_Intersect.HelpValue}' cannot be use both at the same time."); return false; } var functions = ModifyFunctions.None; if ((modifyFlags & ModifyFlags.Distinct) != 0) functions |= ModifyFunctions.Distinct; if ((modifyFlags & ModifyFlags.Ascending) != 0) functions |= ModifyFunctions.Sort; if ((modifyFlags & ModifyFlags.Descending) != 0) functions |= ModifyFunctions.SortDescending; if ((modifyFlags & ModifyFlags.Except) != 0) functions |= ModifyFunctions.Except; if ((modifyFlags & ModifyFlags.Intersect) != 0) functions |= ModifyFunctions.Intersect; if ((modifyFlags & ModifyFlags.RemoveEmpty) != 0) functions |= ModifyFunctions.RemoveEmpty; if ((modifyFlags & ModifyFlags.RemoveWhiteSpace) != 0) functions |= ModifyFunctions.RemoveWhiteSpace; if ((modifyFlags & ModifyFlags.TrimStart) != 0) functions |= ModifyFunctions.TrimStart; if ((modifyFlags & ModifyFlags.TrimEnd) != 0) functions |= ModifyFunctions.TrimEnd; if ((modifyFlags & ModifyFlags.ToLower) != 0) functions |= ModifyFunctions.ToLower; if ((modifyFlags & ModifyFlags.ToUpper) != 0) functions |= ModifyFunctions.ToUpper; aggregateOnly = (modifyFlags & ModifyFlags.AggregateOnly) != 0; if (modifyFlags != ModifyFlags.None) { modifyOptions = new ModifyOptions( functions: functions, aggregate: (modifyFlags & ModifyFlags.Aggregate) != 0 || aggregateOnly, ignoreCase: (modifyFlags & ModifyFlags.IgnoreCase) != 0, cultureInvariant: (modifyFlags & ModifyFlags.CultureInvariant) != 0, sortProperty: sortProperty); } else { modifyOptions = ModifyOptions.Default; } return true; } public static bool TryParseReplaceOptions( IEnumerable<string> values, string optionName, string replacement, MatchEvaluator matchEvaluator, out ReplaceOptions replaceOptions) { replaceOptions = null; var replaceFlags = ReplaceFlags.None; if (values != null && !TryParseAsEnumFlags(values, optionName, out replaceFlags, provider: OptionValueProviders.ReplaceFlagsProvider)) { return false; } var functions = ReplaceFunctions.None; if ((replaceFlags & ReplaceFlags.TrimStart) != 0) functions |= ReplaceFunctions.TrimStart; if ((replaceFlags & ReplaceFlags.TrimEnd) != 0) functions |= ReplaceFunctions.TrimEnd; if ((replaceFlags & ReplaceFlags.ToLower) != 0) functions |= ReplaceFunctions.ToLower; if ((replaceFlags & ReplaceFlags.ToUpper) != 0) functions |= ReplaceFunctions.ToUpper; replaceOptions = new ReplaceOptions( replacement: replacement, matchEvaluator: matchEvaluator, functions: functions, cultureInvariant: (replaceFlags & ReplaceFlags.CultureInvariant) != 0); return true; } public static bool TryParseDisplay( IEnumerable<string> values, string optionName, out ContentDisplayStyle? contentDisplayStyle, out PathDisplayStyle? pathDisplayStyle, out LineDisplayOptions lineDisplayOptions, out DisplayParts displayParts, out ImmutableArray<FileProperty> fileProperties, out string indent, out string separator, OptionValueProvider contentDisplayStyleProvider = null, OptionValueProvider pathDisplayStyleProvider = null) { contentDisplayStyle = null; pathDisplayStyle = null; lineDisplayOptions = LineDisplayOptions.None; displayParts = DisplayParts.None; fileProperties = ImmutableArray<FileProperty>.Empty; indent = null; separator = null; ImmutableArray<FileProperty>.Builder builder = null; foreach (string value in values) { int index = value.IndexOf('='); if (index >= 0) { string key = value.Substring(0, index); string value2 = value.Substring(index + 1); if (OptionValues.Display_Content.IsKeyOrShortKey(key)) { if (!TryParseAsEnum(value2, optionName, out ContentDisplayStyle contentDisplayStyle2, provider: contentDisplayStyleProvider)) return false; contentDisplayStyle = contentDisplayStyle2; } else if (OptionValues.Display_Path.IsKeyOrShortKey(key)) { if (!TryParseAsEnum(value2, optionName, out PathDisplayStyle pathDisplayStyle2, provider: pathDisplayStyleProvider)) return false; pathDisplayStyle = pathDisplayStyle2; } else if (OptionValues.Display_Indent.IsKeyOrShortKey(key)) { indent = value2; } else if (OptionValues.Display_Separator.IsKeyOrShortKey(key)) { separator = value2; } else { ThrowException(value); } } else if (OptionValues.Display_Summary.IsValueOrShortValue(value)) { displayParts |= DisplayParts.Summary; } else if (OptionValues.Display_Count.IsValueOrShortValue(value)) { displayParts |= DisplayParts.Count; } else if (OptionValues.Display_CreationTime.IsValueOrShortValue(value)) { (builder ?? (builder = ImmutableArray.CreateBuilder<FileProperty>())).Add(FileProperty.CreationTime); } else if (OptionValues.Display_ModifiedTime.IsValueOrShortValue(value)) { (builder ?? (builder = ImmutableArray.CreateBuilder<FileProperty>())).Add(FileProperty.ModifiedTime); } else if (OptionValues.Display_Size.IsValueOrShortValue(value)) { (builder ?? (builder = ImmutableArray.CreateBuilder<FileProperty>())).Add(FileProperty.Size); } else if (OptionValues.Display_LineNumber.IsValueOrShortValue(value)) { lineDisplayOptions |= LineDisplayOptions.IncludeLineNumber; } else if (OptionValues.Display_TrimLine.IsValueOrShortValue(value)) { lineDisplayOptions |= LineDisplayOptions.TrimLine; } else if (OptionValues.Display_TrimLine.IsValueOrShortValue(value)) { lineDisplayOptions |= LineDisplayOptions.TrimLine; } else if (OptionValues.Display_TrimLine.IsValueOrShortValue(value)) { lineDisplayOptions |= LineDisplayOptions.TrimLine; } else { ThrowException(value); } } if (builder != null) fileProperties = builder.ToImmutableArray(); return true; void ThrowException(string value) { string helpText = OptionValueProviders.DisplayProvider.GetHelpText(); throw new ArgumentException($"Option '{OptionNames.GetHelpText(optionName)}' has invalid value '{value}'. Allowed values: {helpText}.", nameof(values)); } } public static bool TryParseOutputOptions( IEnumerable<string> values, string optionName, out string path, out Verbosity verbosity, out Encoding encoding, out bool append) { path = null; verbosity = Verbosity.Normal; encoding = Encoding.UTF8; append = false; if (!values.Any()) return true; if (!TryEnsureFullPath(values.First(), out path)) return false; foreach (string value in values.Skip(1)) { string option = value; int index = option.IndexOf('='); if (index >= 0) { string key = option.Substring(0, index); string value2 = option.Substring(index + 1); if (OptionValues.Verbosity.IsKeyOrShortKey(key)) { if (!TryParseVerbosity(value2, out verbosity)) return false; } else if (OptionValues.Encoding.IsKeyOrShortKey(key)) { if (!TryParseEncoding(value2, out encoding)) return false; } else { WriteParseError(value, optionName, OptionValueProviders.OutputFlagsProvider); return false; } } else if (OptionValues.Output_Append.IsValueOrShortValue(value)) { append = true; } else { WriteParseError(value, optionName, OptionValueProviders.OutputFlagsProvider); return false; } } return true; } public static bool TryParseRegex( string pattern, RegexOptions regexOptions, TimeSpan matchTimeout, string patternOptionName, out Regex regex) { regex = null; if (pattern == null) return false; try { regex = new Regex(pattern, regexOptions, matchTimeout); return true; } catch (ArgumentException ex) { WriteError(ex, $"Could not parse '{OptionNames.GetHelpText(patternOptionName)}' value: {ex.Message}"); return false; } } internal static bool TryParseRegexOptions( IEnumerable<string> options, string optionsParameterName, out RegexOptions regexOptions, out PatternOptions patternOptions, PatternOptions includedPatternOptions = PatternOptions.None, OptionValueProvider provider = null) { regexOptions = RegexOptions.None; if (!TryParseAsEnumFlags(options, optionsParameterName, out patternOptions, provider: provider ?? OptionValueProviders.PatternOptionsProvider)) return false; Debug.Assert((patternOptions & (PatternOptions.CaseSensitive | PatternOptions.IgnoreCase)) != (PatternOptions.CaseSensitive | PatternOptions.IgnoreCase)); if ((patternOptions & PatternOptions.CaseSensitive) != 0) { includedPatternOptions &= ~PatternOptions.IgnoreCase; } else if ((patternOptions & PatternOptions.IgnoreCase) != 0) { includedPatternOptions &= ~PatternOptions.CaseSensitive; } patternOptions |= includedPatternOptions; if ((patternOptions & PatternOptions.Compiled) != 0) regexOptions |= RegexOptions.Compiled; if ((patternOptions & PatternOptions.CultureInvariant) != 0) regexOptions |= RegexOptions.CultureInvariant; if ((patternOptions & PatternOptions.ECMAScript) != 0) regexOptions |= RegexOptions.ECMAScript; if ((patternOptions & PatternOptions.ExplicitCapture) != 0) regexOptions |= RegexOptions.ExplicitCapture; if ((patternOptions & PatternOptions.IgnoreCase) != 0) regexOptions |= RegexOptions.IgnoreCase; if ((patternOptions & PatternOptions.IgnorePatternWhitespace) != 0) regexOptions |= RegexOptions.IgnorePatternWhitespace; if ((patternOptions & PatternOptions.Multiline) != 0) regexOptions |= RegexOptions.Multiline; if ((patternOptions & PatternOptions.RightToLeft) != 0) regexOptions |= RegexOptions.RightToLeft; if ((patternOptions & PatternOptions.Singleline) != 0) regexOptions |= RegexOptions.Singleline; return true; } public static bool TryParseReplacement( IEnumerable<string> values, out string replacement) { if (!values.Any()) { replacement = null; return true; } replacement = values.First(); if (!TryParseAsEnumFlags(values.Skip(1), OptionNames.Replacement, out ReplacementOptions options, ReplacementOptions.None, OptionValueProviders.ReplacementOptionsProvider)) return false; if ((options & ReplacementOptions.FromFile) != 0 && !FileSystemHelpers.TryReadAllText(replacement, out replacement)) { return false; } if ((options & ReplacementOptions.Literal) != 0) replacement = RegexEscape.EscapeSubstitution(replacement); if ((options & ReplacementOptions.CharacterEscapes) != 0) replacement = RegexEscape.ConvertCharacterEscapes(replacement); return true; } public static bool TryParseAsEnumFlags<TEnum>( IEnumerable<string> values, string optionName, out TEnum result, TEnum? defaultValue = null, OptionValueProvider provider = null) where TEnum : struct { result = (TEnum)(object)0; if (values?.Any() != true) { if (defaultValue != null) { result = (TEnum)(object)defaultValue; } return true; } int flags = 0; foreach (string value in values) { if (!TryParseAsEnum(value, optionName, out TEnum result2, provider: provider)) return false; flags |= (int)(object)result2; } result = (TEnum)(object)flags; return true; } public static bool TryParseAsEnumValues<TEnum>( IEnumerable<string> values, string optionName, out ImmutableArray<TEnum> result, ImmutableArray<TEnum> defaultValue = default, OptionValueProvider provider = null) where TEnum : struct { if (values?.Any() != true) { result = (defaultValue.IsDefault) ? ImmutableArray<TEnum>.Empty : defaultValue; return true; } ImmutableArray<TEnum>.Builder builder = ImmutableArray.CreateBuilder<TEnum>(); foreach (string value in values) { if (!TryParseAsEnum(value, optionName, out TEnum result2, provider: provider)) return false; builder.Add(result2); } result = builder.ToImmutableArray(); return true; } public static bool TryParseAsEnum<TEnum>( string value, string optionName, out TEnum result, TEnum? defaultValue = null, OptionValueProvider provider = null) where TEnum : struct { if (!TryParseAsEnum(value, out result, defaultValue, provider)) { WriteParseError(value, optionName, provider?.GetHelpText() ?? OptionValue.GetDefaultHelpText<TEnum>()); return false; } return true; } public static bool TryParseAsEnum<TEnum>( string value, out TEnum result, TEnum? defaultValue = null, OptionValueProvider provider = default) where TEnum : struct { if (value == null && defaultValue != null) { result = defaultValue.Value; return true; } if (provider != null) { return provider.TryParseEnum(value, out result); } else { return Enum.TryParse(value?.Replace("-", ""), ignoreCase: true, out result); } } public static bool TryParseVerbosity(string value, out Verbosity verbosity) { return TryParseAsEnum(value, OptionNames.Verbosity, out verbosity, provider: OptionValueProviders.VerbosityProvider); } // https://docs.microsoft.com/en-us/dotnet/api/system.text.encoding#remarks public static bool TryParseEncoding(string name, out Encoding encoding) { if (name == "utf-8-no-bom") { encoding = EncodingHelpers.UTF8NoBom; return true; } try { encoding = Encoding.GetEncoding(name); return true; } catch (ArgumentException ex) { WriteError(ex); encoding = null; return false; } } public static bool TryParseEncoding(string name, out Encoding encoding, Encoding defaultEncoding) { if (name == null) { encoding = defaultEncoding; return true; } return TryParseEncoding(name, out encoding, defaultEncoding); } public static bool TryParseMaxCount(IEnumerable<string> values, out int maxCount, out int maxMatches, out int maxMatchingFiles) { maxCount = 0; maxMatches = 0; maxMatchingFiles = 0; if (!values.Any()) return true; foreach (string value in values) { int index = value.IndexOf('='); if (index >= 0) { string key = value.Substring(0, index); string value2 = value.Substring(index + 1); if (OptionValues.MaxMatches.IsKeyOrShortKey(key)) { if (!TryParseCount(value2, out maxMatches, value)) return false; } else if (OptionValues.MaxMatchingFiles.IsKeyOrShortKey(key)) { if (!TryParseCount(value2, out maxMatchingFiles, value)) return false; } else { WriteParseError(value, OptionNames.MaxCount, OptionValueProviders.MaxOptionsProvider); return false; } } else if (!TryParseCount(value, out maxCount)) { return false; } } return true; } private static bool TryParseCount(string value, out int count, string value2 = null) { if (int.TryParse(value, NumberStyles.None, CultureInfo.InvariantCulture, out count)) return true; WriteError($"Option '{OptionNames.GetHelpText(OptionNames.MaxCount)}' has invalid value '{value2 ?? value}'."); return false; } public static bool TryParseChar(string value, out char result) { if (value.Length == 2 && value[0] == '\\' && value[1] >= 48 && value[1] <= 57) { result = value[1]; return true; } if (int.TryParse(value, NumberStyles.None, CultureInfo.InvariantCulture, out int charCode)) { if (charCode < 0 || charCode > 0xFFFF) { WriteError("Value must be in range from 0 to 65535."); result = default; return false; } result = (char)charCode; } else if (!char.TryParse(value, out result)) { WriteError($"Could not parse '{value}' as character value."); return false; } return true; } public static bool TryEnsureFullPath(IEnumerable<string> paths, out ImmutableArray<string> fullPaths) { ImmutableArray<string>.Builder builder = ImmutableArray.CreateBuilder<string>(); foreach (string path in paths) { if (!TryEnsureFullPath(path, out string fullPath)) return false; builder.Add(fullPath); } fullPaths = builder.ToImmutableArray(); return true; } public static bool TryEnsureFullPath(string path, out string result) { try { if (!Path.IsPathRooted(path)) path = Path.GetFullPath(path); result = path; return true; } catch (ArgumentException ex) { WriteError($"Path '{path}' is invalid: {ex.Message}."); result = null; return false; } } private static void WriteParseError(string value, string optionName, OptionValueProvider provider) { string helpText = provider.GetHelpText(); WriteParseError(value, optionName, helpText); } private static void WriteParseError(string value, string optionName, string helpText) { WriteError($"Option '{OptionNames.GetHelpText(optionName)}' has invalid value '{value}'. Allowed values: {helpText}."); } internal static bool TryParseProperties(string ask, IEnumerable<string> name, FindCommandOptions options) { if (!TryParseAsEnum(ask, OptionNames.Ask, out AskMode askMode, defaultValue: AskMode.None, OptionValueProviders.AskModeProvider)) return false; if (askMode == AskMode.Value && ConsoleOut.Verbosity < Verbosity.Normal) { WriteError($"Option '{OptionNames.GetHelpText(OptionNames.Ask)}' cannot have value '{OptionValueProviders.AskModeProvider.GetValue(nameof(AskMode.Value)).HelpValue}' when '{OptionNames.GetHelpText(OptionNames.Verbosity)}' is set to '{OptionValueProviders.VerbosityProvider.GetValue(ConsoleOut.Verbosity.ToString()).HelpValue}'."); return false; } if (!FilterParser.TryParse(name, OptionNames.Name, OptionValueProviders.PatternOptionsProvider, out Filter nameFilter, allowNull: true)) return false; options.AskMode = askMode; options.NameFilter = nameFilter; return true; } } }
36.195773
346
0.516349
[ "Apache-2.0" ]
atifaziz/Orang
src/CommandLine/ParseHelpers.cs
32,542
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated from a template. // // Manual changes to this file may cause unexpected behavior in your application. // Manual changes to this file will be overwritten if the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace EmpowerBusiness { using System; using System.Collections.Generic; public partial class Eval_PhoneNumbers { public int PhoneID { get; set; } public int ContactID { get; set; } public int NumberTypeID { get; set; } public string AreaCode { get; set; } public string Number { get; set; } public string Extension { get; set; } } }
33.36
85
0.522782
[ "Apache-2.0" ]
HaloImageEngine/EmpowerClaim-hotfix-1.25.1
EmpowerBusiness/Eval_PhoneNumbers.cs
834
C#
using System.Collections.Generic; using Quantumart.QP8.BLL.ListItems; using Quantumart.QP8.BLL.Services.DTO; using Quantumart.QP8.Resources; using Quantumart.QP8.WebMvc.ViewModels.Abstract; using C = Quantumart.QP8.Constants; namespace Quantumart.QP8.WebMvc.ViewModels.UserGroup { public class UserGroupListViewModel : ListViewModel { public IEnumerable<UserGroupListItem> Data { get; set; } public string GettingDataActionName => "_Index"; public static UserGroupListViewModel Create(UserGroupInitListResult result, string tabId, int parentId) { var model = Create<UserGroupListViewModel>(tabId, parentId); model.ShowAddNewItemButton = result.IsAddNewAccessable && !model.IsWindow; model.AllowMultipleEntitySelection = false; return model; } public override string EntityTypeCode => C.EntityTypeCode.UserGroup; public override string ActionCode => C.ActionCode.UserGroups; public override string AddNewItemActionCode => C.ActionCode.AddNewUserGroup; public override string AddNewItemText => UserGroupStrings.AddNewGroup; } }
35.30303
111
0.730472
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
QuantumArt/QP
siteMvc/ViewModels/UserGroup/UserGroupListViewModel.cs
1,165
C#
using Plugin.Permissions.Abstractions; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AICompanion.Services { public interface IPermissionService { Task<PermissionStatus> CheckAsync(Permission permissions, string permissionRequestRationaleMessage = null); Task<Dictionary<Permission, PermissionStatus>> CheckMultipleAsync(string permissionRequestRationaleMessage, params Permission[] permissions); Task<Dictionary<Permission, PermissionStatus>> CheckMultipleAsync(params Permission[] permissions); } }
32.631579
149
0.795161
[ "MIT" ]
marcominerva/AICompanion
AICompanion/AICompanion/Services/IPermissionService.cs
622
C#
using Jobs; using NetworkUI; using NetworkUI.Items; using NPC; using Pandaros.Settlers.Entities; using Pandaros.Settlers.Items; using Pipliz; using Shared; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using static Pandaros.Settlers.Items.StaticItems; namespace Pandaros.Settlers.ColonyManagement { public class ColonyManagementTool : CSType { public static string NAME = GameLoader.NAMESPACE + ".ColonyManagementTool"; public override string name => NAME; public override string icon => GameLoader.ICON_PATH + "ColonyManager.png"; public override bool? isPlaceable => false; public override int? maxStackSize => 1; public override List<string> categories { get; set; } = new List<string>() { "essential", "aaa" }; public override StaticItem StaticItemSettings => new StaticItem() { Name = GameLoader.NAMESPACE + ".ColonyManagementTool" }; } public class JobCounts { public string Name { get; set; } public int AvailableCount { get; set; } public int TakenCount { get; set; } public List<IJob> AvailableJobs { get; set; } = new List<IJob>(); public List<IJob> TakenJobs { get; set; } = new List<IJob>(); } [ModLoader.ModManager] public class ColonyTool { public static List<string> _recruitCount = new List<string>() { "1", "5", "10", "Max" }; static readonly Pandaros.Settlers.localization.LocalizationHelper _localizationHelper = new localization.LocalizationHelper("colonytool"); [ModLoader.ModCallback(ModLoader.EModCallbackType.OnPlayerClicked, GameLoader.NAMESPACE + ".ColonyManager.ColonyTool.OpenMenu")] public static void OpenMenu(Players.Player player, PlayerClickedData playerClickData) { //Only launch on RIGHT click if (player == null || playerClickData.ClickType != PlayerClickedData.EClickType.Right || player.ActiveColony == null) return; if (ItemTypes.IndexLookup.TryGetIndex(GameLoader.NAMESPACE + ".ColonyManagementTool", out var toolItem) && playerClickData.TypeSelected == toolItem) { Dictionary<string, JobCounts> jobCounts = GetJobCounts(player.ActiveColony); NetworkMenuManager.SendServerPopup(player, BuildMenu(player, jobCounts, false, string.Empty, 0)); } } [ModLoader.ModCallback(ModLoader.EModCallbackType.OnPlayerPushedNetworkUIButton, GameLoader.NAMESPACE + ".ColonyManager.ColonyTool.PressButton")] public static void PressButton(ButtonPressCallbackData data) { if ((!data.ButtonIdentifier.Contains(".RecruitButton") && !data.ButtonIdentifier.Contains(".FireButton") && !data.ButtonIdentifier.Contains(".MoveFired") && !data.ButtonIdentifier.Contains(".ColonyToolMainMenu") && !data.ButtonIdentifier.Contains(".KillFired") && !data.ButtonIdentifier.Contains(".CallToArms")) || data.Player.ActiveColony == null) return; Dictionary<string, JobCounts> jobCounts = GetJobCounts(data.Player.ActiveColony); if (data.ButtonIdentifier.Contains(".ColonyToolMainMenu")) { NetworkMenuManager.SendServerPopup(data.Player, BuildMenu(data.Player, jobCounts, false, string.Empty, 0)); } else if (data.ButtonIdentifier.Contains(".FireButton")) { foreach (var job in jobCounts) if (data.ButtonIdentifier.Contains(job.Key)) { var recruit = data.Storage.GetAs<int>(job.Key + ".Recruit"); var count = GetCountValue(recruit); var menu = BuildMenu(data.Player, jobCounts, true, job.Key, count); menu.LocalStorage.SetAs(GameLoader.NAMESPACE + ".FiredJobName", job.Key); menu.LocalStorage.SetAs(GameLoader.NAMESPACE + ".FiredJobCount", count); NetworkMenuManager.SendServerPopup(data.Player, menu); break; } } else if (data.ButtonIdentifier.Contains(".KillFired")) { var firedJob = data.Storage.GetAs<string>(GameLoader.NAMESPACE + ".FiredJobName"); var count = data.Storage.GetAs<int>(GameLoader.NAMESPACE + ".FiredJobCount"); foreach (var job in jobCounts) { if (job.Key == firedJob) { if (count > job.Value.TakenCount) count = job.Value.TakenCount; for (int i = 0; i < count; i++) { var npc = job.Value.TakenJobs[i].NPC; npc.ClearJob(); npc.OnDeath(); } break; } } data.Player.ActiveColony.SendCommonData(); jobCounts = GetJobCounts(data.Player.ActiveColony); NetworkMenuManager.SendServerPopup(data.Player, BuildMenu(data.Player, jobCounts, false, string.Empty, 0)); } else if (data.ButtonIdentifier.Contains(".MoveFired")) { var firedJob = data.Storage.GetAs<string>(GameLoader.NAMESPACE + ".FiredJobName"); var count = data.Storage.GetAs<int>(GameLoader.NAMESPACE + ".FiredJobCount"); foreach (var job in jobCounts) if (data.ButtonIdentifier.Contains(job.Key)) { if (count > job.Value.AvailableCount) count = job.Value.AvailableCount; if (jobCounts.TryGetValue(firedJob, out var firedJobCounts)) { for (int i = 0; i < count; i++) { if (firedJobCounts.TakenCount > i) { var npc = firedJobCounts.TakenJobs[i].NPC; npc.ClearJob(); npc.TakeJob(job.Value.AvailableJobs[i]); data.Player.ActiveColony.JobFinder.Remove(job.Value.AvailableJobs[i]); } else break; } } data.Player.ActiveColony.SendCommonData(); break; } jobCounts = GetJobCounts(data.Player.ActiveColony); NetworkMenuManager.SendServerPopup(data.Player, BuildMenu(data.Player, jobCounts, false, string.Empty, 0)); } else if (data.ButtonIdentifier.Contains(".RecruitButton")) { foreach (var job in jobCounts) if (data.ButtonIdentifier.Contains(job.Key)) { var recruit = data.Storage.GetAs<int>(job.Key + ".Recruit"); var count = GetCountValue(recruit); if (count > job.Value.AvailableCount) count = job.Value.AvailableCount; for (int i = 0; i < count; i++) { var num = 0f; data.Player.ActiveColony.HappinessData.RecruitmentCostCalculator.GetCost(data.Player.ActiveColony.HappinessData.CachedHappiness, data.Player.ActiveColony, out float foodCost); if (data.Player.ActiveColony.Stockpile.TotalFood < foodCost || !data.Player.ActiveColony.Stockpile.TryRemoveFood(ref num, foodCost)) { PandaChat.Send(data.Player, _localizationHelper.LocalizeOrDefault("Notenoughfood", data.Player), ChatColor.red); break; } else { var newGuy = new NPCBase(data.Player.ActiveColony, data.Player.ActiveColony.GetClosestBanner(new Vector3Int(data.Player.Position)).Position); data.Player.ActiveColony.RegisterNPC(newGuy); SettlerInventory.GetSettlerInventory(newGuy); NPCTracker.Add(newGuy); ModLoader.Callbacks.OnNPCRecruited.Invoke(newGuy); if (newGuy.IsValid) { newGuy.TakeJob(job.Value.AvailableJobs[i]); data.Player.ActiveColony.JobFinder.Remove(job.Value.AvailableJobs[i]); } } } data.Player.ActiveColony.SendCommonData(); jobCounts = GetJobCounts(data.Player.ActiveColony); NetworkMenuManager.SendServerPopup(data.Player, BuildMenu(data.Player, jobCounts, false, string.Empty, 0)); } } else if (data.ButtonIdentifier.Contains(".CallToArms")) { AI.CalltoArms.ProcesssCallToArms(data.Player, data.Player.ActiveColony); NetworkMenuManager.SendServerPopup(data.Player, BuildMenu(data.Player, jobCounts, false, string.Empty, 0)); } } public static int GetCountValue(int countIndex) { var value = _recruitCount[countIndex]; int retval = int.MaxValue; if (int.TryParse(value, out int count)) retval = count; return retval; } public static NetworkMenu BuildMenu(Players.Player player, Dictionary<string, JobCounts> jobCounts, bool fired, string firedName, int firedCount) { NetworkMenu menu = new NetworkMenu(); menu.LocalStorage.SetAs("header", _localizationHelper.LocalizeOrDefault("ColonyManagement", player)); menu.Width = 1000; menu.Height = 600; if (fired) { var count = firedCount.ToString(); if (firedCount == int.MaxValue) count = "all"; menu.Items.Add(new ButtonCallback(GameLoader.NAMESPACE + ".KillFired", new LabelData($"{_localizationHelper.LocalizeOrDefault("Kill", player)} {count} {_localizationHelper.LocalizeOrDefault("Fired", player)} {firedName}", UnityEngine.Color.black, UnityEngine.TextAnchor.MiddleCenter))); } else menu.Items.Add(new ButtonCallback(GameLoader.NAMESPACE + ".PlayerDetails", new LabelData(_localizationHelper.GetLocalizationKey("PlayerDetails"), UnityEngine.Color.black, UnityEngine.TextAnchor.MiddleCenter))); menu.Items.Add(new Line()); if (!fired) { ColonyState ps = ColonyState.GetColonyState(player.ActiveColony); if (Configuration.GetorDefault("ColonistsRecruitment", true)) { player.ActiveColony.HappinessData.RecruitmentCostCalculator.GetCost(player.ActiveColony.HappinessData.CachedHappiness, player.ActiveColony, out float num); var cost = Configuration.GetorDefault("CompoundingFoodRecruitmentCost", 2) * ps.ColonistsBought; if (cost < 1) cost = 1; menu.Items.Add(new HorizontalSplit(new Label(new LabelData(_localizationHelper.GetLocalizationKey("RecruitmentCost"), UnityEngine.Color.black)), new Label(new LabelData((cost + num).ToString(), UnityEngine.Color.black)))); } if(ps.CallToArmsEnabled) menu.Items.Add(new ButtonCallback(GameLoader.NAMESPACE + ".CallToArms", new LabelData(_localizationHelper.GetLocalizationKey("DeactivateCallToArms"), UnityEngine.Color.black, UnityEngine.TextAnchor.MiddleCenter))); else menu.Items.Add(new ButtonCallback(GameLoader.NAMESPACE + ".CallToArms", new LabelData(_localizationHelper.GetLocalizationKey("ActivateCallToArms"), UnityEngine.Color.black, UnityEngine.TextAnchor.MiddleCenter))); } List<ValueTuple<IItem, int>> header = new List<ValueTuple<IItem, int>>(); header.Add(ValueTuple.Create<IItem, int>(new Label(new LabelData(_localizationHelper.GetLocalizationKey("Job"), UnityEngine.Color.black)), 140)); if (!fired) header.Add(ValueTuple.Create<IItem, int>(new Label(new LabelData("", UnityEngine.Color.black)), 140)); header.Add(ValueTuple.Create<IItem, int>(new Label(new LabelData(_localizationHelper.GetLocalizationKey("Working"), UnityEngine.Color.black)), 140)); header.Add(ValueTuple.Create<IItem, int>(new Label(new LabelData(_localizationHelper.GetLocalizationKey("NotWorking"), UnityEngine.Color.black)), 140)); header.Add(ValueTuple.Create<IItem, int>(new Label(new LabelData("", UnityEngine.Color.black)), 140)); header.Add(ValueTuple.Create<IItem, int>(new Label(new LabelData("", UnityEngine.Color.black)), 140)); menu.Items.Add(new HorizontalRow(header)); int jobCount = 0; foreach (var jobKvp in jobCounts) { if (fired && jobKvp.Value.AvailableCount == 0) continue; jobCount++; List<ValueTuple<IItem, int>> items = new List<ValueTuple<IItem, int>>(); items.Add(ValueTuple.Create<IItem, int>(new Label(new LabelData(_localizationHelper.LocalizeOrDefault(jobKvp.Key.Replace(" ", ""), player), UnityEngine.Color.black)), 140)); if (!fired) items.Add(ValueTuple.Create<IItem, int>(new ButtonCallback(jobKvp.Key + ".JobDetailsButton", new LabelData(_localizationHelper.GetLocalizationKey("Details"), UnityEngine.Color.black, UnityEngine.TextAnchor.MiddleCenter)), 140)); items.Add(ValueTuple.Create<IItem, int>(new Label(new LabelData(jobKvp.Value.TakenCount.ToString(), UnityEngine.Color.black)), 140)); items.Add(ValueTuple.Create<IItem, int>(new Label(new LabelData(jobKvp.Value.AvailableCount.ToString(), UnityEngine.Color.black)), 140)); if (fired) { items.Add(ValueTuple.Create<IItem, int>(new ButtonCallback(jobKvp.Key + ".MoveFired", new LabelData(_localizationHelper.GetLocalizationKey("MoveFired"), UnityEngine.Color.black, UnityEngine.TextAnchor.MiddleLeft)), 140)); } else { items.Add(ValueTuple.Create<IItem, int>(new DropDown(new LabelData(_localizationHelper.GetLocalizationKey("Amount"), UnityEngine.Color.black), jobKvp.Key + ".Recruit", _recruitCount), 140)); items.Add(ValueTuple.Create<IItem, int>(new ButtonCallback(jobKvp.Key + ".RecruitButton", new LabelData(_localizationHelper.GetLocalizationKey("Recruit"), UnityEngine.Color.black, UnityEngine.TextAnchor.MiddleCenter)), 140)); items.Add(ValueTuple.Create<IItem, int>(new ButtonCallback(jobKvp.Key + ".FireButton", new LabelData(_localizationHelper.GetLocalizationKey("Fire"), UnityEngine.Color.black, UnityEngine.TextAnchor.MiddleCenter)), 140)); } menu.LocalStorage.SetAs(jobKvp.Key + ".Recruit", 0); menu.Items.Add(new HorizontalRow(items)); } if (jobCount == 0) menu.Items.Add(new Label(new LabelData(_localizationHelper.LocalizeOrDefault("NoJobs", player), UnityEngine.Color.black))); return menu; } public static Dictionary<string, JobCounts> GetJobCounts(Colony colony) { Dictionary<string, JobCounts> jobCounts = new Dictionary<string, JobCounts>(); var jobs = colony?.JobFinder?.JobsData?.OpenJobs; var npcs = colony?.Followers; if (jobs != null) foreach (var job in jobs) { if (NPCType.NPCTypes.TryGetValue(job.NPCType, out var nPCTypeSettings)) { if (!jobCounts.ContainsKey(nPCTypeSettings.PrintName)) jobCounts.Add(nPCTypeSettings.PrintName, new JobCounts() { Name = nPCTypeSettings.PrintName }); jobCounts[nPCTypeSettings.PrintName].AvailableCount++; jobCounts[nPCTypeSettings.PrintName].AvailableJobs.Add(job); } } if (npcs != null) foreach (var npc in npcs) { if (npc.Job != null && npc.Job.IsValid && NPCType.NPCTypes.TryGetValue(npc.Job.NPCType, out var nPCTypeSettings)) { if (!jobCounts.ContainsKey(nPCTypeSettings.PrintName)) jobCounts.Add(nPCTypeSettings.PrintName, new JobCounts() { Name = nPCTypeSettings.PrintName }); jobCounts[nPCTypeSettings.PrintName].TakenCount++; jobCounts[nPCTypeSettings.PrintName].TakenJobs.Add(npc.Job); } } return jobCounts; } } }
49.512397
302
0.566071
[ "MIT" ]
Egaliterrier/Pandaros.Settlers
Pandaros.Settlers/Pandaros.Settlers/ColonyManagement/ColonyTool.cs
17,975
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System.Collections.Generic; using System.Linq; using Azure.AI.Translation.Document; namespace Azure.AI.Translation.Document.Models { /// <summary> Model factory for read-only models. </summary> public static partial class BatchDocumentTranslationModelFactory { /// <summary> Initializes a new instance of FileFormat. </summary> /// <param name="format"> Name of the format. </param> /// <param name="fileExtensions"> Supported file extension for this format. </param> /// <param name="contentTypes"> Supported Content-Types for this format. </param> /// <param name="defaultFormatVersion"> Default version if none is specified. </param> /// <param name="formatVersions"> Supported Version. </param> /// <returns> A new <see cref="Document.FileFormat"/> instance for mocking. </returns> public static FileFormat FileFormat(string format = null, IEnumerable<string> fileExtensions = null, IEnumerable<string> contentTypes = null, string defaultFormatVersion = null, IEnumerable<string> formatVersions = null) { fileExtensions ??= new List<string>(); contentTypes ??= new List<string>(); formatVersions ??= new List<string>(); return new FileFormat(format, fileExtensions?.ToList(), contentTypes?.ToList(), defaultFormatVersion, formatVersions?.ToList()); } } }
45.558824
228
0.684312
[ "MIT" ]
OlhaTkachenko/azure-sdk-for-net
sdk/translation/Azure.AI.Translation.Document/src/Generated/BatchDocumentTranslationModelFactory.cs
1,549
C#
//------------------------------------------------------------------------------ // <auto-generated /> // // This file was automatically generated by SWIG (http://www.swig.org). // Version 4.0.1 // // Do not make changes to this file unless you know what you are doing--modify // the SWIG interface file instead. //------------------------------------------------------------------------------ namespace QuantLib { public class MonotonicParabolic : global::System.IDisposable { private global::System.Runtime.InteropServices.HandleRef swigCPtr; protected bool swigCMemOwn; internal MonotonicParabolic(global::System.IntPtr cPtr, bool cMemoryOwn) { swigCMemOwn = cMemoryOwn; swigCPtr = new global::System.Runtime.InteropServices.HandleRef(this, cPtr); } internal static global::System.Runtime.InteropServices.HandleRef getCPtr(MonotonicParabolic obj) { return (obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr; } ~MonotonicParabolic() { Dispose(false); } public void Dispose() { Dispose(true); global::System.GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { lock(this) { if (swigCPtr.Handle != global::System.IntPtr.Zero) { if (swigCMemOwn) { swigCMemOwn = false; NQuantLibcPINVOKE.delete_MonotonicParabolic(swigCPtr); } swigCPtr = new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero); } } } public MonotonicParabolic(QlArray x, QlArray y) : this(NQuantLibcPINVOKE.new_MonotonicParabolic(QlArray.getCPtr(x), QlArray.getCPtr(y)), true) { if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve(); } public double call(double x, bool allowExtrapolation) { double ret = NQuantLibcPINVOKE.MonotonicParabolic_call__SWIG_0(swigCPtr, x, allowExtrapolation); if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve(); return ret; } public double call(double x) { double ret = NQuantLibcPINVOKE.MonotonicParabolic_call__SWIG_1(swigCPtr, x); if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve(); return ret; } public double derivative(double x, bool extrapolate) { double ret = NQuantLibcPINVOKE.MonotonicParabolic_derivative__SWIG_0(swigCPtr, x, extrapolate); if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve(); return ret; } public double derivative(double x) { double ret = NQuantLibcPINVOKE.MonotonicParabolic_derivative__SWIG_1(swigCPtr, x); if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve(); return ret; } public double secondDerivative(double x, bool extrapolate) { double ret = NQuantLibcPINVOKE.MonotonicParabolic_secondDerivative__SWIG_0(swigCPtr, x, extrapolate); if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve(); return ret; } public double secondDerivative(double x) { double ret = NQuantLibcPINVOKE.MonotonicParabolic_secondDerivative__SWIG_1(swigCPtr, x); if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve(); return ret; } public double primitive(double x, bool extrapolate) { double ret = NQuantLibcPINVOKE.MonotonicParabolic_primitive__SWIG_0(swigCPtr, x, extrapolate); if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve(); return ret; } public double primitive(double x) { double ret = NQuantLibcPINVOKE.MonotonicParabolic_primitive__SWIG_1(swigCPtr, x); if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve(); return ret; } } }
40.460784
147
0.71529
[ "Apache-2.0" ]
andrew-stakiwicz-r3/financial_derivatives_demo
quantlib_swig_bindings/CSharp/csharp/MonotonicParabolic.cs
4,127
C#
// Copyright 2007-2016 Chris Patterson, Dru Sellers, Travis Smith, et. al. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. namespace MassTransit.EntityFrameworkCoreIntegration { using GreenPipes.Internals.Extensions; using GreenPipes.Internals.Reflection; using MassTransit.Saga; using Microsoft.EntityFrameworkCore; public static class SagaClassMapping { public static void ConfigureDefaultSagaMap<T>(this ModelBuilder modelBuilder) where T : class, ISaga { ReadWriteProperty<T> property; if (!TypeCache<T>.ReadWritePropertyCache.TryGetProperty("CorrelationId", out property)) throw new ConfigurationException("The CorrelationId property must be read/write for use with Entity Framework. Add a setter to the property."); modelBuilder.Entity<T>().HasKey(t => t.CorrelationId); modelBuilder.Entity<T>().Property(t => t.CorrelationId) .ValueGeneratedNever(); } } }
41.324324
159
0.703728
[ "Apache-2.0" ]
timmi4sa/MassTransit
src/Persistence/MassTransit.EntityFrameworkCoreIntegration/SagaClassMapping.cs
1,531
C#
namespace DynamicTranslator.ViewModel { public class Notifications : MultiThreadObservableCollection<Notification> { } }
31.25
82
0.816
[ "MIT" ]
DynamicTranslator/DynamicTranslator
src/DynamicTranslator/ViewModel/Notifications.cs
127
C#
using System; using System.Collections.Generic; using Raven.Yabt.Database.Common.References; namespace Raven.Yabt.Domain.BacklogItemServices.ByIdQuery.DTOs { public class BacklogItemCommentListGetResponse { public string Id { get; set; } = null!; public string Message { get; set; } = null!; public UserReference Author { get; set; } = null!; public DateTime Created { get; set; } public DateTime LastUpdated { get; set; } public IDictionary<string, string>? MentionedUserIds { get; set; } } }
24.619048
68
0.725338
[ "MIT" ]
gregolsky/samples-yabt
back-end/Domain/BacklogItemServices/ByIdQuery/DTOs/BacklogItemCommentListGetResponse.cs
519
C#
using MicroBootstrap.Persistence.EfCore.Postgres; namespace ECommerce.Services.Customers.Shared.Data; public class CatalogDbContextDesignFactory : DbContextDesignFactoryBase<CustomersDbContext> { public CatalogDbContextDesignFactory() : base("CustomersServiceConnection") { } }
26.545455
91
0.815068
[ "MIT" ]
BuiTanLan/ecommerce-microservices
src/Services/ECommerce.Services.Customers/ECommerce.Services.Customers/Shared/Data/DbContextDesignFactory.cs
292
C#
using System.Collections.Generic; using ISAAR.MSolve.Discretization.FreedomDegrees; using ISAAR.MSolve.FEM.Embedding; using ISAAR.MSolve.FEM.Entities; namespace ISAAR.MSolve.FEM.Interfaces { public interface IEmbeddedElement { IList<EmbeddedNode> EmbeddedNodes { get; } Dictionary<IDofType, int> GetInternalNodalDOFs(Element element, Node node); double[] GetLocalDOFValues(Element hostElement, double[] hostDOFValues); } }
30.733333
83
0.754881
[ "Apache-2.0" ]
TheoChristo/MSolve.Bio
ISAAR.MSolve.FEM/Interfaces/IEmbeddedElement.cs
463
C#
using System.Collections.Generic; using System.Linq; using Content.Server.GameObjects.Components.Markers; using Robust.Server.Interfaces.Console; using Robust.Server.Interfaces.Player; using Robust.Shared.Enums; using Robust.Shared.Interfaces.GameObjects; using Robust.Shared.Interfaces.Map; using Robust.Shared.IoC; using Robust.Shared.Map; namespace Content.Server.Administration { public class WarpCommand : IClientCommand { public string Command => "warp"; public string Description => "Teleports you to predefined areas on the map."; public string Help => "warp <location>\nLocations you can teleport to are predefined by the map. " + "You can specify '?' as location to get a list of valid locations."; public void Execute(IConsoleShell shell, IPlayerSession player, string[] args) { if (player == null) { shell.SendText((IPlayerSession) null, "Only players can use this command"); return; } if (args.Length != 1) { shell.SendText(player, "Expected a single argument."); return; } var comp = IoCManager.Resolve<IComponentManager>(); var location = args[0]; if (location == "?") { var locations = string.Join(", ", comp.EntityQuery<WarpPointComponent>() .Select(p => p.Location) .Where(p => p != null) .OrderBy(p => p) .Distinct()); shell.SendText(player, locations); } else { if (player.Status != SessionStatus.InGame || player.AttachedEntity == null) { shell.SendText(player, "You are not in-game!"); return; } var mapManager = IoCManager.Resolve<IMapManager>(); var currentMap = player.AttachedEntity.Transform.MapID; var currentGrid = player.AttachedEntity.Transform.GridID; var found = comp.EntityQuery<WarpPointComponent>() .Where(p => p.Location == location) .Select(p => p.Owner.Transform.GridPosition) .OrderBy(p => p, Comparer<GridCoordinates>.Create((a, b) => { // Sort so that warp points on the same grid/map are first. // So if you have two maps loaded with the same warp points, // it will prefer the warp points on the map you're currently on. if (a.GridID == b.GridID) { return 0; } if (a.GridID == currentGrid) { return -1; } if (b.GridID == currentGrid) { return 1; } var mapA = mapManager.GetGrid(a.GridID).ParentMapId; var mapB = mapManager.GetGrid(b.GridID).ParentMapId; if (mapA == mapB) { return 0; } if (mapA == currentMap) { return -1; } if (mapB == currentMap) { return 1; } return 0; })) .FirstOrDefault(); if (found.GridID != GridId.Invalid) { player.AttachedEntity.Transform.GridPosition = found; } else { shell.SendText(player, "That location does not exist!"); } } } } }
34.798319
91
0.444579
[ "MIT" ]
Hughgent/space-station-14
Content.Server/Administration/WarpCommand.cs
4,143
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; namespace HospiEnCasa.App.Servicios.Controllers { [ApiController] [Route("[controller]")] public class WeatherForecastController : ControllerBase { private static readonly string[] Summaries = new[] { "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" }; private readonly ILogger<WeatherForecastController> _logger; public WeatherForecastController(ILogger<WeatherForecastController> logger) { _logger = logger; } [HttpGet] public IEnumerable<WeatherForecast> Get() { var rng = new Random(); return Enumerable.Range(1, 5).Select(index => new WeatherForecast { Date = DateTime.Now.AddDays(index), TemperatureC = rng.Next(-20, 55), Summary = Summaries[rng.Next(Summaries.Length)] }) .ToArray(); } } }
28.925
110
0.603284
[ "CC0-1.0" ]
felipeescallon/mision_tic_2022
ciclo3_desarrollo_software/ucaldas/BACKEND/Hospitalizacion_s2/HospiEnCasa.App/HospiEnCasa.App.Servicios/Controllers/WeatherForecastController.cs
1,159
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Events; using System; using System.IO.Ports; using System.Threading; public class Tilt : MonoBehaviour { // Public Variables (for changing in insepctor) private static float magnitude = -9.81f; private static GameObject gravityObject; public static Vector3 Gravity { get { if (gravityObject == null) { return Vector3.up; } return gravityObject.transform.up * magnitude; } } //public GameObject gravPointer; // Private Variables char[] packet = new char[14]; // InvenSense packet int serialCount = 0; // current packet byte position int synced = 0; float[] q = new float[4]; void Start() { // /dev/cu.wchusbserial14xx0 OR COMx if (Director.useGyro && !Director.sp.IsOpen) { SetupController(); } if (gravityObject != null) { throw new Exception(); } gravityObject = gameObject; //gravPointer = GameObject.Find("GravPointer"); } void FixedUpdate() { // if useGyro is false use the if (!Director.useGyro) { if (Input.GetAxis("Horizontal") > .2) { this.transform.rotation *= Quaternion.Euler(0, 0, 0.1f* Director.gyroSensitivity); } if (Input.GetAxis("Horizontal") < -.2) { this.transform.rotation *= Quaternion.Euler(0, 0, -0.1f* Director.gyroSensitivity); } if (Input.GetAxis("Vertical") > .2) { this.transform.rotation *= Quaternion.Euler(0.1f* Director.gyroSensitivity, 0, 0); } if (Input.GetAxis("Vertical") < -.2) { this.transform.rotation *= Quaternion.Euler(-0.1f* Director.gyroSensitivity, 0, 0); } } else { if (Director.sp == null) { SetupController(); } while (Director.sp.BytesToRead > 0) { int ch = Director.sp.ReadByte(); // # indicates that arduino has received button press if (serialCount == 0 && ch == '#') { if (Director.buttonDelay <= 0) { Director.buttonDelay = Director.buttonDelayMax; Director.SetPressed(true); } else { Director.SetPressed(false); } } // @ indicates that arduino has speifically has no button press else if (serialCount == 0 && ch == '@') { Director.buttonDelay = 0; Director.SetPressed(false); } if (synced == 0 && ch != '$') return; // initial synchronization - also used to resync/realign if needed synced = 1; if ((serialCount == 1 && ch != 2) || (serialCount == 12 && ch != '\r') || (serialCount == 13 && ch != '\n')) { serialCount = 0; synced = 0; return; } if (serialCount > 0 || ch == '$') { packet[serialCount++] = (char)ch; if (serialCount == 14) { serialCount = 0; // restart packet byte position // get quaternion from data packet q[0] = ((packet[2] << 8) | packet[3]) / 16384.0f; q[1] = ((packet[4] << 8) | packet[5]) / 16384.0f; q[2] = ((packet[6] << 8) | packet[7]) / 16384.0f; q[3] = ((packet[8] << 8) | packet[9]) / 16384.0f; for (int i = 0; i < 4; i++) if (q[i] >= 2) q[i] = -4 + q[i]; // set our toxilibs quaternion to new data //transform.rotation = new Quaternion(q[2], q[0], -q[1], q[3]); transform.rotation = new Quaternion(q[2], q[0], -q[1], q[3]); } } } } //GameObject.Find("Ball(Clone)").GetComponent<Rigidbody>().AddForce(transform.up * magnitude, ForceMode.Acceleration); //gravPointer.transform.position = transform.up*magnitude; //mCamera.transform.position = 10*(new Vector3(-grav.x, -grav.y, -grav.z)); //mCamera.transform.LookAt(new Vector3(0, 0, 0)); } void SetupController() { // sp = new SerialPort("/dev/cu.wchusbserial14110", 9600); // sp = new SerialPort("COM6", 9600); // sp.Open(); //Auto detect implementation. string[] ports = SerialPort.GetPortNames(); foreach (string p in ports) { try { print("Attempted to connect to: " + p); Director.sp = new SerialPort(p, 9600); Director.sp.Open(); // Sucessfully reads input from sp, meaning the port is valid. if (Director.sp.BytesToRead != 0) { break; } } catch (InvalidOperationException e) { // Port in use print(e); continue; } catch (System.IO.IOException e) { // Port can't be opened print(e); continue; } } } }
32.538889
126
0.446474
[ "MIT" ]
KevinLi3/GyroscopeMaze
SE101 Unity Physics/Assets/Scripts/Systems/Tilt.cs
5,859
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc.RazorPages; namespace asp_core_teamsnap_oauth.Pages { public class ContactModel : PageModel { public string Message { get; set; } public void OnGet() { Message = "Your contact page."; } } }
19.842105
43
0.657825
[ "MIT" ]
EgyTechnology/asp-core-teamsnap-oauth
asp-core-teamsnap-oauth/Pages/Contact.cshtml.cs
379
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("GoFDesignPatternsToolboxItems")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("GoFDesignPatternsToolboxItems")] [assembly: AssemblyCopyright("")] [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)] // 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.382353
84
0.749803
[ "Apache-2.0" ]
jdm7dv/visual-studio
Patterns/umldesignpatterns-15281/Dev/GoFDesignPatternsToolboxItems/GoFDesignPatternsToolboxItems/Properties/AssemblyInfo.cs
1,273
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. namespace TyeExplorer.Tye.Models { public enum V1RunInfoType { Project, Executable, Docker } }
24
71
0.6875
[ "MIT" ]
ikkentim/vs-tye-explorer
TyeExplorer/Tye/Models/V1RunInfoType.cs
338
C#
using AdaptiveCards; using Antares.Bot.Channels; using Microsoft.Bot.Builder.Dialogs; using Microsoft.Bot.Connector; using Microsoft.Bot.Connector.Teams; using Microsoft.Bot.Connector.Teams.Models; using Microsoft.Teams.Apps.QBot.Bot.Services; using Microsoft.Teams.Apps.QBot.Bot.utility; using Microsoft.Teams.Apps.QBot.Model; using Microsoft.Teams.Apps.QBot.Model.Teams; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Web; using Task = System.Threading.Tasks.Task; namespace Microsoft.Teams.Apps.QBot.Bot.Dialogs { [Serializable] public class RootDialog : IDialog<object> { private ResourceService resourceService; public RootDialog() { resourceService = new ResourceService(); } public Task StartAsync(IDialogContext context) { context.Wait(MessageReceivedAsync); return Task.CompletedTask; } private async Task MessageReceivedAsync(IDialogContext context, IAwaitable<object> result) { // Init var activity = await result as Microsoft.Bot.Connector.Activity; // Handle tagged in a question // Check if we already have this particular conversation saved. This is to counter the auto-tagging when replying to a bot in Teams if (SQLService.DoesConversationIdExist(activity.Conversation.Id)) { // Do nothing if we find it. } else { // Check if this is a group (channel) or a 1-on-1 conversation if (activity.Conversation.IsGroup == true) { await HandleChannelConversation(context, activity); } else { await HandleOneOnOneConversation(activity); } } } private async Task HandleOneOnOneConversation(Microsoft.Bot.Connector.Activity activity) { var connector = new ConnectorClient(new Uri(activity.ServiceUrl)); // One-on-one chat isn't support yet, encourage to post question in the channel instead var defaultReply = activity.CreateReply("Please post your question in the channel instead -- and don't forget to tag me, so I know about it!"); await connector.Conversations.ReplyToActivityAsync(defaultReply); } private async Task HandleChannelConversation(IDialogContext context, Microsoft.Bot.Connector.Activity activity) { var connector = new ConnectorClient(new Uri(activity.ServiceUrl)); // Channel conversation // Get the question text, and team and channel details var question = activity.Text; var messageId = activity.Id; var conversationId = activity.Conversation.Id; var channelData = activity.GetChannelData<TeamsChannelData>(); string tenantId = channelData.Tenant.Id; string teamId = channelData.Team.Id; string channelId = channelData.Channel.Id; TeamDetails teamDetails = connector.GetTeamsConnectorClient().Teams.FetchTeamDetails(teamId); var teamName = teamDetails.Name; var groupId = teamDetails.AadGroupId; ConversationList channelList = connector.GetTeamsConnectorClient().Teams.FetchChannelList(teamId); var channel = channelList.Conversations.Where(x => x.Id == channelId).FirstOrDefault(); var channelName = channel?.Name; var topic = channelName ?? "General"; IList<ChannelAccount> members = await connector.Conversations.GetConversationMembersAsync(teamId); var teamsMembers = members.AsTeamsChannelAccounts(); // Get original poster var originalPosterAsTeamsChannelAccount = teamsMembers.Where(x => x.ObjectId == activity.From.Properties["aadObjectId"].ToString()).FirstOrDefault(); var userUpn = originalPosterAsTeamsChannelAccount.UserPrincipalName; var user = SQLService.GetUser(userUpn); // strip @bot mention for teams if (activity.ChannelId == "msteams") { activity = MicrosoftTeamsChannelHelper.StripAtMentionText(activity); } else { activity.Text = activity.Text.Trim(); } // strip the html tags question = MicrosoftTeamsChannelHelper.StripHtmlTags(activity.Text); var questionModel = new QuestionModel() { ID = 0, TenantId = tenantId, GroupId = groupId, TeamId = teamId, TeamName = teamName, ConversationId = conversationId, MessageId = messageId, Topic = topic, QuestionText = question, QuestionSubmitted = DateTime.Now, OriginalPoster = user, Link = CreateLink(conversationId, tenantId, groupId, messageId, teamName, topic), }; if (string.IsNullOrEmpty(question)) { await HandleNoQuestion(context, activity, questionModel, channelId); } else { // get courseID var courseID = SQLService.GetCourseIDByName(teamName.Trim()); var course = SQLService.GetCourse(courseID); questionModel.CourseID = courseID; await HandleQuestionWorkflow(context, activity, course, questionModel); } } private async Task HandleQuestionWorkflow(IDialogContext context, Microsoft.Bot.Connector.Activity activity, Data.Course course, QuestionModel questionModel) { var predictiveQnAService = new PredictiveQnAService(course.Id); QnAAnswer response = await predictiveQnAService.GetAnswer(questionModel.QuestionText); // if result, check confidence level if (response != null && response.Score > Convert.ToDouble(course.PredictiveQnAConfidenceThreshold)) { await HandleBotAnswerWorkflow(context, activity, questionModel, response, questionModel.TeamId); } else { // a score of 0 or a score below threshold both result in regular workflow await HandleTagAdminWorkflow(activity, questionModel, questionModel.TeamId, course.Id); } } private async Task HandleBotAnswerWorkflow(IDialogContext context, Microsoft.Bot.Connector.Activity activity, QuestionModel questionModel, QnAAnswer response, string teamId) { var connector = new ConnectorClient(new Uri(activity.ServiceUrl)); // above threshold // post answer card with helpful/not-helpful // Set question state questionModel.QuestionStatus = Constants.QUESTION_STATUS_UNANSWERED; // Save question var questionId = SQLService.CreateOrUpdateQuestion(questionModel); var attachment = CreateBotAnswerCard(response.Id, response.Answer, response.Score, questionId, questionModel.OriginalPoster.Email); var reply = activity.CreateReply(); reply.Attachments.Add(attachment); await context.PostAsync(reply); } private async Task HandleTagAdminWorkflow(Microsoft.Bot.Connector.Activity activity, QuestionModel questionModel, string teamId, int courseId) { var connector = new ConnectorClient(new Uri(activity.ServiceUrl)); // Tag admin workflow IList<ChannelAccount> members = await connector.Conversations.GetConversationMembersAsync(teamId); var teamsMembers = members.AsTeamsChannelAccounts().ToList(); // Get original poster var originalPosterAsTeamsChannelAccount = teamsMembers.Where(x => x.ObjectId == activity.From.Properties["aadObjectId"].ToString()).FirstOrDefault(); var studentUPN = originalPosterAsTeamsChannelAccount.UserPrincipalName; var mappedStudentCourseRole = SQLService.GetUser(studentUPN); // Set question state var questionStatus = Constants.QUESTION_STATUS_UNANSWERED; // Save question questionModel.QuestionStatus = questionStatus; questionModel.OriginalPoster = mappedStudentCourseRole; var questionId = SQLService.CreateOrUpdateQuestion(questionModel); questionModel.ID = questionId; // TagAdmins var mentionOnlyReply = activity.CreateReply(); var adminsOnTeams = GetAdminChannelAccountsToTag(activity, teamId, courseId, teamsMembers, mappedStudentCourseRole); foreach (var admin in adminsOnTeams) { mentionOnlyReply.AddMentionToText(admin, MentionTextLocation.AppendText); } var r1 = await connector.Conversations.ReplyToActivityAsync(mentionOnlyReply); var reply = activity.CreateReply(); var attachment = CreateUserAnswerCard(questionId); reply.Attachments.Add(attachment); var r2 = await connector.Conversations.ReplyToActivityAsync(reply); questionModel.AnswerCardActivityId = r2?.Id; SQLService.CreateOrUpdateQuestion(questionModel); } private async Task HandleNoQuestion(IDialogContext context, Microsoft.Bot.Connector.Activity activity, QuestionModel questionModel, string channelId) { var messageId = questionModel.MessageId; // We stripped the @mention and html tags. If nothing remains then this means the user forgot to tag the bot in the original question and tagged it in a reply, so we need to handle it // Get the ID of the parent message (which should be the root) var thisTeamsMessage = await GetMessage(questionModel.GroupId, channelId, messageId); // check for null below if (thisTeamsMessage == null) { // Get root message var rootTeamsMessage = await GetRootMessage(questionModel.GroupId, channelId, messageId, questionModel.ConversationId); var question = MicrosoftTeamsChannelHelper.StripHtmlTags(rootTeamsMessage.Body.Content); messageId = rootTeamsMessage.Id; var conversationId = channelId + @";messageid=" + messageId; questionModel.QuestionText = question; questionModel.MessageId = messageId; questionModel.ConversationId = conversationId; // Get original poster var connector = new ConnectorClient(new Uri(activity.ServiceUrl)); IList<ChannelAccount> members = await connector.Conversations.GetConversationMembersAsync(questionModel.TeamId); var teamsMembers = members.AsTeamsChannelAccounts(); var originalPosterAsTeamsChannelAccount = teamsMembers.Where(x => x.ObjectId == rootTeamsMessage.From.User.Id).FirstOrDefault(); var userUpn = originalPosterAsTeamsChannelAccount.UserPrincipalName; var user = SQLService.GetUser(userUpn); // Handle if the bot gets tagged again in the same set of replies if (SQLService.DoesConversationIdExist(conversationId)) { // WE DO NOTHING! } else { // get courseID var courseID = SQLService.GetCourseIDByName(questionModel.TeamName.Trim()); var course = SQLService.GetCourse(courseID); questionModel.CourseID = courseID; await HandleQuestionWorkflow(context, activity, course, questionModel); } } else { // Empty was the root, which means the user simply forgot to ask a question. await context.PostAsync($"If you have a question, please include it as part of your message."); } } private List<ChannelAccount> GetAdminChannelAccountsToTag(Microsoft.Bot.Connector.Activity activity, string teamId, int courseID, List<TeamsChannelAccount> teamsMembers, UserCourseRoleMappingModel mappedStudentCourseRole) { var adminsOnTeams = new List<ChannelAccount>(); if (mappedStudentCourseRole != null) { if (mappedStudentCourseRole.Role != null && mappedStudentCourseRole.Role.Name != Constants.STUDENT_ROLE) { // Not a student - notify lecturer var lecturers = SQLService.GetUsersByRole(Constants.LECTURER_ROLE, courseID); foreach (var admin in lecturers) { var adminOnTeams = teamsMembers.Where(x => (x.Email.ToLower() == admin.Email.ToLower() || x.Email.ToLower() == admin.UserName.ToLower() || x.UserPrincipalName.ToLower() == admin.UserName.ToLower() || x.UserPrincipalName.ToLower() == admin.Email.ToLower()) && (x.Email != mappedStudentCourseRole.Email && x.Email != mappedStudentCourseRole.UserName && x.UserPrincipalName != mappedStudentCourseRole.UserName && x.UserPrincipalName != mappedStudentCourseRole.Email) ).FirstOrDefault(); if (adminOnTeams != null) { adminsOnTeams.Add(adminOnTeams); } } } else { // Is a student if (mappedStudentCourseRole.TutorialGroups != null && mappedStudentCourseRole.TutorialGroups.Count > 0) { // Notify demonstrator var tutorialAdmins = new List<UserCourseRoleMappingModel>(); foreach (var tutorialGroup in mappedStudentCourseRole.TutorialGroups) { tutorialAdmins.AddRange(SQLService.GetDemonstrators(courseID)); } if (tutorialAdmins != null) { foreach (var admin in tutorialAdmins) { var adminOnTeams = teamsMembers.Where(x => (x.Email == admin.Email || x.Email == admin.UserName || x.UserPrincipalName == admin.UserName || x.UserPrincipalName == admin.Email) && (x.Email != mappedStudentCourseRole.Email && x.Email != mappedStudentCourseRole.UserName && x.UserPrincipalName != mappedStudentCourseRole.UserName && x.UserPrincipalName != mappedStudentCourseRole.Email) ).FirstOrDefault(); if (adminOnTeams != null) { adminsOnTeams.Add(adminOnTeams); } } } } else { // student without tutorial class var allAdmins = SQLService.GetAllAdmins(courseID).Distinct(); if (allAdmins != null) { foreach (var admin in allAdmins) { var adminOnTeams = teamsMembers.Where(x => (x.Email == admin.Email || x.Email == admin.UserName || x.UserPrincipalName == admin.UserName || x.UserPrincipalName == admin.Email) && (x.Email != mappedStudentCourseRole.Email && x.Email != mappedStudentCourseRole.UserName && x.UserPrincipalName != mappedStudentCourseRole.UserName && x.UserPrincipalName != mappedStudentCourseRole.Email) ).FirstOrDefault(); if (adminOnTeams != null) { adminsOnTeams.Add(adminOnTeams); } } } } } } else { // User not in database // Notify lecturer var lecturers = SQLService.GetUsersByRole(Constants.LECTURER_ROLE, courseID); foreach (var admin in lecturers) { var adminOnTeams = teamsMembers.Where(x => (x.Email == admin.Email || x.Email == admin.UserName || x.UserPrincipalName == admin.UserName || x.UserPrincipalName == admin.Email) ).FirstOrDefault(); if (adminOnTeams != null) { adminsOnTeams.Add(adminOnTeams); } } } // Avoid tagging same person twice if they are part of multiple tutorial groups var distinct = adminsOnTeams .GroupBy(p => p.Id) .Select(g => g.First()) .ToList(); return distinct; } private Attachment CreateBotAnswerCard(int qnaId, string answerText, double confidenceScore, int questionId, string userUpn) { var card = new AdaptiveCard(); var title = new AdaptiveTextBlock("'" + answerText.ReplaceLinksWithMarkdown() + "'"); title.Weight = AdaptiveTextWeight.Bolder; title.Size = AdaptiveTextSize.Medium; title.Wrap = true; var confidence = new AdaptiveTextBlock("I think that is the answer (confidence score of " + confidenceScore.ToString("0.##") + "%)"); confidence.Wrap = true; card.Body.Add(title); card.Body.Add(confidence); var actionHelpfulJson = "{\"type\":\"" + Constants.ACTIVITY_BOT_HELPFUL + "\",\"questionId\": \"" + questionId + "\", \"answer\": \"" + answerText + "\", \"qnaId\": \"" + qnaId + "\"}"; var actionUnhelpfulJson = "{\"type\":\"" + Constants.ACTIVITY_BOT_NOT_HELPFUL + "\",\"questionId\": \"" + questionId + "\" ,\"userUpn\": \"" + userUpn + "\"}"; card.Actions.AddRange(new List<AdaptiveAction>() { new AdaptiveSubmitAction() { Type = AdaptiveSubmitAction.TypeName, Title = "This is helpful", DataJson = actionHelpfulJson }, new AdaptiveSubmitAction() { Type = AdaptiveSubmitAction.TypeName, Title = this.resourceService.GetValueFor("TagAdmins"), DataJson = actionUnhelpfulJson }, }); Attachment attachment = new Attachment() { ContentType = AdaptiveCard.ContentType, Content = card, }; return attachment; } private Attachment CreateUserAnswerCard(int questionId) { var actionJson = "{\"type\":\"" + Constants.ACTIVITY_SELECT_ANSWER + "\",\"questionId\": \"" + questionId + "\"}"; var card = new HeroCard() { Buttons = new List<CardAction>() { new CardAction(ActivityTypes.Invoke, "Select the answer", value: actionJson), }, }; return card.ToAttachment(); } private string CreateLink(string conversationIdString, string tenantId, string groupId, string messageId, string teamName, string channelName) { var conversationId = conversationIdString.Split(';')[0]; var linkBuilder = new StringBuilder(string.Empty); linkBuilder.Append(@"https://teams.microsoft.com/l/message/" + conversationId); linkBuilder.Append(@"/" + messageId); linkBuilder.Append(@"?tenantId=" + tenantId); linkBuilder.Append(@"&groupId=" + groupId); linkBuilder.Append(@"&parentMessageId=" + messageId); linkBuilder.Append(@"&teamName=" + HttpUtility.UrlEncode(teamName)); linkBuilder.Append(@"&channelName=" + HttpUtility.UrlEncode(channelName)); linkBuilder.Append(@"&createdTime=" + messageId); return linkBuilder.ToString(); } private async Task<TeamsMessage> GetRootMessage(string teamsId, string channelId, string messageId, string conversationId) { // Get root message id from conversationid var rootMessageId = conversationId.Split(';')[1].Split('=')[1]; var authority = ServiceHelper.Authority; var resource = ServiceHelper.GraphResource; var authService = new AuthService(authority); var authResult = await authService.AuthenticateSilently(resource); var graphService = new GraphService(); var teamsMessage = await graphService.GetMessage(authResult.AccessToken, teamsId, channelId, rootMessageId); return teamsMessage; } private async Task<TeamsMessage> GetMessage(string teamsId, string channelId, string messageId) { var authority = ServiceHelper.Authority; var resource = ServiceHelper.GraphResource; var authService = new AuthService(authority); var authResult = await authService.AuthenticateSilently(resource); var graphService = new GraphService(); var teamsMessage = await graphService.GetMessage(authResult.AccessToken, teamsId, channelId, messageId); return teamsMessage; } } }
46.589474
243
0.586534
[ "MIT" ]
FrancisChung/QBot
Source/Microsoft.Teams.Apps.QBot.Bot/Dialogs/RootDialog.cs
22,132
C#
using nscreg.Utilities.Enums.Predicate; namespace nscreg.Business.SampleFrames { public class ExpressionTuple<T> where T : class { public T Predicate { get; set; } public ComparisonEnum? Comparison { get; set; } } }
22.272727
55
0.673469
[ "Apache-2.0" ]
runejo/statbus
src/nscreg.Business/SampleFrames/ExpressionTuple.cs
245
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Pair { public class Pair<T> { private readonly object first; private readonly object second; public object First { get { return first; } } public object Second { get { return second; } } public Pair() { } public Pair(T object1, T object2) { first = object1; second = object2; } public override bool Equals(object obj) { if (obj is Pair<T>) { Pair<T> pair = obj as Pair<T>; if (!first.Equals(pair.first)) { return false; } if (!second.Equals(pair.second)) { return false; } return true; } else return false; } public static bool operator ==(Pair<T> firstPair, Pair<T> secondPair) { return object.Equals(firstPair, secondPair); } public static bool operator !=(Pair<T> firstPair, Pair<T> secondPair) { return !object.Equals(firstPair, secondPair); } public override string ToString() { return string.Format("Pair({0}, {1})", First, Second); } public override int GetHashCode() { unchecked { int hash = 17; hash = hash * 23 + First.GetHashCode(); hash = hash * 23 + Second.GetHashCode(); return hash; } } } }
24.15493
77
0.472886
[ "MIT" ]
dragomirevgeniev/HackBulgaria
Programming101-CSharp/week04/1.Tuesday/GenericPair/Pair.cs
1,717
C#
using System; using System.Collections.Generic; using System.Net; using System.Threading.Tasks; using Moq; using NBitcoin; using NBitcoin.DataEncoders; using NBitcoin.Protocol; using Stratis.Bitcoin.Base; using Stratis.Bitcoin.Configuration; using Stratis.Bitcoin.Connection; using Stratis.Bitcoin.Consensus; using Stratis.Bitcoin.Controllers.Models; using Stratis.Bitcoin.Features.RPC.Controllers; using Stratis.Bitcoin.Features.RPC.Exceptions; using Stratis.Bitcoin.Features.RPC.Models; using Stratis.Bitcoin.Interfaces; using Stratis.Bitcoin.P2P.Peer; using Stratis.Bitcoin.Tests.Common; using Stratis.Bitcoin.Tests.Common.Logging; using Stratis.Bitcoin.Tests.Wallet.Common; using Stratis.Bitcoin.Utilities; using Xunit; namespace Stratis.Bitcoin.Features.RPC.Tests.Controller { public class FullNodeControllerTest : LogsTestBase { private ChainIndexer chain; private readonly Mock<INodeLifetime> nodeLifeTime; private readonly Mock<IFullNode> fullNode; private readonly Mock<IChainState> chainState; private readonly Mock<IConnectionManager> connectionManager; private Network network; private NodeSettings nodeSettings; private readonly Mock<IPooledTransaction> pooledTransaction; private readonly Mock<IPooledGetUnspentTransaction> pooledGetUnspentTransaction; private readonly Mock<IGetUnspentTransaction> getUnspentTransaction; private readonly Mock<INetworkDifficulty> networkDifficulty; private readonly Mock<IConsensusManager> consensusManager; private readonly Mock<IBlockStore> blockStore; private FullNodeController controller; public FullNodeControllerTest() { this.nodeLifeTime = new Mock<INodeLifetime>(); this.fullNode = new Mock<IFullNode>(); this.fullNode.SetupGet(p => p.NodeLifetime).Returns(this.nodeLifeTime.Object); this.chainState = new Mock<IChainState>(); this.connectionManager = new Mock<IConnectionManager>(); this.network = KnownNetworks.TestNet; this.chain = WalletTestsHelpers.GenerateChainWithHeight(3, this.network); this.nodeSettings = new NodeSettings(this.Network); this.pooledTransaction = new Mock<IPooledTransaction>(); this.pooledGetUnspentTransaction = new Mock<IPooledGetUnspentTransaction>(); this.getUnspentTransaction = new Mock<IGetUnspentTransaction>(); this.networkDifficulty = new Mock<INetworkDifficulty>(); this.consensusManager = new Mock<IConsensusManager>(); this.blockStore = new Mock<IBlockStore>(); this.controller = new FullNodeController(this.LoggerFactory.Object, this.pooledTransaction.Object, this.pooledGetUnspentTransaction.Object, this.getUnspentTransaction.Object, this.networkDifficulty.Object, this.fullNode.Object, this.nodeSettings, this.network, this.chain, this.chainState.Object, this.connectionManager.Object, this.consensusManager.Object, this.blockStore.Object); } [Fact] public async Task Stop_WithoutFullNode_DoesNotThrowExceptionAsync() { IFullNode fullNode = null; this.controller = new FullNodeController(this.LoggerFactory.Object, this.pooledTransaction.Object, this.pooledGetUnspentTransaction.Object, this.getUnspentTransaction.Object, this.networkDifficulty.Object, fullNode, this.nodeSettings, this.network, this.chain, this.chainState.Object, this.connectionManager.Object); await this.controller.Stop().ConfigureAwait(false); } [Fact] public async Task Stop_WithFullNode_DisposesFullNodeAsync() { await this.controller.Stop().ConfigureAwait(false); this.nodeLifeTime.Verify(n => n.StopApplication()); } [Fact] public async Task GetRawTransactionAsync_TransactionCannotBeFound_ThrowsExceptionAsync() { var txId = new uint256(12142124); this.pooledTransaction.Setup(p => p.GetTransaction(txId)) .ReturnsAsync((Transaction)null) .Verifiable(); this.blockStore.Setup(b => b.GetTransactionById(txId)) .Returns((Transaction)null) .Verifiable(); RPCServerException exception = await Assert.ThrowsAsync<RPCServerException>(async () => { TransactionModel result = await this.controller.GetRawTransactionAsync(txId.ToString(), 0).ConfigureAwait(false); }); Assert.NotNull(exception); Assert.Equal("No such mempool transaction. Use -txindex to enable blockchain transaction queries.", exception.Message); this.blockStore.Verify(); this.pooledTransaction.Verify(); this.blockStore.Verify(); } [Fact] public async Task GetRawTransactionAsync_TransactionNotInPooledTransaction_ReturnsTransactionFromBlockStoreAsync() { var txId = new uint256(12142124); this.pooledTransaction.Setup(p => p.GetTransaction(txId)) .ReturnsAsync((Transaction)null); Transaction transaction = this.CreateTransaction(); this.blockStore.Setup(b => b.GetTransactionById(txId)) .Returns(transaction); TransactionModel result = await this.controller.GetRawTransactionAsync(txId.ToString(), 0).ConfigureAwait(false); Assert.NotNull(result); var model = Assert.IsType<TransactionBriefModel>(result); Assert.Equal(transaction.ToHex(), model.Hex); } [Fact] public async Task GetRawTransactionAsync_PooledTransactionServiceNotAvailable_ReturnsTransactionFromBlockStoreAsync() { var txId = new uint256(12142124); Transaction transaction = this.CreateTransaction(); this.blockStore.Setup(b => b.GetTransactionById(txId)) .Returns(transaction); this.controller = new FullNodeController(this.LoggerFactory.Object, null, this.pooledGetUnspentTransaction.Object, this.getUnspentTransaction.Object, this.networkDifficulty.Object, this.fullNode.Object, this.nodeSettings, this.network, this.chain, this.chainState.Object, this.connectionManager.Object, this.consensusManager.Object, this.blockStore.Object); TransactionModel result = await this.controller.GetRawTransactionAsync(txId.ToString(), 0).ConfigureAwait(false); Assert.NotNull(result); var model = Assert.IsType<TransactionBriefModel>(result); Assert.Equal(transaction.ToHex(), model.Hex); } [Fact] public async Task GetRawTransactionAsync_PooledTransactionAndBlockStoreServiceNotAvailable_ReturnsNullAsync() { var txId = new uint256(12142124); this.blockStore.Setup(f => f.GetTransactionById(txId)) .Returns((Transaction)null) .Verifiable(); this.controller = new FullNodeController(this.LoggerFactory.Object, null, this.pooledGetUnspentTransaction.Object, this.getUnspentTransaction.Object, this.networkDifficulty.Object, this.fullNode.Object, this.nodeSettings, this.network, this.chain, this.chainState.Object, this.connectionManager.Object, this.consensusManager.Object, this.blockStore.Object); RPCServerException exception = await Assert.ThrowsAsync<RPCServerException>(async () => { TransactionModel result = await this.controller.GetRawTransactionAsync(txId.ToString(), 0).ConfigureAwait(false); }); Assert.NotNull(exception); Assert.Equal("No such mempool transaction. Use -txindex to enable blockchain transaction queries.", exception.Message); this.blockStore.Verify(); } [Fact] public async Task GetTaskAsync_Verbose_ReturnsTransactionVerboseModelAsync() { // Add the 'txindex' setting, otherwise the transactions won't be found. this.nodeSettings.ConfigReader.MergeInto(new TextFileConfiguration("-txindex=1")); this.chainState.Setup(c => c.ConsensusTip) .Returns(this.chain.Tip); ChainedHeader block = this.chain.GetHeader(1); Transaction transaction = this.CreateTransaction(); var txId = new uint256(12142124); this.pooledTransaction.Setup(p => p.GetTransaction(txId)) .ReturnsAsync(transaction); this.blockStore.Setup(b => b.GetBlockIdByTransactionId(txId)) .Returns(block.HashBlock); this.controller = new FullNodeController(this.LoggerFactory.Object, this.pooledTransaction.Object, this.pooledGetUnspentTransaction.Object, this.getUnspentTransaction.Object, this.networkDifficulty.Object, this.fullNode.Object, this.nodeSettings, this.network, this.chain, this.chainState.Object, this.connectionManager.Object, this.consensusManager.Object, this.blockStore.Object); TransactionModel result = await this.controller.GetRawTransactionAsync(txId.ToString(), 1).ConfigureAwait(false); Assert.NotNull(result); var model = Assert.IsType<TransactionVerboseModel>(result); Assert.Equal(transaction.GetHash().ToString(), model.TxId); Assert.Equal(transaction.GetSerializedSize(), model.Size); Assert.Equal(transaction.Version, model.Version); Assert.Equal((uint)transaction.LockTime, model.LockTime); Assert.Equal(transaction.ToHex(), model.Hex); Assert.Equal(block.HashBlock.ToString(), model.BlockHash); Assert.Equal(3, model.Confirmations); Assert.Equal(Utils.DateTimeToUnixTime(block.Header.BlockTime), model.Time); Assert.Equal(Utils.DateTimeToUnixTime(block.Header.BlockTime), model.BlockTime); Assert.NotEmpty(model.VIn); Vin input = model.VIn[0]; var expectedInput = new Vin(transaction.Inputs[0].PrevOut, transaction.Inputs[0].Sequence, transaction.Inputs[0].ScriptSig); Assert.Equal(expectedInput.Coinbase, input.Coinbase); Assert.Equal(expectedInput.ScriptSig, input.ScriptSig); Assert.Equal(expectedInput.Sequence, input.Sequence); Assert.Equal(expectedInput.TxId, input.TxId); Assert.Equal(expectedInput.VOut, input.VOut); Assert.NotEmpty(model.VOut); Vout output = model.VOut[0]; var expectedOutput = new Vout(0, transaction.Outputs[0], this.network); Assert.Equal(expectedOutput.Value, output.Value); Assert.Equal(expectedOutput.N, output.N); Assert.Equal(expectedOutput.ScriptPubKey.Hex, output.ScriptPubKey.Hex); } [Fact] public async Task GetTaskAsync_Verbose_ChainStateTipNull_DoesNotCalulateConfirmationsAsync() { ChainedHeader block = this.chain.GetHeader(1); Transaction transaction = this.CreateTransaction(); var txId = new uint256(12142124); this.pooledTransaction.Setup(p => p.GetTransaction(txId)) .ReturnsAsync(transaction); this.blockStore.Setup(b => b.GetBlockIdByTransactionId(txId)) .Returns(block.HashBlock); TransactionModel result = await this.controller.GetRawTransactionAsync(txId.ToString(), 1).ConfigureAwait(false); Assert.NotNull(result); var model = Assert.IsType<TransactionVerboseModel>(result); Assert.Null(model.Confirmations); } [Fact] public async Task GetTaskAsync_Verbose_BlockNotFoundOnChain_ReturnsTransactionVerboseModelWithoutBlockInformationAsync() { ChainedHeader block = this.chain.GetHeader(1); Transaction transaction = this.CreateTransaction(); var txId = new uint256(12142124); this.pooledTransaction.Setup(p => p.GetTransaction(txId)) .ReturnsAsync(transaction); this.blockStore.Setup(b => b.GetBlockIdByTransactionId(txId)) .Returns((uint256)null); TransactionModel result = await this.controller.GetRawTransactionAsync(txId.ToString(), 1).ConfigureAwait(false); Assert.NotNull(result); var model = Assert.IsType<TransactionVerboseModel>(result); Assert.Null(model.BlockHash); Assert.Null(model.Confirmations); Assert.Null(model.Time); Assert.Null(model.BlockTime); } [Fact] public async Task GetTxOutAsync_NotIncludeInMempool_UnspentTransactionNotFound_ReturnsNullAsync() { var txId = new uint256(1243124); this.getUnspentTransaction.Setup(s => s.GetUnspentTransactionAsync(txId)) .ReturnsAsync((UnspentOutputs)null) .Verifiable(); GetTxOutModel result = await this.controller.GetTxOutAsync(txId.ToString(), 0, false).ConfigureAwait(false); Assert.Null(result); this.getUnspentTransaction.Verify(); } [Fact] public async Task GetTxOutAsync_NotIncludeInMempool_GetUnspentTransactionNotAvailable_ReturnsNullAsync() { var txId = new uint256(1243124); this.controller = new FullNodeController(this.LoggerFactory.Object, this.pooledTransaction.Object, this.pooledGetUnspentTransaction.Object, null, this.networkDifficulty.Object, this.fullNode.Object, this.nodeSettings, this.network, this.chain, this.chainState.Object, this.connectionManager.Object); GetTxOutModel result = await this.controller.GetTxOutAsync(txId.ToString(), 0, false).ConfigureAwait(false); Assert.Null(result); } [Fact] public async Task GetTxOutAsync_IncludeMempool_UnspentTransactionNotFound_ReturnsNullAsync() { var txId = new uint256(1243124); this.pooledGetUnspentTransaction.Setup(s => s.GetUnspentTransactionAsync(txId)) .ReturnsAsync((UnspentOutputs)null) .Verifiable(); GetTxOutModel result = await this.controller.GetTxOutAsync(txId.ToString(), 0, true).ConfigureAwait(false); Assert.Null(result); this.pooledGetUnspentTransaction.Verify(); } [Fact] public async Task GetTxOutAsync_IncludeMempool_PooledGetUnspentTransactionNotAvailable_UnspentTransactionNotFound_ReturnsNullAsync() { var txId = new uint256(1243124); this.controller = new FullNodeController(this.LoggerFactory.Object, this.pooledTransaction.Object, null, this.getUnspentTransaction.Object, this.networkDifficulty.Object, this.fullNode.Object, this.nodeSettings, this.network, this.chain, this.chainState.Object, this.connectionManager.Object); GetTxOutModel result = await this.controller.GetTxOutAsync(txId.ToString(), 0, true).ConfigureAwait(false); Assert.Null(result); } [Fact] public async Task GetTxOutAsync_NotIncludeInMempool_UnspentTransactionFound_ReturnsModelAsync() { var txId = new uint256(1243124); Transaction transaction = this.CreateTransaction(); var unspentOutputs = new UnspentOutputs(1, transaction); this.getUnspentTransaction.Setup(s => s.GetUnspentTransactionAsync(txId)) .ReturnsAsync(unspentOutputs) .Verifiable(); GetTxOutModel model = await this.controller.GetTxOutAsync(txId.ToString(), 0, false).ConfigureAwait(false); this.getUnspentTransaction.Verify(); Assert.Equal(this.chain.Tip.HashBlock, model.BestBlock); Assert.True(model.Coinbase); Assert.Equal(3, model.Confirmations); Assert.Equal(new ScriptPubKey(transaction.Outputs[0].ScriptPubKey, this.network).Hex, model.ScriptPubKey.Hex); Assert.Equal(transaction.Outputs[0].Value, model.Value); } [Fact] public async Task GetTxOutAsync_IncludeInMempool_UnspentTransactionFound_ReturnsModelAsync() { var txId = new uint256(1243124); Transaction transaction = this.CreateTransaction(); var unspentOutputs = new UnspentOutputs(1, transaction); this.pooledGetUnspentTransaction.Setup(s => s.GetUnspentTransactionAsync(txId)) .ReturnsAsync(unspentOutputs) .Verifiable(); this.controller = new FullNodeController(this.LoggerFactory.Object, this.pooledTransaction.Object, this.pooledGetUnspentTransaction.Object, this.getUnspentTransaction.Object, this.networkDifficulty.Object, this.fullNode.Object, this.nodeSettings, this.network, this.chain, this.chainState.Object, this.connectionManager.Object); GetTxOutModel model = await this.controller.GetTxOutAsync(txId.ToString(), 0, true).ConfigureAwait(false); this.pooledGetUnspentTransaction.Verify(); Assert.Equal(this.chain.Tip.HashBlock, model.BestBlock); Assert.True(model.Coinbase); Assert.Equal(3, model.Confirmations); Assert.Equal(new ScriptPubKey(transaction.Outputs[0].ScriptPubKey, this.network).Hex, model.ScriptPubKey.Hex); Assert.Equal(transaction.Outputs[0].Value, model.Value); } [Fact] public async Task GetTxOutAsync_NotIncludeInMempool_UnspentTransactionFound_VOutNotFound_ReturnsModelAsync() { var txId = new uint256(1243124); Transaction transaction = this.CreateTransaction(); var unspentOutputs = new UnspentOutputs(1, transaction); this.getUnspentTransaction.Setup(s => s.GetUnspentTransactionAsync(txId)) .ReturnsAsync(unspentOutputs) .Verifiable(); GetTxOutModel model = await this.controller.GetTxOutAsync(txId.ToString(), 13, false).ConfigureAwait(false); this.getUnspentTransaction.Verify(); Assert.Equal(this.chain.Tip.HashBlock, model.BestBlock); Assert.True(model.Coinbase); Assert.Equal(3, model.Confirmations); Assert.Null(model.ScriptPubKey); Assert.Null(model.Value); } [Fact] public async Task GetTxOutAsync_IncludeInMempool_UnspentTransactionFound_VOutNotFound_ReturnsModelAsync() { var txId = new uint256(1243124); Transaction transaction = this.CreateTransaction(); var unspentOutputs = new UnspentOutputs(1, transaction); this.pooledGetUnspentTransaction.Setup(s => s.GetUnspentTransactionAsync(txId)) .ReturnsAsync(unspentOutputs) .Verifiable(); GetTxOutModel model = await this.controller.GetTxOutAsync(txId.ToString(), 13, true).ConfigureAwait(false); this.pooledGetUnspentTransaction.Verify(); Assert.Equal(this.chain.Tip.HashBlock, model.BestBlock); Assert.True(model.Coinbase); Assert.Equal(3, model.Confirmations); Assert.Null(model.ScriptPubKey); Assert.Null(model.Value); } [Fact] public void GetBlockCount_ReturnsHeightFromConsensusLoopTip() { this.consensusManager.Setup(c => c.Tip) .Returns(this.chain.GetHeader(2)); var serviceProvider = new Mock<IServiceProvider>(); serviceProvider.Setup(s => s.GetService(typeof(IConsensusManager))) .Returns(this.consensusManager.Object); this.fullNode.Setup(f => f.Services.ServiceProvider) .Returns(serviceProvider.Object); int result = this.controller.GetBlockCount(); Assert.Equal(2, result); } [Fact] public void GetInfo_TestNet_ReturnsInfoModel() { this.nodeSettings = new NodeSettings(this.network, protocolVersion: ProtocolVersion.NO_BLOOM_VERSION, args: new[] { "-minrelaytxfeerate=1000" }); this.controller = new FullNodeController(this.LoggerFactory.Object, this.pooledTransaction.Object, this.pooledGetUnspentTransaction.Object, this.getUnspentTransaction.Object, this.networkDifficulty.Object, this.fullNode.Object, this.nodeSettings, this.network, this.chain, this.chainState.Object, this.connectionManager.Object); this.fullNode.Setup(f => f.Version) .Returns(new Version(15, 0)); this.networkDifficulty.Setup(n => n.GetNetworkDifficulty()) .Returns(new Target(121221121212)); this.chainState.Setup(c => c.ConsensusTip) .Returns(this.chain.Tip); this.connectionManager.Setup(c => c.ConnectedPeers) .Returns(new TestReadOnlyNetworkPeerCollection()); GetInfoModel model = this.controller.GetInfo(); Assert.Equal((uint)14999899, model.Version); Assert.Equal((uint)ProtocolVersion.NO_BLOOM_VERSION, model.ProtocolVersion); Assert.Equal(3, model.Blocks); Assert.Equal(0, model.TimeOffset); Assert.Equal(0, model.Connections); Assert.Empty(model.Proxy); Assert.Equal(new Target(121221121212).Difficulty, model.Difficulty); Assert.True(model.Testnet); Assert.Equal(0.00001m, model.RelayFee); Assert.Empty(model.Errors); Assert.Null(model.WalletVersion); Assert.Null(model.Balance); Assert.Null(model.KeypoolOldest); Assert.Null(model.KeypoolSize); Assert.Null(model.UnlockedUntil); Assert.Null(model.PayTxFee); } [Fact] public void GetInfo_MainNet_ReturnsInfoModel() { this.network = KnownNetworks.Main; this.controller = new FullNodeController(this.LoggerFactory.Object, this.pooledTransaction.Object, this.pooledGetUnspentTransaction.Object, this.getUnspentTransaction.Object, this.networkDifficulty.Object, this.fullNode.Object, this.nodeSettings, this.network, this.chain, this.chainState.Object, this.connectionManager.Object); GetInfoModel model = this.controller.GetInfo(); Assert.False(model.Testnet); } [Fact] public void GetInfo_NoChainState_ReturnsModel() { IChainState chainState = null; this.controller = new FullNodeController(this.LoggerFactory.Object, this.pooledTransaction.Object, this.pooledGetUnspentTransaction.Object, this.getUnspentTransaction.Object, this.networkDifficulty.Object, this.fullNode.Object, this.nodeSettings, this.network, this.chain, chainState, this.connectionManager.Object); GetInfoModel model = this.controller.GetInfo(); Assert.Equal(0, model.Blocks); } [Fact] public void GetInfo_NoChainTip_ReturnsModel() { this.chainState.Setup(c => c.ConsensusTip) .Returns((ChainedHeader)null); this.controller = new FullNodeController(this.LoggerFactory.Object, this.pooledTransaction.Object, this.pooledGetUnspentTransaction.Object, this.getUnspentTransaction.Object, this.networkDifficulty.Object, this.fullNode.Object, this.nodeSettings, this.network, this.chain, this.chainState.Object, this.connectionManager.Object); GetInfoModel model = this.controller.GetInfo(); Assert.Equal(0, model.Blocks); } [Fact] public void GetInfo_NoSettings_ReturnsModel() { this.nodeSettings = null; this.controller = new FullNodeController(this.LoggerFactory.Object, this.pooledTransaction.Object, this.pooledGetUnspentTransaction.Object, this.getUnspentTransaction.Object, this.networkDifficulty.Object, this.fullNode.Object, this.nodeSettings, this.network, this.chain, this.chainState.Object, this.connectionManager.Object); GetInfoModel model = this.controller.GetInfo(); Assert.Equal((uint)NodeSettings.SupportedProtocolVersion, model.ProtocolVersion); Assert.Equal(0, model.RelayFee); } [Fact] public void GetInfo_NoConnectionManager_ReturnsModel() { IConnectionManager connectionManager = null; this.controller = new FullNodeController(this.LoggerFactory.Object, this.pooledTransaction.Object, this.pooledGetUnspentTransaction.Object, this.getUnspentTransaction.Object, this.networkDifficulty.Object, this.fullNode.Object, this.nodeSettings, this.network, this.chain, this.chainState.Object, connectionManager); GetInfoModel model = this.controller.GetInfo(); Assert.Equal(0, model.TimeOffset); Assert.Null(model.Connections); } [Fact] public void GetInfo_NoNetworkDifficulty_ReturnsModel() { this.controller = new FullNodeController(this.LoggerFactory.Object, this.pooledTransaction.Object, this.pooledGetUnspentTransaction.Object, this.getUnspentTransaction.Object, null, this.fullNode.Object, this.nodeSettings, this.network, this.chain, this.chainState.Object, this.connectionManager.Object); GetInfoModel model = this.controller.GetInfo(); Assert.Equal(0, model.Difficulty); } [Fact] public void GetInfo_NoVersion_ReturnsModel() { this.fullNode.Setup(f => f.Version) .Returns((Version)null); this.controller = new FullNodeController(this.LoggerFactory.Object, this.pooledTransaction.Object, this.pooledGetUnspentTransaction.Object, this.getUnspentTransaction.Object, this.networkDifficulty.Object, this.fullNode.Object, this.nodeSettings, this.network, this.chain, this.chainState.Object, this.connectionManager.Object); GetInfoModel model = this.controller.GetInfo(); Assert.Equal((uint)0, model.Version); } [Fact] public void GetBlockHeader_ChainNull_ReturnsNull() { this.chain = null; this.controller = new FullNodeController(this.LoggerFactory.Object, this.pooledTransaction.Object, this.pooledGetUnspentTransaction.Object, this.getUnspentTransaction.Object, this.networkDifficulty.Object, this.fullNode.Object, this.nodeSettings, this.network, this.chain, this.chainState.Object, this.connectionManager.Object); BlockHeaderModel result = (BlockHeaderModel)this.controller.GetBlockHeader("", true); Assert.Null(result); } [Fact] public void GetBlockHeader_BlockHeaderFound_ReturnsBlockHeaderModel() { ChainedHeader block = this.chain.GetHeader(2); string bits = GetBlockHeaderBits(block.Header); BlockHeaderModel result = (BlockHeaderModel)this.controller.GetBlockHeader(block.HashBlock.ToString(), true); Assert.NotNull(result); Assert.Equal((uint)block.Header.Version, result.Version); Assert.Equal(block.Header.HashPrevBlock.ToString(), result.PreviousBlockHash); Assert.Equal(block.Header.HashMerkleRoot.ToString(), result.MerkleRoot); Assert.Equal(block.Header.Time, result.Time); Assert.Equal((int)block.Header.Nonce, result.Nonce); Assert.Equal(bits, result.Bits); } [Fact] public void GetBlockHeader_BlockHeaderNotFound_ReturnsNull() { BlockHeaderModel result = (BlockHeaderModel)this.controller.GetBlockHeader(new uint256(2562).ToString(), true); Assert.Null(result); } [Fact] public void ValidateAddress_IsNotAValidBase58Address_ThrowsFormatException() { Assert.Throws<FormatException>(() => { this.controller.ValidateAddress("invalidaddress"); }); } [Fact] public void ValidateAddress_ValidAddressOfDifferentNetwork_ReturnsFalse() { // P2PKH BitcoinPubKeyAddress address = new Key().PubKey.GetAddress(KnownNetworks.Main); ValidatedAddress result = this.controller.ValidateAddress(address.ToString()); bool isValid = result.IsValid; Assert.False(isValid); } [Fact] public void ValidateAddress_ValidP2PKHAddress_ReturnsTrue() { // P2PKH BitcoinPubKeyAddress address = new Key().PubKey.GetAddress(this.network); ValidatedAddress result = this.controller.ValidateAddress(address.ToString()); bool isValid = result.IsValid; Assert.True(isValid); } [Fact] public void ValidateAddress_ValidP2SHAddress_ReturnsTrue() { // P2SH BitcoinScriptAddress address = new Key().ScriptPubKey.GetScriptAddress(this.network); ValidatedAddress result = this.controller.ValidateAddress(address.ToString()); bool isValid = result.IsValid; Assert.True(isValid); } [Fact] public void ValidateAddress_ValidP2WPKHAddress_ReturnsTrue() { // P2WPKH BitcoinAddress address = new Key().PubKey.WitHash.GetAddress(this.network); ValidatedAddress result = this.controller.ValidateAddress(address.ToString()); bool isValid = result.IsValid; Assert.True(isValid); } [Fact] public void ValidateAddress_ValidP2WSHAddress_ReturnsTrue() { // P2WSH BitcoinWitScriptAddress address = new Key().PubKey.ScriptPubKey.WitHash.ScriptPubKey.GetWitScriptAddress(this.network); ValidatedAddress result = this.controller.ValidateAddress(address.ToString()); bool isValid = result.IsValid; Assert.True(isValid); } private Transaction CreateTransaction() { var transaction = new Transaction(); transaction.AddInput(TxIn.CreateCoinbase(23523523)); transaction.AddOutput(new TxOut(this.network.GetReward(23523523), new Key().ScriptPubKey)); return transaction; } private string GetBlockHeaderBits(BlockHeader header) { byte[] bytes = this.GetBytes(header.Bits.ToCompact()); return Encoders.Hex.EncodeData(bytes); } private byte[] GetBytes(uint compact) { return new byte[] { (byte)(compact >> 24), (byte)(compact >> 16), (byte)(compact >> 8), (byte)(compact) }; } public class TestReadOnlyNetworkPeerCollection : IReadOnlyNetworkPeerCollection { public event EventHandler<NetworkPeerEventArgs> Added; public event EventHandler<NetworkPeerEventArgs> Removed; private List<INetworkPeer> networkPeers; public TestReadOnlyNetworkPeerCollection() { this.Added = new EventHandler<NetworkPeerEventArgs>((obj, eventArgs) => { }); this.Removed = new EventHandler<NetworkPeerEventArgs>((obj, eventArgs) => { }); this.networkPeers = new List<INetworkPeer>(); } public TestReadOnlyNetworkPeerCollection(List<INetworkPeer> peers) { this.Added = new EventHandler<NetworkPeerEventArgs>((obj, eventArgs) => { }); this.Removed = new EventHandler<NetworkPeerEventArgs>((obj, eventArgs) => { }); this.networkPeers = peers; } public INetworkPeer FindByEndpoint(IPEndPoint endpoint) { return null; } public List<INetworkPeer> FindByIp(IPAddress ip) { return null; } public INetworkPeer FindLocal() { return null; } public IEnumerator<INetworkPeer> GetEnumerator() { return this.networkPeers.GetEnumerator(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return this.GetEnumerator(); } } } }
45.370319
217
0.6604
[ "MIT" ]
AI-For-Rural/EXOSFullNode
src/Stratis.Bitcoin.Features.RPC.Tests/Controller/FullNodeControllerTest.cs
32,714
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Azure.WebJobs; using Wutnu.Models; using Wutnu.Common; using Wutnu.Common.Helpers; namespace AuditDequeue { public class Functions { /// <summary> /// When the method completes, the queue message is deleted. If the method fails before completing, the queue message /// is not deleted; after a 10-minute lease expires, the message is released to be picked up again and processed. This /// sequence won't be repeated indefinitely if a message always causes an exception. After 5 unsuccessful attempts to /// process a message, the message is moved to a queue named {queuename}-poison. The maximum number of attempts is /// configurable. /// /// https://azure.microsoft.com/en-us/documentation/articles/websites-dotnet-webjobs-sdk-get-started/#configure-storage /// </summary> /// <param name="auditInfo"></param> /// <param name="logger"></param> public static void AddRetrievalAuditLogRecord([QueueTrigger("%queueName%")] AuditDataModel auditInfo, TextWriter logger) { using (var io = new Wutnu.Data.WutNuContext()) { try { var ipInfo = IpLookup.Get(auditInfo.HostIp); io.usp_AddHistory( auditInfo.ShortUrl, auditInfo.CallDate, auditInfo.UserId, auditInfo.HostIp, ipInfo.Latitude, ipInfo.Longitude, ipInfo.City, ipInfo.Region, ipInfo.Country, ipInfo.Continent, ipInfo.Isp); io.SaveChanges(); } catch (Exception ex) { Logging.WriteDebugInfoToErrorLog("Error dequeing", ex, io); var x = ex.GetBaseException(); //logger.WriteLine("Error dequeuing: {0}, {1}", x.Message, x.StackTrace); throw ex; } } } } }
39.133333
128
0.537053
[ "Apache-2.0" ]
Matty9191/Wutnu
AuditDequeue/Functions.cs
2,350
C#
namespace essentialMix.Data.Patterns.Parameters; public interface IGetSettings { object[] KeyValue { get; set; } }
19.5
49
0.769231
[ "MIT" ]
asm2025/essentialMix
Standard/essentialMix.Data/Patterns/Parameters/IGetSettings.cs
119
C#
using ISUF.Base.Attributes; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Threading.Tasks; using System.Xml.Serialization; namespace ISUF.Base.Template { /// <summary> /// Base item type /// </summary> public class BaseItem : AtomicItem { /// <summary> /// Name of item /// </summary> [UIParams(UIOrder = 1)] public string Name { get; set; } /// <summary> /// Description of item /// </summary> [UIParams(UseLongTextInput = true, UIOrder = 2)] public string Description { get; set; } public BaseItem() { } /// <summary> /// Initialize new instance of item from existing one /// </summary> /// <param name="baseItem">Existing item</param> public BaseItem(BaseItem baseItem) : base(baseItem) { Name = baseItem.Name; Description = baseItem.Description; } /// <inheritdoc/> public override object Clone() { return new BaseItem(this); } /// <inheritdoc/> public override string ToString() { return Name.ToString(); } } }
23.101695
61
0.561262
[ "Apache-2.0" ]
JanRajnoha/ISUF
src/ISUF.Base/Templates/BaseItem.cs
1,363
C#
using System.Linq; using Avalonia.Controls.Generators; using Avalonia.Controls.Mixins; using Avalonia.Controls.Primitives; using Avalonia.Controls.Templates; using Avalonia.Input; using Avalonia.LogicalTree; namespace Avalonia.Controls { /// <summary> /// An item in a <see cref="TreeView"/>. /// </summary> public class TreeViewItem : HeaderedItemsControl, ISelectable { /// <summary> /// Defines the <see cref="IsExpanded"/> property. /// </summary> public static readonly DirectProperty<TreeViewItem, bool> IsExpandedProperty = AvaloniaProperty.RegisterDirect<TreeViewItem, bool>( nameof(IsExpanded), o => o.IsExpanded, (o, v) => o.IsExpanded = v); /// <summary> /// Defines the <see cref="IsSelected"/> property. /// </summary> public static readonly StyledProperty<bool> IsSelectedProperty = ListBoxItem.IsSelectedProperty.AddOwner<TreeViewItem>(); /// <summary> /// Defines the <see cref="Level"/> property. /// </summary> public static readonly DirectProperty<TreeViewItem, int> LevelProperty = AvaloniaProperty.RegisterDirect<TreeViewItem, int>( nameof(Level), o => o.Level); private static readonly ITemplate<IPanel> DefaultPanel = new FuncTemplate<IPanel>(() => new StackPanel()); private TreeView _treeView; private IControl _header; private bool _isExpanded; private int _level; /// <summary> /// Initializes static members of the <see cref="TreeViewItem"/> class. /// </summary> static TreeViewItem() { SelectableMixin.Attach<TreeViewItem>(IsSelectedProperty); PressedMixin.Attach<TreeViewItem>(); FocusableProperty.OverrideDefaultValue<TreeViewItem>(true); ItemsPanelProperty.OverrideDefaultValue<TreeViewItem>(DefaultPanel); ParentProperty.Changed.AddClassHandler<TreeViewItem>((o, e) => o.OnParentChanged(e)); RequestBringIntoViewEvent.AddClassHandler<TreeViewItem>((x, e) => x.OnRequestBringIntoView(e)); } /// <summary> /// Gets or sets a value indicating whether the item is expanded to show its children. /// </summary> public bool IsExpanded { get { return _isExpanded; } set { SetAndRaise(IsExpandedProperty, ref _isExpanded, value); } } /// <summary> /// Gets or sets the selection state of the item. /// </summary> public bool IsSelected { get { return GetValue(IsSelectedProperty); } set { SetValue(IsSelectedProperty, value); } } /// <summary> /// Gets the level/indentation of the item. /// </summary> public int Level { get { return _level; } private set { SetAndRaise(LevelProperty, ref _level, value); } } /// <summary> /// Gets the <see cref="ITreeItemContainerGenerator"/> for the tree view. /// </summary> public new ITreeItemContainerGenerator ItemContainerGenerator => (ITreeItemContainerGenerator)base.ItemContainerGenerator; /// <inheritdoc/> protected override IItemContainerGenerator CreateItemContainerGenerator() { return new TreeItemContainerGenerator<TreeViewItem>( this, TreeViewItem.HeaderProperty, TreeViewItem.ItemTemplateProperty, TreeViewItem.ItemsProperty, TreeViewItem.IsExpandedProperty); } /// <inheritdoc/> protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnAttachedToLogicalTree(e); _treeView = this.GetLogicalAncestors().OfType<TreeView>().FirstOrDefault(); Level = CalculateDistanceFromLogicalParent<TreeView>(this) - 1; ItemContainerGenerator.UpdateIndex(); if (ItemTemplate == null && _treeView?.ItemTemplate != null) { ItemTemplate = _treeView.ItemTemplate; } } protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnDetachedFromLogicalTree(e); ItemContainerGenerator.UpdateIndex(); } protected virtual void OnRequestBringIntoView(RequestBringIntoViewEventArgs e) { if (e.TargetObject == this && _header != null) { var m = _header.TransformToVisual(this); if (m.HasValue) { var bounds = new Rect(_header.Bounds.Size); var rect = bounds.TransformToAABB(m.Value); e.TargetRect = rect; } } } /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { if (!e.Handled) { switch (e.Key) { case Key.Right: if (Items != null && Items.Cast<object>().Any()) { IsExpanded = true; } e.Handled = true; break; case Key.Left: IsExpanded = false; e.Handled = true; break; } } // Don't call base.OnKeyDown - let events bubble up to containing TreeView. } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { _header = e.NameScope.Find<IControl>("PART_Header"); } private static int CalculateDistanceFromLogicalParent<T>(ILogical logical, int @default = -1) where T : class { var result = 0; while (logical != null && !(logical is T)) { ++result; logical = logical.LogicalParent; } return logical != null ? result : @default; } private void OnParentChanged(AvaloniaPropertyChangedEventArgs e) { if (!((ILogical)this).IsAttachedToLogicalTree && e.NewValue is null) { // If we're not attached to the logical tree, then OnDetachedFromLogicalTree isn't going to be // called when the item is removed. This results in the item not being removed from the index, // causing #3551. In this case, update the index when Parent is changed to null. ItemContainerGenerator.UpdateIndex(); } } } }
35.132653
117
0.559977
[ "MIT" ]
KieranDevvs/Avalonia
src/Avalonia.Controls/TreeViewItem.cs
6,886
C#
using CommandLine; using CommandLine.Text; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; using Pims.Api.Configuration; using Serilog; using System; using System.Diagnostics.CodeAnalysis; namespace Pims.Api { /// <summary> /// Program class, provides the main program starting point for the Geo-spatial application. /// </summary> [ExcludeFromCodeCoverage] public static class Program { /// <summary> /// The primary entry point for the application. /// </summary> /// <param name="args"></param> public static void Main(string[] args) { var results = Parser.Default.ParseArguments<ProgramOptions>(args); results.WithParsed((options) => { var builder = CreateWebHostBuilder(options); builder.Build().Run(); }) .WithNotParsed((errors) => { var helpText = HelpText.AutoBuild(results, h => { return HelpText.DefaultParsingErrorsHandler(results, h); }, e => e); Console.WriteLine(helpText); }); } /// <summary> /// Create a default configuration and setup for a web application. /// </summary> /// <param name="options"></param> /// <returns></returns> static IWebHostBuilder CreateWebHostBuilder(ProgramOptions options) { var args = options.ToArgs(); DotNetEnv.Env.Load(); var env = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT"); var config = new ConfigurationBuilder() .AddEnvironmentVariables() .AddCommandLine(args) .Build(); return WebHost.CreateDefaultBuilder(args) .ConfigureAppConfiguration((hostingContext, config) => { config.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true); config.AddJsonFile($"appsettings.{env}.json", optional: true, reloadOnChange: true); config.AddJsonFile("connectionstrings.json", optional: true, reloadOnChange: true); config.AddJsonFile($"connectionstrings.{env}.json", optional: true, reloadOnChange: true); config.AddJsonFile("geocoder.json", optional: false, reloadOnChange: true); config.AddJsonFile($"geocoder.{env}.json", optional: true, reloadOnChange: true); config.AddEnvironmentVariables(); config.AddCommandLine(args); }) .UseSerilog() .UseUrls(config.GetValue<string>("ASPNETCORE_URLS")) .UseStartup<Startup>(); } public static IHostBuilder CreateHostBuilder(string[] args) { DotNetEnv.Env.Load(); return Host.CreateDefaultBuilder(args).ConfigureAppConfiguration((hostingContext, config) => { config.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true); config.AddEnvironmentVariables(); config.AddCommandLine(args); }); } } }
39.16092
110
0.571177
[ "Apache-2.0" ]
PryancaJSharma/PSP
backend/api/Program.cs
3,407
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using FruitStoreD.Core; namespace FruitStoreD { public class BananaService : IBananaService { public BananaDto GetBananaDto() { return new BananaDto{ Name="b1", Price=20,Type="B"}; } public decimal BananaDiscount(object dto) { BananaDto bDto = dto as BananaDto; if (bDto == null) return 0; if (bDto.Type == "B") { return 9; } else { return 12; } } } }
20.875
64
0.495509
[ "Apache-2.0" ]
ElandGroup/FruitStore
src/FruitStoreD/Service/BananaService.cs
670
C#
using UnityEngine; using UnityEngine.UI; using System; using System.Collections; public class ScoreController : MonoBehaviour { private GameObject car; private Vector3 startCarPosition; private Text scoreText; private int score; void Start () { score = 0; scoreText = gameObject.GetComponent<Text>(); scoreText.text = String.Format ("score: {0}", score); car = GameObject.Find ("Car"); startCarPosition = car.transform.position; } void Update() { if (score < 0) score = 0; scoreText.text = String.Format ("score: {0}", score); } void FixedUpdate () { score = (int) Vector3.Distance (startCarPosition, car.transform.position); } }
21.451613
76
0.702256
[ "MIT" ]
GATAKAWAKACHICO/TokyoExpressWay2016-09-23
Assets/Scripts/ScoreController.cs
667
C#
#region Copyright notice and license // Copyright 2019 The gRPC Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion using System; using System.Diagnostics; using System.Threading.Tasks; using Grpc.Core; using Grpc.Net.Client; using Race; namespace Client { class Program { private static readonly TimeSpan RaceDuration = TimeSpan.FromSeconds(30); static async Task Main(string[] args) { using var channel = GrpcChannel.ForAddress("https://localhost:5001"); var client = new Racer.RacerClient(channel); Console.WriteLine($"Race duration: {RaceDuration.TotalSeconds} seconds"); Console.WriteLine("Press any key to start race..."); Console.ReadKey(); await BidirectionalStreamingExample(client); Console.WriteLine("Finished"); Console.WriteLine("Press any key to exit..."); Console.ReadKey(); } private static async Task BidirectionalStreamingExample(Racer.RacerClient client) { var headers = new Metadata { new Metadata.Entry("race-duration", RaceDuration.ToString()) }; Console.WriteLine("Ready, set, go!"); using var call = client.ReadySetGo(new CallOptions(headers)); var complete = false; // Read incoming messages in a background task RaceMessage? lastMessageReceived = null; var readTask = Task.Run(async () => { await foreach (var message in call.ResponseStream.ReadAllAsync()) { lastMessageReceived = message; } }); // Write outgoing messages until timer is complete var sw = Stopwatch.StartNew(); var sent = 0; #region Reporting // Report requests in realtime var reportTask = Task.Run(async () => { while (true) { Console.WriteLine($"Messages sent: {sent}"); Console.WriteLine($"Messages received: {lastMessageReceived?.Count ?? 0}"); if (!complete) { await Task.Delay(TimeSpan.FromSeconds(1)); Console.SetCursorPosition(0, Console.CursorTop - 2); } else { break; } } }); #endregion while (sw.Elapsed < RaceDuration) { await call.RequestStream.WriteAsync(new RaceMessage { Count = ++sent }); } // Finish call and report results await call.RequestStream.CompleteAsync(); await readTask; complete = true; await reportTask; } } }
32.358491
104
0.564431
[ "Apache-2.0" ]
Alibesharat/grpc-dotnet
examples/Racer/Client/Program.cs
3,432
C#
namespace Problem_12.Beer_Kegs { using System; public class Program { public static void Main() { var linesCount = int.Parse(Console.ReadLine()); var bestModel = string.Empty; var bestResult = 0.0; for (int i = 0; i < linesCount; i++) { var model = Console.ReadLine(); var radius = double.Parse(Console.ReadLine()); var height = int.Parse(Console.ReadLine()); var volumeAlgorithm = Math.PI * radius * radius * height; if(volumeAlgorithm > bestResult) { bestModel = model; bestResult = volumeAlgorithm; } } Console.WriteLine(bestModel); } } }
25.75
73
0.478155
[ "MIT" ]
ilyogri/SoftUni
Technology Fundamentals/Programming Fundamentals - May 2017/Homeworks/07. Data Types and Variables - More Exercises/Problem 12. Beer Kegs/Program.cs
826
C#
using System; using System.Linq; using System.Collections.Generic; using Dx29.Data; namespace Dx29.Services { public partial class EnsembleService { public EnsembleService() { BioEntity = new BioEntityService(); BioEntity.Initialize(); Orpha = new OrphaNET(); Orpha.Initialize(); Omim = new Omim(BioEntity); Omim.Initialize(); DiagnosisOrpha = new DiagnosisService(BioEntity, Orpha); DiagnosisOrpha.Initialize(); DiagnosisOmim = new DiagnosisService(BioEntity, Omim); DiagnosisOmim.Initialize(); OrphaTranslator = new OrphaTranslator(); OrphaTranslator.Initialize("_data/ordo-es-3.2.owl"); OmimTranslator = new BioTranslator(); OmimTranslator.Initialize("_data/mondo-es.tsv"); Omim.Mappings = Orpha.Mappings; } public BioEntityService BioEntity { get; } public OrphaNET Orpha { get; } public Omim Omim { get; } public DiagnosisService DiagnosisOrpha { get; } public DiagnosisService DiagnosisOmim { get; } public OrphaTranslator OrphaTranslator { get; } public BioTranslator OmimTranslator { get; } public DiagnosisResults Predict(string hpos, IDictionary<string, double> genes = null, int skip = 0, int count = 100) { return Predict(hpos.Split(',').Select(r => r.Trim()).ToArray(), genes, skip, count); } public DiagnosisResults Predict(IList<string> hpos, IDictionary<string, double> genes = null, int skip = 0, int count = 100) { var resOrpha = DiagnosisOrpha.Predict(hpos, genes, skip: 0, count: 5_000); var resOmim = DiagnosisOmim.Predict(hpos, genes, skip: 0, count: 5_000); //var results = Merge(resOrpha, resOmim); var results = MergeWithMapping(resOrpha, resOmim); var total = results.Count; var bestTotal = GetBestTotal(results); //results = results.Take(bestTotal).ToArray(); var items = results.Skip(skip).Take(count).ToArray(); return new DiagnosisResults { Diseases = items, Count = items.Count(), Total = total, BestTotal = bestTotal }; } public DiagnosisResults Phrank(string hpos, IDictionary<string, double> genes = null, int skip = 0, int count = 100) { return Phrank(hpos.Split(',').Select(r => r.Trim()).ToArray(), genes, skip, count); } public DiagnosisResults Phrank(IList<string> hpos, IDictionary<string, double> genes = null, int skip = 0, int count = 100) { var resOrpha = DiagnosisOrpha.Phrank(hpos, genes, skip: 0, count: 5_000); var resOmim = DiagnosisOmim.Phrank(hpos, genes, skip: 0, count: 5_000); //var results = Merge(resOrpha, resOmim); var results = MergeWithMapping(resOrpha, resOmim); var total = results.Count; var bestTotal = GetBestTotal(results); //results = results.Take(bestTotal).ToArray(); var items = results.Skip(skip).Take(count).ToArray(); return new DiagnosisResults { Diseases = items, Count = items.Count(), Total = total, BestTotal = bestTotal }; } private IList<DiseaseInfo> Merge(DiagnosisResults resOrpha, DiagnosisResults resOmim) { var dic = new Dictionary<string, DiseaseInfo>(); int position = 0; foreach (var orpha in resOrpha.Diseases.OrderByDescending(r => r.Score)) { var disease = new DiseaseInfo(orpha.Id, orpha.Name) { Desc = orpha.Desc }; disease.Symptoms = orpha.Symptoms; disease.Genes = orpha.Genes; disease.Score = orpha.Score; disease.Position = position; dic.Add(orpha.Id, disease); position += 2; } position = 1; foreach (var omim in resOmim.Diseases.OrderByDescending(r => r.Score)) { var disease = new DiseaseInfo(omim.Id, omim.Name) { Desc = omim.Desc }; disease.Symptoms = omim.Symptoms; disease.Genes = omim.Genes; disease.Score = omim.Score; disease.Position = position; dic.Add(omim.Id, disease); position += 2; } return dic.Values.OrderBy(r => r.Position).OrderByDescending(r => r.Score).ToArray(); //return dic.Values.OrderByDescending(r => r.Score).OrderBy(r => r.Position).ToArray(); //return dic.Values.OrderByDescending(r => r.Score).ToArray(); //return dic.Values.OrderBy(r => r.Position).ToArray(); } private IList<DiseaseInfo> MergeWithMapping(DiagnosisResults resOrpha, DiagnosisResults resOmim) { var dic = new Dictionary<string, DiseaseInfo>(); int position = 0; foreach (var orpha in resOrpha.Diseases.OrderByDescending(r => r.Score)) { if (!dic.ContainsKey(orpha.Id)) { var disease = CreateDisease(orpha); disease.Position = position; dic.Add(orpha.Id, disease); } position += 2; } position = 1; foreach (var omim in resOmim.Diseases.OrderByDescending(r => r.Score)) { var mappings = GetOmimMappings(omim).ToArray(); if (mappings.Length > 0) { foreach (var disease in mappings) { if (!dic.ContainsKey(disease.Id)) { dic.Add(disease.Id, disease); } } } else { var disease = CreateDisease(omim); disease.Position = position; dic.Add(omim.Id, disease); } position += 2; } return dic.Values.OrderBy(r => r.Position).OrderByDescending(r => r.Score).ToArray(); //return dic.Values.OrderByDescending(r => r.Score).OrderBy(r => r.Position).ToArray(); //return dic.Values.OrderByDescending(r => r.Score).ToArray(); //return dic.Values.OrderBy(r => r.Position).ToArray(); } private IEnumerable<DiseaseInfo> GetOmimMappings(DiseaseInfo omim) { foreach (var orphaId in Orpha.OmimToOrpha(omim.Id)) { var orpha = Orpha.Diseases[orphaId]; var disease = new DiseaseInfo(orpha.Id, orpha.Name) { Desc = orpha.Desc }; disease.Symptoms = omim.Symptoms; disease.Genes = omim.Genes; disease.Score = omim.Score; yield return disease; } } private static DiseaseInfo CreateDisease(DiseaseInfo info) { var disease = new DiseaseInfo(info.Id, info.Name) { Desc = info.Desc }; disease.Symptoms = info.Symptoms; disease.Genes = info.Genes; disease.Score = info.Score; return disease; } private int GetBestTotal(IList<DiseaseInfo> results) { var matches = results.Select(r => r.Symptoms.Count).ToHashSet(); if (matches.Count < 2) { return results.Count; } int threshold = matches.OrderByDescending(r => r).Take(3).Last(); return results.Where(r => r.Symptoms.Count >= threshold).Count(); } } }
37.665094
132
0.536756
[ "MIT" ]
foundation29org/Dx29.BioNET
src/Dx29.BioNET/Services/Ensemble/EnsembleService.cs
7,987
C#
using System; using System.Globalization; using System.Linq; using System.Reflection; using Xamarin.Forms; namespace MaterialIcons.FormsPlugin.Abstractions { public sealed class MaterialIconsConverter : TypeConverter { /// <summary> /// Determines whether this instance [can convert from] the specified source type. /// </summary> /// <param name="sourceType">Type of the source.</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException"></exception> public override Boolean CanConvertFrom(Type sourceType) { if (sourceType == null) //throw new ArgumentNullException(nameof(sourceType)); throw new ArgumentNullException("sourceType"); return sourceType == typeof(String); } /// <summary> /// Converts from. /// </summary> /// <param name="culture">The culture.</param> /// <param name="value">The value.</param> /// <returns></returns> /// <exception cref="System.NotImplementedException"></exception> public override Object ConvertFrom(CultureInfo culture, Object value) { if (value == null) return null; var valuestring = value as String; if (valuestring != null) { var fieldInfo = typeof(MaterialIcons).GetRuntimeFields().FirstOrDefault(x => x.Name == valuestring); if (fieldInfo != null) { return (MaterialIcons)fieldInfo.GetValue(null); } } //throw new InvalidOperationException($"Cannot convert {value} into {typeof(MaterialIcons)}"); throw new InvalidOperationException(String.Format("Cannot convert {0} into {1}", value, typeof(MaterialIcons))); } } }
36.423077
124
0.587117
[ "MIT" ]
Ali-YousefiTelori/Xamarin.Plugins
MaterialIcons/MaterialIcons.FormsPlugin.Abstractions/MaterialIconsConverter.cs
1,896
C#
using UnityEngine; namespace UnityEditor.U2D.Animation { internal interface ICircleSelector<T> : ISelector<T> { float radius { get; set; } } }
17.3
57
0.624277
[ "Apache-2.0" ]
AJTheEnder/E428
Projet/E428/Library/PackageCache/com.unity.2d.animation@5.0.4/Editor/SkinningModule/Selectors/ICircleSelector.cs
173
C#
namespace PackageEditor { partial class ADPermissionsForm { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ADPermissionsForm)); this.panel1 = new System.Windows.Forms.Panel(); this.panel8 = new System.Windows.Forms.Panel(); this.btnOk = new System.Windows.Forms.Button(); this.btnCancel = new System.Windows.Forms.Button(); this.panel2 = new System.Windows.Forms.Panel(); this.groupBox4 = new System.Windows.Forms.GroupBox(); this.tbAuthDenyMsg = new System.Windows.Forms.TextBox(); this.cbAuthDenyMsg = new System.Windows.Forms.CheckBox(); this.groupBox3 = new System.Windows.Forms.GroupBox(); this.label1 = new System.Windows.Forms.Label(); this.lblOfflineUsage = new System.Windows.Forms.Label(); this.numOfflineUsage = new System.Windows.Forms.NumericUpDown(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.cbNestedCheck = new System.Windows.Forms.CheckBox(); this.btnRemove = new System.Windows.Forms.Button(); this.lblTotalEvents = new System.Windows.Forms.Label(); this.btnAddSave = new System.Windows.Forms.Button(); this.txtCmd = new System.Windows.Forms.TextBox(); this.comboBox = new System.Windows.Forms.ComboBox(); this.listBox = new System.Windows.Forms.ListBox(); this.groupBox2 = new System.Windows.Forms.GroupBox(); this.tbRequireDomainConnection = new System.Windows.Forms.TextBox(); this.cbRequireDomainConnection = new System.Windows.Forms.CheckBox(); this.panel8.SuspendLayout(); this.panel2.SuspendLayout(); this.groupBox4.SuspendLayout(); this.groupBox3.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.numOfflineUsage)).BeginInit(); this.groupBox1.SuspendLayout(); this.groupBox2.SuspendLayout(); this.SuspendLayout(); // // panel1 // resources.ApplyResources(this.panel1, "panel1"); this.panel1.Name = "panel1"; // // panel8 // resources.ApplyResources(this.panel8, "panel8"); this.panel8.Controls.Add(this.btnOk); this.panel8.Controls.Add(this.btnCancel); this.panel8.Controls.Add(this.panel2); this.panel8.Name = "panel8"; // // btnOk // resources.ApplyResources(this.btnOk, "btnOk"); this.btnOk.Name = "btnOk"; this.btnOk.UseVisualStyleBackColor = true; this.btnOk.Click += new System.EventHandler(this.btnSave_Click); // // btnCancel // resources.ApplyResources(this.btnCancel, "btnCancel"); this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.btnCancel.Name = "btnCancel"; this.btnCancel.UseVisualStyleBackColor = true; this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click); // // panel2 // resources.ApplyResources(this.panel2, "panel2"); this.panel2.Controls.Add(this.groupBox4); this.panel2.Controls.Add(this.groupBox3); this.panel2.Controls.Add(this.groupBox1); this.panel2.Controls.Add(this.groupBox2); this.panel2.Name = "panel2"; // // groupBox4 // this.groupBox4.Controls.Add(this.tbAuthDenyMsg); this.groupBox4.Controls.Add(this.cbAuthDenyMsg); resources.ApplyResources(this.groupBox4, "groupBox4"); this.groupBox4.Name = "groupBox4"; this.groupBox4.TabStop = false; // // tbAuthDenyMsg // resources.ApplyResources(this.tbAuthDenyMsg, "tbAuthDenyMsg"); this.tbAuthDenyMsg.Name = "tbAuthDenyMsg"; // // cbAuthDenyMsg // resources.ApplyResources(this.cbAuthDenyMsg, "cbAuthDenyMsg"); this.cbAuthDenyMsg.Name = "cbAuthDenyMsg"; this.cbAuthDenyMsg.UseVisualStyleBackColor = true; // // groupBox3 // this.groupBox3.Controls.Add(this.label1); this.groupBox3.Controls.Add(this.lblOfflineUsage); this.groupBox3.Controls.Add(this.numOfflineUsage); resources.ApplyResources(this.groupBox3, "groupBox3"); this.groupBox3.Name = "groupBox3"; this.groupBox3.TabStop = false; // // label1 // resources.ApplyResources(this.label1, "label1"); this.label1.Name = "label1"; // // lblOfflineUsage // resources.ApplyResources(this.lblOfflineUsage, "lblOfflineUsage"); this.lblOfflineUsage.Name = "lblOfflineUsage"; // // numOfflineUsage // resources.ApplyResources(this.numOfflineUsage, "numOfflineUsage"); this.numOfflineUsage.Name = "numOfflineUsage"; // // groupBox1 // this.groupBox1.Controls.Add(this.cbNestedCheck); this.groupBox1.Controls.Add(this.btnRemove); this.groupBox1.Controls.Add(this.lblTotalEvents); this.groupBox1.Controls.Add(this.btnAddSave); this.groupBox1.Controls.Add(this.txtCmd); this.groupBox1.Controls.Add(this.comboBox); this.groupBox1.Controls.Add(this.listBox); resources.ApplyResources(this.groupBox1, "groupBox1"); this.groupBox1.Name = "groupBox1"; this.groupBox1.TabStop = false; // // cbNestedCheck // resources.ApplyResources(this.cbNestedCheck, "cbNestedCheck"); this.cbNestedCheck.Name = "cbNestedCheck"; this.cbNestedCheck.UseVisualStyleBackColor = true; // // btnRemove // resources.ApplyResources(this.btnRemove, "btnRemove"); this.btnRemove.Name = "btnRemove"; this.btnRemove.UseVisualStyleBackColor = true; this.btnRemove.Click += new System.EventHandler(this.btnRemove_Click); // // lblTotalEvents // resources.ApplyResources(this.lblTotalEvents, "lblTotalEvents"); this.lblTotalEvents.Name = "lblTotalEvents"; // // btnAddSave // resources.ApplyResources(this.btnAddSave, "btnAddSave"); this.btnAddSave.Name = "btnAddSave"; this.btnAddSave.UseVisualStyleBackColor = true; this.btnAddSave.Click += new System.EventHandler(this.btnAddSave_Click); // // txtCmd // resources.ApplyResources(this.txtCmd, "txtCmd"); this.txtCmd.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.txtCmd.Name = "txtCmd"; // // comboBox // resources.ApplyResources(this.comboBox, "comboBox"); this.comboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.comboBox.FormattingEnabled = true; this.comboBox.Items.AddRange(new object[] { resources.GetString("comboBox.Items"), resources.GetString("comboBox.Items1")}); this.comboBox.Name = "comboBox"; this.comboBox.SelectedIndexChanged += new System.EventHandler(this.comboBox_SelectedIndexChanged); // // listBox // resources.ApplyResources(this.listBox, "listBox"); this.listBox.FormattingEnabled = true; this.listBox.Name = "listBox"; this.listBox.SelectedIndexChanged += new System.EventHandler(this.listBox_SelectedIndexChanged); // // groupBox2 // this.groupBox2.Controls.Add(this.tbRequireDomainConnection); this.groupBox2.Controls.Add(this.cbRequireDomainConnection); resources.ApplyResources(this.groupBox2, "groupBox2"); this.groupBox2.Name = "groupBox2"; this.groupBox2.TabStop = false; // // tbRequireDomainConnection // resources.ApplyResources(this.tbRequireDomainConnection, "tbRequireDomainConnection"); this.tbRequireDomainConnection.Name = "tbRequireDomainConnection"; // // cbRequireDomainConnection // resources.ApplyResources(this.cbRequireDomainConnection, "cbRequireDomainConnection"); this.cbRequireDomainConnection.Name = "cbRequireDomainConnection"; this.cbRequireDomainConnection.UseVisualStyleBackColor = true; this.cbRequireDomainConnection.CheckedChanged += new System.EventHandler(this.cbRequireDomainConnection_CheckedChanged); // // ADPermissionsForm // this.AcceptButton = this.btnOk; resources.ApplyResources(this, "$this"); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.CancelButton = this.btnCancel; this.Controls.Add(this.panel8); this.Controls.Add(this.panel1); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "ADPermissionsForm"; this.Load += new System.EventHandler(this.ADPermissionsForm_Load); this.panel8.ResumeLayout(false); this.panel2.ResumeLayout(false); this.groupBox4.ResumeLayout(false); this.groupBox4.PerformLayout(); this.groupBox3.ResumeLayout(false); this.groupBox3.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.numOfflineUsage)).EndInit(); this.groupBox1.ResumeLayout(false); this.groupBox1.PerformLayout(); this.groupBox2.ResumeLayout(false); this.groupBox2.PerformLayout(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.Panel panel1; private System.Windows.Forms.Panel panel8; private System.Windows.Forms.Panel panel2; private System.Windows.Forms.ComboBox comboBox; private System.Windows.Forms.Button btnAddSave; private System.Windows.Forms.TextBox txtCmd; private System.Windows.Forms.Button btnOk; private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.Button btnCancel; private System.Windows.Forms.ListBox listBox; private System.Windows.Forms.Label lblTotalEvents; private System.Windows.Forms.GroupBox groupBox2; private System.Windows.Forms.CheckBox cbRequireDomainConnection; private System.Windows.Forms.TextBox tbRequireDomainConnection; private System.Windows.Forms.GroupBox groupBox3; private System.Windows.Forms.TextBox tbAuthDenyMsg; private System.Windows.Forms.CheckBox cbAuthDenyMsg; private System.Windows.Forms.NumericUpDown numOfflineUsage; private System.Windows.Forms.Label label1; private System.Windows.Forms.Label lblOfflineUsage; private System.Windows.Forms.Button btnRemove; private System.Windows.Forms.CheckBox cbNestedCheck; private System.Windows.Forms.GroupBox groupBox4; } }
45.632143
149
0.60288
[ "MIT" ]
ChenallFork/cameyo
PackageEditor/ADPermissions.Designer.cs
12,779
C#
using System.Collections.Generic; using MirRemakeBackend.Util; namespace MirRemakeBackend.Entity { /// <summary> /// 处理阵营信息, 组队 /// </summary> class EM_BossDamage { public static EM_BossDamage s_instance; private const float c_bossDmgRefreshTime = 1800; /// <summary> /// 键为 charId /// </summary> private List < (int, Dictionary < int, (int, string) >) > m_bossDmgList = new List < (int, Dictionary < int, (int, string) >) > (); private List < (int, MyTimer.Time) > m_bossDmgRefreshList = new List < (int, MyTimer.Time) > (); public void AddBoss (int bossNetId) { m_bossDmgList.Add ((bossNetId, new Dictionary < int, (int, string) > ())); m_bossDmgRefreshList.Add ((bossNetId, MyTimer.s_CurTime)); } /// <summary> /// 键为 charId /// </summary> public IReadOnlyList < (int, Dictionary < int, (int, string) >) > GetBossDmgList () { return m_bossDmgList; } /// <summary> /// 键为 charId /// </summary> public Dictionary < int, (int, string) > GetBossDmgDict (int bossNetId) { for (int i = 0; i < m_bossDmgList.Count; i++) if (m_bossDmgList[i].Item1 == bossNetId) return m_bossDmgList[i].Item2; return null; } public void UpdateBossDmg (int netId) { for (int i = 0; i < m_bossDmgRefreshList.Count; i++) if (m_bossDmgRefreshList[i].Item1 == netId) m_bossDmgRefreshList[i] = (netId, MyTimer.s_CurTime.Ticked (c_bossDmgRefreshTime)); } public void RefreshBossDmg () { for (int i = 0; i < m_bossDmgList.Count; i++) { if (m_bossDmgList[i].Item2.Count == 0) continue; if (MyTimer.CheckTimeUp (m_bossDmgRefreshList[i].Item2)) m_bossDmgList[i].Item2.Clear (); } } } }
41.1875
139
0.550835
[ "MIT" ]
HeBomou/mir-remake-ios-server
Entity/EntityManager/EM_BossDamage.cs
2,005
C#
namespace Okta.Aws.Cli.Cli.Interfaces; public interface ICliArgumentHandler { string Argument { get; } Task Handle(CancellationToken cancellationToken); }
23.428571
53
0.77439
[ "MIT" ]
nizanrosh/okta-aws-cli
src/main/Okta.Aws.Cli/Cli/Interfaces/ICliArgumentHandler.cs
166
C#
using System.Reflection; 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("AWSSDK.DocDB")] [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - Amazon DocumentDB with MongoDB compatibility. Amazon DocumentDB is a fast, reliable, and fully managed MongoDB compatible database service.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("Amazon Web Services SDK for .NET")] [assembly: AssemblyCompany("Amazon.com, Inc")] [assembly: AssemblyCopyright("Copyright 2009-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.")] [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)] // 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("3.3")] [assembly: AssemblyFileVersion("3.3.102.49")]
46.5625
219
0.752349
[ "Apache-2.0" ]
shivamjhaonthecloud/aws-sdk-net
sdk/code-analysis/ServiceAnalysis/DocDB/Properties/AssemblyInfo.cs
1,490
C#
using System; using Xamarin.Forms; namespace XLabs.Forms.Controls { /// <summary> /// Class CalendarView. /// </summary> public class CalendarView : View { /// <summary> /// Enum BackgroundStyle /// </summary> public enum BackgroundStyle{ /// <summary> /// The fill /// </summary> Fill, /// <summary> /// The circle fill /// </summary> CircleFill, /// <summary> /// The circle outline /// </summary> CircleOutline } /** * SelectedDate property */ /// <summary> /// The minimum date property /// </summary> public static readonly BindableProperty MinDateProperty = BindableProperty.Create( "MinDate", typeof(DateTime), typeof(CalendarView), FirstDayOfMonth(DateTime.Today), BindingMode.OneWay, null, null, null, null); /// <summary> /// Gets or sets the minimum date. /// </summary> /// <value>The minimum date.</value> public DateTime MinDate { get { return (DateTime)base.GetValue(CalendarView.MinDateProperty); } set { base.SetValue(CalendarView.MinDateProperty, value); } } /// <summary> /// The maximum date property /// </summary> public static readonly BindableProperty MaxDateProperty = BindableProperty.Create( "MaxDate", typeof(DateTime), typeof(CalendarView), LastDayOfMonth(DateTime.Today), BindingMode.OneWay, null, null, null, null); /// <summary> /// Gets or sets the maximum date. /// </summary> /// <value>The maximum date.</value> public DateTime MaxDate { get { return (DateTime)base.GetValue(CalendarView.MaxDateProperty); } set { base.SetValue(CalendarView.MaxDateProperty, value); } } //Helper method /// <summary> /// Firsts the day of month. /// </summary> /// <param name="date">The date.</param> /// <returns>DateTime.</returns> public static DateTime FirstDayOfMonth(DateTime date) { return date.AddDays(1-date.Day); } //Helper method /// <summary> /// Lasts the day of month. /// </summary> /// <param name="date">The date.</param> /// <returns>DateTime.</returns> public static DateTime LastDayOfMonth(DateTime date) { return new DateTime(date.Year, date.Month, DateTime.DaysInMonth(date.Year, date.Month)); } /** * SelectedDate property */ /// <summary> /// The selected date property /// </summary> public static readonly BindableProperty SelectedDateProperty = BindableProperty.Create( "SelectedDate", typeof(DateTime?), typeof(CalendarView), null, BindingMode.TwoWay, null, null, null, null); /// <summary> /// Gets or sets the selected date. /// </summary> /// <value>The selected date.</value> public DateTime? SelectedDate { get { return (DateTime?)base.GetValue(CalendarView.SelectedDateProperty); } set { base.SetValue(CalendarView.SelectedDateProperty, value); } } /** * Displayed date property */ /// <summary> /// The displayed month property /// </summary> public static readonly BindableProperty DisplayedMonthProperty = BindableProperty.Create( "DisplayedMonth", typeof(DateTime), typeof(CalendarView), DateTime.Now, BindingMode.TwoWay, null, null, null, null); /// <summary> /// Gets or sets the displayed month. /// </summary> /// <value>The displayed month.</value> public DateTime DisplayedMonth { get { return (DateTime)base.GetValue(CalendarView.DisplayedMonthProperty); } set { base.SetValue(CalendarView.DisplayedMonthProperty, value); } } /** * DateLabelFont property */ /// <summary> /// The date label font property /// </summary> public static readonly BindableProperty DateLabelFontProperty = BindableProperty.Create("DateLabelFont", typeof(Font), typeof(CalendarView), Font.Default, BindingMode.OneWay, null, null, null, null); /** * Font used by the calendar dates and day labels */ /// <summary> /// Gets or sets the date label font. /// </summary> /// <value>The date label font.</value> public Font DateLabelFont { get { return (Font)base.GetValue(CalendarView.DateLabelFontProperty); } set { base.SetValue(CalendarView.DateLabelFontProperty, value); } } /** * Font property */ /// <summary> /// The month title font property /// </summary> public static readonly BindableProperty MonthTitleFontProperty = BindableProperty.Create("MonthTitleFont", typeof(Font), typeof(CalendarView), Font.Default, BindingMode.OneWay, null, null, null, null); /** * Font used by the month title */ /// <summary> /// Gets or sets the month title font. /// </summary> /// <value>The month title font.</value> public Font MonthTitleFont { get { return (Font)base.GetValue(CalendarView.MonthTitleFontProperty); } set { base.SetValue(CalendarView.MonthTitleFontProperty, value); } } /** * TextColorProperty property */ /// <summary> /// The text color property /// </summary> public static readonly BindableProperty TextColorProperty = BindableProperty.Create("TextColor", typeof(Color), typeof(CalendarView), Color.Default, BindingMode.OneWay, null, null, null, null); /** * Overall text color property. Default color is platform specific. */ /// <summary> /// Gets or sets the color of the text. /// </summary> /// <value>The color of the text.</value> public Color TextColor { get { return (Color)base.GetValue(CalendarView.TextColorProperty); } set { base.SetValue(CalendarView.TextColorProperty, value); } } /** * TodayDateForegroundColorProperty property */ /// <summary> /// The today date foreground color property /// </summary> public static readonly BindableProperty TodayDateForegroundColorProperty = BindableProperty.Create("TodayDateForegroundColor", typeof(Color), typeof(CalendarView), Color.Default, BindingMode.OneWay, null, null, null, null); /** * Foreground color of today date. Default color is platform specific. */ /// <summary> /// Gets or sets the color of the today date foreground. /// </summary> /// <value>The color of the today date foreground.</value> public Color TodayDateForegroundColor { get { return (Color)base.GetValue(CalendarView.TodayDateForegroundColorProperty); } set { base.SetValue(CalendarView.TodayDateForegroundColorProperty, value); } } /** * TodayDateBackgroundColorProperty property */ /// <summary> /// The today date background color property /// </summary> public static readonly BindableProperty TodayDateBackgroundColorProperty = BindableProperty.Create("TodayDateBackgroundColor", typeof(Color), typeof(CalendarView), Color.Default, BindingMode.OneWay, null, null, null, null); /** * Background color of today date. Default color is platform specific. */ /// <summary> /// Gets or sets the color of the today date background. /// </summary> /// <value>The color of the today date background.</value> public Color TodayDateBackgroundColor { get { return (Color)base.GetValue(CalendarView.TodayDateBackgroundColorProperty); } set { base.SetValue(CalendarView.TodayDateBackgroundColorProperty, value); } } /** * DateForegroundColorProperty property */ /// <summary> /// The date foreground color property /// </summary> public static readonly BindableProperty DateForegroundColorProperty = BindableProperty.Create("DateForegroundColor", typeof(Color), typeof(CalendarView), Color.Default, BindingMode.OneWay, null, null, null, null); /** * Foreground color of date in the calendar. Default color is platform specific. */ /// <summary> /// Gets or sets the color of the date foreground. /// </summary> /// <value>The color of the date foreground.</value> public Color DateForegroundColor { get { return (Color)base.GetValue(CalendarView.DateForegroundColorProperty); } set { base.SetValue(CalendarView.DateForegroundColorProperty, value); } } /** * DateBackgroundColorProperty property */ /// <summary> /// The date background color property /// </summary> public static readonly BindableProperty DateBackgroundColorProperty = BindableProperty.Create("DateBackgroundColor", typeof(Color), typeof(CalendarView), Color.Default, BindingMode.OneWay, null, null, null, null); /** * Background color of date in the calendar. Default color is platform specific. */ /// <summary> /// Gets or sets the color of the date background. /// </summary> /// <value>The color of the date background.</value> public Color DateBackgroundColor { get { return (Color)base.GetValue(CalendarView.DateBackgroundColorProperty); } set { base.SetValue(CalendarView.DateBackgroundColorProperty, value); } } /** * InactiveDateForegroundColorProperty property */ /// <summary> /// The inactive date foreground color property /// </summary> public static readonly BindableProperty InactiveDateForegroundColorProperty = BindableProperty.Create("InactiveDateForegroundColor", typeof(Color), typeof(CalendarView), Color.Default, BindingMode.OneWay, null, null, null, null); /** * Foreground color of date in the calendar which is outside of the current month. Default color is platform specific. */ /// <summary> /// Gets or sets the color of the inactive date foreground. /// </summary> /// <value>The color of the inactive date foreground.</value> public Color InactiveDateForegroundColor { get { return (Color)base.GetValue(CalendarView.InactiveDateForegroundColorProperty); } set { base.SetValue(CalendarView.InactiveDateForegroundColorProperty, value); } } /** * InactiveDateBackgroundColorProperty property */ /// <summary> /// The inactive date background color property /// </summary> public static readonly BindableProperty InactiveDateBackgroundColorProperty = BindableProperty.Create("InactiveDateBackgroundColor", typeof(Color), typeof(CalendarView), Color.Default, BindingMode.OneWay, null, null, null, null); /** * Background color of date in the calendar which is outside of the current month. Default color is platform specific. */ /// <summary> /// Gets or sets the color of the inactive date background. /// </summary> /// <value>The color of the inactive date background.</value> public Color InactiveDateBackgroundColor { get { return (Color)base.GetValue(CalendarView.InactiveDateBackgroundColorProperty); } set { base.SetValue(CalendarView.InactiveDateBackgroundColorProperty, value); } } /** * HighlightedDateForegroundColorProperty property */ /// <summary> /// The highlighted date foreground color property /// </summary> public static readonly BindableProperty HighlightedDateForegroundColorProperty = BindableProperty.Create("HighlightedDateForegroundColor", typeof(Color), typeof(CalendarView), Color.Default, BindingMode.OneWay, null, null, null, null); /** * Foreground color of highlighted date in the calendar. Default color is platform specific. */ /// <summary> /// Gets or sets the color of the highlighted date foreground. /// </summary> /// <value>The color of the highlighted date foreground.</value> public Color HighlightedDateForegroundColor { get { return (Color)base.GetValue(CalendarView.HighlightedDateForegroundColorProperty); } set { base.SetValue(CalendarView.HighlightedDateForegroundColorProperty, value); } } /** * HighlightedDateBackgroundColor property */ /// <summary> /// The highlighted date background color property /// </summary> public static readonly BindableProperty HighlightedDateBackgroundColorProperty = BindableProperty.Create("HighlightedDateBackgroundColor", typeof(Color), typeof(CalendarView), Color.Default, BindingMode.OneWay, null, null, null, null); /** * Background color of selected date in the calendar. Default color is platform specific. */ /// <summary> /// Gets or sets the color of the highlighted date background. /// </summary> /// <value>The color of the highlighted date background.</value> public Color HighlightedDateBackgroundColor { get { return (Color)base.GetValue(CalendarView.HighlightedDateBackgroundColorProperty); } set { base.SetValue(CalendarView.HighlightedDateBackgroundColorProperty, value); } } /** * TodayBackgroundStyle property */ /// <summary> /// The today background style property /// </summary> public static readonly BindableProperty TodayBackgroundStyleProperty = BindableProperty.Create("TodayBackgroundStyle", typeof(BackgroundStyle), typeof(CalendarView), BackgroundStyle.Fill, BindingMode.OneWay, null, null, null, null); /** * Background style for today cell. It is only respected on iOS for now. */ /// <summary> /// Gets or sets the today background style. /// </summary> /// <value>The today background style.</value> public BackgroundStyle TodayBackgroundStyle { get { return (BackgroundStyle)base.GetValue(CalendarView.TodayBackgroundStyleProperty); } set { base.SetValue(CalendarView.TodayBackgroundStyleProperty, value); } } /** * SelectionBackgroundStyle property */ /// <summary> /// The selection background style property /// </summary> public static readonly BindableProperty SelectionBackgroundStyleProperty = BindableProperty.Create("SelectionBackgroundStyle", typeof(BackgroundStyle), typeof(CalendarView), BackgroundStyle.Fill, BindingMode.OneWay, null, null, null, null); /** * Background style for selecting the cells. It is only respected on iOS for now. */ /// <summary> /// Gets or sets the selection background style. /// </summary> /// <value>The selection background style.</value> public BackgroundStyle SelectionBackgroundStyle { get { return (BackgroundStyle)base.GetValue(CalendarView.SelectionBackgroundStyleProperty); } set { base.SetValue(CalendarView.SelectionBackgroundStyleProperty, value); } } /** * SelectedDateForegroundColorProperty property */ /// <summary> /// The selected date foreground color property /// </summary> public static readonly BindableProperty SelectedDateForegroundColorProperty = BindableProperty.Create("SelectedDateForegroundColor", typeof(Color), typeof(CalendarView), Color.Default, BindingMode.OneWay, null, null, null, null); /** * Foreground color of selected date in the calendar. Default color is platform specific. */ /// <summary> /// Gets or sets the color of the selected date foreground. /// </summary> /// <value>The color of the selected date foreground.</value> public Color SelectedDateForegroundColor { get { return (Color)base.GetValue(CalendarView.SelectedDateForegroundColorProperty); } set { base.SetValue(CalendarView.SelectedDateForegroundColorProperty, value); } } /** * DateBackgroundColorProperty property */ /// <summary> /// The selected date background color property /// </summary> public static readonly BindableProperty SelectedDateBackgroundColorProperty = BindableProperty.Create("SelectedDateBackgroundColor", typeof(Color), typeof(CalendarView), Color.Default, BindingMode.OneWay, null, null, null, null); /** * Background color of selected date in the calendar. Default color is platform specific. */ /// <summary> /// Gets or sets the color of the selected date background. /// </summary> /// <value>The color of the selected date background.</value> public Color SelectedDateBackgroundColor { get { return (Color)base.GetValue(CalendarView.SelectedDateBackgroundColorProperty); } set { base.SetValue(CalendarView.SelectedDateBackgroundColorProperty, value); } } /** * DayOfWeekLabelForegroundColorProperty property */ /// <summary> /// The day of week label foreground color property /// </summary> public static readonly BindableProperty DayOfWeekLabelForegroundColorProperty = BindableProperty.Create("DayOfWeekLabelForegroundColor", typeof(Color), typeof(CalendarView), Color.Default, BindingMode.OneWay, null, null, null, null); /** * Foreground color of week day labels in the month header. Default color is platform specific. */ /// <summary> /// Gets or sets the color of the day of week label foreground. /// </summary> /// <value>The color of the day of week label foreground.</value> public Color DayOfWeekLabelForegroundColor { get { return (Color)base.GetValue(CalendarView.DayOfWeekLabelForegroundColorProperty); } set { base.SetValue(CalendarView.DayOfWeekLabelForegroundColorProperty, value); } } /** * DayOfWeekLabelForegroundColorProperty property */ /// <summary> /// The day of week label background color property /// </summary> public static readonly BindableProperty DayOfWeekLabelBackgroundColorProperty = BindableProperty.Create("DayOfWeekLabelBackgroundColor", typeof(Color), typeof(CalendarView), Color.Default, BindingMode.OneWay, null, null, null, null); /** * Background color of week day labels in the month header. Default color is platform specific. */ /// <summary> /// Gets or sets the color of the day of week label background. /// </summary> /// <value>The color of the day of week label background.</value> public Color DayOfWeekLabelBackgroundColor { get { return (Color)base.GetValue(CalendarView.DayOfWeekLabelBackgroundColorProperty); } set { base.SetValue(CalendarView.DayOfWeekLabelBackgroundColorProperty, value); } } /** * DayOfWeekLabelForegroundColorProperty property */ /// <summary> /// The month title foreground color property /// </summary> public static readonly BindableProperty MonthTitleForegroundColorProperty = BindableProperty.Create("MonthTitleForegroundColor", typeof(Color), typeof(CalendarView), Color.Default, BindingMode.OneWay, null, null, null, null); /** * Foreground color of week day labels in the month header. Default color is platform specific. */ /// <summary> /// Gets or sets the color of the month title foreground. /// </summary> /// <value>The color of the month title foreground.</value> public Color MonthTitleForegroundColor { get { return (Color)base.GetValue(CalendarView.MonthTitleForegroundColorProperty); } set { base.SetValue(CalendarView.MonthTitleForegroundColorProperty, value); } } /** * DayOfWeekLabelForegroundColorProperty property */ /// <summary> /// The month title background color property /// </summary> public static readonly BindableProperty MonthTitleBackgroundColorProperty = BindableProperty.Create("MonthTitleBackgroundColor", typeof(Color), typeof(CalendarView), Color.Default, BindingMode.OneWay, null, null, null, null); /** * Background color of week day labels in the month header. Default color is platform specific. */ /// <summary> /// Gets or sets the color of the month title background. /// </summary> /// <value>The color of the month title background.</value> public Color MonthTitleBackgroundColor { get { return (Color)base.GetValue(CalendarView.MonthTitleBackgroundColorProperty); } set { base.SetValue(CalendarView.MonthTitleBackgroundColorProperty, value); } } /** * DateSeparatorColorProperty property */ /// <summary> /// The date separator color property /// </summary> public static readonly BindableProperty DateSeparatorColorProperty = BindableProperty.Create("DateSeparatorColor", typeof(Color), typeof(CalendarView), Color.Default, BindingMode.OneWay, null, null, null, null); /** * Color of separator between dates. Default color is platform specific. */ /// <summary> /// Gets or sets the color of the date separator. /// </summary> /// <value>The color of the date separator.</value> public Color DateSeparatorColor { get { return (Color)base.GetValue(CalendarView.DateSeparatorColorProperty); } set { base.SetValue(CalendarView.DateSeparatorColorProperty, value); } } /** * ShowNavigationArrowsProperty property */ /// <summary> /// The show navigation arrows property /// </summary> public static readonly BindableProperty ShowNavigationArrowsProperty = BindableProperty.Create("ShowNavigationArrows", typeof(bool), typeof(CalendarView), false, BindingMode.OneWay, null, null, null, null); /** * Whether to show navigation arrows for going through months. The navigation arrows */ /// <summary> /// Gets or sets a value indicating whether [show navigation arrows]. /// </summary> /// <value><c>true</c> if [show navigation arrows]; otherwise, <c>false</c>.</value> public bool ShowNavigationArrows { get { return (bool)base.GetValue(CalendarView.ShowNavigationArrowsProperty); } set { base.SetValue(CalendarView.ShowNavigationArrowsProperty, value); } } /** * NavigationArrowsColorProperty property */ /// <summary> /// The navigation arrows color property /// </summary> public static readonly BindableProperty NavigationArrowsColorProperty = BindableProperty.Create("NavigationArrowsColorProperty", typeof(Color), typeof(CalendarView), Color.Default, BindingMode.OneWay, null, null, null, null); /** * Color of the navigation colors (if shown). Default color is platform specific */ /// <summary> /// Gets or sets the color of the navigation arrows. /// </summary> /// <value>The color of the navigation arrows.</value> public Color NavigationArrowsColor { get { return (Color)base.GetValue(CalendarView.NavigationArrowsColorProperty); } set { base.SetValue(CalendarView.NavigationArrowsColorProperty, value); } } /** * ShouldHighlightDaysOfWeekLabelsProperty property */ /// <summary> /// The should highlight days of week labels property /// </summary> public static readonly BindableProperty ShouldHighlightDaysOfWeekLabelsProperty = BindableProperty.Create("ShouldHighlightDaysOfWeekLabels", typeof(bool), typeof(CalendarView), false, BindingMode.OneWay, null, null, null, null); /** * Whether to highlight also the labels of week days when the entire column is highlighted. */ /// <summary> /// Gets or sets a value indicating whether [should highlight days of week labels]. /// </summary> /// <value><c>true</c> if [should highlight days of week labels]; otherwise, <c>false</c>.</value> public bool ShouldHighlightDaysOfWeekLabels { get { return (bool)base.GetValue(CalendarView.ShouldHighlightDaysOfWeekLabelsProperty); } set { base.SetValue(CalendarView.ShouldHighlightDaysOfWeekLabelsProperty, value); } } /** * HighlightedDaysOfWeekProperty property */ /// <summary> /// The highlighted days of week property /// </summary> public static readonly BindableProperty HighlightedDaysOfWeekProperty = BindableProperty.Create("HighlightedDaysOfWeek", typeof(DayOfWeek[]), typeof(CalendarView), new DayOfWeek[]{}, BindingMode.OneWay, null, null, null, null); /** * Background color of selected date in the calendar. Default color is platform specific. */ /// <summary> /// Gets or sets the highlighted days of week. /// </summary> /// <value>The highlighted days of week.</value> public DayOfWeek[] HighlightedDaysOfWeek { get { return (DayOfWeek[])base.GetValue(CalendarView.HighlightedDaysOfWeekProperty); } set { base.SetValue(CalendarView.HighlightedDaysOfWeekProperty, value); } } #region ColorHelperProperties /// <summary> /// Gets the actual color of the date background. /// </summary> /// <value>The actual color of the date background.</value> public Color ActualDateBackgroundColor{ get{ return this.DateBackgroundColor; } } /// <summary> /// Gets the actual color of the date foreground. /// </summary> /// <value>The actual color of the date foreground.</value> public Color ActualDateForegroundColor{ get{ if(this.DateForegroundColor != Color.Default) { return this.DateForegroundColor; } return this.TextColor; } } /// <summary> /// Gets the actual color of the inactive date background. /// </summary> /// <value>The actual color of the inactive date background.</value> public Color ActualInactiveDateBackgroundColor{ get{ if(this.InactiveDateBackgroundColor != Color.Default) { return this.InactiveDateBackgroundColor; } return this.ActualDateBackgroundColor; } } /// <summary> /// Gets the actual color of the inactive date foreground. /// </summary> /// <value>The actual color of the inactive date foreground.</value> public Color ActualInactiveDateForegroundColor{ get{ if(this.InactiveDateForegroundColor != Color.Default) { return this.InactiveDateForegroundColor; } return this.ActualDateForegroundColor; } } /// <summary> /// Gets the actual color of the today date foreground. /// </summary> /// <value>The actual color of the today date foreground.</value> public Color ActualTodayDateForegroundColor{ get{ if(this.TodayDateForegroundColor != Color.Default) { return this.TodayDateForegroundColor; } return this.ActualDateForegroundColor; } } /// <summary> /// Gets the actual color of the today date background. /// </summary> /// <value>The actual color of the today date background.</value> public Color ActualTodayDateBackgroundColor{ get{ if(this.TodayDateBackgroundColor != Color.Default) { return this.TodayDateBackgroundColor; } return this.ActualDateBackgroundColor; } } /// <summary> /// Gets the actual color of the selected date foreground. /// </summary> /// <value>The actual color of the selected date foreground.</value> public Color ActualSelectedDateForegroundColor{ get{ if(this.SelectedDateForegroundColor != Color.Default){ return this.SelectedDateForegroundColor; } return this.ActualDateForegroundColor; } } /// <summary> /// Gets the actual color of the selected date background. /// </summary> /// <value>The actual color of the selected date background.</value> public Color ActualSelectedDateBackgroundColor{ get{ if(this.SelectedDateBackgroundColor != Color.Default){ return this.SelectedDateBackgroundColor; } return this.ActualDateBackgroundColor; } } /// <summary> /// Gets the actual color of the month title foreground. /// </summary> /// <value>The actual color of the month title foreground.</value> public Color ActualMonthTitleForegroundColor{ get{ if(this.MonthTitleForegroundColor != Color.Default){ return MonthTitleForegroundColor; } return this.TextColor; } } /// <summary> /// Gets the actual color of the month title background. /// </summary> /// <value>The actual color of the month title background.</value> public Color ActualMonthTitleBackgroundColor{ get{ if(this.MonthTitleBackgroundColor != Color.Default){ return MonthTitleBackgroundColor; } return this.BackgroundColor; } } /// <summary> /// Gets the actual color of the day of week label foreground. /// </summary> /// <value>The actual color of the day of week label foreground.</value> public Color ActualDayOfWeekLabelForegroundColor{ get{ if(this.DayOfWeekLabelForegroundColor != Color.Default){ return DayOfWeekLabelForegroundColor; } return this.TextColor; } } /// <summary> /// Gets the actual color of the day of week label backround. /// </summary> /// <value>The actual color of the day of week label backround.</value> public Color ActualDayOfWeekLabelBackroundColor{ get{ if(this.DayOfWeekLabelBackgroundColor != Color.Default){ return DayOfWeekLabelBackgroundColor; } return this.BackgroundColor; } } /// <summary> /// Gets the actual color of the navigation arrows. /// </summary> /// <value>The actual color of the navigation arrows.</value> public Color ActualNavigationArrowsColor{ get{ if(this.NavigationArrowsColor != Color.Default){ return NavigationArrowsColor; } return this.ActualMonthTitleForegroundColor; } } /// <summary> /// Gets the actual color of the highlighted date foreground. /// </summary> /// <value>The actual color of the highlighted date foreground.</value> public Color ActualHighlightedDateForegroundColor{ get{ return HighlightedDateForegroundColor; } } /// <summary> /// Gets the actual color of the highlighted date background. /// </summary> /// <value>The actual color of the highlighted date background.</value> public Color ActualHighlightedDateBackgroundColor{ get{ return HighlightedDateBackgroundColor; } } #endregion /// <summary> /// Initializes a new instance of the <see cref="CalendarView"/> class. /// </summary> public CalendarView() { if(Device.OS == TargetPlatform.iOS){ HeightRequest = 198 + 20; //This is the size of the original iOS calendar }else if(Device.OS == TargetPlatform.Android){ HeightRequest = 300; //This is the size in which Android calendar renders comfortably on most devices } } /// <summary> /// Notifies the displayed month changed. /// </summary> /// <param name="date">The date.</param> public void NotifyDisplayedMonthChanged(DateTime date) { DisplayedMonth = date; if (MonthChanged != null) MonthChanged(this, date); } /// <summary> /// Occurs when [month changed]. /// </summary> public event EventHandler<DateTime> MonthChanged; /// <summary> /// Notifies the date selected. /// </summary> /// <param name="dateSelected">The date selected.</param> public void NotifyDateSelected(DateTime dateSelected) { SelectedDate = dateSelected; if (DateSelected != null) DateSelected(this, dateSelected); } /// <summary> /// Occurs when [date selected]. /// </summary> public event EventHandler<DateTime> DateSelected; } }
30.172311
242
0.703331
[ "Apache-2.0" ]
DarkLotus/Xamarin-Forms-Labs
src/Forms/XLabs.Forms/Controls/CalendarView.cs
30,295
C#
namespace DisPlay.Umbraco.EmbeddedContent.Courier { using System.Collections.Generic; using System.Linq; using Newtonsoft.Json; using global::Umbraco.Courier.Core; using global::Umbraco.Courier.Core.ProviderModel; using global::Umbraco.Courier.DataResolvers; using global::Umbraco.Courier.ItemProviders; using Models; public class EmbeddedContentDataResolverProvider : PropertyDataResolverProvider { public override string EditorAlias => Constants.PropertyEditorAlias; public override void PackagingDataType(DataType item) { DataTypePrevalue preValue = item.Prevalues.FirstOrDefault(_ => _.Alias == "embeddedContentConfig"); if(preValue != null) { var config = JsonConvert.DeserializeObject<EmbeddedContentConfig>(preValue.Value); foreach(EmbeddedContentConfigDocumentType docTypeConfig in config.DocumentTypes) { var contentType = ExecutionContext.DatabasePersistence.RetrieveItem<DocumentType>( new ItemIdentifier(docTypeConfig.DocumentTypeAlias, ItemProviderIds.documentTypeItemProviderGuid) ); if(contentType != null) { item.Dependencies.Add(contentType.UniqueId.ToString(), ItemProviderIds.documentTypeItemProviderGuid); } } } } public override void PackagingProperty(Item item, ContentProperty propertyData) { ProcessProperty(item, propertyData, true); } public override void ExtractingProperty(Item item, ContentProperty propertyData) { ProcessProperty(item, propertyData, false); } private void ProcessProperty(Item item, ContentProperty propertyData, bool packaging) { ItemProvider propertyItemProvider = ItemProviderCollection.Instance.GetProvider(ItemProviderIds.propertyDataItemProviderGuid, ExecutionContext); if (propertyData.Value != null) { var items = JsonConvert.DeserializeObject<EmbeddedContentItem[]>(propertyData.Value.ToString()); foreach (EmbeddedContentItem embeddedContent in items) { var contentType = ExecutionContext.DatabasePersistence.RetrieveItem<DocumentType>( new ItemIdentifier(embeddedContent.ContentTypeAlias, ItemProviderIds.documentTypeItemProviderGuid) ); if (contentType == null) { continue; } if (packaging) { item.Dependencies.Add(contentType.UniqueId.ToString(), ItemProviderIds.documentTypeItemProviderGuid); } foreach (KeyValuePair<string, object> property in embeddedContent.Properties.ToList()) { ContentTypeProperty propertyType = contentType.Properties.FirstOrDefault(_ => _.Alias == property.Key); if (propertyType == null) { continue; } var dataType = ExecutionContext.DatabasePersistence.RetrieveItem<DataType>( new ItemIdentifier(propertyType.DataTypeDefinitionId.ToString(), ItemProviderIds.dataTypeItemProviderGuid) ); if (dataType == null) { continue; } var fakeItem = new ContentPropertyData { ItemId = item.ItemId, Name = $"{item.Name} [{EditorAlias}: Nested {dataType.PropertyEditorAlias} ({property.Key})]", Data = new List<ContentProperty> { new ContentProperty { Alias = propertyType.Alias, DataType = propertyType.DataTypeDefinitionId, PropertyEditorAlias = dataType.PropertyEditorAlias, Value = property.Value } } }; if (packaging) { ResolutionManager.Instance.PackagingItem(fakeItem, propertyItemProvider); item.Dependencies.AddRange(fakeItem.Dependencies); item.Resources.AddRange(fakeItem.Resources); } else { ResolutionManager.Instance.ExtractingItem(fakeItem, propertyItemProvider); } ContentProperty data = fakeItem.Data?.FirstOrDefault(); if (data != null) { embeddedContent.Properties[property.Key] = data.Value; if (packaging) { item.Dependencies.Add(data.DataType.ToString(), ItemProviderIds.dataTypeItemProviderGuid); } } } } propertyData.Value = JsonConvert.SerializeObject(items); } } } }
42.148148
156
0.514938
[ "MIT" ]
display/Umbraco-Embedded-Content
src/DisPlay.Umbraco.EmbeddedContent.Courier/EmbeddedContentDataResolverProvider.cs
5,690
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; namespace TelegramBotApi { public class Program { public static void Main(string[] args) { CreateWebHostBuilder(args).Build().Run(); } public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>(); } }
24.4
76
0.695082
[ "MIT" ]
RomanTymokhov/TelegramBotApiTest
TelegramBotApi/TelegramBotApi/Program.cs
612
C#
using System; using System.Collections.Generic; using System.Linq; using System.Security.Claims; using System.Text; using System.Threading.Tasks; namespace FleetControl.WebUI.Auth { public interface IJwtFactory { Task<string> GenerateEncodedToken(string userName, ClaimsIdentity identity); ClaimsIdentity GenerateClaimsIdentity(string userName, string id); } }
24.4375
84
0.767263
[ "MIT" ]
sdemaine/FleetControl_CQRS_CORE
FleetControl.WebUI/Auth/IJwtFactory.cs
393
C#
namespace 多线程登录 { partial class frmSplash { /// <summary> /// 必需的设计器变量。 /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// 清理所有正在使用的资源。 /// </summary> /// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows 窗体设计器生成的代码 /// <summary> /// 设计器支持所需的方法 - 不要 /// 使用代码编辑器修改此方法的内容。 /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(frmSplash)); this.progressBar1 = new System.Windows.Forms.ProgressBar(); this.lblInfo = new System.Windows.Forms.Label(); this.SuspendLayout(); // // progressBar1 // this.progressBar1.Dock = System.Windows.Forms.DockStyle.Bottom; this.progressBar1.Location = new System.Drawing.Point(0, 229); this.progressBar1.Name = "progressBar1"; this.progressBar1.Size = new System.Drawing.Size(302, 18); this.progressBar1.TabIndex = 0; // // lblInfo // this.lblInfo.AutoSize = true; this.lblInfo.BackColor = System.Drawing.Color.Transparent; this.lblInfo.Font = new System.Drawing.Font("宋体", 14.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134))); this.lblInfo.ForeColor = System.Drawing.Color.Yellow; this.lblInfo.Location = new System.Drawing.Point(12, 235); this.lblInfo.Name = "lblInfo"; this.lblInfo.Size = new System.Drawing.Size(75, 19); this.lblInfo.TabIndex = 1; this.lblInfo.Text = "label1"; // // frmSplash // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("$this.BackgroundImage"))); this.ClientSize = new System.Drawing.Size(302, 247); this.ControlBox = false; this.Controls.Add(this.lblInfo); this.Controls.Add(this.progressBar1); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Fixed3D; this.Name = "frmSplash"; this.ShowIcon = false; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.TopMost = true; this.Load += new System.EventHandler(this.frmSplash_Load); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.ProgressBar progressBar1; private System.Windows.Forms.Label lblInfo; } }
39.085366
151
0.579095
[ "MIT" ]
cqkxzyi/ZhangYi.Utilities
doNet/站点/WinForm/示例窗口/多线程/frmSplash.designer.cs
3,371
C#
namespace WildFarm.Models.Food { public class Seeds : Food { public Seeds(int quantity) : base(quantity) { } } }
14.727273
34
0.5
[ "MIT" ]
tonkatawe/SoftUni-Advanced
OOP/Polymorphism - Exercise/WildFarm/Models/Food/Seeds.cs
164
C#
namespace BARS.ClickHouse.Client { using System; using System.IO; using System.Text; internal class TsvOutputter : Outputter { private TextWriter writer; public TsvOutputter(Stream s) { writer = new StreamWriter(s, Encoding.UTF8); } public override void ResultStart() { } public override void ResultEnd() { } public override void RowStart() { } public override void RowEnd() { Console.WriteLine(); } public override void HeaderCell(string name) { } public override void ValueCell(object value) { Console.Write(value); Console.Write('\t'); } public override void DataStart() { } } }
18.361702
56
0.508691
[ "MIT" ]
enragez/BARS.ClickHouse.NET
BARS.ClickHouse.Client/TsvOutputter.cs
865
C#
/* This file is part of the EasySII (R) project. Copyright (c) 2017-2018 Irene Solutions SL Authors: Irene Solutions SL. This program is free software; you can redistribute it and/or modify it under the terms of the GNU Affero General Public License version 3 as published by the Free Software Foundation with the addition of the following permission added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY IRENE SOLUTIONS SL. IRENE SOLUTIONS SL DISCLAIMS THE WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program; if not, see http://www.gnu.org/licenses or write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA, 02110-1301 USA, or download the license from the following URL: http://www.irenesolutions.com/terms-of-use.pdf The interactive user interfaces in modified source and object code versions of this program must display Appropriate Legal Notices, as required under Section 5 of the GNU Affero General Public License. You can be released from the requirements of the license by purchasing a commercial license. Buying such a license is mandatory as soon as you develop commercial activities involving the EasySII software without disclosing the source code of your own applications. These activities include: offering paid services to customers as an ASP, serving sii XML data on the fly in a web application, shipping EasySII with a closed source product. For more information, please contact Irene Solutions SL. at this address: info@irenesolutions.com */ using System.ComponentModel; using System.Configuration.Install; using System.Diagnostics; using System.ServiceProcess; namespace EasySII.Watcher.Service { [RunInstaller(true)] public partial class ProjectInstaller : System.Configuration.Install.Installer { /// <summary> /// Construye una nueva instancia de la clase ProjectInstaller. /// </summary> public ProjectInstaller() { InitializeComponent(); EasySIIWProcessInstaller.Account = System.ServiceProcess.ServiceAccount.LocalSystem; } private void EasySIIWInstaller_AfterInstall(object sender, InstallEventArgs e) { var process = Process.Start($"{Context.Parameters["path"]}\\EasySII.Watcher.Admin.exe"); process.WaitForExit(); EasySII.Watcher.Settings.Save(); EasySII.Settings.Save(); new ServiceController(EasySIIWInstaller.ServiceName).Start(); } } }
42.514286
100
0.735551
[ "MIT" ]
mdiago/EasySII.Watcher
EasySII.Watcher.Service/ProjectInstaller.cs
2,978
C#
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace Microsoft.Extensions.DependencyModel { public class DependencyContext { #if !NETSTANDARD1_3 private static readonly Lazy<DependencyContext> _defaultContext = new Lazy<DependencyContext>(LoadDefault); #endif public DependencyContext(TargetInfo target, CompilationOptions compilationOptions, IEnumerable<CompilationLibrary> compileLibraries, IEnumerable<RuntimeLibrary> runtimeLibraries, IEnumerable<RuntimeFallbacks> runtimeGraph) { if (target == null) { throw new ArgumentNullException(nameof(target)); } if (compilationOptions == null) { throw new ArgumentNullException(nameof(compilationOptions)); } if (compileLibraries == null) { throw new ArgumentNullException(nameof(compileLibraries)); } if (runtimeLibraries == null) { throw new ArgumentNullException(nameof(runtimeLibraries)); } if (runtimeGraph == null) { throw new ArgumentNullException(nameof(runtimeGraph)); } Target = target; CompilationOptions = compilationOptions; CompileLibraries = compileLibraries.ToArray(); RuntimeLibraries = runtimeLibraries.ToArray(); RuntimeGraph = runtimeGraph.ToArray(); } #if !NETSTANDARD1_3 public static DependencyContext Default => _defaultContext.Value; #endif public TargetInfo Target { get; } public CompilationOptions CompilationOptions { get; } public IReadOnlyList<CompilationLibrary> CompileLibraries { get; } public IReadOnlyList<RuntimeLibrary> RuntimeLibraries { get; } public IReadOnlyList<RuntimeFallbacks> RuntimeGraph { get; } public DependencyContext Merge(DependencyContext other) { if (other == null) { throw new ArgumentNullException(nameof(other)); } return new DependencyContext( Target, CompilationOptions, CompileLibraries.Union(other.CompileLibraries, new LibraryMergeEqualityComparer<CompilationLibrary>()), RuntimeLibraries.Union(other.RuntimeLibraries, new LibraryMergeEqualityComparer<RuntimeLibrary>()), RuntimeGraph.Union(other.RuntimeGraph) ); } #if !NETSTANDARD1_3 private static DependencyContext LoadDefault() { var entryAssembly = Assembly.GetEntryAssembly(); if (entryAssembly == null) { return null; } return Load(entryAssembly); } public static DependencyContext Load(Assembly assembly) { return DependencyContextLoader.Default.Load(assembly); } #endif private class LibraryMergeEqualityComparer<T> : IEqualityComparer<T> where T : Library { public bool Equals(T x, T y) { return StringComparer.OrdinalIgnoreCase.Equals(x.Name, y.Name); } public int GetHashCode(T obj) { return StringComparer.OrdinalIgnoreCase.GetHashCode(obj.Name); } } } }
32.548673
119
0.608211
[ "MIT" ]
AzureMentor/core-setup
src/managed/Microsoft.Extensions.DependencyModel/DependencyContext.cs
3,680
C#
//------------------------------------------------- // NGUI: Next-Gen UI kit // Copyright © 2011-2018 Tasharen Entertainment Inc //------------------------------------------------- using UnityEngine; using UnityEditor; [CanEditMultipleObjects] [CustomEditor(typeof(UIToggle))] public class UIToggleInspector : UIWidgetContainerEditor { enum Transition { Smooth, Instant, } public override void OnInspectorGUI () { serializedObject.Update(); NGUIEditorTools.SetLabelWidth(100f); UIToggle toggle = target as UIToggle; GUILayout.Space(6f); GUI.changed = false; GUILayout.BeginHorizontal(); SerializedProperty sp = NGUIEditorTools.DrawProperty("Group", serializedObject, "group", GUILayout.Width(120f)); GUILayout.Label(" - zero means 'none'"); GUILayout.EndHorizontal(); EditorGUI.BeginDisabledGroup(sp.intValue == 0); NGUIEditorTools.DrawProperty(" State of 'None'", serializedObject, "optionCanBeNone"); EditorGUI.EndDisabledGroup(); NGUIEditorTools.DrawProperty("Starting State", serializedObject, "startsActive"); NGUIEditorTools.SetLabelWidth(80f); if (NGUIEditorTools.DrawMinimalisticHeader("State Transition")) { NGUIEditorTools.BeginContents(true); SerializedProperty sprite = serializedObject.FindProperty("activeSprite"); SerializedProperty animator = serializedObject.FindProperty("animator"); SerializedProperty animation = serializedObject.FindProperty("activeAnimation"); SerializedProperty tween = serializedObject.FindProperty("tween"); if (sprite.objectReferenceValue != null) { NGUIEditorTools.DrawProperty("Sprite", sprite, false); serializedObject.DrawProperty("invertSpriteState"); } else if (animator.objectReferenceValue != null) { NGUIEditorTools.DrawProperty("Animator", animator, false); } else if (animation.objectReferenceValue != null) { NGUIEditorTools.DrawProperty("Animation", animation, false); } else if (tween.objectReferenceValue != null) { NGUIEditorTools.DrawProperty("Tween", tween, false); } else { NGUIEditorTools.DrawProperty("Sprite", serializedObject, "activeSprite"); NGUIEditorTools.DrawProperty("Animator", animator, false); NGUIEditorTools.DrawProperty("Animation", animation, false); NGUIEditorTools.DrawProperty("Tween", tween, false); } if (serializedObject.isEditingMultipleObjects) { NGUIEditorTools.DrawProperty("Instant", serializedObject, "instantTween"); } else { GUI.changed = false; Transition tr = toggle.instantTween ? Transition.Instant : Transition.Smooth; GUILayout.BeginHorizontal(); tr = (Transition)EditorGUILayout.EnumPopup("Transition", tr); NGUIEditorTools.DrawPadding(); GUILayout.EndHorizontal(); if (GUI.changed) { NGUIEditorTools.RegisterUndo("Toggle Change", toggle); toggle.instantTween = (tr == Transition.Instant); NGUITools.SetDirty(toggle); } } NGUIEditorTools.EndContents(); } NGUIEditorTools.DrawEvents("On Value Change", toggle, toggle.onChange); serializedObject.ApplyModifiedProperties(); } }
30.598039
114
0.71099
[ "MIT" ]
Enanyy/LuaGame-slua
Assets/NGUI/Scripts/Editor/UIToggleInspector.cs
3,122
C#
 using System.Collections.Generic; using System.Linq; using System; using UnityEngine; using System.Runtime.CompilerServices; public static class Summarizer { public static string SummarizeEffect(Effect effect) { string summary = ""; summary += SummarizeTrigger(effect.trigger); summary += SummarizeConditionTree(effect.conditionTree); summary += SummarizeModifierTargets(effect.modifier); return summary; } private static string SummarizeTrigger(Effect.Trigger trigger) { switch (trigger) { case Effect.Trigger.ALWAYS_ACTIVE: return "Always: " + Environment.NewLine; case Effect.Trigger.ON_INTERACTION_START: return "When interaction starts: " + Environment.NewLine; case Effect.Trigger.INTERACTION_END: return "When interaction ends:" + Environment.NewLine; default: return ""; } } public static string SummarizeConditionTree(ConditionTree conditionTree) { string finalString = ""; if (conditionTree != null && conditionTree.root != null) { finalString += SummarizeConditionNode(conditionTree.root); } return finalString; } private static string SummarizeConditionNode(ConditionTree.Node conditionNode, int layer = 0) { string conditionString = ""; switch (conditionNode.logicOperator) { case LogicOperator.IF: conditionString += "If the following is true:" + Environment.NewLine; break; case LogicOperator.AND: conditionString += "If all of the following is true: " + Environment.NewLine; break; case LogicOperator.OR: conditionString += "If any of the following is true: " + Environment.NewLine; break; default: conditionString += "LOGIC_OPERATOR"; break; } conditionNode.conditions.ForEach(condition => { conditionString += SummarizeCondition(condition); }); return conditionString; } public static string SummarizeCondition(Condition condition) { string conditionString = ""; switch (condition.initiator) { case Condition.Initiator.ATTRIBUTE_RANGE: switch (condition.agent) { case Condition.Agent.SELF: conditionString += "Own attribute "; break; case Condition.Agent.TARGET: conditionString += "Target attribute "; break; case Condition.Agent.PLAYER: conditionString += "Player attribute "; break; } if (condition.attrRange.attrRangeParameters == null || condition.attrRange.attrRangeParameters.Count() == 0) { return conditionString; } int[] attrParams = condition.attrRange.attrRangeParameters; Attribute attribute = StoreController.instance.FindAttribute(condition.attrRange.attrRangeParameters[0]); conditionString += attribute.name + ' '; int firstNumberAttr = attrParams.Count() > 1 ? attrParams[1] : -1; int secondNumberAttr = attrParams.Count() > 2 ? attrParams[2] : -1; conditionString += EnumToString.GetStringOfConditionNumericSelectorValues( condition.attrRange.selector, firstNumberAttr, secondNumberAttr ); break; case Condition.Initiator.STATUS_RANGE: conditionString += condition.statusRange.statusRangeParameters; int[] statusParams = condition.attrRange.attrRangeParameters; if (statusParams == null || statusParams.Count() == 0) { return conditionString; } conditionString += (Character.Status)statusParams[0]; int firstNumberStatus = statusParams.Count() > 1 ? statusParams[1] : -1; int secondNumberStatus = statusParams.Count() > 2 ? statusParams[2] : -1; conditionString += EnumToString.GetStringOfConditionNumericSelectorValues( condition.statusRange.selector, firstNumberStatus, secondNumberStatus ); break; } return conditionString; } private static string SummarizeModifierTargets(Modifier modifier) { if (modifier.type == Modifier.Type.UNDEFINED) { Debug.LogError("The modifier has no targets, please check the effect"); return ""; } switch (modifier.type) { case Modifier.Type.MODIFY_ATTRIBUTE_VALUE: string initial = "Modify " + (modifier.modifierTargets.Count > 1 ? "attributes" : "attribute") + Environment.NewLine; string finalString = ""; foreach (int modifierTarget in modifier.modifierTargets) { Attribute skill = StoreController.instance.attributes.Find(skill => skill.id == modifierTarget); finalString += " " + skill.name + " by "; finalString += modifier.effectiveChange == 0 ? "X" : modifier.effectiveChange.ToString(); finalString += Environment.NewLine; } return initial + finalString; default: return "TARGET TYPE " + modifier.type + " NOT FOUND IN ENUMERATOR"; } } public struct TargetAttributeArguments { public string name; public int absoluteChange; public float percentageChange; } }
37.942308
133
0.575942
[ "MIT" ]
Vitorr32/ruler
Assets/Source/Utils/Summarizer.cs
5,921
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // Getter and Setter: throw using System; namespace JitInliningTest { public class A { private int _prop; public int prop { get { if (_prop != 100) throw new Exception("Excect m_prop=100"); return _prop; } set { if (value != 1000 - 9 * value) throw new Exception("Excect 100 as input"); _prop = value; } } } internal class throwTest { public static int Main() { A a = new A(); a.prop = 100; int retval = a.prop; return retval; } } }
22.275
101
0.462402
[ "MIT" ]
corefan/coreclr
tests/src/JIT/opt/Inline/tests/throwTest.cs
891
C#
using System; namespace PureFreak.DataAccess { public abstract class DataQueryBase<TDataProvider> where TDataProvider : DataProvider { #region Fields private readonly TDataProvider _dataProvider; #endregion #region Constructor public DataQueryBase(TDataProvider dataProvider) { if (dataProvider == null) { throw new ArgumentNullException(nameof(dataProvider)); } _dataProvider = dataProvider; } #endregion #region Methods #endregion #region Properties protected TDataProvider Provider { get { return _dataProvider; } } #endregion } }
18.585366
70
0.570866
[ "MIT" ]
Gartenschlaeger/DataAccess
PureFreak.DataAccess/DataQueryBase.cs
764
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; using DS4Windows; namespace DS4Windows.InputDevices { public class DualSenseDevice : DS4Device { public class GyroMouseSensDualSense : GyroMouseSens { private const double MOUSE_COEFFICIENT = 0.009; private const double MOUSE_OFFSET = 0.15; private const double SMOOTH_MOUSE_OFFSET = 0.15; public GyroMouseSensDualSense() : base() { mouseCoefficient = MOUSE_COEFFICIENT; mouseOffset = MOUSE_OFFSET; mouseSmoothOffset = SMOOTH_MOUSE_OFFSET; } } public abstract class InputReportDataBytes { public const int REPORT_OFFSET = 0; public const int REPORT_ID = 0; public const int LX = 1; public const int LY = 2; } public class InputReportDataBytesUSB : InputReportDataBytes { } public class InputReportDataBytesBT : InputReportDataBytesUSB { public new const int REPORT_OFFSET = 2; public new const int REPORT_ID = InputReportDataBytes.REPORT_ID; public new const int LX = InputReportDataBytes.LX + REPORT_OFFSET; public new const int LY = InputReportDataBytes.LY + REPORT_OFFSET; } public struct TriggerEffectData { public byte triggerMotorMode; public byte triggerStartResistance; public byte triggerEffectForce; public byte triggerRangeForce; public byte triggerNearReleaseStrength; public byte triggerNearMiddleStrength; public byte triggerPressedStrength; public byte triggerActuationFrequency; public void ChangeData(TriggerEffects effect) { switch (effect) { case TriggerEffects.None: triggerMotorMode = triggerStartResistance = triggerEffectForce = triggerRangeForce = triggerNearReleaseStrength = triggerNearMiddleStrength = triggerPressedStrength = triggerActuationFrequency = 0; break; case TriggerEffects.FullClick: triggerMotorMode = 0x02; triggerStartResistance = 0xA4; triggerEffectForce = 0xB4; triggerRangeForce = 0xFF; triggerNearReleaseStrength = 0x00; triggerNearMiddleStrength = 0x00; triggerPressedStrength = 0x00; triggerActuationFrequency = 0x00; break; case TriggerEffects.Rigid: triggerMotorMode = 0x01; triggerStartResistance = 0x00; triggerEffectForce = 0x00; triggerRangeForce = 0x00; triggerNearReleaseStrength = 0x00; triggerNearMiddleStrength = 0x00; triggerPressedStrength = 0x00; triggerActuationFrequency = 0x00; break; case TriggerEffects.Pulse: triggerMotorMode = 0x02; triggerStartResistance = 0x00; triggerEffectForce = 0x00; triggerRangeForce = 0x00; triggerNearReleaseStrength = 0x00; triggerNearMiddleStrength = 0x00; triggerPressedStrength = 0x00; triggerActuationFrequency = 0x00; break; default: break; } } } public enum HapticIntensity : uint { Low, Medium, High, } private const int BT_REPORT_OFFSET = 2; private InputReportDataBytes dataBytes; protected new const int BT_OUTPUT_REPORT_LENGTH = 78; private new const int BT_INPUT_REPORT_LENGTH = 78; protected const int TOUCHPAD_DATA_OFFSET = 33; private new const int BATTERY_MAX = 8; public new const byte SERIAL_FEATURE_ID = 9; public override byte SerialReportID { get => SERIAL_FEATURE_ID; } private const byte OUTPUT_REPORT_ID_USB = 0x02; private const byte OUTPUT_REPORT_ID_BT = 0x31; private const byte OUTPUT_REPORT_ID_DATA = 0x02; private new const byte USB_OUTPUT_CHANGE_LENGTH = 48; private const int OUTPUT_MIN_COUNT_BT = 20; private const byte LED_PLAYER_BAR_TOGGLE = 0x10; private bool timeStampInit = false; private uint timeStampPrevious = 0; private uint deltaTimeCurrent = 0; private bool outputDirty = false; private DS4HapticState previousHapticState = new DS4HapticState(); private byte[] outputBTCrc32Head = new byte[] { 0xA2 }; //private byte outputPendCount = 0; private new GyroMouseSensDualSense gyroMouseSensSettings; public override GyroMouseSens GyroMouseSensSettings { get => gyroMouseSensSettings; } private byte activePlayerLEDMask = 0x00; private byte hapticsIntensityByte = 0x02; public HapticIntensity HapticChoice { set { switch (value) { case HapticIntensity.Low: hapticsIntensityByte = 0x05; break; case HapticIntensity.High: hapticsIntensityByte = 0x00; break; case HapticIntensity.Medium: default: hapticsIntensityByte = 0x02; break; } } } private TriggerEffectData l2EffectData; private TriggerEffectData r2EffectData; private byte muteLEDByte = 0x00; private DualSenseControllerOptions nativeOptionsStore; public DualSenseControllerOptions NativeOptionsStore { get => nativeOptionsStore; } public override event ReportHandler<EventArgs> Report = null; public override event EventHandler BatteryChanged; public override event EventHandler ChargingChanged; public DualSenseDevice(HidDevice hidDevice, string disName, VidPidFeatureSet featureSet = VidPidFeatureSet.DefaultDS4) : base(hidDevice, disName, featureSet) { synced = true; DeviceSlotNumberChanged += (sender, e) => { CalculateDeviceSlotMask(); }; BatteryChanged += (sender, e) => { PreparePlayerLEDBarByte(); }; } public override void PostInit() { HidDevice hidDevice = hDevice; deviceType = InputDeviceType.DualSense; gyroMouseSensSettings = new GyroMouseSensDualSense(); optionsStore = nativeOptionsStore = new DualSenseControllerOptions(deviceType); SetupOptionsEvents(); conType = DetermineConnectionType(hDevice); if (conType == ConnectionType.USB) { dataBytes = new InputReportDataBytesUSB(); inputReport = new byte[64]; outputReport = new byte[hDevice.Capabilities.OutputReportByteLength]; outReportBuffer = new byte[hDevice.Capabilities.OutputReportByteLength]; warnInterval = WARN_INTERVAL_USB; } else { //btInputReport = new byte[BT_INPUT_REPORT_LENGTH]; //inputReport = new byte[BT_INPUT_REPORT_LENGTH - 2]; // Only plan to use one input report array. Avoid copying data inputReport = new byte[BT_INPUT_REPORT_LENGTH]; // Default DS4 logic while writing data to gamepad outputReport = new byte[BT_OUTPUT_REPORT_LENGTH]; outReportBuffer = new byte[BT_OUTPUT_REPORT_LENGTH]; warnInterval = WARN_INTERVAL_BT; synced = isValidSerial(); } if (runCalib) RefreshCalibration(); if (!hDevice.IsFileStreamOpen()) { hDevice.OpenFileStream(outputReport.Length); } // Need to blank LED lights so lightbar will change colors // as requested if (conType == ConnectionType.BT) { SendInitialBTOutputReport(); } } public static ConnectionType DetermineConnectionType(HidDevice hidDevice) { ConnectionType result; if (hidDevice.Capabilities.InputReportByteLength == 64) { result = ConnectionType.USB; } else { result = ConnectionType.BT; } return result; } public override bool DisconnectBT(bool callRemoval = false) { return base.DisconnectBT(callRemoval); } public override bool DisconnectDongle(bool remove = false) { // Do Nothing return true; } public override bool DisconnectWireless(bool callRemoval = false) { return base.DisconnectWireless(callRemoval); } public override bool IsAlive() { return synced; } public override void RefreshCalibration() { byte[] calibration = new byte[41]; calibration[0] = conType == ConnectionType.BT ? (byte)0x05 : (byte)0x05; if (conType == ConnectionType.BT) { bool found = false; for (int tries = 0; !found && tries < 5; tries++) { hDevice.readFeatureData(calibration); uint recvCrc32 = calibration[DS4_FEATURE_REPORT_5_CRC32_POS] | (uint)(calibration[DS4_FEATURE_REPORT_5_CRC32_POS + 1] << 8) | (uint)(calibration[DS4_FEATURE_REPORT_5_CRC32_POS + 2] << 16) | (uint)(calibration[DS4_FEATURE_REPORT_5_CRC32_POS + 3] << 24); uint calcCrc32 = ~Crc32Algorithm.Compute(new byte[] { 0xA3 }); calcCrc32 = ~Crc32Algorithm.CalculateBasicHash(ref calcCrc32, ref calibration, 0, DS4_FEATURE_REPORT_5_LEN - 4); bool validCrc = recvCrc32 == calcCrc32; if (!validCrc && tries >= 5) { AppLogger.LogToGui("Gyro Calibration Failed", true); continue; } else if (validCrc) { found = true; } } sixAxis.setCalibrationData(ref calibration, true); } else { hDevice.readFeatureData(calibration); sixAxis.setCalibrationData(ref calibration, true); } } public override void StartUpdate() { this.inputReportErrorCount = 0; if (ds4Input == null) { if (conType == ConnectionType.BT) { //ds4Output = new Thread(performDs4Output); //ds4Output.Priority = ThreadPriority.Normal; //ds4Output.Name = "DS4 Output thread: " + Mac; //ds4Output.IsBackground = true; //ds4Output.Start(); timeoutCheckThread = new Thread(TimeoutTestThread); timeoutCheckThread.Priority = ThreadPriority.BelowNormal; timeoutCheckThread.Name = "DualSense Timeout thread: " + Mac; timeoutCheckThread.IsBackground = true; timeoutCheckThread.Start(); } //else //{ // ds4Output = new Thread(OutReportCopy); // ds4Output.Priority = ThreadPriority.Normal; // ds4Output.Name = "DS4 Arr Copy thread: " + Mac; // ds4Output.IsBackground = true; // ds4Output.Start(); //} ds4Input = new Thread(ReadInput); ds4Input.Priority = ThreadPriority.AboveNormal; ds4Input.Name = "DualSense Input thread: " + Mac; ds4Input.IsBackground = true; ds4Input.Start(); } else Console.WriteLine("Thread already running for DS4: " + Mac); } private void TimeoutTestThread() { while (!timeoutExecuted) { if (timeoutEvent) { timeoutExecuted = true; // Request serial feature report data. Causes Windows to notice the dead // device. byte[] tmpFeatureData = new byte[64]; tmpFeatureData[0] = SERIAL_FEATURE_ID; hDevice.readFeatureData(tmpFeatureData); // Kick Windows into noticing the disconnection. } else { timeoutEvent = true; Thread.Sleep(READ_STREAM_TIMEOUT); } } } private unsafe void ReadInput() { unchecked { firstActive = DateTime.UtcNow; NativeMethods.HidD_SetNumInputBuffers(hDevice.safeReadHandle.DangerousGetHandle(), 3); Queue<long> latencyQueue = new Queue<long>(21); // Set capacity at max + 1 to avoid any resizing int tempLatencyCount = 0; long oldtime = 0; string currerror = string.Empty; long curtime = 0; long testelapsed = 0; timeoutEvent = false; ds4InactiveFrame = true; idleInput = true; bool syncWriteReport = conType != ConnectionType.BT; //bool forceWrite = false; int maxBatteryValue = 0; int tempBattery = 0; bool tempCharging = charging; bool tempFull = false; uint tempStamp = 0; double elapsedDeltaTime = 0.0; uint tempDelta = 0; byte tempByte = 0; int CRC32_POS_1 = BT_INPUT_REPORT_CRC32_POS + 1, CRC32_POS_2 = BT_INPUT_REPORT_CRC32_POS + 2, CRC32_POS_3 = BT_INPUT_REPORT_CRC32_POS + 3; int crcpos = BT_INPUT_REPORT_CRC32_POS; int crcoffset = 0; long latencySum = 0; int reportOffset = conType == ConnectionType.BT ? 1 : 0; // Run continuous calibration on Gyro when starting input loop sixAxis.ResetContinuousCalibration(); standbySw.Start(); while (!exitInputThread) { oldCharging = charging; currerror = string.Empty; if (tempLatencyCount >= 20) { latencySum -= latencyQueue.Dequeue(); tempLatencyCount--; } latencySum += this.lastTimeElapsed; latencyQueue.Enqueue(this.lastTimeElapsed); tempLatencyCount++; //Latency = latencyQueue.Average(); Latency = latencySum / (double)tempLatencyCount; readWaitEv.Set(); if (conType == ConnectionType.BT) { timeoutEvent = false; HidDevice.ReadStatus res = hDevice.ReadWithFileStream(inputReport); if (res == HidDevice.ReadStatus.Success) { uint recvCrc32 = inputReport[BT_INPUT_REPORT_CRC32_POS] | (uint)(inputReport[CRC32_POS_1] << 8) | (uint)(inputReport[CRC32_POS_2] << 16) | (uint)(inputReport[CRC32_POS_3] << 24); uint calcCrc32 = ~Crc32Algorithm.CalculateFasterBT78Hash(ref HamSeed, ref inputReport, ref crcoffset, ref crcpos); if (recvCrc32 != calcCrc32) { cState.PacketCounter = pState.PacketCounter + 1; //still increase so we know there were lost packets if (this.inputReportErrorCount >= 10) { exitInputThread = true; AppLogger.LogToGui(DS4WinWPF.Translations.Strings.CRC32Fail, true); readWaitEv.Reset(); //sendOutputReport(true, true); // Kick Windows into noticing the disconnection. StopOutputUpdate(); isDisconnecting = true; RunRemoval(); timeoutExecuted = true; continue; } else { this.inputReportErrorCount++; } readWaitEv.Reset(); continue; } else { this.inputReportErrorCount = 0; } } else { if (res == HidDevice.ReadStatus.WaitTimedOut) { AppLogger.LogToGui(Mac.ToString() + " disconnected due to timeout", true); } else { int winError = Marshal.GetLastWin32Error(); Console.WriteLine(Mac.ToString() + " " + DateTime.UtcNow.ToString("o") + "> disconnect due to read failure: " + winError); //Log.LogToGui(Mac.ToString() + " disconnected due to read failure: " + winError, true); AppLogger.LogToGui(Mac.ToString() + " disconnected due to read failure: " + winError, true); } exitInputThread = true; readWaitEv.Reset(); //SendEmptyOutputReport(); //sendOutputReport(true, true); // Kick Windows into noticing the disconnection. StopOutputUpdate(); isDisconnecting = true; RunRemoval(); timeoutExecuted = true; continue; } } else { HidDevice.ReadStatus res = hDevice.ReadWithFileStream(inputReport); if (res != HidDevice.ReadStatus.Success) { if (res == HidDevice.ReadStatus.WaitTimedOut) { AppLogger.LogToGui(Mac.ToString() + " disconnected due to timeout", true); } else { int winError = Marshal.GetLastWin32Error(); Console.WriteLine(Mac.ToString() + " " + DateTime.UtcNow.ToString("o") + "> disconnect due to read failure: " + winError); //Log.LogToGui(Mac.ToString() + " disconnected due to read failure: " + winError, true); } exitInputThread = true; readWaitEv.Reset(); StopOutputUpdate(); isDisconnecting = true; RunRemoval(); timeoutExecuted = true; continue; } } readWaitEv.Wait(); readWaitEv.Reset(); curtime = Stopwatch.GetTimestamp(); testelapsed = curtime - oldtime; lastTimeElapsedDouble = testelapsed * (1.0 / Stopwatch.Frequency) * 1000.0; lastTimeElapsed = (long)lastTimeElapsedDouble; oldtime = curtime; if (conType == ConnectionType.BT && inputReport[0] != 0x31) { // Received incorrect report, skip it continue; } utcNow = DateTime.UtcNow; // timestamp with UTC in case system time zone changes cState.PacketCounter = pState.PacketCounter + 1; cState.ReportTimeStamp = utcNow; cState.LX = inputReport[1 + reportOffset]; cState.LY = inputReport[2 + reportOffset]; cState.RX = inputReport[3 + reportOffset]; cState.RY = inputReport[4 + reportOffset]; cState.L2 = inputReport[5 + reportOffset]; cState.R2 = inputReport[6 + reportOffset]; tempByte = inputReport[8 + reportOffset]; cState.Triangle = (tempByte & (1 << 7)) != 0; cState.Circle = (tempByte & (1 << 6)) != 0; cState.Cross = (tempByte & (1 << 5)) != 0; cState.Square = (tempByte & (1 << 4)) != 0; // First 4 bits denote dpad state. Clock representation // with 8 meaning centered and 0 meaning DpadUp. byte dpad_state = (byte)(tempByte & 0x0F); switch (dpad_state) { case 0: cState.DpadUp = true; cState.DpadDown = false; cState.DpadLeft = false; cState.DpadRight = false; break; case 1: cState.DpadUp = true; cState.DpadDown = false; cState.DpadLeft = false; cState.DpadRight = true; break; case 2: cState.DpadUp = false; cState.DpadDown = false; cState.DpadLeft = false; cState.DpadRight = true; break; case 3: cState.DpadUp = false; cState.DpadDown = true; cState.DpadLeft = false; cState.DpadRight = true; break; case 4: cState.DpadUp = false; cState.DpadDown = true; cState.DpadLeft = false; cState.DpadRight = false; break; case 5: cState.DpadUp = false; cState.DpadDown = true; cState.DpadLeft = true; cState.DpadRight = false; break; case 6: cState.DpadUp = false; cState.DpadDown = false; cState.DpadLeft = true; cState.DpadRight = false; break; case 7: cState.DpadUp = true; cState.DpadDown = false; cState.DpadLeft = true; cState.DpadRight = false; break; case 8: default: cState.DpadUp = false; cState.DpadDown = false; cState.DpadLeft = false; cState.DpadRight = false; break; } tempByte = inputReport[9 + reportOffset]; cState.R3 = (tempByte & (1 << 7)) != 0; cState.L3 = (tempByte & (1 << 6)) != 0; cState.Options = (tempByte & (1 << 5)) != 0; cState.Share = (tempByte & (1 << 4)) != 0; cState.R2Btn = (tempByte & (1 << 3)) != 0; cState.L2Btn = (tempByte & (1 << 2)) != 0; cState.R1 = (tempByte & (1 << 1)) != 0; cState.L1 = (tempByte & (1 << 0)) != 0; tempByte = inputReport[10 + reportOffset]; cState.PS = (tempByte & (1 << 0)) != 0; cState.TouchButton = (tempByte & 0x02) != 0; cState.OutputTouchButton = cState.TouchButton; cState.Mute = (tempByte & (1 << 2)) != 0; //cState.FrameCounter = (byte)(tempByte >> 2); if ((this.featureSet & VidPidFeatureSet.NoBatteryReading) == 0) { tempByte = inputReport[54 + reportOffset]; tempCharging = (tempByte & 0x08) != 0; if (tempCharging != charging) { charging = tempCharging; ChargingChanged?.Invoke(this, EventArgs.Empty); } tempByte = inputReport[53 + reportOffset]; tempFull = (tempByte & 0x20) != 0; // Check for Full status maxBatteryValue = BATTERY_MAX; if (tempFull) { // Full Charge flag found tempBattery = 100; } else { // Partial charge tempBattery = (tempByte & 0x0F) * 100 / maxBatteryValue; tempBattery = Math.Min(tempBattery, 100); } if (tempBattery != battery) { battery = tempBattery; BatteryChanged?.Invoke(this, EventArgs.Empty); } cState.Battery = (byte)battery; //System.Diagnostics.Debug.WriteLine("CURRENT BATTERY: " + (inputReport[30] & 0x0f) + " | " + tempBattery + " | " + battery); } else { // Some gamepads don't send battery values in DS4 compatible data fields, so use dummy 99% value to avoid constant low battery warnings //priorInputReport30 = 0x0F; battery = 99; cState.Battery = 99; } tempStamp = inputReport[28+reportOffset] | (uint)(inputReport[29+reportOffset] << 8) | (uint)(inputReport[30+reportOffset] << 16) | (uint)(inputReport[31+reportOffset] << 24); if (timeStampInit == false) { timeStampInit = true; deltaTimeCurrent = tempStamp * 1u / 3u; } else if (timeStampPrevious > tempStamp) { tempDelta = uint.MaxValue - timeStampPrevious + tempStamp + 1u; deltaTimeCurrent = tempDelta * 1u / 3u; } else { tempDelta = tempStamp - timeStampPrevious; deltaTimeCurrent = tempDelta * 1u / 3u; } //if (tempStamp == timeStampPrevious) //{ // Console.WriteLine("PINEAPPLES"); //} // Make sure timestamps don't match if (deltaTimeCurrent != 0) { elapsedDeltaTime = 0.000001 * deltaTimeCurrent; // Convert from microseconds to seconds cState.totalMicroSec = pState.totalMicroSec + deltaTimeCurrent; } else { // Duplicate timestamp. Use system clock for elapsed time instead elapsedDeltaTime = lastTimeElapsedDouble * .001; cState.totalMicroSec = pState.totalMicroSec + (uint)(elapsedDeltaTime * 1000000); } //Console.WriteLine("{0} {1} {2} {3} {4} Diff({5}) TSms({6}) Sys({7})", tempStamp, inputReport[31 + reportOffset], inputReport[30 + reportOffset], inputReport[29 + reportOffset], inputReport[28 + reportOffset], tempStamp - timeStampPrevious, elapsedDeltaTime, lastTimeElapsedDouble * 0.001); cState.elapsedTime = elapsedDeltaTime; cState.ds4Timestamp = (ushort)((tempStamp / 16) % ushort.MaxValue); timeStampPrevious = tempStamp; //elapsedDeltaTime = lastTimeElapsedDouble * .001; //cState.elapsedTime = elapsedDeltaTime; //cState.totalMicroSec = pState.totalMicroSec + (uint)(elapsedDeltaTime * 1000000); // Simpler touch storing cState.TrackPadTouch0.RawTrackingNum = inputReport[33+reportOffset]; cState.TrackPadTouch0.Id = (byte)(inputReport[33+reportOffset] & 0x7f); cState.TrackPadTouch0.IsActive = (inputReport[33+reportOffset] & 0x80) == 0; cState.TrackPadTouch0.X = (short)(((ushort)(inputReport[35+reportOffset] & 0x0f) << 8) | (ushort)(inputReport[34+reportOffset])); cState.TrackPadTouch0.Y = (short)(((ushort)(inputReport[36+reportOffset]) << 4) | ((ushort)(inputReport[35+reportOffset] & 0xf0) >> 4)); cState.TrackPadTouch0.RawTrackingNum = inputReport[37+reportOffset]; cState.TrackPadTouch1.Id = (byte)(inputReport[37+reportOffset] & 0x7f); cState.TrackPadTouch1.IsActive = (inputReport[37+reportOffset] & 0x80) == 0; cState.TrackPadTouch1.X = (short)(((ushort)(inputReport[39+reportOffset] & 0x0f) << 8) | (ushort)(inputReport[38+reportOffset])); cState.TrackPadTouch1.Y = (short)(((ushort)(inputReport[40+reportOffset]) << 4) | ((ushort)(inputReport[39+reportOffset] & 0xf0) >> 4)); // XXX DS4State mapping needs fixup, turn touches into an array[4] of structs. And include the touchpad details there instead. try { // Only care if one touch packet is detected. Other touch packets // don't seem to contain relevant data. ds4drv does not use them either. int touchOffset = 0; cState.TouchPacketCounter = inputReport[-1 + TOUCHPAD_DATA_OFFSET + reportOffset + touchOffset]; cState.Touch1 = (inputReport[0 + TOUCHPAD_DATA_OFFSET + reportOffset + touchOffset] >> 7) != 0 ? false : true; // finger 1 detected cState.Touch1Identifier = (byte)(inputReport[0 + TOUCHPAD_DATA_OFFSET + reportOffset + touchOffset] & 0x7f); cState.Touch2 = (inputReport[4 + TOUCHPAD_DATA_OFFSET + reportOffset + touchOffset] >> 7) != 0 ? false : true; // finger 2 detected cState.Touch2Identifier = (byte)(inputReport[4 + TOUCHPAD_DATA_OFFSET + reportOffset + touchOffset] & 0x7f); cState.Touch1Finger = cState.Touch1 || cState.Touch2; // >= 1 touch detected cState.Touch2Fingers = cState.Touch1 && cState.Touch2; // 2 touches detected int touchX = (((inputReport[2 + TOUCHPAD_DATA_OFFSET + reportOffset + touchOffset] & 0xF) << 8) | inputReport[1 + TOUCHPAD_DATA_OFFSET + reportOffset + touchOffset]); cState.TouchLeft = touchX >= DS4Touchpad.RESOLUTION_X_MAX * 2 / 5 ? false : true; cState.TouchRight = touchX < DS4Touchpad.RESOLUTION_X_MAX * 2 / 5 ? false : true; // Even when idling there is still a touch packet indicating no touch 1 or 2 if (synced) { touchpad.handleTouchpad(inputReport, cState, TOUCHPAD_DATA_OFFSET + reportOffset, touchOffset); } } catch (Exception ex) { currerror = $"Touchpad: {ex.Message}"; } fixed (byte* pbInput = &inputReport[16+reportOffset], pbGyro = gyro, pbAccel = accel) { for (int i = 0; i < 6; i++) { pbGyro[i] = pbInput[i]; } for (int i = 6; i < 12; i++) { pbAccel[i - 6] = pbInput[i]; } if (synced) { sixAxis.handleSixaxis(pbGyro, pbAccel, cState, elapsedDeltaTime); } } /* Debug output of incoming HID data: if (cState.L2 == 0xff && cState.R2 == 0xff) { Console.Write(MacAddress.ToString() + " " + System.DateTime.UtcNow.ToString("o") + ">"); for (int i = 0; i < inputReport.Length; i++) Console.Write(" " + inputReport[i].ToString("x2")); Console.WriteLine(); } ///*/ if (conType == ConnectionType.USB) { if (idleTimeout == 0) { lastActive = utcNow; } else { idleInput = isDS4Idle(); if (!idleInput) { lastActive = utcNow; } } } else { bool shouldDisconnect = false; if (!isRemoved && idleTimeout > 0) { idleInput = isDS4Idle(); if (idleInput) { DateTime timeout = lastActive + TimeSpan.FromSeconds(idleTimeout); if (!charging) shouldDisconnect = utcNow >= timeout; } else { lastActive = utcNow; } } else { lastActive = utcNow; } if (shouldDisconnect) { AppLogger.LogToGui(Mac.ToString() + " disconnecting due to idle disconnect", false); if (conType == ConnectionType.BT) { if (DisconnectBT(true)) { exitInputThread = true; timeoutExecuted = true; return; // all done } } } } Report?.Invoke(this, EventArgs.Empty); PrepareOutReport(); if (outputDirty) { WriteReport(); previousHapticState = currentHap; } outputDirty = false; //forceWrite = false; if (!string.IsNullOrEmpty(currerror)) error = currerror; else if (!string.IsNullOrEmpty(error)) error = string.Empty; cState.CopyTo(pState); if (hasInputEvts) { lock (eventQueueLock) { Action tempAct = null; for (int actInd = 0, actLen = eventQueue.Count; actInd < actLen; actInd++) { tempAct = eventQueue.Dequeue(); tempAct.Invoke(); } hasInputEvts = false; } } } } timeoutExecuted = true; } protected override void StopOutputUpdate() { SendEmptyOutputReport(); } private void SendEmptyOutputReport() { int reportOffset = conType == ConnectionType.BT ? 1 : 0; Array.Clear(outputReport, 0, outputReport.Length); outputReport[0] = conType == ConnectionType.USB ? OUTPUT_REPORT_ID_USB : OUTPUT_REPORT_ID_BT; // Disable haptics and trigger motors outputReport[1 + reportOffset] = useRumble ? (byte)0x0F : (byte)0x0C; outputReport[2 + reportOffset] = 0x15; // Toggle all LED lights. 0x01 | 0x04 | 0x10 if (conType == ConnectionType.BT) { outputReport[1] = OUTPUT_REPORT_ID_DATA; // Need to calculate and populate CRC32 data so controller will accept the report uint calcCrc32 = ~Crc32Algorithm.Compute(outputBTCrc32Head); calcCrc32 = ~Crc32Algorithm.CalculateBasicHash(ref calcCrc32, ref outputReport, 0, BT_OUTPUT_REPORT_LENGTH - 4); outputReport[74] = (byte)calcCrc32; outputReport[75] = (byte)(calcCrc32 >> 8); outputReport[76] = (byte)(calcCrc32 >> 16); outputReport[77] = (byte)(calcCrc32 >> 24); } WriteReport(); //hDevice.fileStream.Flush(); } private void SendInitialBTOutputReport() { Array.Clear(outputReport, 0, outputReport.Length); outputReport[0] = OUTPUT_REPORT_ID_BT; // Report ID outputReport[1] = OUTPUT_REPORT_ID_DATA; outputReport[3] = 0x15; // Toggle all LED lights. 0x01 | 0x04 | 0x10 // Need to calculate and populate CRC32 data so controller will accept the report uint calcCrc32 = ~Crc32Algorithm.Compute(outputBTCrc32Head); calcCrc32 = ~Crc32Algorithm.CalculateBasicHash(ref calcCrc32, ref outputReport, 0, BT_OUTPUT_REPORT_LENGTH - 4); outputReport[74] = (byte)calcCrc32; outputReport[75] = (byte)(calcCrc32 >> 8); outputReport[76] = (byte)(calcCrc32 >> 16); outputReport[77] = (byte)(calcCrc32 >> 24); WriteReport(); } private unsafe void PrepareOutReport() { MergeStates(); bool change = false; bool rumbleSet = currentHap.IsRumbleSet(); if (conType == ConnectionType.USB) { outputReport[0] = OUTPUT_REPORT_ID_USB; // Report ID // 0x01 Set the main motors (also requires flag 0x02) // 0x02 Set the main motors (also requires flag 0x01) // 0x04 Set the right trigger motor // 0x08 Set the left trigger motor // 0x10 Enable modification of audio volume // 0x20 Enable internal speaker (even while headset is connected) // 0x40 Enable modification of microphone volume // 0x80 Enable internal mic (even while headset is connected) outputReport[1] = useRumble ? (byte)0x0F : (byte)0x0C; // 0x02 | 0x01 | 0x04 | 0x08; // 0x01 Toggling microphone LED, 0x02 Toggling Audio/Mic Mute // 0x04 Toggling LED strips on the sides of the Touchpad, 0x08 Turn off all LED lights // 0x10 Toggle player LED lights below Touchpad, 0x20 ??? // 0x40 Adjust overall motor/effect power, 0x80 ??? outputReport[2] = 0x55; // 0x04 | 0x01 | 0x10 | 0x40 if (useRumble) { // Right? High Freq Motor outputReport[3] = currentHap.rumbleState.RumbleMotorStrengthRightLightFast; // Left? Low Freq Motor outputReport[4] = currentHap.rumbleState.RumbleMotorStrengthLeftHeavySlow; } /* // Headphone volume outputReport[5] = 0x00; outputReport[5] = Convert.ToByte(audio.getVolume()); // Left and Right // Internal speaker volume outputReport[6] = 0x00; // Internal microphone volume outputReport[7] = 0x00; outputReport[7] = Convert.ToByte(micAudio.getVolume()); // 0x01 Enable internal microphone, 0x10 Disable attached headphones (must set 0x20 as well) // 0x20 Enable internal speaker outputReport[8] = 0x00; //*/ // Mute button LED. 0x01 = Solid. 0x02 = Pulsating outputReport[9] = muteLEDByte; // audio settings requiring mute toggling flags //outputReport[10] = 0x00; // 0x10 microphone mute, 0x40 audio mute /* TRIGGER MOTORS */ // R2 Effects outputReport[11] = r2EffectData.triggerMotorMode; // right trigger motor mode (0 = no resistance, 1 = continuous resistance, 2 = section resistance, 0x20 and 0x04 enable additional effects together with 1 and 2 (configuration yet unknown), 252 = likely a calibration program* / PS Remote Play defaults this to 5; bit 4 only disables the motor?) outputReport[12] = r2EffectData.triggerStartResistance; // right trigger start of resistance section 0-255 (0 = released state; 0xb0 roughly matches trigger value 0xff); in mode 26 this field has something to do with motor re-extension after a press-release-cycle (0 = no re-extension) outputReport[13] = r2EffectData.triggerEffectForce; // right trigger // (mode1) amount of force exerted; 0-255 // (mode2) end of resistance section (>= begin of resistance section is enforced); 0xff makes it behave like mode1 // (supplemental mode 4+20) flag(s?) 0x02 = do not pause effect when fully pressed outputReport[14] = r2EffectData.triggerRangeForce; // right trigger force exerted in range (mode2), 0-255 outputReport[15] = r2EffectData.triggerNearReleaseStrength; // strength of effect near release state (requires supplement modes 4 and 20) outputReport[16] = r2EffectData.triggerNearMiddleStrength; // strength of effect near middle (requires supplement modes 4 and 20) outputReport[17] = r2EffectData.triggerPressedStrength; // strength of effect at pressed state (requires supplement modes 4 and 20) outputReport[20] = r2EffectData.triggerActuationFrequency; // effect actuation frequency in Hz (requires supplement modes 4 and 20) // L2 Effects outputReport[22] = l2EffectData.triggerMotorMode; // left trigger motor mode (0 = no resistance, 1 = continuous resistance, 2 = section resistance, 0x20 and 0x04 enable additional effects together with 1 and 2 (configuration yet unknown), 252 = likely a calibration program* / PS Remote Play defaults this to 5; bit 4 only disables the motor?) outputReport[23] = l2EffectData.triggerStartResistance; // left trigger start of resistance section 0-255 (0 = released state; 0xb0 roughly matches trigger value 0xff); in mode 26 this field has something to do with motor re-extension after a press-release-cycle (0 = no re-extension) outputReport[24] = l2EffectData.triggerEffectForce; // left trigger // (mode1) amount of force exerted; 0-255 // (mode2) end of resistance section (>= begin of resistance section is enforced); 0xff makes it behave like mode1 // (supplemental mode 4+20) flag(s?) 0x02 = do not pause effect when fully pressed outputReport[25] = l2EffectData.triggerRangeForce; // left trigger: (mode2) amount of force exerted within range; 0-255 outputReport[26] = l2EffectData.triggerNearReleaseStrength; // strength of effect near release state (requires supplement modes 4 and 20) outputReport[27] = l2EffectData.triggerNearMiddleStrength; // strength of effect near middle (requires supplement modes 4 and 20) outputReport[28] = l2EffectData.triggerPressedStrength; // strength of effect at pressed state (requires supplement modes 4 and 20) outputReport[31] = l2EffectData.triggerActuationFrequency; // effect actuation frequency in Hz (requires supplement modes 4 and 20) // (lower nibble: main motor; upper nibble trigger effects) 0x00 to 0x07 - reduce overall power of the respective motors/effects by 12.5% per increment (this does not affect the regular trigger motor settings, just the automatically repeating trigger effects) outputReport[37] = hapticsIntensityByte; // Volume of internal speaker (0-7; ties in with index 6. The PS5 default appears to be set a 4) //outputReport[38] = 0x00; /* Player LED section */ // 0x01 Enabled LED brightness (value in index 43) // 0x02 Uninterruptable blue LED pulse (action in index 42) outputReport[39] = 0x02; // 0x01 Slowly (2s?) fade to blue (scheduled to when the regular LED settings are active) // 0x02 Slowly (2s?) fade out (scheduled after fade-in completion) with eventual switch back to configured LED color; only a fade-out can cancel the pulse (neither index 2, 0x08, nor turning this off will cancel it!) outputReport[42] = 0x02; // 0x00 High Brightness, 0x01 Medium Brightness, 0x02 Low Brightness outputReport[43] = 0x02; // 5 player LED lights below Touchpad. // Bitmask 0x00-0x1F from left to right with 0x04 being the center LED. Bit 0x20 sets the brightness immediately with no fade in outputReport[44] = activePlayerLEDMask; /* Lightbar colors */ outputReport[45] = currentHap.lightbarState.LightBarColor.red; outputReport[46] = currentHap.lightbarState.LightBarColor.green; outputReport[47] = currentHap.lightbarState.LightBarColor.blue; if (!previousHapticState.Equals(currentHap)) { change = true; } /*fixed (byte* bytePrevBuff = outputReport, byteTmpBuff = outReportBuffer) { for (int i = 0, arlen = USB_OUTPUT_CHANGE_LENGTH; !change && i < arlen; i++) change = bytePrevBuff[i] != byteTmpBuff[i]; } */ if (change) { //Console.WriteLine("DIRTY"); outputDirty = true; if (rumbleSet) { standbySw.Restart(); } else { standbySw.Reset(); } //outReportBuffer.CopyTo(outputReport, 0); } else if (rumbleSet && standbySw.ElapsedMilliseconds >= 4000L) { outputDirty = true; standbySw.Restart(); } //bool res = hDevice.WriteOutputReportViaInterrupt(outputReport, READ_STREAM_TIMEOUT); //Console.WriteLine("STAUTS: {0}", res); } else { //outReportBuffer[0] = OUTPUT_REPORT_ID_BT; // Report ID outputReport[0] = OUTPUT_REPORT_ID_BT; // Report ID outputReport[1] = OUTPUT_REPORT_ID_DATA; // 0x01 Set the main motors (also requires flag 0x02) // 0x02 Set the main motors (also requires flag 0x01) // 0x04 Set the right trigger motor // 0x08 Set the left trigger motor // 0x10 Enable modification of audio volume // 0x20 Enable internal speaker (even while headset is connected) // 0x40 Enable modification of microphone volume // 0x80 Enable internal mic (even while headset is connected) outputReport[2] = useRumble ? (byte)0x0F : (byte)0x0C; // 0x02 | 0x01 | 0x04 | 0x08; // 0x01 Toggling microphone LED, 0x02 Toggling Audio/Mic Mute // 0x04 Toggling LED strips on the sides of the Touchpad, 0x08 Turn off all LED lights // 0x10 Toggle player LED lights below Touchpad, 0x20 ??? // 0x40 Adjust overall motor/effect power, 0x80 ??? outputReport[3] = 0x55; // 0x04 | 0x01 | 0x10 | 0x40 if (useRumble) { // Right? High Freq Motor outputReport[4] = currentHap.rumbleState.RumbleMotorStrengthRightLightFast; // Left? Low Freq Motor outputReport[5] = currentHap.rumbleState.RumbleMotorStrengthLeftHeavySlow; } /* // Headphone volume outputReport[6] = 0x00; outputReport[6] = Convert.ToByte(audio.getVolume()); // Left and Right // Internal speaker volume outputReport[7] = 0x00; // Internal microphone volume outputReport[8] = 0x00; outputReport[8] = Convert.ToByte(micAudio.getVolume()); // 0x01 Enable internal microphone, 0x10 Disable attached headphones (must set 0x20 as well) // 0x20 Enable internal speaker outputReport[9] = 0x00; //*/ // Mute button LED. 0x01 = Solid. 0x02 = Pulsating outputReport[10] = muteLEDByte; // audio settings requiring mute toggling flags //outputReport[11] = 0x00; // 0x10 microphone mute, 0x40 audio mute /* TRIGGER MOTORS */ // R2 Effects outputReport[12] = r2EffectData.triggerMotorMode; // right trigger motor mode (0 = no resistance, 1 = continuous resistance, 2 = section resistance, 0x20 and 0x04 enable additional effects together with 1 and 2 (configuration yet unknown), 252 = likely a calibration program* / PS Remote Play defaults this to 5; bit 4 only disables the motor?) outputReport[13] = r2EffectData.triggerStartResistance; // right trigger start of resistance section 0-255 (0 = released state; 0xb0 roughly matches trigger value 0xff); in mode 26 this field has something to do with motor re-extension after a press-release-cycle (0 = no re-extension) outputReport[14] = r2EffectData.triggerEffectForce; // right trigger // (mode1) amount of force exerted; 0-255 // (mode2) end of resistance section (>= begin of resistance section is enforced); 0xff makes it behave like mode1 // (supplemental mode 4+20) flag(s?) 0x02 = do not pause effect when fully pressed outputReport[15] = r2EffectData.triggerRangeForce; // right trigger force exerted in range (mode2), 0-255 outputReport[16] = r2EffectData.triggerNearReleaseStrength; // strength of effect near release state (requires supplement modes 4 and 20) outputReport[17] = r2EffectData.triggerNearMiddleStrength; // strength of effect near middle (requires supplement modes 4 and 20) outputReport[18] = r2EffectData.triggerPressedStrength; // strength of effect at pressed state (requires supplement modes 4 and 20) outputReport[21] = r2EffectData.triggerActuationFrequency; // effect actuation frequency in Hz (requires supplement modes 4 and 20) // L2 Effects outputReport[23] = l2EffectData.triggerMotorMode; // left trigger motor mode (0 = no resistance, 1 = continuous resistance, 2 = section resistance, 0x20 and 0x04 enable additional effects together with 1 and 2 (configuration yet unknown), 252 = likely a calibration program* / PS Remote Play defaults this to 5; bit 4 only disables the motor?) outputReport[24] = l2EffectData.triggerStartResistance; // left trigger start of resistance section 0-255 (0 = released state; 0xb0 roughly matches trigger value 0xff); in mode 26 this field has something to do with motor re-extension after a press-release-cycle (0 = no re-extension) outputReport[25] = l2EffectData.triggerEffectForce; // left trigger // (mode1) amount of force exerted; 0-255 // (mode2) end of resistance section (>= begin of resistance section is enforced); 0xff makes it behave like mode1 // (supplemental mode 4+20) flag(s?) 0x02 = do not pause effect when fully pressed outputReport[26] = l2EffectData.triggerRangeForce; // left trigger: (mode2) amount of force exerted within range; 0-255 outputReport[27] = l2EffectData.triggerNearReleaseStrength; // strength of effect near release state (requires supplement modes 4 and 20) outputReport[28] = l2EffectData.triggerNearMiddleStrength; // strength of effect near middle (requires supplement modes 4 and 20) outputReport[29] = l2EffectData.triggerPressedStrength; // strength of effect at pressed state (requires supplement modes 4 and 20) outputReport[32] = l2EffectData.triggerActuationFrequency; // effect actuation frequency in Hz (requires supplement modes 4 and 20) // (lower nibble: main motor; upper nibble trigger effects) 0x00 to 0x07 - reduce overall power of the respective motors/effects by 12.5% per increment (this does not affect the regular trigger motor settings, just the automatically repeating trigger effects) outputReport[38] = hapticsIntensityByte; // Volume of internal speaker (0-7; ties in with index 6. The PS5 default appears to be set a 4) //outputReport[39] = 0x00; /* Player LED section */ // 0x01 Enabled LED brightness (value in index 43) // 0x02 Uninterruptable blue LED pulse (action in index 42) outputReport[40] = 0x02; // 0x01 Slowly (2s?) fade to blue (scheduled to when the regular LED settings are active) // 0x02 Slowly (2s?) fade out (scheduled after fade-in completion) with eventual switch back to configured LED color; only a fade-out can cancel the pulse (neither index 2, 0x08, nor turning this off will cancel it!) outputReport[43] = 0x02; // 0x00 High Brightness, 0x01 Medium Brightness, 0x02 Low Brightness outputReport[44] = 0x02; // 5 player LED lights below Touchpad. // Bitmask 0x00-0x1F from left to right with 0x04 being the center LED. Bit 0x20 sets the brightness immediately with no fade in outputReport[45] = activePlayerLEDMask; /* Lightbar colors */ outputReport[46] = currentHap.lightbarState.LightBarColor.red; outputReport[47] = currentHap.lightbarState.LightBarColor.green; outputReport[48] = currentHap.lightbarState.LightBarColor.blue; change = !previousHapticState.Equals(currentHap); // Need to calculate and populate CRC32 data so controller will accept the report uint calcCrc32 = 0; if (change) //if (outputPendCount >= 1 || change) //if (!previousHapticState.Equals(currentHap)) { //change = true; outputDirty = true; if (rumbleSet) { standbySw.Restart(); } else { standbySw.Reset(); } } else if (rumbleSet && standbySw.ElapsedMilliseconds >= 4000L) { outputDirty = true; standbySw.Restart(); } if (outputDirty) { int crcOffset = 0; int crcpos = BT_OUTPUT_REPORT_LENGTH - 4; calcCrc32 = ~Crc32Algorithm.Compute(outputBTCrc32Head); //calcCrc32 = ~Crc32Algorithm.CalculateBasicHash(ref calcCrc32, ref outputReport, 0, BT_OUTPUT_REPORT_LENGTH-4); calcCrc32 = ~Crc32Algorithm.CalculateFasterBT78Hash(ref calcCrc32, ref outputReport, ref crcOffset, ref crcpos); } outputReport[74] = (byte)calcCrc32; outputReport[75] = (byte)(calcCrc32 >> 8); outputReport[76] = (byte)(calcCrc32 >> 16); outputReport[77] = (byte)(calcCrc32 >> 24); /*fixed (byte* bytePrevBuff = outputReport, byteTmpBuff = outReportBuffer) { for (int i = 0, arlen = BT_OUTPUT_CHANGE_LENGTH; !change && i < arlen; i++) change = bytePrevBuff[i] != byteTmpBuff[i]; } */ /*if (change) { outputPendCount = OUTPUT_MIN_COUNT_BT; //Console.WriteLine("DIRTY"); outputDirty = true; //outReportBuffer.CopyTo(outputReport, 0); } else if (outputPendCount >= 1) { Console.WriteLine("CURRENT: {0}", outputPendCount); outputPendCount--; outputDirty = outputPendCount >= 1; } */ //outputDirty = true; //bool res = hDevice.WriteOutputReportViaControl(outputReport); //Console.WriteLine("STAUTS: {0}", res); } } private bool WriteReport() { bool result; if (conType == ConnectionType.BT) { // DualSense seems to only accept output data via the Interrupt endpoint result = hDevice.WriteOutputReportViaInterrupt(outputReport, READ_STREAM_TIMEOUT); //result = hDevice.WriteOutputReportViaControl(outputReport); } else { result = hDevice.WriteOutputReportViaInterrupt(outputReport, READ_STREAM_TIMEOUT); } //Console.WriteLine("STAUTS: {0}", result); return result; } private void Detach() { SendEmptyOutputReport(); } private void CalculateDeviceSlotMask() { // Map 1-8 to a symmetrical LED array from a set of // 5 LED lights switch (deviceSlotNumber) { case 0: deviceSlotMask = 0x04; break; case 1: deviceSlotMask = 0x02 | 0x08; break; case 2: deviceSlotMask = 0x01 | 0x04 | 0x10; break; case 3: deviceSlotMask = 0x02 | 0x04 | 0x08; break; case 4: deviceSlotMask = 0x01 | 0x10; break; case 5: deviceSlotMask = 0x01 | 0x02 | 0x08 | 0x10; break; case 6: deviceSlotMask = 0x01 | 0x02 | 0x04 | 0x08 | 0x10; break; case 7: default: deviceSlotMask = 0x00; break; } } private void PrepareMuteLEDByte() { if (nativeOptionsStore != null) { switch (nativeOptionsStore.MuteLedMode) { case DualSenseControllerOptions.MuteLEDMode.Off: muteLEDByte = 0x00; break; case DualSenseControllerOptions.MuteLEDMode.On: muteLEDByte = 0x01; break; case DualSenseControllerOptions.MuteLEDMode.Pulse: muteLEDByte = 0x02; break; default: muteLEDByte = 0x00; break; } } } private void PreparePlayerLEDBarByte() { if (nativeOptionsStore != null) { if (nativeOptionsStore.LedMode == DualSenseControllerOptions.LEDBarMode.Off) { activePlayerLEDMask = 0x00; } else if (nativeOptionsStore.LedMode == DualSenseControllerOptions.LEDBarMode.On) { activePlayerLEDMask = deviceSlotMask; } else if (nativeOptionsStore.LedMode == DualSenseControllerOptions.LEDBarMode.BatteryPercentage) { activePlayerLEDMask = DeviceBatteryLinearMask(battery); } } } public override void PrepareTriggerEffect(TriggerId trigger, TriggerEffects effect) { if (trigger == TriggerId.LeftTrigger) { l2EffectData.ChangeData(effect); } else if (trigger == TriggerId.RightTrigger) { r2EffectData.ChangeData(effect); } else { throw new ArgumentOutOfRangeException("Invalid Trigger Id"); } queueEvent(() => { outputDirty = true; PrepareOutReport(); }); } private byte DeviceBatteryLinearMask(int deviceBattery) { byte batteryMask; if (deviceBattery >= 95) batteryMask = 0x01 | 0x02 | 0x08 | 0x10; else if (deviceBattery >= 70) batteryMask = 0x01 | 0x02 | 0x08; else if (deviceBattery >= 50) batteryMask = 0x01 | 0x02; else if (deviceBattery >= 20) batteryMask = 0x01; else if (deviceBattery >= 5) batteryMask = 0x01 | 0x02 | 0x04; else batteryMask = 0x00; return batteryMask; } public override void CheckControllerNumDeviceSettings(int numControllers) { if (nativeOptionsStore != null) { if (nativeOptionsStore.LedMode == DualSenseControllerOptions.LEDBarMode.MultipleControllers) { if (numControllers > 1) { activePlayerLEDMask = deviceSlotMask; } else { activePlayerLEDMask = 0x00; } } } queueEvent(() => { outputDirty = true; //PrepareOutReport(); }); } private void SetupOptionsEvents() { if (nativeOptionsStore != null) { nativeOptionsStore.EnableRumbleChanged += (sender, e) => { UseRumble = nativeOptionsStore.EnableRumble; queueEvent(() => { outputDirty = true; }); }; nativeOptionsStore.HapticIntensityChanged += (sender, e) => { HapticChoice = nativeOptionsStore.HapticIntensity; queueEvent(() => { outputDirty = true; }); }; nativeOptionsStore.MuteLedModeChanged += (sender, e) => { PrepareMuteLEDByte(); queueEvent(() => { outputDirty = true; }); }; nativeOptionsStore.LedModeChanged += (sender, e) => { PreparePlayerLEDBarByte(); queueEvent(() => { outputDirty = true; }); }; } } public override void LoadStoreSettings() { if (nativeOptionsStore != null) { UseRumble = nativeOptionsStore.EnableRumble; HapticChoice = nativeOptionsStore.HapticIntensity; PrepareMuteLEDByte(); PreparePlayerLEDBarByte(); } } } }
47.380581
360
0.502618
[ "MIT" ]
Renzo904/DS4Windows
DS4Windows/DS4Library/InputDevices/DualSenseDevice.cs
66,856
C#
namespace WeLoveFood.Data { public class DataConstants { public class Common { public const int IdMaxLength = 40; } public class City { public const int NameMinLength = 3; public const int NameMaxLength = 20; } public class Restaurant { public const int NameMinLength = 2; public const int NameMaxLength = 40; public const string WorkingTimeRegularExpression = @"^([0-1]?[0-9]|2[0-3]):[0-5][0-9]$"; } public class Meal { public const int NameMinLength = 3; public const int NameMaxLength = 32; public const int WeightMinValue = 10; public const int WeightMaxValue = 1000; public const int DescriptionMaxLength = 60; } public class MealsCategory { public const int NameMinLength = 3; public const int NameMaxLength = 25; } public class User { public const int PasswordMinLength = 6; public const int PasswordMaxLength = 100; public const int NameMinLength = 2; public const int NameMaxLength = 25; public const int AddressMaxLength = 40; public const string PhoneNumberRegularExpression = @"^[+]*[(]{0,1}[0-9]{1,4}[)]{0,1}[-\s\./0-9]*$"; } } }
26.163636
111
0.537874
[ "MIT" ]
dbegogow/We-Love-Food
WeLoveFood.Data/DataConstants.cs
1,441
C#