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 System;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Data;
namespace WindowsIoTDashboard.App.Helpers
{
public class LevelToMarginConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
return new Thickness((int)value * 15, 0, 0, 0);
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
return null;
}
}
}
| 26.2 | 100 | 0.625954 | [
"MIT"
] | hyprsoftcorp/WindowsIoTCoreDashboard | WindowsIoTDashboard.App/Helpers/LevelToMarginConverter.cs | 526 | C# |
using Android.Content;
using Android.Content.Res;
using Android.Graphics;
using Android.OS;
using MobileApp.CustomRenderers;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
[assembly: ExportRenderer(typeof(EntryRenderer), typeof(WhiteEntry))]
namespace MobileApp.Droid.CustomRenderers
{
public class WhiteEntry : EntryRenderer
{
public WhiteEntry(Context context):base(context)
{
}
protected override void OnElementChanged(ElementChangedEventArgs<Entry> e)
{
base.OnElementChanged(e);
if(e.NewElement!=null)
{
if (Build.VERSION.SdkInt >= BuildVersionCodes.Lollipop)
Control.BackgroundTintList = ColorStateList.ValueOf(Android.Graphics.Color.White);
else
Control.Background.SetColorFilter(Android.Graphics.Color.White, PorterDuff.Mode.SrcAtop);
}
}
}
} | 29.59375 | 109 | 0.658923 | [
"MIT"
] | tarikcosovic/Cross-Platform-Application-Pokloni.ba- | MobileApp/MobileApp.Android/CustomRenderers/WhiteEntry.cs | 949 | C# |
using System;
using System.Linq;
namespace plinq_merge_options
{
internal class Program
{
public static void Main(string[] args)
{
var numbers = Enumerable.Range(1, 20).ToArray();
var results = numbers
.AsParallel()
.WithMergeOptions(ParallelMergeOptions.FullyBuffered)
.Select(x =>
{
var result = Math.Log10(x);
Console.Write($"p {result}\t");
return result;
});
foreach (var result in results)
{
Console.Write($"c {result}\t");
}
}
}
} | 24.75 | 69 | 0.458874 | [
"MIT"
] | gakalin/CSharp_Practices | plinq_merge_options/plinq_merge_options/Program.cs | 695 | C# |
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
// Ported from shared/dxgi1_4.h in the Windows SDK for Windows 10.0.20348.0
// Original source is Copyright © Microsoft. All rights reserved.
using NUnit.Framework;
using System;
using static TerraFX.Interop.Windows.IID;
namespace TerraFX.Interop.Windows.UnitTests;
/// <summary>Provides validation of the <see cref="IID" /> class.</summary>
public static partial class IIDTests
{
/// <summary>Validates that the value of the <see cref="IID_IDXGISwapChain3" /> property is correct.</summary>
[Test]
public static void IID_IDXGISwapChain3Test()
{
Assert.That(IID_IDXGISwapChain3, Is.EqualTo(new Guid(0x94d99bdb, 0xf1f8, 0x4ab0, 0xb2, 0x36, 0x7d, 0xa0, 0x17, 0x0e, 0xda, 0xb1)));
}
/// <summary>Validates that the value of the <see cref="IID_IDXGIOutput4" /> property is correct.</summary>
[Test]
public static void IID_IDXGIOutput4Test()
{
Assert.That(IID_IDXGIOutput4, Is.EqualTo(new Guid(0xdc7dca35, 0x2196, 0x414d, 0x9F, 0x53, 0x61, 0x78, 0x84, 0x03, 0x2a, 0x60)));
}
/// <summary>Validates that the value of the <see cref="IID_IDXGIFactory4" /> property is correct.</summary>
[Test]
public static void IID_IDXGIFactory4Test()
{
Assert.That(IID_IDXGIFactory4, Is.EqualTo(new Guid(0x1bc6ea02, 0xef36, 0x464f, 0xbf, 0x0c, 0x21, 0xca, 0x39, 0xe5, 0x16, 0x8a)));
}
/// <summary>Validates that the value of the <see cref="IID_IDXGIAdapter3" /> property is correct.</summary>
[Test]
public static void IID_IDXGIAdapter3Test()
{
Assert.That(IID_IDXGIAdapter3, Is.EqualTo(new Guid(0x645967A4, 0x1392, 0x4310, 0xA7, 0x98, 0x80, 0x53, 0xCE, 0x3E, 0x93, 0xFD)));
}
}
| 42.395349 | 145 | 0.708173 | [
"MIT"
] | IngmarBitter/terrafx.interop.windows | tests/Interop/Windows/DirectX/shared/dxgi1_4/IIDTests.cs | 1,825 | C# |
namespace IDTO.WebAPI.Areas.HelpPage.ModelDescriptions
{
public class KeyValuePairModelDescription : ModelDescription
{
public ModelDescription KeyModelDescription { get; set; }
public ModelDescription ValueModelDescription { get; set; }
}
} | 30 | 67 | 0.740741 | [
"Apache-2.0"
] | OSADP/IDTO | IDTO Azure Hosted Systems/IDTO.WebAPI/Areas/HelpPage/ModelDescriptions/KeyValuePairModelDescription.cs | 270 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace AsyncInn.Models.DTO
{
public class RoomDTO
{
// Room data transfer object that will normalize for viewer
public int ID { get; set; }
public string Name { get; set; }
public string Layout { get; set; }
public List<AmenitiesDTO> Amenities { get; set; }
}
}
| 23.166667 | 67 | 0.652278 | [
"MIT"
] | jinwoov/Async-Inn | AsyncInn/AsyncInn/Models/DTO/RoomDTO.cs | 419 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Text;
using Silk.NET.Core;
using Silk.NET.Core.Native;
using Silk.NET.Core.Attributes;
using Silk.NET.Core.Contexts;
using Silk.NET.Core.Loader;
#pragma warning disable 1591
namespace Silk.NET.Direct3D11
{
[NativeName("Name", "CD3D11_RENDER_TARGET_VIEW_DESC")]
public unsafe partial struct CD3D11RenderTargetViewDesc
{
public CD3D11RenderTargetViewDesc
(
Silk.NET.DXGI.Format? format = null,
RtvDimension? viewDimension = null,
RenderTargetViewDescUnion? anonymous = null,
BufferRtv? buffer = null,
Tex1DRtv? texture1D = null,
Tex1DArrayRtv? texture1DArray = null,
Tex2DRtv? texture2D = null,
Tex2DArrayRtv? texture2DArray = null,
Tex2DmsRtv? texture2DMS = null,
Tex2DmsArrayRtv? texture2DMSArray = null,
Tex3DRtv? texture3D = null
) : this()
{
if (format is not null)
{
Format = format.Value;
}
if (viewDimension is not null)
{
ViewDimension = viewDimension.Value;
}
if (anonymous is not null)
{
Anonymous = anonymous.Value;
}
if (buffer is not null)
{
Buffer = buffer.Value;
}
if (texture1D is not null)
{
Texture1D = texture1D.Value;
}
if (texture1DArray is not null)
{
Texture1DArray = texture1DArray.Value;
}
if (texture2D is not null)
{
Texture2D = texture2D.Value;
}
if (texture2DArray is not null)
{
Texture2DArray = texture2DArray.Value;
}
if (texture2DMS is not null)
{
Texture2DMS = texture2DMS.Value;
}
if (texture2DMSArray is not null)
{
Texture2DMSArray = texture2DMSArray.Value;
}
if (texture3D is not null)
{
Texture3D = texture3D.Value;
}
}
[NativeName("Type", "DXGI_FORMAT")]
[NativeName("Type.Name", "DXGI_FORMAT")]
[NativeName("Name", "Format")]
public Silk.NET.DXGI.Format Format;
[NativeName("Type", "D3D11_RTV_DIMENSION")]
[NativeName("Type.Name", "D3D11_RTV_DIMENSION")]
[NativeName("Name", "ViewDimension")]
public RtvDimension ViewDimension;
[NativeName("Type", "")]
[NativeName("Type.Name", "__AnonymousRecord_d3d11_L3803_C5")]
[NativeName("Name", "anonymous1")]
public RenderTargetViewDescUnion Anonymous;
#if NETSTANDARD2_1 || NETCOREAPP3_1 || NET5_0 || NET5_0_OR_GREATER
public ref BufferRtv Buffer
{
[MethodImpl((MethodImplOptions) 768)]
get => ref MemoryMarshal.CreateSpan(ref Anonymous, 1)[0].Buffer;
}
#else
public BufferRtv Buffer
{
get => Anonymous.Buffer;
set => Anonymous.Buffer = value;
}
#endif
#if NETSTANDARD2_1 || NETCOREAPP3_1 || NET5_0 || NET5_0_OR_GREATER
public ref Tex1DRtv Texture1D
{
[MethodImpl((MethodImplOptions) 768)]
get => ref MemoryMarshal.CreateSpan(ref Anonymous, 1)[0].Texture1D;
}
#else
public Tex1DRtv Texture1D
{
get => Anonymous.Texture1D;
set => Anonymous.Texture1D = value;
}
#endif
#if NETSTANDARD2_1 || NETCOREAPP3_1 || NET5_0 || NET5_0_OR_GREATER
public ref Tex1DArrayRtv Texture1DArray
{
[MethodImpl((MethodImplOptions) 768)]
get => ref MemoryMarshal.CreateSpan(ref Anonymous, 1)[0].Texture1DArray;
}
#else
public Tex1DArrayRtv Texture1DArray
{
get => Anonymous.Texture1DArray;
set => Anonymous.Texture1DArray = value;
}
#endif
#if NETSTANDARD2_1 || NETCOREAPP3_1 || NET5_0 || NET5_0_OR_GREATER
public ref Tex2DRtv Texture2D
{
[MethodImpl((MethodImplOptions) 768)]
get => ref MemoryMarshal.CreateSpan(ref Anonymous, 1)[0].Texture2D;
}
#else
public Tex2DRtv Texture2D
{
get => Anonymous.Texture2D;
set => Anonymous.Texture2D = value;
}
#endif
#if NETSTANDARD2_1 || NETCOREAPP3_1 || NET5_0 || NET5_0_OR_GREATER
public ref Tex2DArrayRtv Texture2DArray
{
[MethodImpl((MethodImplOptions) 768)]
get => ref MemoryMarshal.CreateSpan(ref Anonymous, 1)[0].Texture2DArray;
}
#else
public Tex2DArrayRtv Texture2DArray
{
get => Anonymous.Texture2DArray;
set => Anonymous.Texture2DArray = value;
}
#endif
#if NETSTANDARD2_1 || NETCOREAPP3_1 || NET5_0 || NET5_0_OR_GREATER
public ref Tex2DmsRtv Texture2DMS
{
[MethodImpl((MethodImplOptions) 768)]
get => ref MemoryMarshal.CreateSpan(ref Anonymous, 1)[0].Texture2DMS;
}
#else
public Tex2DmsRtv Texture2DMS
{
get => Anonymous.Texture2DMS;
set => Anonymous.Texture2DMS = value;
}
#endif
#if NETSTANDARD2_1 || NETCOREAPP3_1 || NET5_0 || NET5_0_OR_GREATER
public ref Tex2DmsArrayRtv Texture2DMSArray
{
[MethodImpl((MethodImplOptions) 768)]
get => ref MemoryMarshal.CreateSpan(ref Anonymous, 1)[0].Texture2DMSArray;
}
#else
public Tex2DmsArrayRtv Texture2DMSArray
{
get => Anonymous.Texture2DMSArray;
set => Anonymous.Texture2DMSArray = value;
}
#endif
#if NETSTANDARD2_1 || NETCOREAPP3_1 || NET5_0 || NET5_0_OR_GREATER
public ref Tex3DRtv Texture3D
{
[MethodImpl((MethodImplOptions) 768)]
get => ref MemoryMarshal.CreateSpan(ref Anonymous, 1)[0].Texture3D;
}
#else
public Tex3DRtv Texture3D
{
get => Anonymous.Texture3D;
set => Anonymous.Texture3D = value;
}
#endif
}
}
| 29.103604 | 86 | 0.572976 | [
"MIT"
] | DmitryGolubenkov/Silk.NET | src/Microsoft/Silk.NET.Direct3D11/Structs/CD3D11RenderTargetViewDesc.gen.cs | 6,461 | C# |
using Microsoft.Management.Infrastructure;
using System;
using System.Collections.Generic;
using System.Linq;
using SimCim.Core;
namespace SimCim.Root.StandardCimV2
{
public class MSFTNetAdapterHardwareInfoElementSetting : MSFTNetAdapterElementSettingData
{
public MSFTNetAdapterHardwareInfoElementSetting()
{
}
public MSFTNetAdapterHardwareInfoElementSetting(IInfrastructureObjectScope scope, CimInstance instance): base(scope, instance)
{
}
public new MSFTNetAdapterHardwareInfoSettingData SettingData
{
get
{
MSFTNetAdapterHardwareInfoSettingData result;
this.GetInfrastructureObjectProperty("SettingData", out result);
return result;
}
set
{
this.SetProperty("SettingData", value);
}
}
}
} | 27.970588 | 135 | 0.616193 | [
"Apache-2.0"
] | simonferquel/simcim | SimCim.Root.StandardCimV2/ClassMSFTNetAdapterHardwareInfoElementSetting.cs | 953 | 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 Fixtures.AcceptanceTestsAzureCompositeModelClient.Models
{
using Fixtures.AcceptanceTestsAzureCompositeModelClient;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
public partial class CatalogDictionaryOfArray
{
/// <summary>
/// Initializes a new instance of the CatalogDictionaryOfArray class.
/// </summary>
public CatalogDictionaryOfArray()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the CatalogDictionaryOfArray class.
/// </summary>
/// <param name="productDictionaryOfArray">Dictionary of Array of
/// product</param>
public CatalogDictionaryOfArray(IDictionary<string, IList<Product>> productDictionaryOfArray = default(IDictionary<string, IList<Product>>))
{
ProductDictionaryOfArray = productDictionaryOfArray;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets or sets dictionary of Array of product
/// </summary>
[JsonProperty(PropertyName = "productDictionaryOfArray")]
public IDictionary<string, IList<Product>> ProductDictionaryOfArray { get; set; }
}
}
| 34.333333 | 148 | 0.667619 | [
"MIT"
] | bloudraak/autorest | src/generator/AutoRest.CSharp.Azure.Tests/Expected/AcceptanceTests/AzureCompositeModelClient/Models/CatalogDictionaryOfArray.cs | 1,751 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace QuikSync.LocalWorks.Attributes
{
/// <summary>
/// Attribute made for easy reading data from ini file.
/// </summary>
public class Reading : Attribute
{
public string Section;
}
}
| 20 | 59 | 0.688235 | [
"MIT"
] | Halozzee/QuikSync | QuikSync/LocalWorks/Attributes/Reading.cs | 342 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the ec2-2016-11-15.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Serialization;
using Amazon.EC2.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
namespace Amazon.EC2.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for DisableImageDeprecation operation
/// </summary>
public class DisableImageDeprecationResponseUnmarshaller : EC2ResponseUnmarshaller
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public override AmazonWebServiceResponse Unmarshall(XmlUnmarshallerContext context)
{
DisableImageDeprecationResponse response = new DisableImageDeprecationResponse();
int originalDepth = context.CurrentDepth;
int targetDepth = originalDepth + 1;
if (context.IsStartOfDocument)
targetDepth = 2;
while (context.ReadAtDepth(originalDepth))
{
if (context.IsStartElement || context.IsAttribute)
{
if (context.TestExpression("return", targetDepth))
{
var unmarshaller = BoolUnmarshaller.Instance;
response.Return = unmarshaller.Unmarshall(context);
continue;
}
}
}
return response;
}
/// <summary>
/// Unmarshaller error response to exception.
/// </summary>
/// <param name="context"></param>
/// <param name="innerException"></param>
/// <param name="statusCode"></param>
/// <returns></returns>
public override AmazonServiceException UnmarshallException(XmlUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode)
{
ErrorResponse errorResponse = ErrorResponseUnmarshaller.GetInstance().Unmarshall(context);
return new AmazonEC2Exception(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
private static DisableImageDeprecationResponseUnmarshaller _instance = new DisableImageDeprecationResponseUnmarshaller();
internal static DisableImageDeprecationResponseUnmarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static DisableImageDeprecationResponseUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 35.683168 | 158 | 0.642342 | [
"Apache-2.0"
] | ChristopherButtars/aws-sdk-net | sdk/src/Services/EC2/Generated/Model/Internal/MarshallTransformations/DisableImageDeprecationResponseUnmarshaller.cs | 3,604 | C# |
using System.Management.Automation;
using SendGrid.PowerShell.Common;
namespace SendGrid.PowerShell.Unsubscribes
{
[Cmdlet(VerbsCommon.Add, "SendGridUnsubscribes")]
public class AddSendGridUnsubscribes : CmdletBase
{
[Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)]
[ValidateNotNullOrEmpty]
public string Email { get; set; }
protected override void ProcessRecord()
{
var result = Post<GenericResult>("unsubscribes", "add", new { email = Email });
WriteObject(result);
}
}
}
| 28.545455 | 117 | 0.66879 | [
"Apache-2.0"
] | shibayan/SendGrid.PowerShell | src/SendGrid.PowerShell/Unsubscribes/AddSendGridUnsubscribes.cs | 630 | C# |
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
namespace Nop.Plugin.Api.DTO.Errors
{
public class ErrorsRootObject : ISerializableObject
{
[JsonProperty("errors")]
public Dictionary<string, List<string>> Errors { get; set; }
public string GetPrimaryPropertyName()
{
return "errors";
}
public Type GetPrimaryPropertyType()
{
return Errors.GetType();
}
}
}
| 21 | 68 | 0.608696 | [
"MIT"
] | DataplaceDevs/api-for-nopcommerce | Nop.Plugin.Api/DTOs/Errors/ErrorsRootObject.cs | 485 | C# |
using AllLive.Core.Interface;
using AllLive.Core.Models;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AllLive.UWP.ViewModels
{
public class CategoryDetailVM:BaseViewModel
{
public CategoryDetailVM()
{
Items = new ObservableCollection<Core.Models.LiveRoomItem>();
}
public ObservableCollection<AllLive.Core.Models.LiveRoomItem> Items { get; set; }
private ILiveSite _site;
public ILiveSite Site
{
get { return _site; }
set { _site = value; }
}
private LiveSubCategory _category;
public LiveSubCategory Category
{
get { return _category; }
set { _category = value; }
}
public async void LoadData(ILiveSite site, LiveSubCategory category)
{
try
{
Site = site;
Category = category;
Loading = true;
CanLoadMore = false;
IsEmpty = false;
var result = await site.GetCategoryRooms(category, Page);
foreach (var item in result.Rooms)
{
Items.Add(item);
}
IsEmpty = Items.Count == 0;
CanLoadMore = result.HasMore;
Page++;
}
catch (Exception ex)
{
HandleError(ex);
}
finally
{
Loading = false;
}
}
public override void Refresh()
{
base.Refresh();
Items.Clear();
LoadData(_site, _category);
}
public override void LoadMore()
{
base.LoadMore();
LoadData(_site, _category);
}
}
}
| 25.363636 | 89 | 0.499744 | [
"MIT"
] | xiaoyaocz/AllLive | AllLive.UWP/ViewModels/CategoryDetailVM.cs | 1,955 | C# |
// Generated by TankLibHelper
using TankLib.STU.Types.Enums;
// ReSharper disable All
namespace TankLib.STU.Types
{
[STU(0x33752503, 12)]
public class StatEventScoreScaler : STUInstance
{
[STUField(0xB44A42A0, 0)] // size: 4
public STUStatEvent m_B44A42A0;
[STUField(0x9A97C666, 4)] // size: 4
public float m_9A97C666;
[STUField(0x20100AF4, 8)] // size: 1
public byte m_20100AF4;
}
}
| 23.35 | 51 | 0.620985 | [
"MIT"
] | Pandaaa2507/OWLib | TankLib/STU/Types/StatEventScoreScaler.cs | 467 | C# |
//
// Copyright (c) David Wendland. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
//
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
// ReSharper disable once CheckNamespace
namespace SniffCore.Layouting
{
/// <summary>
/// Represents the shown tab in the <see cref="DynamicTabControl" />.
/// </summary>
public class DynamicTabItem : TabItem
{
/// <summary>
/// Identifies the <see cref="CloseButtonPosition" /> dependency property.
/// </summary>
public static readonly DependencyProperty CloseButtonPositionProperty =
DependencyProperty.Register("CloseButtonPosition", typeof(Dock), typeof(DynamicTabItem), new UIPropertyMetadata(Dock.Right));
/// <summary>
/// Identifies the <see cref="CloseButtonMargin" /> dependency property.
/// </summary>
public static readonly DependencyProperty CloseButtonMarginProperty =
DependencyProperty.Register("CloseButtonMargin", typeof(Thickness), typeof(DynamicTabItem), new UIPropertyMetadata(new Thickness(5, 0, 0, 0)));
/// <summary>
/// Identifies the <see cref="HorizontalCloseButtonAlignment" /> dependency property.
/// </summary>
public static readonly DependencyProperty HorizontalCloseButtonAlignmentProperty =
DependencyProperty.Register("HorizontalCloseButtonAlignment", typeof(HorizontalAlignment), typeof(DynamicTabItem), new UIPropertyMetadata(HorizontalAlignment.Center));
/// <summary>
/// Identifies the <see cref="VerticalCloseButtonAlignment" /> dependency property.
/// </summary>
public static readonly DependencyProperty VerticalCloseButtonAlignmentProperty =
DependencyProperty.Register("VerticalCloseButtonAlignment", typeof(VerticalAlignment), typeof(DynamicTabItem), new UIPropertyMetadata(VerticalAlignment.Center));
/// <summary>
/// Identifies the <see cref="CloseButtonHeight" /> dependency property.
/// </summary>
public static readonly DependencyProperty CloseButtonHeightProperty =
DependencyProperty.Register("CloseButtonHeight", typeof(double), typeof(DynamicTabItem), new UIPropertyMetadata(14.0));
/// <summary>
/// Identifies the <see cref="CloseButtonWidth" /> dependency property.
/// </summary>
public static readonly DependencyProperty CloseButtonWidthProperty =
DependencyProperty.Register("CloseButtonWidth", typeof(double), typeof(DynamicTabItem), new UIPropertyMetadata(14.0));
/// <summary>
/// Identifies the <see cref="ShowCloseButton" /> dependency property.
/// </summary>
public static readonly DependencyProperty ShowCloseButtonProperty =
DependencyProperty.Register("ShowCloseButton", typeof(bool), typeof(DynamicTabItem), new UIPropertyMetadata(true));
static DynamicTabItem()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(DynamicTabItem), new FrameworkPropertyMetadata(typeof(DynamicTabItem)));
}
/// <summary>
/// Gets or sets a value which indicates where the close tab item button have to be placed in the header.
/// </summary>
[DefaultValue(Dock.Right)]
public Dock CloseButtonPosition
{
get => (Dock) GetValue(CloseButtonPositionProperty);
set => SetValue(CloseButtonPositionProperty, value);
}
/// <summary>
/// Gets or sets the margin of the close tab item button.
/// </summary>
public Thickness CloseButtonMargin
{
get => (Thickness) GetValue(CloseButtonMarginProperty);
set => SetValue(CloseButtonMarginProperty, value);
}
/// <summary>
/// Gets or sets the horizontal alignment of the close tab item button.
/// </summary>
[DefaultValue(HorizontalAlignment.Center)]
public HorizontalAlignment HorizontalCloseButtonAlignment
{
get => (HorizontalAlignment) GetValue(HorizontalCloseButtonAlignmentProperty);
set => SetValue(HorizontalCloseButtonAlignmentProperty, value);
}
/// <summary>
/// Gets or sets the vertical alignment of the close tab item button.
/// </summary>
[DefaultValue(VerticalAlignment.Center)]
public VerticalAlignment VerticalCloseButtonAlignment
{
get => (VerticalAlignment) GetValue(VerticalCloseButtonAlignmentProperty);
set => SetValue(VerticalCloseButtonAlignmentProperty, value);
}
/// <summary>
/// Gets or sets the height of the close tab item button.
/// </summary>
[DefaultValue(14.0)]
public double CloseButtonHeight
{
get => (double) GetValue(CloseButtonHeightProperty);
set => SetValue(CloseButtonHeightProperty, value);
}
/// <summary>
/// Gets or sets the width of the close tab item button
/// </summary>
[DefaultValue(14.0)]
public double CloseButtonWidth
{
get => (double) GetValue(CloseButtonWidthProperty);
set => SetValue(CloseButtonWidthProperty, value);
}
/// <summary>
/// Gets or sets a value which indicates if the close tab item button is visible or not.
/// </summary>
[DefaultValue(true)]
public bool ShowCloseButton
{
get => (bool) GetValue(ShowCloseButtonProperty);
set => SetValue(ShowCloseButtonProperty, value);
}
}
} | 42.903704 | 179 | 0.649517 | [
"MIT"
] | devicenator/SniffCore.Layouting | SniffCore.Layouting/DynamicTabControl/DynamicTabItem.cs | 5,801 | C# |
#region Copyright & License
// Copyright © 2012 - 2021 François Chabot
//
// 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.CodeAnalysis;
using Microsoft.BizTalk.Adapter.ServiceBus;
using Microsoft.ServiceBus;
namespace Be.Stateless.BizTalk.Dsl.Binding.Adapter
{
public abstract partial class WcfNetTcpRelayAdapter
{
#region Nested Type: Inbound
/// <summary>
/// Microsoft BizTalk Server uses the WCF-NetTcpRelay adapter when receiving and sending WCF service requests through the
/// <see cref="NetTcpRelayBinding"/>. The WCF-NetTcpRelay adapter enables you to send and receive messages from the
/// Service Bus relay endpoints using the <see cref="NetTcpRelayBinding"/>.
/// </summary>
/// <seealso href="https://docs.microsoft.com/en-us/biztalk/core/wcf-nettcprelay-adapter">WCF-NetTcpRelay Adapter</seealso>
[SuppressMessage("ReSharper", "UnusedMember.Global", Justification = "Public DSL API.")]
public class Inbound : WcfNetTcpRelayAdapter<NetTcpRelayRLConfig>,
IInboundAdapter,
IAdapterConfigMaxConcurrentCalls,
IAdapterConfigInboundSuspendRequestMessageOnFailure,
IAdapterConfigInboundIncludeExceptionDetailInFaults,
IAdapterConfigServiceCertificate
{
[SuppressMessage("ReSharper", "MemberCanBePrivate.Global", Justification = "Public DSL API.")]
public Inbound()
{
// Binding Tab - Service Throttling Behavior Settings
MaxConcurrentCalls = 200;
// Security Tab - Client Security Settings
RelayClientAuthenticationType = RelayClientAuthenticationType.RelayAccessToken;
// Messages Tab - Error Handling Settings
SuspendRequestMessageOnFailure = true;
IncludeExceptionDetailInFaults = true;
}
public Inbound(Action<Inbound> adapterConfigurator) : this()
{
if (adapterConfigurator == null) throw new ArgumentNullException(nameof(adapterConfigurator));
adapterConfigurator(this);
}
#region IAdapterConfigInboundIncludeExceptionDetailInFaults Members
public bool IncludeExceptionDetailInFaults
{
get => AdapterConfig.IncludeExceptionDetailInFaults;
set => AdapterConfig.IncludeExceptionDetailInFaults = value;
}
#endregion
#region IAdapterConfigInboundSuspendRequestMessageOnFailure Members
public bool SuspendRequestMessageOnFailure
{
get => AdapterConfig.SuspendMessageOnFailure;
set => AdapterConfig.SuspendMessageOnFailure = value;
}
#endregion
#region IAdapterConfigMaxConcurrentCalls Members
public int MaxConcurrentCalls
{
get => AdapterConfig.MaxConcurrentCalls;
set => AdapterConfig.MaxConcurrentCalls = value;
}
#endregion
#region IAdapterConfigServiceCertificate Members
public string ServiceCertificate
{
get => AdapterConfig.ServiceCertificate;
set => AdapterConfig.ServiceCertificate = value;
}
#endregion
#region Security Tab - Client Security Settings
/// <summary>
/// Specify the option to authenticate with the Service Bus relay endpoint from where the message is received.
/// </summary>
/// <remarks>
/// <para>
/// Valid values include the following:
/// <list type="bullet">
/// <item>
/// <term><see cref="Microsoft.ServiceBus.RelayClientAuthenticationType.None"/></term>
/// <description>
/// No authentication is required.
/// </description>
/// </item>
/// <item>
/// <term><see cref="Microsoft.ServiceBus.RelayClientAuthenticationType.RelayAccessToken"/></term>
/// <description>
/// Specify this to use a security token to authorize with the Service Bus Relay endpoint.
/// </description>
/// </item>
/// </list>
/// </para>
/// <para>
/// It defaults to <see cref="Microsoft.ServiceBus.RelayClientAuthenticationType.RelayAccessToken"/>.
/// </para>
/// </remarks>
[SuppressMessage("ReSharper", "MemberCanBePrivate.Global", Justification = "Public DSL API.")]
public RelayClientAuthenticationType RelayClientAuthenticationType
{
get => AdapterConfig.RelayClientAuthenticationType;
set => AdapterConfig.RelayClientAuthenticationType = value;
}
#endregion
#region Security Tab - Service Discovery Settings
/// <summary>
/// Specify whether the behavior of the service is published in the Service Registry.
/// </summary>
public bool EnableServiceDiscovery
{
get => AdapterConfig.EnableServiceDiscovery;
set => AdapterConfig.EnableServiceDiscovery = value;
}
/// <summary>
/// Specify the name with which the service is published to the Service Registry.
/// </summary>
public string ServiceDisplayName
{
get => AdapterConfig.ServiceDisplayName;
set => AdapterConfig.ServiceDisplayName = value;
}
/// <summary>
/// Set the discovery mode for the service published in the Service Registry.
/// </summary>
/// <remarks>
/// For more information about the discovery modes, see <see cref="DiscoveryType"/>.
/// </remarks>
public DiscoveryType DiscoveryMode
{
get => AdapterConfig.DiscoveryMode;
set => AdapterConfig.DiscoveryMode = value;
}
#endregion
}
#endregion
}
}
| 31.820225 | 125 | 0.726871 | [
"Apache-2.0"
] | emmanuelbenitez/Be.Stateless.BizTalk.Dsl.Binding | src/Be.Stateless.BizTalk.Dsl.Binding/Dsl/Binding/Adapter/WcfNetTcpRelayAdapter.Inbound.cs | 5,668 | C# |
using log4net;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Senparc.CO2NET;
using Senparc.CO2NET.RegisterServices;
using Senparc.Scf.XscfBase.Database;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace Senparc.Xscf.DatabaseToolkit
{
/// <summary>
/// 设计时 DbContext 创建(仅在开发时创建 Code-First 的数据库 Migration 使用,在生产环境不会执行)
/// </summary>
public class SenparcDbContextFactory : SenparcDesignTimeDbContextFactoryBase<DatabaseToolkitEntities, Register>
{
/// <summary>
/// 用于寻找 App_Data 文件夹,从而找到数据库连接字符串配置信息
/// </summary>
public override string RootDictionaryPath => Path.Combine(AppContext.BaseDirectory, "..\\..\\..\\"/* Debug模式下项目根目录 */);
}
}
| 31.6 | 127 | 0.731646 | [
"Apache-2.0"
] | SenparcCoreFramework/ScfPackageSources | src/Extensions/Senparc.Xscf.DatabaseToolkit/Senparc.Xscf.DatabaseToolkit/Models/SenparcDbContextFactory.cs | 916 | C# |
#if !WEB
using Newtonsoft.Json;
using RestSharp;
#if WINDOWS_PHONE_APP
using RestSharp.Portable;
#endif
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Stencil.SDK.Exceptions;
namespace Stencil.SDK
{
public partial class StencilSDK
{
#region Public Methods
public IRestResponse Execute(RestRequest request)
{
RestClient client = new RestClient();
this.PrepareRequest(client, request);
#if WINDOWS_PHONE_APP
IRestResponse response = client.ExecuteSynchronous(request);
#else
IRestResponse response = client.Execute(request);
#endif
this.ValidateResponse(response);
return response;
}
public T Execute<T>(RestRequest request)
where T : new()
{
RestClient client = new RestClient();
this.PrepareRequest(client, request);
#if WINDOWS_PHONE_APP
IRestResponse<T> response = client.ExecuteSynchronous<T>(request);
#else
IRestResponse<T> response = client.Execute<T>(request);
#endif
this.ValidateResponse(response);
return response.Data;
}
public async Task<IRestResponse> ExecuteAsync(RestRequest request)
{
return await ExecuteAsync(request, this.AsyncTimeoutMillisecond);
}
public async Task<IRestResponse> ExecuteAsync(RestRequest request, int milliSecondTimeout)
{
return await Task.Factory.StartNew(() =>
{
if (milliSecondTimeout <= 0)
{
milliSecondTimeout = this.AsyncTimeoutMillisecond;
}
Task<IRestResponse> task = ExecuteAsyncInternal(request);
bool completed = task.Wait(milliSecondTimeout);
if (completed)
{
return task.Result;
}
throw new EndpointTimeoutException(System.Net.HttpStatusCode.GatewayTimeout, "Error communicating with server, connection timed out.");
});
}
public async Task<T> ExecuteAsync<T>(RestRequest request)
where T : new()
{
return await ExecuteAsync<T>(request, this.AsyncTimeoutMillisecond);
}
public async Task<T> ExecuteAsync<T>(RestRequest request, int milliSecondTimeout)
where T : new()
{
return await Task.Factory.StartNew(() =>
{
if (milliSecondTimeout <= 0)
{
milliSecondTimeout = this.AsyncTimeoutMillisecond;
}
Task<T> task = ExecuteAsyncInternal<T>(request);
bool completed = task.Wait(milliSecondTimeout);
if (completed)
{
return task.Result;
}
throw new EndpointTimeoutException(System.Net.HttpStatusCode.GatewayTimeout, "Error communicating with server, connection timed out.");
});
}
#endregion
#region Protected Methods
protected virtual void PrepareRequest(RestClient client, RestRequest request)
{
client.BaseUrl = new Uri(BaseUrl);
#if !WINDOWS_PHONE_APP
request.RequestFormat = DataFormat.Json;
request.JsonSerializer = new Stencil.SDK.Serialization.NewtonSoftSerializer();
#endif
this.AddAuthorizationHeaders(client, request);
this.AddCustomHeaders(client, request);
}
protected virtual async Task<IRestResponse> ExecuteAsyncInternal(RestRequest request)
{
RestClient client = new RestClient();
this.PrepareRequest(client, request);
IRestResponse response = await client.ExecuteTaskAsync(request);
this.ValidateResponse(response);
return response;
}
protected virtual async Task<T> ExecuteAsyncInternal<T>(RestRequest request)
where T : new()
{
RestClient client = new RestClient();
#if WINDOWS_PHONE_APP
client.IgnoreResponseStatusCode = true;
#endif
this.PrepareRequest(client, request);
#if DEBUG && __MOBILE__
Console.WriteLine("------> Calling Server: " + request.Resource);
#endif
IRestResponse response = await client.ExecuteTaskAsync(request);
this.ValidateResponse(response);
#if WINDOWS_PHONE_APP
string content = response.GetContent();
#else
string content = response.Content;
#endif
return JsonConvert.DeserializeObject<T>(content);
}
protected virtual void AddCustomHeaders(RestClient client, RestRequest request)
{
if (this.CustomHeaders != null)
{
foreach (var item in this.CustomHeaders)
{
if (!string.IsNullOrEmpty(item.Key))
{
client.AddDefaultHeader(item.Key, item.Value);
}
}
}
}
protected virtual void AddAuthorizationHeaders(RestClient client, RestRequest request)
{
List<KeyValuePair<string, string>> authHeaders = this.GenerateAuthorizationHeader();
foreach (var item in authHeaders)
{
client.AddDefaultHeader(item.Key, item.Value);
}
if (!string.IsNullOrEmpty(this.ApplicationKey) && !string.IsNullOrEmpty(this.ApplicationSecret))
{
client.AddDefaultHeader(API_PARAM_SIG, this.SignatureGenerator.CreateSignature(this.ApplicationKey, this.ApplicationSecret));
}
}
public virtual List<KeyValuePair<string, string>> GenerateAuthorizationHeader()
{
List<KeyValuePair<string, string>> headers = new List<KeyValuePair<string, string>>();
if (!string.IsNullOrEmpty(this.ApplicationKey) && !string.IsNullOrEmpty(this.ApplicationSecret))
{
headers.Add(new KeyValuePair<string, string>(API_PARAM_KEY, this.ApplicationKey));
headers.Add(new KeyValuePair<string, string>(API_PARAM_SIG, this.SignatureGenerator.CreateSignature(this.ApplicationKey, this.ApplicationSecret)));
}
return headers;
}
protected virtual void ValidateResponse(IRestResponse response)
{
switch (response.StatusCode)
{
case System.Net.HttpStatusCode.Continue:
case System.Net.HttpStatusCode.Accepted:
case System.Net.HttpStatusCode.Created:
case System.Net.HttpStatusCode.NoContent:
case System.Net.HttpStatusCode.NotModified:
case System.Net.HttpStatusCode.OK:
// do nothing
break;
default:
throw new EndpointException(response.StatusCode, response.StatusDescription);
}
#if !WINDOWS_PHONE_APP
if (response.ErrorException != null)
{
throw new ApplicationException("Error retrieving response. Check inner details for more info.", response.ErrorException);
}
#endif
}
#endregion
}
}
#endif | 33.894495 | 163 | 0.595886 | [
"MIT"
] | DanMasterson1/stencil | Source/Stencil.Server/Stencil.SDK.Shared/StencilSDK_Sharp.cs | 7,391 | C# |
/*
* Exchange Web Services Managed API
*
* Copyright (c) Microsoft Corporation
* All rights reserved.
*
* MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this
* software and associated documentation files (the "Software"), to deal in the Software
* without restriction, including without limitation the rights to use, copy, modify, merge,
* publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
* to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
* FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
namespace Microsoft.Exchange.WebServices.Data.Groups
{
/// <summary>
/// Defines the RequestedUnifiedGroupsSet class.
/// </summary>
public sealed class RequestedUnifiedGroupsSet : ComplexProperty, ISelfValidate
{
/// <summary>
/// Initializes a new instance of the <see cref="RequestedUnifiedGroupsSet"/> class.
/// </summary>
public RequestedUnifiedGroupsSet()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="RequestedUnifiedGroupsSet"/> class.
/// </summary>
/// <param name="filterType">The filterType for the list of groups to be returned</param>
/// <param name="sortType">The sort type for the list of groups to be returned</param>
/// <param name="sortDirection">The sort direction for list of groups to be returned</param>
public RequestedUnifiedGroupsSet(
UnifiedGroupsFilterType filterType,
UnifiedGroupsSortType sortType,
SortDirection sortDirection)
{
this.FilterType = filterType;
this.SortType = sortType;
this.SortDirection = sortDirection;
}
/// <summary>
/// Gets or sets the sort type for the list of groups to be returned
/// </summary>
public UnifiedGroupsSortType SortType { get; set; }
/// <summary>
/// Gets or sets the filter Type for the list of groups to be returned
/// </summary>
public UnifiedGroupsFilterType FilterType { get; set; }
/// <summary>
/// Gets or sets the Sort Direction for the list of groups to be returned.
/// </summary>
public SortDirection SortDirection { get; set; }
/// <summary>
/// Writes to XML.
/// </summary>
/// <param name="writer">The writer.</param>
/// <param name="xmlElementName">Name of the XML element.</param>
internal override void WriteToXml(EwsServiceXmlWriter writer, string xmlElementName)
{
writer.WriteStartElement(XmlNamespace.Types, xmlElementName);
writer.WriteElementValue(XmlNamespace.Types, XmlElementNames.SortType, this.SortType.ToString());
writer.WriteElementValue(XmlNamespace.Types, XmlElementNames.FilterType, this.FilterType.ToString());
writer.WriteElementValue(XmlNamespace.Types, XmlElementNames.SortDirection, this.SortDirection.ToString());
writer.WriteEndElement();
}
}
} | 43.302326 | 119 | 0.672664 | [
"MIT"
] | 4thOffice/ews-managed-api | Groups/ComplexProperties/RequestedUnifiedGroupsSet.cs | 3,724 | C# |
// The MIT License (MIT)
//
// Copyright (c) 2015-2018 Rasmus Mikkelsen
// Copyright (c) 2015-2018 eBay Software Foundation
// https://github.com/eventflow/EventFlow
//
// 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.Linq;
using System.Reflection;
using EventFlow.Jobs;
namespace EventFlow.Extensions
{
public static class EventFlowOptionsJobExtensions
{
public static IEventFlowOptions AddJobs(
this IEventFlowOptions eventFlowOptions,
params Type[] jobTypes)
{
return eventFlowOptions.AddJobs(jobTypes);
}
public static IEventFlowOptions AddJobs(
this IEventFlowOptions eventFlowOptions,
Assembly fromAssembly,
Predicate<Type> predicate = null)
{
predicate = predicate ?? (t => true);
var jobTypes = fromAssembly
.GetTypes()
.Where(type => !type.GetTypeInfo().IsAbstract && type.IsAssignableTo<IJob>())
.Where(t => !t.HasConstructorParameterOfType(i => i.IsAssignableTo<IJob>()))
.Where(t => predicate(t));
return eventFlowOptions.AddJobs(jobTypes);
}
}
} | 41.574074 | 93 | 0.691314 | [
"MIT"
] | AntonSmolkov/EventFlow | Source/EventFlow/Extensions/EventFlowOptionsJobExtensions.cs | 2,247 | C# |
// This file is part of Core WF which is licensed under the MIT license.
// See LICENSE file in the project root for full license information.
namespace System.Activities.Statements
{
using System.Activities;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Runtime.Serialization;
/// <summary>
/// StateMachineEventManager is used to manage triggered events globally.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses",
Justification = "This type is actually used in LINQ expression and FxCop didn't detect that.")]
[DataContract]
internal class StateMachineEventManager
{
// To avoid out of memory, set a fixed length of event queue.
private const int MaxQueueLength = 1 << 25;
// queue is used to store triggered events
private Queue<TriggerCompletedEvent> queue;
// If a state is running, its condition evaluation bookmark will be added in to activityBookmarks.
// If a state is completed, its bookmark will be removed.
private Collection<Bookmark> activeBookmarks;
/// <summary>
/// Constructor to do initialization.
/// </summary>
public StateMachineEventManager()
{
this.queue = new Queue<TriggerCompletedEvent>();
this.activeBookmarks = new Collection<Bookmark>();
}
/// <summary>
/// Gets or sets the trigger index of current being processed event.
/// </summary>
[DataMember(EmitDefaultValue = false)]
public TriggerCompletedEvent CurrentBeingProcessedEvent
{
get;
set;
}
/// <summary>
/// Gets or sets the CurrentConditionIndex denotes the index of condition is being evaluated.
/// </summary>
[DataMember(EmitDefaultValue = false)]
public int CurrentConditionIndex
{
get;
set;
}
/// <summary>
/// Gets or sets a value indicating whether StateMachine is on the way of transition.
/// </summary>
[DataMember(EmitDefaultValue = false)]
public bool OnTransition
{
get;
set;
}
/// <summary>
/// Gets the EventManager queue.
/// </summary>
public IEnumerable<TriggerCompletedEvent> Queue
{
get
{
return this.queue;
}
}
/// <summary>
/// Gets a value indicating whether StateMachineManger is ready to process an event immediately.
/// </summary>
private bool CanProcessEventImmediately
{
get
{
return this.CurrentBeingProcessedEvent == null && !this.OnTransition && this.queue.Count == 0;
}
}
[DataMember(EmitDefaultValue = false, Name = "queue")]
internal Queue<TriggerCompletedEvent> SerializedQueue
{
get { return this.queue; }
set { this.queue = value; }
}
[DataMember(EmitDefaultValue = false, Name = "activeBookmarks")]
internal Collection<Bookmark> SerializedActiveBookmarks
{
get { return this.activeBookmarks; }
set { this.activeBookmarks = value; }
}
/// <summary>
/// When StateMachine enters a state, condition evaluation bookmark of that state would be added to activeBookmarks collection.
/// </summary>
/// <param name="bookmark">Bookmark reference.</param>
public void AddActiveBookmark(Bookmark bookmark)
{
this.activeBookmarks.Add(bookmark);
}
/// <summary>
/// Gets next completed events queue.
/// </summary>
/// <returns>Top TriggerCompletedEvent item in the queue.</returns>
public TriggerCompletedEvent GetNextCompletedEvent()
{
while (this.queue.Any())
{
TriggerCompletedEvent completedEvent = this.queue.Dequeue();
if (this.activeBookmarks.Contains(completedEvent.Bookmark))
{
this.CurrentBeingProcessedEvent = completedEvent;
return completedEvent;
}
}
return null;
}
/// <summary>
/// This method is used to denote whether a given bookmark is referred by currently processed event.
/// </summary>
/// <param name="bookmark">Bookmark reference.</param>
/// <returns>True is the bookmark references to the event being processed.</returns>
public bool IsReferredByBeingProcessedEvent(Bookmark bookmark)
{
return this.CurrentBeingProcessedEvent != null && this.CurrentBeingProcessedEvent.Bookmark == bookmark;
}
/// <summary>
/// Register a completed event and returns whether the event could be processed immediately.
/// </summary>
/// <param name="completedEvent">TriggerCompletedEvent reference.</param>
/// <param name="canBeProcessedImmediately">True if the Condition can be evaluated.</param>
public void RegisterCompletedEvent(TriggerCompletedEvent completedEvent, out bool canBeProcessedImmediately)
{
canBeProcessedImmediately = this.CanProcessEventImmediately;
this.queue.Enqueue(completedEvent);
return;
}
/// <summary>
/// When StateMachine leaves a state, condition evaluation bookmark of that state would be removed from activeBookmarks collection.
/// </summary>
/// <param name="bookmark">Bookmark reference.</param>
public void RemoveActiveBookmark(Bookmark bookmark)
{
this.activeBookmarks.Remove(bookmark);
}
}
}
| 36.096386 | 139 | 0.606642 | [
"MIT"
] | DosSEdo/corewf | src/CoreWf/Statements/StateMachineEventManager.cs | 5,992 | C# |
using dnlib.DotNet;
using dnlib.DotNet.Emit;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TropicalDeobfuscator.Protections
{
internal class RemoveJunk
{
public static void Fix()
{
var module = DeobfuscatorContext.Module;
MethodDef intDecryptor = null;
MethodDef antiTamperMethod = null;
MethodDef antiDebugMethod = null;
var instrGlobal = module.GlobalType.FindOrCreateStaticConstructor().Body.Instructions;
foreach (TypeDef type in module.GetTypes().ToArray())
{
foreach(var method in type.Methods.ToArray())
{
if (method == DeobfuscatorContext.BoolDecryptionMethod)
module.Types.Remove(method.DeclaringType);
var someJunk = instrGlobal[0].Operand as MethodDef;
var someJunk2 = instrGlobal[1].Operand as MethodDef;
var someJunk3 = instrGlobal[2].Operand as MethodDef;
module.Types.Remove(someJunk.DeclaringType);
module.Types.Remove(someJunk2.DeclaringType);
module.Types.Remove(someJunk3.DeclaringType);
}
}
instrGlobal[0].OpCode = OpCodes.Nop;
instrGlobal[1].OpCode = OpCodes.Nop;
instrGlobal[2].OpCode = OpCodes.Nop;
}
}
}
| 30.22 | 98 | 0.588352 | [
"Apache-2.0"
] | Yeetret/MountainDeobfuscator | TropicalDeobfuscator/Protections/RemoveJunk.cs | 1,513 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Rendering;
using PertensaCo.Web.Attributes;
using PertensaCo.Web.Models;
using static PertensaCo.Common.Constants.EmployeeConstants;
using static PertensaCo.Common.Constants.GlobalConstants;
using static PertensaCo.Common.Constants.UserConstants;
namespace PertensaCo.Web.Areas.Personnel.Models
{
public class EmployeeHireViewModel : ViewModel
{
public EmployeeHireViewModel()
{
Departments = new List<SelectListItem>();
Managers = new List<SelectListItem>();
Profiles = new List<SelectListItem>();
Roles = new List<SelectListItem>();
}
[DataType(DataType.Date)]
[Display(Name = "Contract start")]
[Required(ErrorMessage = StringBlankErrorMessage)]
public DateTime DateHired { get; set; }
[DataType(DataType.Date)]
[Display(Name = "Contract end")]
public DateTime? DateRelieved { get; set; }
[Display(Name = "Department")]
[Required(ErrorMessage = StringBlankErrorMessage)]
public string DepartmentName { get; set; }
public IEnumerable<SelectListItem> Departments { get; set; }
[PersonalName]
[Display(Name = "First name")]
[Required(ErrorMessage = StringBlankErrorMessage)]
public string FirstName { get; set; }
[Display(Name = "Home address")]
[StringLength(AddressMaxLength)]
[Required(ErrorMessage = StringBlankErrorMessage)]
public string HomeAddress { get; set; }
[Display(Name = "Temporary contractor")]
public bool IsTemporary { get; set; }
[PersonalName]
[Display(Name = "Last name")]
[Required(ErrorMessage = StringBlankErrorMessage)]
public string LastName { get; set; }
[Display(Name = "Manager")]
[Required(ErrorMessage = StringBlankErrorMessage)]
public string ManagerId { get; set; }
public IEnumerable<SelectListItem> Managers { get; set; }
[PersonalName]
[Display(Name = "Middle name")]
[Required(ErrorMessage = StringBlankErrorMessage)]
public string MiddleName { get; set; }
[Display(Name = "Salary")]
[DataType(DataType.Currency)]
[Required(ErrorMessage = StringBlankErrorMessage)]
[Range(typeof(decimal), minimum: SalaryMinTextValue, maximum: SalaryMaxTextValue,
ErrorMessage = RangeErrorMessage)]
public decimal MonthlySalaryInEUR { get; set; }
public override string PageTitle => "New employee";
[Display(Name = "National ID")]
[Required(ErrorMessage = StringBlankErrorMessage)]
[RegularExpression(PersonalIdentificationNumberPattern,
ErrorMessage = FormatMismatchErrorMessage)]
public string PIN { get; set; }
[Display(Name = "Profile")]
public string ProfileId { get; set; }
[DataType(DataType.Upload)]
[Display(Name = "Profile picture")]
public IFormFile Portrait { get; set; }
public IEnumerable<SelectListItem> Profiles { get; set; }
[Display(Name = "Position")]
[Required(ErrorMessage = StringBlankErrorMessage)]
public string RoleName { get; set; }
public IEnumerable<SelectListItem> Roles { get; set; }
[Display(Name = "Office location")]
[StringLength(AddressMaxLength)]
[Required(ErrorMessage = StringBlankErrorMessage)]
public string WorkAddress { get; set; }
}
}
| 30.942308 | 83 | 0.739901 | [
"MIT"
] | AscenKeeprov/CSharp-MVC-Frameworks | XAM10012019/PertensaCo.Web/Areas/Personnel/Models/EmployeeHireViewModel.cs | 3,220 | C# |
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Sitecore.Commerce.Core;
using Sitecore.Framework.Pipelines;
namespace Sitecore.HabitatHome.Feature.Catalog.Engine.Pipelines.Blocks
{
[PipelineDisplayName(HabitatHomeConstants.Pipelines.Blocks.RegisteredPluginBlock)]
public class RegisteredPluginBlock : PipelineBlock<IEnumerable<RegisteredPluginModel>, IEnumerable<RegisteredPluginModel>, CommercePipelineExecutionContext>
{
/// <summary>
/// The run.
/// </summary>
/// <param name="arg">
/// The argument.
/// </param>
/// <param name="context">
/// The context.
/// </param>
/// <returns>
/// The list of <see cref="RegisteredPluginModel"/>
/// </returns>
public override Task<IEnumerable<RegisteredPluginModel>> Run(IEnumerable<RegisteredPluginModel> arg, CommercePipelineExecutionContext context)
{
if (arg == null)
{
return Task.FromResult((IEnumerable<RegisteredPluginModel>)null);
}
var plugins = arg.ToList();
PluginHelper.RegisterPlugin(this, plugins);
return Task.FromResult(plugins.AsEnumerable());
}
}
}
| 33.789474 | 160 | 0.639408 | [
"MPL-2.0"
] | vijayraavi/Sitecore.HabitatHome.Commerce | src/Feature/Catalog/engine/Pipelines/Blocks/RegisteredPluginBlock.cs | 1,286 | 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.GoogleNative.Ml.V1
{
/// <summary>
/// Creates a study.
/// Auto-naming is currently not supported for this resource.
/// </summary>
[GoogleNativeResourceType("google-native:ml/v1:Study")]
public partial class Study : Pulumi.CustomResource
{
/// <summary>
/// Time at which the study was created.
/// </summary>
[Output("createTime")]
public Output<string> CreateTime { get; private set; } = null!;
/// <summary>
/// A human readable reason why the Study is inactive. This should be empty if a study is ACTIVE or COMPLETED.
/// </summary>
[Output("inactiveReason")]
public Output<string> InactiveReason { get; private set; } = null!;
/// <summary>
/// The name of a study.
/// </summary>
[Output("name")]
public Output<string> Name { get; private set; } = null!;
/// <summary>
/// The detailed state of a study.
/// </summary>
[Output("state")]
public Output<string> State { get; private set; } = null!;
/// <summary>
/// Configuration of the study.
/// </summary>
[Output("studyConfig")]
public Output<Outputs.GoogleCloudMlV1__StudyConfigResponse> StudyConfig { get; private set; } = null!;
/// <summary>
/// Create a Study resource with the given unique name, arguments, and options.
/// </summary>
///
/// <param name="name">The unique name of the resource</param>
/// <param name="args">The arguments used to populate this resource's properties</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public Study(string name, StudyArgs args, CustomResourceOptions? options = null)
: base("google-native:ml/v1:Study", name, args ?? new StudyArgs(), MakeResourceOptions(options, ""))
{
}
private Study(string name, Input<string> id, CustomResourceOptions? options = null)
: base("google-native:ml/v1:Study", name, null, MakeResourceOptions(options, id))
{
}
private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id)
{
var defaultOptions = new CustomResourceOptions
{
Version = Utilities.Version,
};
var merged = CustomResourceOptions.Merge(defaultOptions, options);
// Override the ID if one was specified for consistency with other language SDKs.
merged.Id = id ?? merged.Id;
return merged;
}
/// <summary>
/// Get an existing Study resource's state with the given name, ID, and optional extra
/// properties used to qualify the lookup.
/// </summary>
///
/// <param name="name">The unique name of the resulting resource.</param>
/// <param name="id">The unique provider ID of the resource to lookup.</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public static Study Get(string name, Input<string> id, CustomResourceOptions? options = null)
{
return new Study(name, id, options);
}
}
public sealed class StudyArgs : Pulumi.ResourceArgs
{
[Input("location")]
public Input<string>? Location { get; set; }
[Input("project")]
public Input<string>? Project { get; set; }
/// <summary>
/// Configuration of the study.
/// </summary>
[Input("studyConfig", required: true)]
public Input<Inputs.GoogleCloudMlV1__StudyConfigArgs> StudyConfig { get; set; } = null!;
[Input("studyId", required: true)]
public Input<string> StudyId { get; set; } = null!;
public StudyArgs()
{
}
}
}
| 37.298246 | 118 | 0.599247 | [
"Apache-2.0"
] | AaronFriel/pulumi-google-native | sdk/dotnet/Ml/V1/Study.cs | 4,252 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Autofac;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace AutofacDemo
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
}
public void ConfigureContainer(ContainerBuilder builder)
{
// Add any Autofac modules or registrations.
// This is called after ConfigureServices so things
// registered here OVERRIDE things registered in ConfigureServices.
builder.RegisterModule(new AutofacRootModule());
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
| 28.984615 | 106 | 0.612527 | [
"MIT"
] | manoj-choudhari-git/dotnet-on-thecodeblogger | AutofacDemo/AutofacDemo/Startup.cs | 1,884 | C# |
using System;
using System.Collections.Generic;
using System.Data;//DataRowView,DataTable
using System.Linq;
using System.Text;
using Xenon.Syntax;//HumanInputFilePath,WarningReports
namespace Xenon.Table
{
/// <summary>
/// 縦棒「 | 」区切り文字列。
/// </summary>
public interface PipeSeparatedString
{
#region アクション
//────────────────────────────────────────
/// <summary>
/// 例えば、次の2つの物を与えると、
/// ●ID=10、EXPL=赤、と入っている行。
/// ●「%1%:%2%|ID|EXPL」という文字列。
///
/// すると、次の文字列が返ってくる。
/// ●「10:EXPL」
///
/// %1%はID、%2%はEXPLに当たる。
/// </summary>
/// <param name="sFormat"></param>
/// <param name="dataRowView"></param>
/// <param name="xenonTable"></param>
/// <param name="log_Reports"></param>
/// <returns></returns>
string Perform(
string sFormat,
DataRowView dataRowView,
Table_Humaninput xenonTable,
Log_Reports log_Reports
);
//────────────────────────────────────────
#endregion
}
}
| 21.75 | 54 | 0.481874 | [
"MIT"
] | muzudho/csharp-frame-memo | Csvexe_L02_Table/Project/CSharp_Interface/800_PipeStr/PipeSeparatedString.cs | 1,459 | C# |
//------------------------------------------------------------------------------
/// <copyright file="IVsOutputGroup.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
//---------------------------------------------------------------------------
// IVsProject.cs
//---------------------------------------------------------------------------
// WARNING: this file autogenerated
//---------------------------------------------------------------------------
// Copyright (c) 1999, Microsoft Corporation All Rights Reserved
// Information Contained Herein Is Proprietary and Confidential.
//---------------------------------------------------------------------------
namespace Microsoft.VisualStudio.Interop {
using System.Runtime.InteropServices;
using System.Diagnostics;
using System;
[
ComImport(),Guid("FCC03D95-7C2E-4398-AAAE-0F4B56104FC8"),
InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown),
CLSCompliant(false)
]
interface IVsOutputGroup
{
// These return identical information regardless of cfg setting:
void get_CanonicalName(out string pbstrCanonicalName);
void get_DisplayName(out string pbstrDisplayName);
// The results of these will vary based on the configuration:
void get_KeyOutput(out string pbstrCanonicalName);
// Back pointer to project cfg:
void get_ProjectCfg(out IVsProjectCfg2 ppIVsProjectCfg2);
// The list of outputs. There might be none! Not all files go out
// on every configuration, and a groups files might all be configuration
// dependent!
void get_Outputs(uint celt,
[In, Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex=0, ArraySubType=UnmanagedType.Interface)] object[] rgpcfg,
out uint pcActual);
void get_DeployDependencies(uint celt,
[In, Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex=0)] IVsDeployDependency[] rgpdpd,
out uint pcActual);
void get_Description(out string pbstrDescription);
}
}
| 44.166667 | 133 | 0.510273 | [
"Unlicense"
] | bestbat/Windows-Server | com/netfx/src/framework/vsdesigner/designer/microsoft/visualstudio/interop/ivsoutputgroup.cs | 2,385 | C# |
using MasterDevs.ChromeDevTools;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
namespace MasterDevs.ChromeDevTools.Protocol.Chrome.Debugger
{
/// <summary>
/// Defines pause on exceptions state. Can be set to stop on all exceptions, uncaught exceptions or
/// no exceptions. Initial pause on exceptions state is `none`.
/// </summary>
[Command(ProtocolName.Debugger.SetPauseOnExceptions)]
[SupportedBy("Chrome")]
public class SetPauseOnExceptionsCommand: ICommand<SetPauseOnExceptionsCommandResponse>
{
/// <summary>
/// Gets or sets Pause on exceptions mode.
/// </summary>
public string State { get; set; }
}
}
| 29.818182 | 100 | 0.754573 | [
"MIT"
] | Kim-SSi/ChromeDevToolsCore | main/MasterDevs.ChromeDevTools/Protocol/Chrome/Debugger/SetPauseOnExceptionsCommand.cs | 656 | C# |
// Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System.Collections;
using Avalonia.Controls.Generators;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives;
using Avalonia.Controls.Templates;
using Avalonia.Input;
using Avalonia.VisualTree;
namespace Avalonia.Controls
{
/// <summary>
/// An <see cref="ItemsControl"/> in which individual items can be selected.
/// </summary>
public class ListBox : SelectingItemsControl
{
/// <summary>
/// The default value for the <see cref="ItemsControl.ItemsPanel"/> property.
/// </summary>
private static readonly FuncTemplate<IPanel> DefaultPanel =
new FuncTemplate<IPanel>(() => new VirtualizingStackPanel());
/// <summary>
/// Defines the <see cref="Scroll"/> property.
/// </summary>
public static readonly DirectProperty<ListBox, IScrollable> ScrollProperty =
AvaloniaProperty.RegisterDirect<ListBox, IScrollable>(nameof(Scroll), o => o.Scroll);
/// <summary>
/// Defines the <see cref="SelectedItems"/> property.
/// </summary>
public static readonly new DirectProperty<SelectingItemsControl, IList> SelectedItemsProperty =
SelectingItemsControl.SelectedItemsProperty;
/// <summary>
/// Defines the <see cref="SelectionMode"/> property.
/// </summary>
public static readonly new StyledProperty<SelectionMode> SelectionModeProperty =
SelectingItemsControl.SelectionModeProperty;
/// <summary>
/// Defines the <see cref="VirtualizationMode"/> property.
/// </summary>
public static readonly StyledProperty<ItemVirtualizationMode> VirtualizationModeProperty =
ItemsPresenter.VirtualizationModeProperty.AddOwner<ListBox>();
private IScrollable _scroll;
/// <summary>
/// Initializes static members of the <see cref="ItemsControl"/> class.
/// </summary>
static ListBox()
{
ItemsPanelProperty.OverrideDefaultValue<ListBox>(DefaultPanel);
VirtualizationModeProperty.OverrideDefaultValue<ListBox>(ItemVirtualizationMode.Simple);
}
/// <summary>
/// Gets the scroll information for the <see cref="ListBox"/>.
/// </summary>
public IScrollable Scroll
{
get { return _scroll; }
private set { SetAndRaise(ScrollProperty, ref _scroll, value); }
}
/// <inheritdoc/>
public new IList SelectedItems
{
get => base.SelectedItems;
set => base.SelectedItems = value;
}
/// <summary>
/// Gets or sets the selection mode.
/// </summary>
/// <remarks>
/// Note that the selection mode only applies to selections made via user interaction.
/// Multiple selections can be made programatically regardless of the value of this property.
/// </remarks>
public new SelectionMode SelectionMode
{
get { return base.SelectionMode; }
set { base.SelectionMode = value; }
}
/// <summary>
/// Gets or sets the virtualization mode for the items.
/// </summary>
public ItemVirtualizationMode VirtualizationMode
{
get { return GetValue(VirtualizationModeProperty); }
set { SetValue(VirtualizationModeProperty, value); }
}
/// <summary>
/// Selects all items in the <see cref="ListBox"/>.
/// </summary>
public new void SelectAll() => base.SelectAll();
/// <summary>
/// Deselects all items in the <see cref="ListBox"/>.
/// </summary>
public new void UnselectAll() => base.UnselectAll();
/// <inheritdoc/>
protected override IItemContainerGenerator CreateItemContainerGenerator()
{
return new ItemContainerGenerator<ListBoxItem>(
this,
ListBoxItem.ContentProperty,
ListBoxItem.ContentTemplateProperty);
}
/// <inheritdoc/>
protected override void OnGotFocus(GotFocusEventArgs e)
{
base.OnGotFocus(e);
if (e.NavigationMethod == NavigationMethod.Directional)
{
e.Handled = UpdateSelectionFromEventSource(
e.Source,
true,
(e.InputModifiers & InputModifiers.Shift) != 0);
}
}
/// <inheritdoc/>
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
base.OnPointerPressed(e);
if (e.Source is IVisual source)
{
var point = e.GetCurrentPoint(source);
if (point.Properties.IsLeftButtonPressed || point.Properties.IsRightButtonPressed)
{
e.Handled = UpdateSelectionFromEventSource(
e.Source,
true,
(e.KeyModifiers & KeyModifiers.Shift) != 0,
(e.KeyModifiers & KeyModifiers.Control) != 0,
point.Properties.IsRightButtonPressed);
}
}
}
protected override void OnTemplateApplied(TemplateAppliedEventArgs e)
{
Scroll = e.NameScope.Find<IScrollable>("PART_ScrollViewer");
base.OnTemplateApplied(e);
}
}
}
| 35.54717 | 104 | 0.590057 | [
"MIT"
] | MarchingCube/Avalonia | src/Avalonia.Controls/ListBox.cs | 5,652 | C# |
using System;
namespace JedzenioPlanner.Api.Application.Common.Interfaces
{
public interface ICurrentUserService
{
string GetUserId();
}
} | 17.777778 | 59 | 0.7125 | [
"MIT"
] | JedzenioPlanner/JedzenioPlanner.Api | src/JedzenioPlanner.Api.Application/Common/Interfaces/ICurrentUserService.cs | 162 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
/// <summary>
/// Test binding of the target-typed conditional (aka ternary) operator.
/// </summary>
public class TargetTypedConditionalOperatorTests : CSharpTestBase
{
[Fact]
public void TestImplicitConversions_Good()
{
// NOTE: Some of these are currently error cases, but they would become accepted (non-error) cases
// if we extend the spec to permit target typing even when there is a natural type. Until then,
// they are error cases but included here for convenience.
// Implicit constant expression conversions
TestConditional("b ? 1 : 2", "System.Int16", "System.Int32",
// (6,26): error CS0266: Cannot implicitly convert type 'int' to 'short'. An explicit conversion exists (are you missing a cast?)
// System.Int16 t = b ? 1 : 2;
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "b ? 1 : 2").WithArguments("int", "short").WithLocation(6, 26));
TestConditional("b ? -1L : 1UL", "System.Double", null);
// Implicit reference conversions
TestConditional("b ? GetB() : GetC()", "A", null);
TestConditional("b ? Get<IOut<B>>() : Get<IOut<C>>()", "IOut<A>", null);
TestConditional("b ? Get<IOut<IOut<B>>>() : Get<IOut<IOut<C>>>()", "IOut<IOut<A>>", null);
TestConditional("b ? Get<IOut<B[]>>() : Get<IOut<C[]>>()", "IOut<A[]>", null);
TestConditional("b ? Get<U>() : Get<V>()", "T", null);
// Implicit numeric conversions
TestConditional("b ? GetUInt() : GetInt()", "System.Int64", null);
// Implicit enumeration conversions
TestConditional("b ? 0 : 0", "color", "System.Int32",
// (6,19): error CS0266: Cannot implicitly convert type 'int' to 'color'. An explicit conversion exists (are you missing a cast?)
// color t = b ? 0 : 0;
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "b ? 0 : 0").WithArguments("int", "color").WithLocation(6, 19));
// Implicit interpolated string conversions
TestConditional(@"b ? $""x"" : $""x""", "System.FormattableString", "System.String",
// (6,38): error CS0029: Cannot implicitly convert type 'string' to 'System.FormattableString'
// System.FormattableString t = b ? $"x" : $"x";
Diagnostic(ErrorCode.ERR_NoImplicitConv, @"b ? $""x"" : $""x""").WithArguments("string", "System.FormattableString").WithLocation(6, 38));
// Implicit nullable conversions
// Null literal conversions
TestConditional("b ? 1 : null", "System.Int64?", null);
// Boxing conversions
TestConditional("b ? GetUInt() : GetInt()", "System.IComparable", null);
// User - defined implicit conversions
TestConditional("b ? GetB() : GetC()", "X", null);
// Anonymous function conversions
TestConditional("b ? a=>a : b=>b", "Del", null);
// Method group conversions
TestConditional("b ? M1 : M2", "Del", null);
// Pointer conversions
TestConditional("b ? GetIntp() : GetLongp()", "void*", null);
TestConditional("b ? null : null", "System.Int32*", null);
}
[Fact]
public void TestImplicitConversions_Bad()
{
// Implicit constant expression conversions
TestConditional("b ? 1000000 : 2", "System.Int16", "System.Int32",
// (6,26): error CS0266: Cannot implicitly convert type 'int' to 'short'. An explicit conversion exists (are you missing a cast?)
// System.Int16 t = b ? 1000000 : 2;
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "b ? 1000000 : 2").WithArguments("int", "short").WithLocation(6, 26)
);
// Implicit reference conversions
TestConditional("b ? GetB() : GetC()", "System.String", null,
// (6,31): error CS0029: Cannot implicitly convert type 'B' to 'string'
// System.String t = b ? GetB() : GetC();
Diagnostic(ErrorCode.ERR_NoImplicitConv, "GetB()").WithArguments("B", "string").WithLocation(6, 31),
// (6,40): error CS0029: Cannot implicitly convert type 'C' to 'string'
// System.String t = b ? GetB() : GetC();
Diagnostic(ErrorCode.ERR_NoImplicitConv, "GetC()").WithArguments("C", "string").WithLocation(6, 40)
);
// Implicit numeric conversions
TestConditional("b ? GetUInt() : GetInt()", "System.UInt64", null,
// (6,43): error CS0029: Cannot implicitly convert type 'int' to 'ulong'
// System.UInt64 t = b ? GetUInt() : GetInt();
Diagnostic(ErrorCode.ERR_NoImplicitConv, "GetInt()").WithArguments("int", "ulong").WithLocation(6, 43)
);
// Implicit enumeration conversions
TestConditional("b ? 1 : 0", "color", "System.Int32",
// (6,19): error CS0266: Cannot implicitly convert type 'int' to 'color'. An explicit conversion exists (are you missing a cast?)
// color t = b ? 1 : 0;
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "b ? 1 : 0").WithArguments("int", "color").WithLocation(6, 19)
);
// Implicit interpolated string conversions
TestConditional(@"b ? $""x"" : ""x""", "System.FormattableString", "System.String",
// (6,38): error CS0029: Cannot implicitly convert type 'string' to 'System.FormattableString'
// System.FormattableString t = b ? $"x" : "x";
Diagnostic(ErrorCode.ERR_NoImplicitConv, @"b ? $""x"" : ""x""").WithArguments("string", "System.FormattableString").WithLocation(6, 38)
);
// Implicit nullable conversions
// Null literal conversions
TestConditional(@"b ? """" : null", "System.Int64?", "System.String",
// (6,27): error CS0029: Cannot implicitly convert type 'string' to 'long?'
// System.Int64? t = b ? "" : null;
Diagnostic(ErrorCode.ERR_NoImplicitConv, @"b ? """" : null").WithArguments("string", "long?").WithLocation(6, 27)
);
TestConditional(@"b ? 1 : """"", "System.Int64?", null,
// (6,35): error CS0029: Cannot implicitly convert type 'string' to 'long?'
// System.Int64? t = b ? 1 : "";
Diagnostic(ErrorCode.ERR_NoImplicitConv, @"""""").WithArguments("string", "long?").WithLocation(6, 35)
);
// Boxing conversions
TestConditional("b ? GetUInt() : GetInt()", "System.Collections.IList", null,
// (6,42): error CS0029: Cannot implicitly convert type 'uint' to 'System.Collections.IList'
// System.Collections.IList t = b ? GetUInt() : GetInt();
Diagnostic(ErrorCode.ERR_NoImplicitConv, "GetUInt()").WithArguments("uint", "System.Collections.IList").WithLocation(6, 42),
// (6,54): error CS0029: Cannot implicitly convert type 'int' to 'System.Collections.IList'
// System.Collections.IList t = b ? GetUInt() : GetInt();
Diagnostic(ErrorCode.ERR_NoImplicitConv, "GetInt()").WithArguments("int", "System.Collections.IList").WithLocation(6, 54)
);
// User - defined implicit conversions
TestConditional("b ? GetB() : GetD()", "X", null,
// (6,28): error CS0619: 'D.implicit operator X(D)' is obsolete: 'D'
// X t = b ? GetB() : GetD();
Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "GetD()").WithArguments("D.implicit operator X(D)", "D").WithLocation(6, 28)
);
// Anonymous function conversions
TestConditional(@"b ? a=>a : b=>""""", "Del", null,
// (6,31): error CS0029: Cannot implicitly convert type 'string' to 'int'
// Del t = b ? a=>a : b=>"";
Diagnostic(ErrorCode.ERR_NoImplicitConv, @"""""").WithArguments("string", "int").WithLocation(6, 31),
// (6,31): error CS1662: Cannot convert lambda expression to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type
// Del t = b ? a=>a : b=>"";
Diagnostic(ErrorCode.ERR_CantConvAnonMethReturns, @"""""").WithArguments("lambda expression").WithLocation(6, 31)
);
// Method group conversions
TestConditional("b ? M1 : M3", "Del", null,
// (6,26): error CS0123: No overload for 'M3' matches delegate 'Del'
// Del t = b ? M1 : M3;
Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "M3").WithArguments("M3", "Del").WithLocation(6, 26)
);
}
[Fact]
public void NonBreakingChange_01()
{
var source = @"
class C
{
static void M(short x) => System.Console.WriteLine(""M(short)"");
static void M(long l) => System.Console.WriteLine(""M(long)"");
static void Main()
{
bool b = true;
M(b ? 1 : 2); // should call M(long)
}
}
";
foreach (var langVersion in new[] { LanguageVersion.CSharp8, MessageID.IDS_FeatureTargetTypedConditional.RequiredVersion() })
{
var comp = CreateCompilation(
source, options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular.WithLanguageVersion(langVersion))
.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "M(long)");
}
}
[Fact]
public void NonBreakingChange_02()
{
var source = @"
class C
{
static void M(short x, short y) { }
static void M(long x, long y) { }
static void Main()
{
bool b = true;
M(b ? 1 : 2, 1);
}
}
";
foreach (var langVersion in new[] { LanguageVersion.CSharp8, MessageID.IDS_FeatureTargetTypedConditional.RequiredVersion() })
{
var comp = CreateCompilation(
source, options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular.WithLanguageVersion(langVersion))
.VerifyDiagnostics();
}
}
[Fact]
public void NonBreakingChange_03()
{
var source = @"
class C
{
static void Main()
{
bool b = true;
_ = (short)(b ? 1 : 2);
}
}
";
foreach (var langVersion in new[] { LanguageVersion.CSharp8, MessageID.IDS_FeatureTargetTypedConditional.RequiredVersion() })
{
var comp = CreateCompilation(
source, options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular.WithLanguageVersion(langVersion))
.VerifyDiagnostics(
);
}
}
[Fact]
public void NonBreakingChange_04()
{
var source = @"
class Program
{
static void Main()
{
M(true, new A(), new B());
}
static void M(bool x, A a, B b)
{
_ = (C)(x ? a : b);
}
}
class A
{
public static implicit operator B(A a) { System.Console.WriteLine(""A->B""); return new B(); }
public static implicit operator C(A a) { System.Console.WriteLine(""A->C""); return new C(); }
}
class B
{
public static implicit operator C(B b) { System.Console.WriteLine(""B->C""); return new C(); }
}
class C { }
";
foreach (var langVersion in new[] { LanguageVersion.CSharp8, MessageID.IDS_FeatureTargetTypedConditional.RequiredVersion() })
{
var comp = CreateCompilation(
source, options: TestOptions.ReleaseExe,
parseOptions: TestOptions.Regular.WithLanguageVersion(langVersion))
.VerifyDiagnostics(
);
CompileAndVerify(comp, expectedOutput:
@"A->B
B->C");
}
}
private static void TestConditional(string conditionalExpression, string targetType, string? naturalType, params DiagnosticDescription[] expectedDiagnostics)
{
TestConditional(conditionalExpression, targetType, naturalType, null, expectedDiagnostics);
}
private static void TestConditional(
string conditionalExpression,
string targetType,
string? naturalType,
CSharpParseOptions? parseOptions,
params DiagnosticDescription[] expectedDiagnostics)
{
string source = $@"
class Program
{{
unsafe void Test<T, U, V>(bool b) where T : class where U : class, T where V : class, T
{{
{targetType} t = {conditionalExpression};
Use(t);
}}
A GetA() {{ return null; }}
B GetB() {{ return null; }}
C GetC() {{ return null; }}
D GetD() {{ return null; }}
int GetInt() {{ return 1; }}
uint GetUInt() {{ return 1; }}
T Get<T>() where T : class {{ return null; }}
void Use(object t) {{ }}
unsafe void Use(void* t) {{ }}
unsafe int* GetIntp() {{ return null; }}
unsafe long* GetLongp() {{ return null; }}
static int M1(int x) => x;
static int M2(int x) => x;
static int M3(int x, int y) => x;
}}
public enum color {{ Red, Blue, Green }};
class A {{ }}
class B : A {{ public static implicit operator X(B self) => new X(); }}
class C : A {{ public static implicit operator X(C self) => new X(); }}
class D : A {{ [System.Obsolete(""D"", true)] public static implicit operator X(D self) => new X(); }}
class X {{ }}
interface IOut<out T> {{ }}
interface IIn<in T> {{ }}
delegate int Del(int x);
";
parseOptions ??= TestOptions.Regular;
parseOptions = parseOptions.WithLanguageVersion(MessageID.IDS_FeatureTargetTypedConditional.RequiredVersion());
var tree = Parse(source, options: parseOptions);
var comp = CreateCompilation(tree, options: TestOptions.DebugDll.WithAllowUnsafe(true));
comp.VerifyDiagnostics(expectedDiagnostics);
var compUnit = tree.GetCompilationUnitRoot();
var classC = (TypeDeclarationSyntax)compUnit.Members.First();
var methodTest = (MethodDeclarationSyntax)classC.Members.First();
var stmt = (LocalDeclarationStatementSyntax)methodTest.Body!.Statements.First();
var conditionalExpr = (ConditionalExpressionSyntax)stmt.Declaration.Variables[0].Initializer!.Value;
var model = comp.GetSemanticModel(tree);
if (naturalType is null)
{
var actualType = model.GetTypeInfo(conditionalExpr).Type;
if (actualType is { })
{
Assert.NotEmpty(expectedDiagnostics);
Assert.Equal("?", actualType.ToTestDisplayString(includeNonNullable: false));
}
}
else
{
Assert.Equal(naturalType, model.GetTypeInfo(conditionalExpr).Type.ToTestDisplayString(includeNonNullable: false));
}
var convertedType = targetType switch { "void*" => "System.Void*", _ => targetType };
Assert.Equal(convertedType, model.GetTypeInfo(conditionalExpr).ConvertedType.ToTestDisplayString(includeNonNullable: false));
if (!expectedDiagnostics.Any())
{
Assert.Equal(SpecialType.System_Boolean, model.GetTypeInfo(conditionalExpr.Condition).Type!.SpecialType);
Assert.Equal(convertedType, model.GetTypeInfo(conditionalExpr.WhenTrue).ConvertedType.ToTestDisplayString(includeNonNullable: false)); //in parent to catch conversion
Assert.Equal(convertedType, model.GetTypeInfo(conditionalExpr.WhenFalse).ConvertedType.ToTestDisplayString(includeNonNullable: false)); //in parent to catch conversion
}
}
[Fact, WorkItem(45460, "https://github.com/dotnet/roslyn/issues/45460")]
public void TestConstantConditional()
{
var source = @"
using System;
public class Program {
static void Main()
{
Test1();
Test2();
}
public static void Test1() {
const bool b = true;
uint u1 = M1<uint>(b ? 1 : 0);
Console.WriteLine(u1); // 1
uint s1 = M2(b ? 2 : 3);
Console.WriteLine(s1); // 2
uint u2 = b ? 4 : 5;
Console.WriteLine(u2); // 4
static uint M2(uint t) => t;
}
public static void Test2() {
const bool b = true;
short s1 = M1<short>(b ? 1 : 0);
Console.WriteLine(s1); // 1
short s2 = M2(b ? 2 : 3);
Console.WriteLine(s2); // 2
short s3 = b ? 4 : 5;
Console.WriteLine(s3); // 4
static short M2(short t) => t;
}
public static T M1<T>(T t) => t;
}";
var expectedOutput = @"
1
2
4
1
2
4";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8, options: TestOptions.DebugExe)
.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: expectedOutput);
comp = CreateCompilation(source, parseOptions: TestOptions.Regular.WithLanguageVersion(MessageID.IDS_FeatureTargetTypedConditional.RequiredVersion()), options: TestOptions.DebugExe)
.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: expectedOutput);
}
[Fact, WorkItem(46231, "https://github.com/dotnet/roslyn/issues/46231")]
public void TestFixedConditional()
{
var source = @"
public class Program {
public unsafe static void Test(bool b, int i)
{
fixed (byte * p = b ? new byte[i] : null)
{
}
}
}";
CreateCompilation(source, parseOptions: TestOptions.Regular8, options: TestOptions.DebugDll.WithAllowUnsafe(true))
.VerifyEmitDiagnostics();
CreateCompilation(source, parseOptions: TestOptions.Regular.WithLanguageVersion(MessageID.IDS_FeatureTargetTypedConditional.RequiredVersion()), options: TestOptions.DebugDll.WithAllowUnsafe(true))
.VerifyEmitDiagnostics();
}
[Fact]
public void TestUsingConditional()
{
var source = @"
using System;
public class Program {
public static void Test(bool b, IDisposable d)
{
using (IDisposable x = b ? d : null)
{
}
}
}";
CreateCompilation(source, parseOptions: TestOptions.Regular8, options: TestOptions.DebugDll)
.VerifyEmitDiagnostics();
CreateCompilation(source, parseOptions: TestOptions.Regular.WithLanguageVersion(MessageID.IDS_FeatureTargetTypedConditional.RequiredVersion()), options: TestOptions.DebugDll)
.VerifyEmitDiagnostics();
}
[Theory]
[InlineData("sbyte", "System.Int32", "System.SByte")]
[InlineData("short", "System.Int32", "System.Int16")]
[InlineData("int", "System.Int32", "System.Int32")]
[InlineData("long", "System.Int64", "System.Int64")]
[InlineData("byte", "System.Int32", "System.Byte")]
[InlineData("ushort", "System.Int32", "System.UInt16")]
[WorkItem(49598, "https://github.com/dotnet/roslyn/issues/49598")]
public void IntType_01(string sourceType, string resultType1, string resultType2)
{
var source =
$@"class Program
{{
static void Main()
{{
{sourceType}? a = 1;
var b = true;
var c1 = a ?? (b ? 2 : 3);
var c2 = a ?? (true ? 2 : 3);
var c3 = a ?? (false ? 2 : 3);
Report(c1);
Report(c2);
Report(c3);
}}
static void Report(object obj)
{{
System.Console.WriteLine(""{{0}}: {{1}}"", obj.GetType().FullName, obj);
}}
}}";
var expectedOutput =
$@"{resultType1}: 1
{resultType2}: 1
{resultType2}: 1";
CompileAndVerify(source, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp3), expectedOutput: expectedOutput);
CompileAndVerify(source, parseOptions: TestOptions.Regular.WithLanguageVersion(MessageID.IDS_FeatureTargetTypedConditional.RequiredVersion()), expectedOutput: expectedOutput);
}
[Theory]
[InlineData("uint")]
[InlineData("ulong")]
[WorkItem(49598, "https://github.com/dotnet/roslyn/issues/49598")]
public void IntType_02(string sourceType)
{
var source =
$@"class Program
{{
static void Main()
{{
{sourceType}? a = 1;
var b = true;
var c1 = a ?? (b ? 2 : 3);
var c2 = a ?? (true ? 2 : 3);
var c3 = a ?? (false ? 2 : 3);
Report(c1);
Report(c2);
Report(c3);
}}
static void Report(object obj)
{{
System.Console.WriteLine(""{{0}}: {{1}}"", obj.GetType().FullName, obj);
}}
}}";
var expectedDiagnostics = new DiagnosticDescription[]
{
// (7,18): error CS0019: Operator '??' cannot be applied to operands of type 'uint?' and 'int'
// var c1 = a ?? (b ? 2 : 3);
Diagnostic(ErrorCode.ERR_BadBinaryOps, "a ?? (b ? 2 : 3)").WithArguments("??", $"{sourceType}?", "int").WithLocation(7, 18)
};
CreateCompilation(source, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp3)).VerifyDiagnostics(expectedDiagnostics);
CreateCompilation(source, parseOptions: TestOptions.Regular.WithLanguageVersion(MessageID.IDS_FeatureTargetTypedConditional.RequiredVersion())).VerifyDiagnostics(expectedDiagnostics);
}
[Fact]
[WorkItem(49598, "https://github.com/dotnet/roslyn/issues/49598")]
public void IntType_03()
{
var source =
@"class Program
{
static void Main()
{
char? a = 'A';
var b = true;
var c1 = a ?? (b ? 'B' : 'C');
var c2 = a ?? (true ? 'B' : 'C');
var c3 = a ?? (false ? 'B' : 'C');
Report(c1);
Report(c2);
Report(c3);
}
static void Report(object obj)
{
System.Console.WriteLine(""{0}: {1}"", obj.GetType().FullName, obj);
}
}";
var expectedOutput =
@"System.Char: A
System.Char: A
System.Char: A";
CompileAndVerify(source, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp3), expectedOutput: expectedOutput);
CompileAndVerify(source, parseOptions: TestOptions.Regular.WithLanguageVersion(MessageID.IDS_FeatureTargetTypedConditional.RequiredVersion()), expectedOutput: expectedOutput);
}
[Fact]
[WorkItem(49598, "https://github.com/dotnet/roslyn/issues/49598")]
public void IntType_04()
{
var source =
@"class Program
{
static void Main()
{
char? a = 'A';
var b = true;
var c1 = a ?? (b ? 0 : 0);
var c2 = a ?? (true ? 0 : 0);
var c3 = a ?? (false ? 0 : 0);
Report(c1);
Report(c2);
Report(c3);
}
static void Report(object obj)
{
System.Console.WriteLine(""{0}: {1}"", obj.GetType().FullName, obj);
}
}";
var expectedOutput =
@"System.Int32: 65
System.Int32: 65
System.Int32: 65";
CompileAndVerify(source, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp3), expectedOutput: expectedOutput);
CompileAndVerify(source, parseOptions: TestOptions.Regular.WithLanguageVersion(MessageID.IDS_FeatureTargetTypedConditional.RequiredVersion()), expectedOutput: expectedOutput);
}
[Fact]
[WorkItem(49627, "https://github.com/dotnet/roslyn/issues/49627")]
public void UserDefinedConversions_01()
{
var source =
@"struct A
{
public static implicit operator A(short s) => throw null;
public static implicit operator int(A a) => throw null;
public static A operator+(A x, A y) => throw null;
}
struct B
{
public static implicit operator B(int i) => throw null;
}
class Program
{
static B F(bool b, A a)
{
return (b ? a : 0) + a;
}
}";
CreateCompilation(source, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_3)).VerifyDiagnostics();
CreateCompilation(source, parseOptions: TestOptions.Regular.WithLanguageVersion(MessageID.IDS_FeatureTargetTypedConditional.RequiredVersion())).VerifyDiagnostics();
}
[Fact]
[WorkItem(49627, "https://github.com/dotnet/roslyn/issues/49627")]
public void UserDefinedConversions_02()
{
var source =
@"struct A
{
public static implicit operator A(int i) => throw null;
public static implicit operator int(A a) => throw null;
public static A operator+(A x, A y) => throw null;
}
struct B
{
public static implicit operator B(int i) => throw null;
}
class Program
{
static B F(bool b, A a)
{
return (b ? a : 0) + a;
}
}";
CreateCompilation(source, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_3)).VerifyDiagnostics(
// (15,16): error CS0029: Cannot implicitly convert type 'A' to 'B'
// return (b ? a : 0) + a;
Diagnostic(ErrorCode.ERR_NoImplicitConv, "(b ? a : 0) + a").WithArguments("A", "B").WithLocation(15, 16),
// (15,17): error CS8370: Feature 'target-typed conditional expression' is not available in C# 7.3. Please use language version 9.0 or greater.
// return (b ? a : 0) + a;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "b ? a : 0").WithArguments("target-typed conditional expression", "9.0").WithLocation(15, 17));
CreateCompilation(source, parseOptions: TestOptions.Regular.WithLanguageVersion(MessageID.IDS_FeatureTargetTypedConditional.RequiredVersion())).VerifyDiagnostics(
// (15,16): error CS0029: Cannot implicitly convert type 'A' to 'B'
// return (b ? a : 0) + a;
Diagnostic(ErrorCode.ERR_NoImplicitConv, "(b ? a : 0) + a").WithArguments("A", "B").WithLocation(15, 16));
}
[Fact]
public void NaturalType_01()
{
var source =
@"class Program
{
static void F(bool b, object x, string y)
{
_ = b ? x : y;
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics();
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var expr = tree.GetRoot().DescendantNodes().OfType<ConditionalExpressionSyntax>().Single();
var typeInfo = model.GetTypeInfo(expr);
Assert.Equal("System.Object", typeInfo.Type.ToTestDisplayString());
Assert.Equal("System.Object", typeInfo.ConvertedType.ToTestDisplayString());
}
[Fact]
public void NaturalType_02()
{
var source =
@"class Program
{
static void F(bool b, int x)
{
int? y = b ? x : null;
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics();
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var expr = tree.GetRoot().DescendantNodes().OfType<ConditionalExpressionSyntax>().Single();
var typeInfo = model.GetTypeInfo(expr);
Assert.Null(typeInfo.Type);
Assert.Equal("System.Int32?", typeInfo.ConvertedType.ToTestDisplayString());
}
}
}
| 41.165468 | 208 | 0.581475 | [
"MIT"
] | Acidburn0zzz/roslyn | src/Compilers/CSharp/Test/Semantic/Semantics/TargetTypedConditionalOperatorTests.cs | 28,612 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using NuGet.Common;
using NuGet.Configuration;
using NuGet.Packaging;
using NuGet.ProjectModel;
using NuGet.Protocol;
using NuGet.Protocol.Core.Types;
using NuGet.Shared;
namespace NuGet.Commands
{
public class RestoreArgs
{
public string ConfigFile { get; set; }
public IMachineWideSettings MachineWideSettings { get; set; }
public string GlobalPackagesFolder { get; set; }
public bool? IsLowercaseGlobalPackagesFolder { get; set; }
public bool DisableParallel { get; set; }
public bool AllowNoOp {get; set;}
public HashSet<string> Runtimes { get; set; } = new HashSet<string>(StringComparer.Ordinal);
public HashSet<string> FallbackRuntimes { get; set; } = new HashSet<string>(StringComparer.Ordinal);
public List<string> Inputs { get; set; } = new List<string>();
public SourceCacheContext CacheContext { get; set; }
public ILogger Log { get; set; }
/// <summary>
/// Sources to use for restore. This is not used if SourceRepositories contains the
/// already built SourceRepository objects.
/// </summary>
public List<string> Sources { get; set; } = new List<string>();
public CachingSourceProvider CachingSourceProvider { get; set; }
public List<IRestoreRequestProvider> RequestProviders { get; set; } = new List<IRestoreRequestProvider>();
public List<IPreLoadedRestoreRequestProvider> PreLoadedRequestProviders { get; set; } = new List<IPreLoadedRestoreRequestProvider>();
public PackageSaveMode PackageSaveMode { get; set; } = PackageSaveMode.Defaultv3;
public int? LockFileVersion { get; set; }
public bool? ValidateRuntimeAssets { get; set; }
public bool HideWarningsAndErrors { get; set; } = false;
public Guid ParentId { get; set; }
public bool IsRestoreOriginalAction { get; set; } = true;
public bool RestoreForceEvaluate { get; set; }
// Cache directory -> ISettings
private ConcurrentDictionary<string, ISettings> _settingsCache
= new ConcurrentDictionary<string, ISettings>(StringComparer.Ordinal);
// ISettings.Root -> SourceRepositories
private ConcurrentDictionary<string, List<SourceRepository>> _sourcesCache
= new ConcurrentDictionary<string, List<SourceRepository>>(StringComparer.Ordinal);
public ISettings GetSettings(string projectDirectory)
{
if (string.IsNullOrEmpty(ConfigFile))
{
return _settingsCache.GetOrAdd(projectDirectory, (dir) =>
{
return Settings.LoadDefaultSettings(dir,
configFileName : null,
machineWideSettings: MachineWideSettings);
});
}
else
{
var configFileFullPath = Path.GetFullPath(ConfigFile);
var directory = Path.GetDirectoryName(configFileFullPath);
var configFileName = Path.GetFileName(configFileFullPath);
return _settingsCache.GetOrAdd(directory, (dir) =>
{
return Settings.LoadSpecificSettings(dir,
configFileName: configFileName);
});
}
}
public string GetEffectiveGlobalPackagesFolder(string rootDirectory, ISettings settings)
{
if (!string.IsNullOrEmpty(GlobalPackagesFolder))
{
// Resolve as relative to the CWD
return Path.GetFullPath(GlobalPackagesFolder);
}
// Load from environment, nuget.config or default location, and resolve relative paths
// to the project root.
var globalPath = SettingsUtility.GetGlobalPackagesFolder(settings);
return Path.GetFullPath(Path.Combine(rootDirectory, globalPath));
}
public IReadOnlyList<string> GetEffectiveFallbackPackageFolders(ISettings settings)
{
return SettingsUtility.GetFallbackPackageFolders(settings);
}
/// <summary>
/// Uses either Sources or Settings, and then adds Fallback sources.
/// </summary>
internal List<SourceRepository> GetEffectiveSources(ISettings settings, IList<PackageSource> dgSpecSources)
{
if (settings == null)
{
throw new ArgumentNullException(nameof(settings));
}
var values = settings.GetConfigRoots();
if(dgSpecSources != null)
{
values.AddRange(dgSpecSources.Select(e => e.Source));
}
var cacheKey = string.Join("|", values);
return _sourcesCache.GetOrAdd(cacheKey, (root) => GetEffectiveSourcesCore(settings, dgSpecSources));
}
private List<SourceRepository> GetEffectiveSourcesCore(ISettings settings, IList<PackageSource> dgSpecSources)
{
var packageSourceProvider = new PackageSourceProvider(settings);
var packageSourcesFromProvider = packageSourceProvider.LoadPackageSources();
var sourceObjects = new Dictionary<string, PackageSource>();
for(var i = 0; i < dgSpecSources.Count; i++)
{
sourceObjects[dgSpecSources[i].Source] = dgSpecSources[i];
}
foreach (var sourceUri in Sources)
{
//DGSpecSources should always match the Sources
if (!sourceObjects.ContainsKey(sourceUri))
{
Log.LogDebug($"{sourceUri} is in the RestoreArgs Sources but not in the passed in dgSpecSources");
sourceObjects[sourceUri] = new PackageSource(sourceUri);
}
}
// Use PackageSource objects from the provider when possible (since those will have credentials from nuget.config)
foreach (var source in packageSourcesFromProvider)
{
if (source.IsEnabled && (sourceObjects.ContainsKey(source.Source)))
{
sourceObjects[source.Source] = source;
}
}
if (CachingSourceProvider == null)
{
// Create a shared caching provider if one does not exist already
CachingSourceProvider = new CachingSourceProvider(packageSourceProvider);
}
return sourceObjects.Select(entry => CachingSourceProvider.CreateRepository(entry.Value)).ToList();
}
public void ApplyStandardProperties(RestoreRequest request)
{
if (request.ProjectStyle == ProjectStyle.PackageReference
|| request.ProjectStyle == ProjectStyle.DotnetToolReference
|| request.ProjectStyle == ProjectStyle.Standalone)
{
request.LockFilePath = Path.Combine(request.RestoreOutputPath, LockFileFormat.AssetsFileName);
}
else if (request.ProjectStyle != ProjectStyle.DotnetCliTool)
{
request.LockFilePath = ProjectJsonPathUtilities.GetLockFilePath(request.Project.FilePath);
}
if (request.Project.RestoreMetadata?.CacheFilePath == null) {
request.Project.RestoreMetadata.CacheFilePath = NoOpRestoreUtilities.GetCacheFilePath(request);
}
request.MaxDegreeOfConcurrency =
DisableParallel ? 1 : RestoreRequest.DefaultDegreeOfConcurrency;
request.RequestedRuntimes.UnionWith(Runtimes);
request.FallbackRuntimes.UnionWith(FallbackRuntimes);
if (IsLowercaseGlobalPackagesFolder.HasValue)
{
request.IsLowercasePackagesDirectory = IsLowercaseGlobalPackagesFolder.Value;
}
if (LockFileVersion.HasValue && LockFileVersion.Value > 0)
{
request.LockFileVersion = LockFileVersion.Value;
}
// Run runtime asset checks for project.json, and for other types if enabled.
if (ValidateRuntimeAssets == null)
{
if (request.ProjectStyle == ProjectStyle.ProjectJson
|| request.Project.RestoreMetadata == null)
{
request.ValidateRuntimeAssets = request.ProjectStyle == ProjectStyle.ProjectJson;
}
else
{
request.ValidateRuntimeAssets = request.Project.RestoreMetadata.ValidateRuntimeAssets;
}
}
else
{
request.ValidateRuntimeAssets = ValidateRuntimeAssets.Value;
}
request.AllowNoOp = !request.CacheContext.NoCache && AllowNoOp;
request.HideWarningsAndErrors = HideWarningsAndErrors;
request.ParentId = ParentId;
request.IsRestoreOriginalAction = IsRestoreOriginalAction;
request.RestoreForceEvaluate = RestoreForceEvaluate;
}
}
}
| 39.638655 | 141 | 0.616812 | [
"Apache-2.0"
] | BdDsl/NuGet.Client | src/NuGet.Core/NuGet.Commands/RestoreCommand/RequestFactory/RestoreArgs.cs | 9,434 | C# |
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
// Ported from um/dwrite_2.h in the Windows SDK for Windows 10.0.20348.0
// Original source is Copyright © Microsoft. All rights reserved.
using NUnit.Framework;
using System;
using System.Runtime.InteropServices;
using static TerraFX.Interop.Windows;
namespace TerraFX.Interop.UnitTests
{
/// <summary>Provides validation of the <see cref="IDWriteTextAnalyzer2" /> struct.</summary>
public static unsafe partial class IDWriteTextAnalyzer2Tests
{
/// <summary>Validates that the <see cref="Guid" /> of the <see cref="IDWriteTextAnalyzer2" /> struct is correct.</summary>
[Test]
public static void GuidOfTest()
{
Assert.That(typeof(IDWriteTextAnalyzer2).GUID, Is.EqualTo(IID_IDWriteTextAnalyzer2));
}
/// <summary>Validates that the <see cref="IDWriteTextAnalyzer2" /> struct is blittable.</summary>
[Test]
public static void IsBlittableTest()
{
Assert.That(Marshal.SizeOf<IDWriteTextAnalyzer2>(), Is.EqualTo(sizeof(IDWriteTextAnalyzer2)));
}
/// <summary>Validates that the <see cref="IDWriteTextAnalyzer2" /> struct has the right <see cref="LayoutKind" />.</summary>
[Test]
public static void IsLayoutSequentialTest()
{
Assert.That(typeof(IDWriteTextAnalyzer2).IsLayoutSequential, Is.True);
}
/// <summary>Validates that the <see cref="IDWriteTextAnalyzer2" /> struct has the correct size.</summary>
[Test]
public static void SizeOfTest()
{
if (Environment.Is64BitProcess)
{
Assert.That(sizeof(IDWriteTextAnalyzer2), Is.EqualTo(8));
}
else
{
Assert.That(sizeof(IDWriteTextAnalyzer2), Is.EqualTo(4));
}
}
}
}
| 38.019231 | 145 | 0.645928 | [
"MIT"
] | DaZombieKiller/terrafx.interop.windows | tests/Interop/Windows/um/dwrite_2/IDWriteTextAnalyzer2Tests.cs | 1,979 | C# |
namespace Sqlbi.Bravo.Infrastructure.Windows.Interop
{
internal static class ExternDll
{
//public const string Activeds = "activeds.dll";
public const string Advapi32 = "advapi32.dll";
public const string Comctl32 = "comctl32.dll";
public const string Comdlg32 = "comdlg32.dll";
public const string Credui = "credui.dll";
public const string Dwmapi = "dwmapi.dll";
//public const string Gdi32 = "gdi32.dll";
public const string Gdiplus = "gdiplus.dll";
//public const string Hhctrl = "hhctrl.ocx";
//public const string Imm32 = "imm32.dll";
public const string Iphlpapi = "iphlpapi.dll";
public const string Kernel32 = "kernel32.dll";
//public const string Loadperf = "Loadperf.dll";
//public const string Mqrt = "mqrt.dll";
//public const string Mscoree = "mscoree.dll";
//public const string MsDrm = "msdrm.dll";
//public const string Mshwgst = "mshwgst.dll";
//public const string Msi = "msi.dll";
//public const string NaturalLanguage6 = "naturallanguage6.dll";
public const string Ntdll = "ntdll.dll";
//public const string Ole32 = "ole32.dll";
//public const string Oleacc = "oleacc.dll";
//public const string Oleaut32 = "oleaut32.dll";
//public const string Olepro32 = "olepro32.dll";
//public const string Penimc = "penimc2_v0400.dll";
//public const string PresentationHostDll = "PresentationHost_v0400.dll";
//public const string PresentationNativeDll = "PresentationNative_v0400.dll";
//public const string Psapi = "psapi.dll";
public const string Shcore = "shcore.dll";
//public const string Shell32 = "shell32.dll";
//public const string Shfolder = "shfolder.dll";
//public const string Urlmon = "urlmon.dll";
public const string User32 = "user32.dll";
public const string Uxtheme = "uxtheme.dll";
//public const string Version = "version.dll";
//public const string Vsassert = "vsassert.dll";
public const string WebView2Loader = "WebView2Loader.dll";
//public const string Wininet = "wininet.dll";
//public const string Winmm = "winmm.dll";
//public const string Winspool = "winspool.drv";
//public const string Wldp = "wldp.dll";
//public const string WtsApi32 = "wtsapi32.dll";
}
}
| 27.666667 | 85 | 0.627309 | [
"MIT"
] | hanaseleb/Bravo | src/Infrastructure/Windows/Interop/ExternDll.cs | 2,492 | C# |
using System;
using Triangle.Content;
using Triangle.Resources;
using Triangle.Time;
namespace Triangle
{
public class TaskTriangleBuilder
{
private TaskTime mTime;
private readonly TaskContent mContent = new TaskContent();
private readonly TaskResources mResources = new TaskResources();
public TaskTriangleBuilder SetTime(DateTime dateTime, TimeSpan duration)
{
mTime = new TaskTime(dateTime, duration);
return this;
}
private TaskTime CreateDefaultTime()
{
return new TaskTime(DateTime.Now, TimeSpan.FromHours(TimeConsts.WorkHoursPerDay));
}
public TaskTriangleBuilder AddContent(string content)
{
mContent.AddContent(content);
return this;
}
public TaskTriangleBuilder AddResource(string resource)
{
mResources.AddResource(resource);
return this;
}
public TaskTriangle Build()
{
if (mTime == null)
mTime = CreateDefaultTime();
return new TaskTriangle(mTime, mContent, mResources);
}
}
} | 26.177778 | 94 | 0.610357 | [
"MIT"
] | DorShaar/TaskTriangle | TaskTriangle/TaskTriangleBuilder.cs | 1,180 | C# |
using System;
using NetRuntimeSystem = System;
using System.ComponentModel;
using NetOffice.Attributes;
namespace NetOffice.PublisherApi
{
/// <summary>
/// DispatchInterface MailMergeDataField
/// SupportByVersion Publisher, 14,15,16
/// </summary>
[SupportByVersion("Publisher", 14,15,16)]
[EntityType(EntityType.IsDispatchInterface)]
public class MailMergeDataField : NetOffice.OfficeApi._IMsoDispObj
{
#pragma warning disable
#region Type Information
/// <summary>
/// Instance Type
/// </summary>
[EditorBrowsable(EditorBrowsableState.Advanced), Browsable(false), Category("NetOffice"), CoreOverridden]
public override Type InstanceType
{
get
{
return LateBindingApiWrapperType;
}
}
private static Type _type;
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public static Type LateBindingApiWrapperType
{
get
{
if (null == _type)
_type = typeof(MailMergeDataField);
return _type;
}
}
#endregion
#region Ctor
/// <param name="factory">current used factory core</param>
/// <param name="parentObject">object there has created the proxy</param>
/// <param name="proxyShare">proxy share instead if com proxy</param>
public MailMergeDataField(Core factory, ICOMObject parentObject, COMProxyShare proxyShare) : base(factory, parentObject, proxyShare)
{
}
///<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 MailMergeDataField(Core factory, ICOMObject 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 MailMergeDataField(ICOMObject 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 MailMergeDataField(Core factory, ICOMObject 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 MailMergeDataField(ICOMObject 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 MailMergeDataField(ICOMObject replacedObject) : base(replacedObject)
{
}
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public MailMergeDataField() : base()
{
}
/// <param name="progId">registered progID</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public MailMergeDataField(string progId) : base(progId)
{
}
#endregion
#region Properties
/// <summary>
/// SupportByVersion Publisher 14, 15, 16
/// Get
/// </summary>
[SupportByVersion("Publisher", 14,15,16)]
public Int32 Index
{
get
{
return Factory.ExecuteInt32PropertyGet(this, "Index");
}
}
/// <summary>
/// SupportByVersion Publisher 14, 15, 16
/// Get
/// </summary>
[SupportByVersion("Publisher", 14,15,16)]
public string Name
{
get
{
return Factory.ExecuteStringPropertyGet(this, "Name");
}
}
/// <summary>
/// SupportByVersion Publisher 14, 15, 16
/// Get
/// Unknown COM Proxy
/// </summary>
[SupportByVersion("Publisher", 14,15,16), ProxyResult]
public object Parent
{
get
{
return Factory.ExecuteReferencePropertyGet(this, "Parent");
}
}
/// <summary>
/// SupportByVersion Publisher 14, 15, 16
/// Get
/// </summary>
[SupportByVersion("Publisher", 14,15,16)]
public string Value
{
get
{
return Factory.ExecuteStringPropertyGet(this, "Value");
}
}
/// <summary>
/// SupportByVersion Publisher 14, 15, 16
/// Get/Set
/// </summary>
[SupportByVersion("Publisher", 14,15,16)]
public NetOffice.PublisherApi.Enums.PbMailMergeDataFieldType FieldType
{
get
{
return Factory.ExecuteEnumPropertyGet<NetOffice.PublisherApi.Enums.PbMailMergeDataFieldType>(this, "FieldType");
}
set
{
Factory.ExecuteEnumPropertySet(this, "FieldType", value);
}
}
/// <summary>
/// SupportByVersion Publisher 14, 15, 16
/// Get
/// </summary>
[SupportByVersion("Publisher", 14,15,16)]
public bool IsMapped
{
get
{
return Factory.ExecuteBoolPropertyGet(this, "IsMapped");
}
}
/// <summary>
/// SupportByVersion Publisher 14, 15, 16
/// Get
/// </summary>
[SupportByVersion("Publisher", 14,15,16)]
public string MappedTo
{
get
{
return Factory.ExecuteStringPropertyGet(this, "MappedTo");
}
}
#endregion
#region Methods
/// <summary>
/// SupportByVersion Publisher 14, 15, 16
/// </summary>
/// <param name="range">optional NetOffice.PublisherApi.TextRange range</param>
[SupportByVersion("Publisher", 14,15,16)]
public NetOffice.PublisherApi.Shape Insert(object range)
{
return Factory.ExecuteKnownReferenceMethodGet<NetOffice.PublisherApi.Shape>(this, "Insert", NetOffice.PublisherApi.Shape.LateBindingApiWrapperType, range);
}
/// <summary>
/// SupportByVersion Publisher 14, 15, 16
/// </summary>
[CustomMethod]
[SupportByVersion("Publisher", 14,15,16)]
public NetOffice.PublisherApi.Shape Insert()
{
return Factory.ExecuteKnownReferenceMethodGet<NetOffice.PublisherApi.Shape>(this, "Insert", NetOffice.PublisherApi.Shape.LateBindingApiWrapperType);
}
/// <summary>
/// SupportByVersion Publisher 14, 15, 16
/// </summary>
[SupportByVersion("Publisher", 14,15,16)]
public void AddToRecipientFields()
{
Factory.ExecuteMethod(this, "AddToRecipientFields");
}
/// <summary>
/// SupportByVersion Publisher 14, 15, 16
/// </summary>
/// <param name="bstrValue">optional string bstrValue</param>
[SupportByVersion("Publisher", 14,15,16)]
public void MapToRecipientField(object bstrValue)
{
Factory.ExecuteMethod(this, "MapToRecipientField", bstrValue);
}
/// <summary>
/// SupportByVersion Publisher 14, 15, 16
/// </summary>
[CustomMethod]
[SupportByVersion("Publisher", 14,15,16)]
public void MapToRecipientField()
{
Factory.ExecuteMethod(this, "MapToRecipientField");
}
/// <summary>
/// SupportByVersion Publisher 14, 15, 16
/// </summary>
[SupportByVersion("Publisher", 14,15,16)]
public void UnMapRecipientField()
{
Factory.ExecuteMethod(this, "UnMapRecipientField");
}
#endregion
#pragma warning restore
}
}
| 27.490842 | 173 | 0.686609 | [
"MIT"
] | DominikPalo/NetOffice | Source/Publisher/DispatchInterfaces/MailMergeDataField.cs | 7,507 | C# |
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using VerifyXunit;
using Xunit;
namespace NetEscapades.EnumGenerators.Tests;
[UsesVerify]
public class SourceGenerationHelperSnapshotTests
{
[Fact]
public Task GeneratesEnumCorrectly()
{
var value = new EnumToGenerate(
"ShortName",
"Something.Blah",
"Something.Blah.ShortName",
"int",
isPublic: true,
new Dictionary<string, EnumValueOption>
{
{ "First", new EnumValueOption(null, false) },
{ "Second", new EnumValueOption(null, false) }
}.ToList(),
hasFlags: false,
isDisplaAttributeUsed: false);
var sb = new StringBuilder();
var result = SourceGenerationHelper.GenerateExtensionClass(sb, value);
return Verifier.Verify(result)
.UseDirectory("Snapshots");
}
[Fact]
public Task GeneratesFlagsEnumCorrectly()
{
var value = new EnumToGenerate(
"ShortName",
"Something.Blah",
"Something.Blah.ShortName",
"int",
isPublic: true,
new Dictionary<string, EnumValueOption>
{
{ "First", new EnumValueOption(null, false) },
{ "Second", new EnumValueOption(null, false) }
}.ToList(),
hasFlags: true,
isDisplaAttributeUsed: false);
var sb = new StringBuilder();
var result = SourceGenerationHelper.GenerateExtensionClass(sb, value);
return Verifier.Verify(result)
.UseDirectory("Snapshots");
}
} | 28.6 | 78 | 0.579254 | [
"MIT"
] | tothalexlaszlo/NetEscapades.EnumGenerators | tests/NetEscapades.EnumGenerators.Tests/SourceGenerationHelperSnapshotTests.cs | 1,716 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Redis
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// REST API for Azure Redis Cache Service
/// </summary>
public partial interface IRedisManagementClient : System.IDisposable
{
/// <summary>
/// The base URI of the service.
/// </summary>
System.Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
Newtonsoft.Json.JsonSerializerSettings SerializationSettings { get; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
Newtonsoft.Json.JsonSerializerSettings DeserializationSettings { get; }
/// <summary>
/// Credentials needed for the client to connect to Azure.
/// </summary>
Microsoft.Rest.ServiceClientCredentials Credentials { get; }
/// <summary>
/// Gets subscription credentials which uniquely identify Microsoft
/// Azure subscription. The subscription ID forms part of the URI for
/// every service call.
/// </summary>
string SubscriptionId { get; set; }
/// <summary>
/// Client Api Version.
/// </summary>
string ApiVersion { get; }
/// <summary>
/// Gets or sets the preferred language for the response.
/// </summary>
string AcceptLanguage { get; set; }
/// <summary>
/// Gets or sets the retry timeout in seconds for Long Running
/// Operations. Default value is 30.
/// </summary>
int? LongRunningOperationRetryTimeout { get; set; }
/// <summary>
/// When set to true a unique x-ms-client-request-id value is
/// generated and included in each request. Default is true.
/// </summary>
bool? GenerateClientRequestId { get; set; }
/// <summary>
/// Gets the IRedisOperations.
/// </summary>
IRedisOperations Redis { get; }
/// <summary>
/// Gets the IPatchSchedulesOperations.
/// </summary>
IPatchSchedulesOperations PatchSchedules { get; }
}
}
| 31.292683 | 79 | 0.601715 | [
"MIT"
] | AzureAutomationTeam/azure-sdk-for-net | src/SDKs/RedisCache/Management.Redis/Generated/IRedisManagementClient.cs | 2,566 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
public class PolyTerrain : MonoBehaviour
{
public Material terrainmat;
//public Material linemat;
public int polyscale = 10;
public float heightscale = 2;
public float sizescale = 1;
public float perlinscale = .75f;
public float perlinoffset = 100;
//public float linewidth = .04f;
//public float lineheight = .02f;
public bool deform = false;
public float deformamount = .1f;
public int deformseed = 15;
private Vector3[,] areaMap;
private Vector3[] terrainVertices;
//private Vector3[] lineVertices;
private GameObject polyTerrainMesh;
//private GameObject polyLineMesh;
void Start()
{
areaMap = new Vector3[polyscale, polyscale];
for (int z = 0; z < polyscale; z++)
{
for (int x = 0; x < polyscale; x++)
{
areaMap[z, x] = new Vector3(x * sizescale, 0, z * sizescale);
}
}
polyTerrainMesh = new GameObject("Plane");
polyTerrainMesh.layer = 9;
polyTerrainMesh.AddComponent<MeshFilter>();
polyTerrainMesh.GetComponent<MeshFilter>().mesh.indexFormat = UnityEngine.Rendering.IndexFormat.UInt32;
polyTerrainMesh.AddComponent<MeshRenderer>();
polyTerrainMesh.GetComponent<MeshRenderer>().material = terrainmat;
polyTerrain();
}
void Update()
{
}
public void polyTerrain()
{
terrainVertices = new Vector3[polyscale * polyscale + (polyscale - 1) * (polyscale - 1)]; //areamap in the first polyscale square, the inbetweens in the second
int[] terrainTriangles = new int[(polyscale - 1) * (polyscale - 1) * 12];
for (int z = 0; z < polyscale; z++)
{
for (int x = 0; x < polyscale; x++)
{
terrainVertices[z * polyscale + x] = areaMap[x, z];
}
}
for (int z = 0; z < polyscale - 1; z++)
{
for (int x = 0; x < polyscale - 1; x++)
{
float y = (areaMap[x, z].y + areaMap[x + 1, z].y + areaMap[x, z + 1].y + areaMap[x + 1, z + 1].y) / 4;
terrainVertices[polyscale * polyscale + ((polyscale - 1) * z) + x] = new Vector3(areaMap[x, z].x + .5f * sizescale, y, areaMap[x, z].z + .5f * sizescale);
}
}
int cur = 0;
for (int z = 0; z < polyscale - 1; z++)
{
for (int x = 0; x < polyscale - 1; x++)
{
//setting triangles
terrainTriangles[cur + 2] = z * polyscale + x;
terrainTriangles[cur + 1] = polyscale * polyscale + ((polyscale - 1) * z) + x;
terrainTriangles[cur + 0] = z * polyscale + x + 1;
terrainTriangles[cur + 3] = polyscale * polyscale + ((polyscale - 1) * z) + x;
terrainTriangles[cur + 4] = z * polyscale + x + 1;
terrainTriangles[cur + 5] = (z + 1) * polyscale + x + 1;
terrainTriangles[cur + 8] = z * polyscale + x;
terrainTriangles[cur + 7] = (z + 1) * polyscale + x;
terrainTriangles[cur + 6] = polyscale * polyscale + ((polyscale - 1) * z) + x;
terrainTriangles[cur + 9] = (z + 1) * polyscale + x;
terrainTriangles[cur + 10] = polyscale * polyscale + ((polyscale - 1) * z) + x;
terrainTriangles[cur + 11] = (z + 1) * polyscale + x + 1;
//increment
cur += 12;
}
}
polyTerrainMesh.GetComponent<MeshFilter>().mesh.vertices = terrainVertices;
polyTerrainMesh.GetComponent<MeshFilter>().mesh.triangles = terrainTriangles;
polyTerrainMesh.GetComponent<MeshFilter>().mesh.RecalculateNormals();
Vector2[] terrainUV = new Vector2[terrainVertices.Length];
for (int z = 0; z < polyscale; z++)
{
for (int x = 0; x < polyscale; x++)
{
terrainUV[z * polyscale + x] = new Vector2(areaMap[x, z].z / polyscale / 5, areaMap[x, z].x / polyscale / 5);
}
}
for (int z = 0; z < polyscale - 1; z++)
{
for (int x = 0; x < polyscale - 1; x++)
{
terrainUV[polyscale * polyscale + ((polyscale - 1) * z) + x] = new Vector2((areaMap[x, z].z + .5f * sizescale) / polyscale / 5, (areaMap[x, z].x + .5f * sizescale) / polyscale / 5);
}
}
polyTerrainMesh.GetComponent<MeshFilter>().mesh.uv = terrainUV;
}
}
| 32.65 | 185 | 0.632721 | [
"MIT"
] | Millmoss/boatgame | AboatBoats/Assets/Scripts/PolyTerrain.cs | 3,920 | C# |
/* ================================================================================
* This is free and unencumbered software released into the public domain.
*
* Anyone is free to copy, modify, publish, use, compile, sell, or
* distribute this software, either in source code form or as a compiled
* binary, for any purpose, commercial or non-commercial, and by any
* means.
*
* In jurisdictions that recognize copyright laws, the author or authors
* of this software dedicate any and all copyright interest in the
* software to the public domain. We make this dedication for the benefit
* of the public at large and to the detriment of our heirs and
* successors. We intend this dedication to be an overt act of
* relinquishment in perpetuity of all present and future rights to this
* software under copyright law.
*
* 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 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.
*
* For more information, please refer to <https://unlicense.org>
* ================================================================================
*/
namespace Commons.Convertible
{
/// <summary>
/// <see cref="int"/>に変換できることを示すインタフェース。
/// </summary>
public interface IConvertibleInt32
{
/// <summary>
/// <see cref="int"/>に変換する。
/// </summary>
/// <returns><see cref="int"/>値</returns>
public int ToInt32();
}
} | 43.333333 | 84 | 0.628571 | [
"Unlicense"
] | kameske/CSharpCommons | Convertible/IConvertibleInt32.cs | 1,872 | C# |
using System.Collections;
using System.Collections.Generic;
using System.Runtime.ExceptionServices;
using System.Threading.Tasks;
public static class TaskExtensions
{
public static IEnumerator AsIEnumerator(this Task task)
{
while (!task.IsCompleted)
{
yield return null;
}
if (task.IsFaulted)
{
ExceptionDispatchInfo.Capture(task.Exception).Throw();
}
}
public static IEnumerator<T> AsIEnumerator<T>(this Task<T> task)
{
while (!task.IsCompleted)
{
yield return default(T);
}
if (task.IsFaulted)
{
ExceptionDispatchInfo.Capture(task.Exception).Throw();
}
yield return task.Result;
}
}
| 21.305556 | 68 | 0.597132 | [
"MIT"
] | XiNanSky/Framework | Plugins/Awaiter/TaskExtensions.cs | 767 | C# |
namespace XOutput.Diagnostics
{
/// <summary>
/// Diagnostics result values enum.
/// </summary>
public enum DiagnosticsResultState
{
Failed,
Warning,
Passed,
}
}
| 16.307692 | 39 | 0.561321 | [
"MIT"
] | Glitched-Manual/XOutput | XOutput/Diagnostics/DiagnosticsResultState.cs | 214 | C# |
using System.ComponentModel.DataAnnotations;
using Smartive.Core.Database.Models;
namespace Smartive.Core.Database.Test.Models
{
public class UserItem : Base
{
public string Name { get; set; }
[Required]
public string UserId { get; set; }
public User User { get; set; }
}
}
| 20.0625 | 44 | 0.64486 | [
"MIT"
] | smartive/smartive-core | test/Smartive.Core.Database.Test/Models/UserItem.cs | 321 | C# |
using UnityEngine;
using System.Collections;
public class EatThem : MonoBehaviour
{
private GameControl gk;
public int sc;
void Start()
{
gk = GameObject.Find ("game").GetComponent<GameControl> ();
}
void OnTriggerEnter2D(Collider2D other)
{
if(other.gameObject.name == "Spider")
{
other.GetComponent<AudioSource>().Play();
gk.AddScore(sc);
this.gameObject.SetActive(false);
}
}
} | 17.826087 | 61 | 0.697561 | [
"MIT"
] | TechNawabs/Webber | Assets/Scripts/EatThem.cs | 412 | C# |
#Mon Feb 27 04:08:29 GMT 2017
lib/features/com.ibm.websphere.appserver.javax.interceptor-1.1.mf=50641a1d8ef457a8982fa7ea216bebd1
dev/api/spec/com.ibm.websphere.javaee.interceptor.1.1_1.0.16.jar=ccb8decef733a051147dbe440a5fde4f
| 56.75 | 98 | 0.845815 | [
"Apache-2.0"
] | jeffwdg/chansyapp | target/liberty/wlp/lib/features/checksums/com.ibm.websphere.appserver.javax.interceptor-1.1.cs | 227 | C# |
/*
© Siemens AG, 2017-2018
Author: Dr. Martin Bischoff (martin.bischoff@siemens.com)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
<http://www.apache.org/licenses/LICENSE-2.0>.
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.IO;
using System.Collections.Generic;
using System.Threading;
using System.Linq;
using System.Xml.Linq;
namespace RosSharp.RosBridgeClient
{
public delegate void ReceiveEventHandler(ServiceReceiver sender, object ServiceResponse);
public class ServiceReceiver
{
public string ServiceName { get; private set; }
public object ServiceParameter { get; private set; }
public object HandlerParameter { get; set; }
public event ReceiveEventHandler ReceiveEventHandler;
public ServiceReceiver(RosSocket rosSocket, string service, object parameter, object handlerParameter, Type responseType)
{
ServiceName = service;
ServiceParameter = parameter;
HandlerParameter = handlerParameter;
rosSocket.CallService(ServiceName, responseType, receive, ServiceParameter);
}
private void receive(object ServiceResponse)
{
if (ReceiveEventHandler != null)
ReceiveEventHandler.Invoke(this, ServiceResponse);
}
}
public class UrdfImporter
{
private RosSocket rosSocket;
private string localDirectory;
public string robotName { get; private set; }
public string LocalDirectory
{
get
{
Status["robotNameReceived"].WaitOne();
return Path.Combine(localDirectory, robotName);
}
}
public Dictionary<string, ManualResetEvent> Status = new Dictionary<string, ManualResetEvent>
{
{ "robotNameReceived",new ManualResetEvent(false) },
{ "robotDescriptionReceived", new ManualResetEvent(false) },
{ "resourceFilesReceived", new ManualResetEvent(false) }
};
public Dictionary<Uri, bool> RequestedResourceFiles = new Dictionary<Uri, bool>();
public UrdfImporter(RosSocket _rosSocket, string _localDirectory)
{
rosSocket = _rosSocket;
localDirectory = _localDirectory;
}
public bool Import(int maxTimeOut = int.MaxValue)
{
rosSocket.CallService("/rosapi/get_param", typeof(ParamValueString), receiveRobotName, new ParamName("/robot/name"));
ServiceReceiver robotDescriptionReceiver = new ServiceReceiver(rosSocket, "/rosapi/get_param", new ParamName("/robot_description"), Path.DirectorySeparatorChar + "robot_description.urdf", typeof(ParamValueString));
robotDescriptionReceiver.ReceiveEventHandler += receiveRobotDescription;
return (WaitHandle.WaitAll(Status.Values.ToArray(), maxTimeOut));
}
private void receiveRobotName(object serviceResponse)
{
robotName = formatTextFileContents(((ParamValueString)serviceResponse).value);
Status["robotNameReceived"].Set();
}
private void receiveRobotDescription(ServiceReceiver serviceReciever, object serviceResponse)
{
#if NETFX_CORE
//TODO imprementation
#else
string robotDescription = formatTextFileContents(((ParamValueString)serviceResponse).value);
Thread importResourceFilesThread = new Thread(() => importResourceFiles(robotDescription));
importResourceFilesThread.Start();
Thread writeTextFileThread = new Thread(() => writeTextFile((string)serviceReciever.HandlerParameter, robotDescription));
writeTextFileThread.Start();
Status["robotDescriptionReceived"].Set();
#endif
}
private void importResourceFiles(string fileContents)
{
List<ServiceReceiver> serviceReceivers = requestResourceFiles(readResourceFileUris(fileContents));
if (serviceReceivers.Count > 0)
{
foreach (ServiceReceiver serviceReceiver in serviceReceivers)
serviceReceiver.ReceiveEventHandler += receiveResourceFile;
}
else
{
// no files to receive
Status["resourceFilesReceived"].Set();
}
}
private static List<Uri> readResourceFileUris(string robotDescription)
{
XElement root = XElement.Parse(robotDescription);
return (from seg in root.Descendants("mesh") where seg.Attribute("filename") != null select new Uri(seg.Attribute("filename").Value)).ToList();
}
private List<ServiceReceiver> requestResourceFiles(List<Uri> resourceFileUris)
{
List<ServiceReceiver> serviceReceivers = new List<ServiceReceiver>();
foreach (Uri resourceFilePath in resourceFileUris)
{
if (!RequestedResourceFiles.ContainsKey(resourceFilePath))
{
RequestedResourceFiles.Add(resourceFilePath, false);
serviceReceivers.Add(new ServiceReceiver(rosSocket, "/file_server/get_file", new ParamName(resourceFilePath.ToString()), getLocalFilename(resourceFilePath), typeof(ParamValueByte)));
}
}
return serviceReceivers;
}
private void receiveResourceFile(ServiceReceiver serviceReceiver, object serviceResponse)
{
#if NETFX_CORE
//TODO imprementation
#else
byte[] fileContents = ((ParamValueByte)serviceResponse).value;
Uri resourceFileUri = new Uri(((ParamName)serviceReceiver.ServiceParameter).name);
if (isColladaFile(resourceFileUri))
{
Thread importResourceFilesThread = new Thread(() => importDaeTextureFiles(resourceFileUri, System.Text.Encoding.UTF8.GetString(fileContents)));
importResourceFilesThread.Start();
}
Thread writeTextFileThread = new Thread(() => writeBinaryResponseToFile((string)serviceReceiver.HandlerParameter, fileContents));
writeTextFileThread.Start();
updateFileRequestStatus(resourceFileUri);
#endif
}
private void updateFileRequestStatus(Uri resourceFileUri)
{
RequestedResourceFiles[resourceFileUri] = true;
if (RequestedResourceFiles.Values.All(x => x == true))
Status["resourceFilesReceived"].Set();
}
private static bool isColladaFile(Uri uri)
{
return Path.GetExtension(uri.LocalPath) == ".dae";
}
private void importDaeTextureFiles(Uri daeFileUri, string fileContents)
{
List<ServiceReceiver> serviceReceivers = requestResourceFiles(readDaeTextureUris(daeFileUri, fileContents));
foreach (ServiceReceiver serviceReceiver in serviceReceivers)
serviceReceiver.ReceiveEventHandler += receiveTextureFiles;
}
private List<Uri> readDaeTextureUris(Uri resourceFileUri, string fileContents)
{
XNamespace xmlns = "http://www.collada.org/2005/11/COLLADASchema";
XElement root = XElement.Parse(fileContents);
return (from x in root.Elements()
where x.Name.LocalName == "library_images"
select new Uri(resourceFileUri, x.Element(xmlns + "image").Element(xmlns + "init_from").Value)).ToList();
}
private void receiveTextureFiles(ServiceReceiver serviceReceiver, object serviceResponse)
{
writeBinaryResponseToFile((string)serviceReceiver.HandlerParameter, ((ParamValueByte)serviceResponse).value);
updateFileRequestStatus(new Uri(((ParamName)serviceReceiver.ServiceParameter).name));
}
private void writeBinaryResponseToFile(string relativeLocalFilename, byte[] fileContents)
{
string filename = LocalDirectory + relativeLocalFilename;
Directory.CreateDirectory(Path.GetDirectoryName(filename));
File.WriteAllBytes(filename, fileContents);
}
private void writeTextFile(string relativeLocalFilename, string fileContents)
{
string filename = LocalDirectory + relativeLocalFilename;
Directory.CreateDirectory(Path.GetDirectoryName(filename));
File.WriteAllText(filename, fileContents);
}
private static string getLocalFilename(Uri resourceFilePath)
{
return Path.DirectorySeparatorChar
+ resourceFilePath.Host
+ resourceFilePath.LocalPath.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
}
private static string formatTextFileContents(string fileContents)
{
// remove enclosing quotations if existend:
if (fileContents.Substring(0, 1) == "\"" && fileContents.Substring(fileContents.Length - 1, 1) == "\"")
fileContents = fileContents.Substring(1, fileContents.Length - 2);
// replace \" quotation sign by actual quotation:
fileContents = fileContents.Replace("\\\"", "\"");
// replace \n newline sign by actual new line:
return fileContents.Replace("\\n", Environment.NewLine);
}
}
}
| 41.752137 | 226 | 0.658956 | [
"Apache-2.0"
] | EmergentSystemLabStudent/HSR-ros-sharp | RosBridgeClient/Shared/UrdfImporter.cs | 9,773 | C# |
using System.Collections.Generic;
using UnityEngine;
namespace Library
{
public class LibraryContent : MonoBehaviour
{
public List<BookItem> allBooks = new List<BookItem>();
}
}
| 17.181818 | 58 | 0.740741 | [
"MIT"
] | brinleyzhao1/Whimel-A-Magic-Academy | Assets/Scripts/Library/LibraryContent.cs | 189 | C# |
using System;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Windows.Forms;
using SDRSharp.Radio;
namespace SDRSharp.PanView
{
public enum BandType
{
Lower,
Upper,
Center
}
public delegate void ManualFrequencyChange (object sender, FrequencyEventArgs e);
public delegate void ManualBandwidthChange (object sender, BandwidthEventArgs e);
public class Waterfall : UserControl
{
private const float TrackingFontSize = 12.0f;
private const float TimestampFontSize = 10.0f;
private const int CarrierPenWidth = 1;
private const int AxisMargin = 30;
public const int CursorSnapDistance = 4;
public const float MaxZoom = 4.0f;
public const int RightClickSnapDistance = 500; // Snap distance in Hz, for Ellie
private double _attack;
private double _decay;
private bool _performNeeded;
private Bitmap _buffer;
private Bitmap _buffer2;
private Graphics _graphics;
private Graphics _graphics2;
private BandType _bandType;
private int _filterBandwidth;
private int _filterOffset;
private float _xIncrement;
private byte[] _temp;
private byte[] _powerSpectrum;
private byte[] _scaledPowerSpectrum;
private long _centerFrequency;
private long _spectrumWidth;
private int _stepSize;
private long _frequency;
private float _lower;
private float _upper;
private float _scale = 1f;
private long _displayCenterFrequency;
private bool _changingBandwidth;
private bool _changingFrequency;
private bool _changingCenterFrequency;
private bool _mouseIn;
private int _oldX;
private long _oldFrequency;
private long _oldCenterFrequency;
private int _oldFilterBandwidth;
private int[] _gradientPixels;
private int _contrast;
private int _zoom;
private bool _useSmoothing;
private bool _useSnap;
private int _trackingY;
private int _trackingX;
private long _trackingFrequency;
private bool _useTimestamps;
private int _scanlines;
private int _timestampInterval;
private int _displayRange = 130;
private int _displayOffset;
private LinearGradientBrush _gradientBrush;
private ColorBlend _gradientColorBlend = GetGradientBlend ();
public Waterfall ()
{
_powerSpectrum = new byte[ClientRectangle.Width - 2 * AxisMargin];
_temp = new byte[_powerSpectrum.Length];
_buffer = new Bitmap (ClientRectangle.Width, ClientRectangle.Height, PixelFormat.Format32bppPArgb);
_buffer2 = new Bitmap (ClientRectangle.Width, ClientRectangle.Height, PixelFormat.Format32bppPArgb);
_graphics = Graphics.FromImage (_buffer);
_graphics2 = Graphics.FromImage (_buffer2);
_gradientBrush = new LinearGradientBrush (new Rectangle (AxisMargin / 2, AxisMargin / 2, ClientRectangle.Width - AxisMargin / 2, ClientRectangle.Height - AxisMargin / 2), Color.White, Color.Black, LinearGradientMode.Vertical);
_gradientBrush.InterpolationColors = _gradientColorBlend;
SetStyle (ControlStyles.OptimizedDoubleBuffer, true);
SetStyle (ControlStyles.DoubleBuffer, true);
SetStyle (ControlStyles.UserPaint, true);
SetStyle (ControlStyles.AllPaintingInWmPaint, true);
UpdateStyles ();
}
public static ColorBlend GetGradientBlend ()
{
return Utils.GetGradientBlend (255);
}
~Waterfall ()
{
_buffer.Dispose ();
_buffer2.Dispose ();
_graphics.Dispose ();
_graphics2.Dispose ();
_gradientBrush.Dispose ();
}
public void Perform ()
{
if (_performNeeded && _mouseIn)
{
CopyMainBuffer ();
DrawCursor ();
Invalidate ();
_performNeeded = false;
}
}
public event ManualFrequencyChange FrequencyChanged;
public event ManualFrequencyChange CenterFrequencyChanged;
public event ManualBandwidthChange BandwidthChanged;
[Browsable (false)]
[DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
public ColorBlend GradientColorBlend
{
get
{
return _gradientColorBlend;
}
set
{
if (_gradientColorBlend != value)
{
_gradientColorBlend = value;
_gradientBrush.Dispose ();
_gradientBrush = new LinearGradientBrush (new Rectangle (AxisMargin / 2, AxisMargin / 2, ClientRectangle.Width - AxisMargin / 2, ClientRectangle.Height - AxisMargin / 2), Color.White, Color.Black, LinearGradientMode.Vertical);
_gradientPixels = null;
_gradientBrush.InterpolationColors = _gradientColorBlend;
DrawGradient ();
BuildGradientVector ();
_performNeeded = true;
}
}
}
public long CenterFrequency
{
get
{
return _centerFrequency;
}
set
{
if (_centerFrequency != value)
{
_displayCenterFrequency += value - _centerFrequency;
_centerFrequency = value;
_performNeeded = true;
}
}
}
public int SpectrumWidth
{
get
{
return (int) _spectrumWidth;
}
set
{
if (_spectrumWidth != value)
{
_spectrumWidth = value;
ApplyZoom ();
}
}
}
public long Frequency
{
get
{
return _frequency;
}
set
{
if (_frequency != value)
{
_frequency = value;
_performNeeded = true;
}
}
}
public int FilterBandwidth
{
get
{
return _filterBandwidth;
}
set
{
if (_filterBandwidth != value)
{
_filterBandwidth = value;
_performNeeded = true;
}
}
}
public int DisplayRange
{
get { return _displayRange; }
set { _displayRange = value; }
}
public int DisplayOffset
{
get { return _displayOffset; }
set { _displayOffset = value; }
}
public int FilterOffset
{
get
{
return _filterOffset;
}
set
{
if (_filterOffset != value)
{
_filterOffset = value;
_performNeeded = true;
}
}
}
public BandType BandType
{
get
{
return _bandType;
}
set
{
if (_bandType != value)
{
_bandType = value;
_performNeeded = true;
}
}
}
public int Contrast
{
get
{
return _contrast;
}
set
{
_contrast = value;
}
}
public int Zoom
{
get
{
return _zoom;
}
set
{
if (_zoom != value)
{
_zoom = value;
ApplyZoom ();
}
}
}
public bool UseSmoothing
{
get { return _useSmoothing; }
set { _useSmoothing = value; }
}
public double Decay
{
get { return _decay; }
set { _decay = value; }
}
public double Attack
{
get { return _attack; }
set { _attack = value; }
}
public int StepSize
{
get { return _stepSize; }
set
{
_performNeeded = true;
_stepSize = value;
}
}
public bool UseSnap
{
get { return _useSnap; }
set { _useSnap = value; }
}
public bool UseTimestamps
{
get { return _useTimestamps; }
set
{
_useTimestamps = value;
_scanlines = 0;
}
}
public int TimestampInterval
{
get { return _timestampInterval; }
set { _timestampInterval = value; }
}
private void ApplyZoom ()
{
_scale = (float) Math.Pow (10, _zoom * MaxZoom / 100.0f);
_displayCenterFrequency = GetDisplayCenterFrequency ();
if (_spectrumWidth > 0)
{
_xIncrement = _scale * (ClientRectangle.Width - 2 * AxisMargin) / _spectrumWidth;
_performNeeded = true;
}
}
public void CenterZoom ()
{
_displayCenterFrequency = GetDisplayCenterFrequency ();
}
private long GetDisplayCenterFrequency ()
{
var f = _frequency;
switch (_bandType)
{
case BandType.Lower:
f -= _filterBandwidth / 2 + _filterOffset;
break;
case BandType.Upper:
f += _filterBandwidth / 2 + _filterOffset;
break;
}
var lowerLeadingSpectrum = (long) ((_centerFrequency - _spectrumWidth / 2) - (f - _spectrumWidth / _scale / 2));
if (lowerLeadingSpectrum > 0)
{
f += lowerLeadingSpectrum + 10;
}
var upperLeadingSpectrum = (long) ((f + _spectrumWidth / _scale / 2) - (_centerFrequency + _spectrumWidth / 2));
if (upperLeadingSpectrum > 0)
{
f -= upperLeadingSpectrum + 10;
}
return f;
}
public unsafe void Render (float * powerSpectrum, int length)
{
if (_scaledPowerSpectrum == null || _scaledPowerSpectrum.Length != length)
{
_scaledPowerSpectrum = new byte[length];
}
fixed (byte * scaledPowerSpectrumPtr = _scaledPowerSpectrum)
{
var displayOffset = _displayOffset / 10 * 10;
var displayRange = _displayRange / 10 * 10;
Fourier.ScaleFFT (powerSpectrum, scaledPowerSpectrumPtr, length, displayOffset - displayRange, displayOffset);
}
var scaledLength = (int) (length / _scale);
var offset = (int) ((length - scaledLength) / 2.0 + length * (double) (_displayCenterFrequency - _centerFrequency) / _spectrumWidth);
if (_useSmoothing)
{
Fourier.SmoothCopy (_scaledPowerSpectrum, _temp, length, _scale, offset);
for (var i = 0; i < _powerSpectrum.Length; i++)
{
var ratio = _powerSpectrum[i] < _temp[i] ? Attack : Decay;
_powerSpectrum[i] = (byte) Math.Round (_powerSpectrum[i] * (1 - ratio) + _temp[i] * ratio);
}
}
else
{
Fourier.SmoothCopy (_scaledPowerSpectrum, _powerSpectrum, length, _scale, offset);
}
Draw ();
Invalidate ();
}
private void Draw ()
{
#region Draw only if needed
if (ClientRectangle.Width <= AxisMargin || ClientRectangle.Height <= AxisMargin)
{
return;
}
#endregion
#region Shift image
ShiftImage ();
#endregion
#region Draw Spectrum
DrawSpectrum ();
#endregion
#region Timestamps
if (_useTimestamps && ++_scanlines >= TimestampInterval)
{
_scanlines = 0;
DrawTimestamp ();
}
#endregion
#region Draw gradient
DrawGradient ();
#endregion
#region Draw cursor
if (_mouseIn)
{
CopyMainBuffer ();
DrawCursor ();
}
#endregion
}
private unsafe void ShiftImage ()
{
var bmpData = _buffer.LockBits (ClientRectangle, ImageLockMode.ReadWrite, _buffer.PixelFormat);
void * src;
void * dest;
if (bmpData.Stride > 0)
{
src = (void * ) bmpData.Scan0;
dest = (void * ) ((long) bmpData.Scan0 + bmpData.Stride);
}
else
{
dest = (void * ) bmpData.Scan0;
src = (void * ) ((long) bmpData.Scan0 - bmpData.Stride);
}
Utils.Memmove (dest, src, (bmpData.Height - 1) * Math.Abs (bmpData.Stride));
_buffer.UnlockBits (bmpData);
}
private unsafe void DrawSpectrum ()
{
if (_powerSpectrum == null || _powerSpectrum.Length == 0)
{
return;
}
var bits = _buffer.LockBits (ClientRectangle, ImageLockMode.ReadWrite, _buffer.PixelFormat);
int * ptr;
if (bits.Stride > 0)
{
ptr = (int * ) bits.Scan0 + AxisMargin;
}
else
{
ptr = (int * ) ((long) bits.Scan0 - bits.Stride * (bits.Height - 1)) + AxisMargin;
}
for (var i = 0; i < _powerSpectrum.Length; i++)
{
var colorIndex = (int) ((_powerSpectrum[i] + _contrast * 50.0 / 25.0) * _gradientPixels.Length / byte.MaxValue);
colorIndex = Math.Max (colorIndex, 0);
colorIndex = Math.Min (colorIndex, _gradientPixels.Length - 1);
* ptr++ = _gradientPixels[colorIndex];
}
_buffer.UnlockBits (bits);
}
private void DrawTimestamp ()
{
using (var path = new GraphicsPath ())
using (var outlinePen = new Pen (Color.Black))
{
var timestamp = DateTime.Now.ToString ("yyyy.MM.dd HH:mm:ss");
path.AddString ( timestamp,
FontFamily.GenericSansSerif,
(int) FontStyle.Regular,
_graphics.DpiY * TimestampFontSize / 72f,
new Point (AxisMargin, 0),
StringFormat.GenericTypographic);
var smoothingMode = _graphics.SmoothingMode;
var interpolationMode = _graphics.InterpolationMode;
_graphics.SmoothingMode = SmoothingMode.AntiAlias;
_graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
outlinePen.Width = 2;
_graphics.DrawPath (outlinePen, path);
_graphics.FillPath (Brushes.White, path);
_graphics.SmoothingMode = smoothingMode;
_graphics.InterpolationMode = interpolationMode;
}
}
private void DrawCursor ()
{
_lower = 0f;
float bandpassOffset;
var bandpassWidth = 0f;
var cursorWidth = Math.Max ((_filterBandwidth + _filterOffset) * _xIncrement, 2);
var xCarrier = (float) ClientRectangle.Width / 2 + (_frequency - _displayCenterFrequency) * _xIncrement;
switch (_bandType)
{
case BandType.Upper:
bandpassOffset = _filterOffset * _xIncrement;
bandpassWidth = cursorWidth - bandpassOffset;
_lower = xCarrier + bandpassOffset;
break;
case BandType.Lower:
bandpassOffset = _filterOffset * _xIncrement;
bandpassWidth = cursorWidth - bandpassOffset;
_lower = xCarrier - bandpassOffset - bandpassWidth;
break;
case BandType.Center:
_lower = xCarrier - cursorWidth / 2;
bandpassWidth = cursorWidth;
break;
}
_upper = _lower + bandpassWidth;
using (var transparentBrush = new SolidBrush (Color.FromArgb (80, Color.DarkGray)))
using (var hotTrackPen = new Pen (Color.Red))
using (var carrierPen = new Pen (Color.Red))
using (var path = new GraphicsPath ())
using (var outlinePen = new Pen (Color.Black))
{
carrierPen.Width = CarrierPenWidth;
if (cursorWidth < ClientRectangle.Width)
{
_graphics2.FillRectangle (transparentBrush, (int) _lower + 1, 0, (int) bandpassWidth, ClientRectangle.Height);
if (xCarrier >= AxisMargin && xCarrier <= ClientRectangle.Width - AxisMargin)
{
_graphics2.DrawLine (carrierPen, xCarrier, 0, xCarrier, ClientRectangle.Height);
}
}
if (_trackingX >= AxisMargin && _trackingX <= ClientRectangle.Width - AxisMargin)
{
if (!_changingFrequency && !_changingCenterFrequency && !_changingBandwidth)
{
_graphics2.DrawLine (hotTrackPen, _trackingX, 0, _trackingX, ClientRectangle.Height);
}
string fstring;
if (_changingFrequency)
{
fstring = "VFO = " + SpectrumAnalyzer.GetFrequencyDisplay (_frequency);
}
else if (_changingBandwidth)
{
fstring = "BW = " + SpectrumAnalyzer.GetFrequencyDisplay (_filterBandwidth);
}
else if (_changingCenterFrequency)
{
fstring = "Center Freq. = " + SpectrumAnalyzer.GetFrequencyDisplay (_centerFrequency);
}
else
{
fstring = SpectrumAnalyzer.GetFrequencyDisplay (_trackingFrequency);
}
path.AddString (fstring, FontFamily.GenericSansSerif, (int) FontStyle.Regular, TrackingFontSize, Point.Empty, StringFormat.GenericTypographic);
var stringSize = path.GetBounds ();
var currentCursor = Cursor.Current;
var xOffset = _trackingX + 15.0f;
var yOffset = _trackingY + (currentCursor == null ? SpectrumAnalyzer.DefaultCursorHeight : currentCursor.Size.Height) - 8.0f;
xOffset = Math.Min (xOffset, ClientRectangle.Width - stringSize.Width - 5);
yOffset = Math.Min (yOffset, ClientRectangle.Height - stringSize.Height - 5);
path.Reset ();
path.AddString (fstring, FontFamily.GenericSansSerif, (int) FontStyle.Regular, TrackingFontSize, new Point ((int) xOffset, (int) yOffset), StringFormat.GenericTypographic);
var smoothingMode = _graphics2.SmoothingMode;
var interpolationMode = _graphics2.InterpolationMode;
_graphics2.SmoothingMode = SmoothingMode.AntiAlias;
_graphics2.InterpolationMode = InterpolationMode.HighQualityBicubic;
outlinePen.Width = 2;
_graphics2.DrawPath (outlinePen, path);
_graphics2.FillPath (Brushes.White, path);
_graphics2.SmoothingMode = smoothingMode;
_graphics2.InterpolationMode = interpolationMode;
}
}
}
private unsafe void CopyMainBuffer ()
{
var rect = new Rectangle (0, 0, _buffer.Width, _buffer.Height);
var data1 = _buffer.LockBits (rect, ImageLockMode.ReadOnly, _buffer.PixelFormat);
var data2 = _buffer2.LockBits (rect, ImageLockMode.WriteOnly, _buffer2.PixelFormat);
Utils.Memcpy ((void * ) data2.Scan0, (void * ) data1.Scan0, Math.Abs (data1.Stride) * data1.Height);
_buffer.UnlockBits (data1);
_buffer2.UnlockBits (data2);
}
protected override void OnPaint (PaintEventArgs e)
{
SpectrumAnalyzer.ConfigureGraphics (e.Graphics);
e.Graphics.DrawImageUnscaled (_mouseIn ? _buffer2 : _buffer, 0, 0);
}
protected override void OnResize (EventArgs e)
{
base.OnResize (e);
if (ClientRectangle.Width <= AxisMargin || ClientRectangle.Height <= AxisMargin)
{
return;
}
var temp = new byte[ClientRectangle.Width - 2 * AxisMargin];
Fourier.SmoothCopy (_powerSpectrum, temp, _powerSpectrum.Length, (_temp.Length + temp.Length) / (float) _temp.Length, 0);
_powerSpectrum = temp;
_temp = new byte[_powerSpectrum.Length];
var oldBuffer = _buffer;
_buffer = new Bitmap (ClientRectangle.Width, ClientRectangle.Height, PixelFormat.Format32bppPArgb);
var oldBuffer2 = _buffer2;
_buffer2 = new Bitmap (ClientRectangle.Width, ClientRectangle.Height, PixelFormat.Format32bppPArgb);
_graphics.Dispose ();
_graphics = Graphics.FromImage (_buffer);
SpectrumAnalyzer.ConfigureGraphics (_graphics);
_graphics2.Dispose ();
_graphics2 = Graphics.FromImage (_buffer2);
SpectrumAnalyzer.ConfigureGraphics (_graphics2);
_graphics.Clear (Color.Black);
var rect = new Rectangle (AxisMargin, 0, _buffer.Width - 2 * AxisMargin, _buffer.Height);
_graphics.DrawImage (oldBuffer, rect, AxisMargin, 0, oldBuffer.Width - 2 * AxisMargin, oldBuffer.Height, GraphicsUnit.Pixel);
oldBuffer.Dispose ();
oldBuffer2.Dispose ();
if (_spectrumWidth > 0)
{
_xIncrement = _scale * (ClientRectangle.Width - 2 * AxisMargin) / _spectrumWidth;
}
_gradientBrush.Dispose ();
_gradientBrush = new LinearGradientBrush (new Rectangle (AxisMargin / 2, AxisMargin / 2, Width - AxisMargin / 2, ClientRectangle.Height - AxisMargin / 2), Color.White, Color.Black, LinearGradientMode.Vertical);
_gradientPixels = null;
_gradientBrush.InterpolationColors = _gradientColorBlend;
DrawGradient ();
BuildGradientVector ();
_performNeeded = true;
var oldMouseIn = _mouseIn;
_mouseIn = true;
Perform ();
_mouseIn = oldMouseIn;
}
private void DrawGradient ()
{
using (var pen = new Pen (_gradientBrush, 10))
{
_graphics.FillRectangle (Brushes.Black,
ClientRectangle.Width - AxisMargin,
0,
AxisMargin,
ClientRectangle.Height);
_graphics.DrawLine (pen,
ClientRectangle.Width - AxisMargin / 2,
ClientRectangle.Height - AxisMargin / 2,
ClientRectangle.Width - AxisMargin / 2,
AxisMargin / 2);
}
}
private void BuildGradientVector ()
{
if (_gradientPixels == null || _gradientPixels.Length != ClientRectangle.Height - AxisMargin)
{
_gradientPixels = new int[ClientRectangle.Height - AxisMargin - 1];
}
for (var i = 0; i < _gradientPixels.Length; i++)
{
_gradientPixels[_gradientPixels.Length - i - 1] = _buffer.GetPixel (ClientRectangle.Width - AxisMargin / 2, i + AxisMargin / 2 + 1).ToArgb ();
}
}
protected override void OnPaintBackground (PaintEventArgs e)
{
// Prevent default background painting
}
protected virtual void OnFrequencyChanged (FrequencyEventArgs e)
{
if (FrequencyChanged != null)
{
FrequencyChanged (this, e);
}
}
protected virtual void OnCenterFrequencyChanged (FrequencyEventArgs e)
{
if (CenterFrequencyChanged != null)
{
CenterFrequencyChanged (this, e);
}
}
protected virtual void OnBandwidthChanged (BandwidthEventArgs e)
{
if (BandwidthChanged != null)
{
BandwidthChanged (this, e);
}
}
private void UpdateFrequency (long f, FrequencyChangeSource source)
{
var min = (long) (_displayCenterFrequency - _spectrumWidth / _scale / 2);
if (f < min)
{
f = min;
}
var max = (long) (_displayCenterFrequency + _spectrumWidth / _scale / 2);
if (f > max)
{
f = max;
}
if (_useSnap)
{
f = (f + Math.Sign (f) * _stepSize / 2) / _stepSize * _stepSize;
}
if (f != _frequency)
{
var args = new FrequencyEventArgs (f, source);
OnFrequencyChanged (args);
if (!args.Cancel)
{
_frequency = args.Frequency;
_performNeeded = true;
}
}
}
private void UpdateCenterFrequency (long f)
{
if (f < 0)
{
f = 0;
}
if (_useSnap)
{
f = (f + Math.Sign (f) * _stepSize / 2) / _stepSize * _stepSize;
}
if (f != _centerFrequency)
{
var args = new FrequencyEventArgs (f, FrequencyChangeSource.Scroll);
OnCenterFrequencyChanged (args);
if (!args.Cancel)
{
var delta = args.Frequency - _centerFrequency;
_displayCenterFrequency += delta;
_centerFrequency = args.Frequency;
_performNeeded = true;
}
}
}
private void UpdateBandwidth (int bw)
{
bw = 10 * (bw / 10);
if (bw < 10)
{
bw = 10;
}
if (bw != _filterBandwidth)
{
var args = new BandwidthEventArgs (bw);
OnBandwidthChanged (args);
if (!args.Cancel)
{
_filterBandwidth = args.Bandwidth;
_performNeeded = true;
}
}
}
protected override void OnMouseDown (MouseEventArgs e)
{
base.OnMouseDown (e);
if (e.Button == MouseButtons.Left)
{
var cursorWidth = Math.Max (_filterBandwidth * _xIncrement, 2);
if (e.X > _lower && e.X < _upper && cursorWidth < ClientRectangle.Width)
{
_oldX = e.X;
_oldFrequency = _frequency;
_changingFrequency = true;
}
else if ((Math.Abs (e.X - _lower + CursorSnapDistance) <= CursorSnapDistance &&
(_bandType == BandType.Center || _bandType == BandType.Lower)) ||
(Math.Abs (e.X - _upper - CursorSnapDistance) <= CursorSnapDistance &&
(_bandType == BandType.Center || _bandType == BandType.Upper)))
{
_oldX = e.X;
_oldFilterBandwidth = _filterBandwidth;
_changingBandwidth = true;
}
else
{
_oldX = e.X;
_oldCenterFrequency = _centerFrequency;
_changingCenterFrequency = true;
}
}
else if (e.Button == MouseButtons.Right)
{
UpdateFrequency (_frequency / RightClickSnapDistance * RightClickSnapDistance, FrequencyChangeSource.Click);
}
}
protected override void OnMouseUp (MouseEventArgs e)
{
base.OnMouseUp (e);
if (_changingCenterFrequency && e.X == _oldX)
{
var f = (long) ((_oldX - ClientRectangle.Width / 2) * _spectrumWidth / _scale / (ClientRectangle.Width - 2 * AxisMargin) + _displayCenterFrequency);
UpdateFrequency (f, FrequencyChangeSource.Click);
}
_changingCenterFrequency = false;
_performNeeded = true;
_changingBandwidth = false;
_changingFrequency = false;
}
protected override void OnMouseMove (MouseEventArgs e)
{
base.OnMouseMove (e);
_trackingX = e.X;
_trackingY = e.Y;
_trackingFrequency = (long) ((e.X - ClientRectangle.Width / 2) * _spectrumWidth / _scale / (ClientRectangle.Width - 2 * AxisMargin) + _displayCenterFrequency);
if (_useSnap)
{
_trackingFrequency = (_trackingFrequency + Math.Sign (_trackingFrequency) * _stepSize / 2) / _stepSize * _stepSize;
}
if (_changingFrequency)
{
var f = (long) ((e.X - _oldX) * _spectrumWidth / _scale / (ClientRectangle.Width - 2 * AxisMargin) + _oldFrequency);
UpdateFrequency (f, FrequencyChangeSource.Drag);
}
else if (_changingCenterFrequency)
{
var f = (long) ((_oldX - e.X) * _spectrumWidth / _scale / (ClientRectangle.Width - 2 * AxisMargin) + _oldCenterFrequency);
UpdateCenterFrequency (f);
}
else if (_changingBandwidth)
{
var bw = 0;
switch (_bandType)
{
case BandType.Upper:
bw = e.X - _oldX;
break;
case BandType.Lower:
bw = _oldX - e.X;
break;
case BandType.Center:
bw = (_oldX > (_lower + _upper) / 2 ? e.X - _oldX : _oldX - e.X) * 2;
break;
}
bw = (int) (bw * _spectrumWidth / _scale / (ClientRectangle.Width - 2 * AxisMargin) + _oldFilterBandwidth);
UpdateBandwidth (bw);
}
else if ((Math.Abs (e.X - _lower + CursorSnapDistance) <= CursorSnapDistance &&
(_bandType == BandType.Center || _bandType == BandType.Lower)) ||
(Math.Abs (e.X - _upper - CursorSnapDistance) <= CursorSnapDistance &&
(_bandType == BandType.Center || _bandType == BandType.Upper)))
{
Cursor = Cursors.SizeWE;
}
else
{
Cursor = Cursors.Default;
}
_performNeeded = true;
}
protected override void OnMouseEnter (EventArgs e)
{
Focus ();
base.OnMouseEnter (e);
_mouseIn = true;
_performNeeded = true;
CopyMainBuffer ();
}
protected override void OnMouseLeave (EventArgs e)
{
base.OnMouseLeave (e);
_performNeeded = true;
Perform ();
_mouseIn = false;
}
protected override void OnMouseWheel (MouseEventArgs e)
{
base.OnMouseWheel (e);
UpdateFrequency (_frequency + _stepSize * Math.Sign (e.Delta), FrequencyChangeSource.Scroll);
}
}
public enum FrequencyChangeSource
{
Scroll,
Drag,
Click
}
public class FrequencyEventArgs : EventArgs
{
public long Frequency { get; set; }
public FrequencyChangeSource Source { get; set; }
public bool Cancel { get; set; }
public FrequencyEventArgs (long frequency, FrequencyChangeSource source)
{
Frequency = frequency;
Source = source;
}
}
public class BandwidthEventArgs : EventArgs
{
public int Bandwidth { get; set; }
public bool Cancel { get; set; }
public BandwidthEventArgs (int bandwidth)
{
Bandwidth = bandwidth;
}
}
}
| 35.088799 | 247 | 0.490668 | [
"MIT"
] | CraftyBastard/sdrsharp | PanView/Waterfall.cs | 34,775 | C# |
using System;
using System.Threading.Tasks;
using Jellyfin.Sdk;
using SystemException = Jellyfin.Sdk.SystemException;
namespace Simple;
/// <summary>
/// Sample Jellyfin service.
/// </summary>
public class SampleService
{
private readonly SdkClientSettings _sdkClientSettings;
private readonly ISystemClient _systemClient;
private readonly IUserClient _userClient;
private readonly IUserViewsClient _userViewsClient;
/// <summary>
/// Initializes a new instance of the <see cref="SampleService"/> class.
/// </summary>
/// <param name="sdkClientSettings">Instance of the <see cref="_sdkClientSettings"/>.</param>
/// <param name="systemClient">Instance of the <see cref="ISystemClient"/> interface.</param>
/// <param name="userClient">Instance of the <see cref="IUserClient"/> interface.</param>
/// <param name="userViewsClient">Instance of the <see cref="IUserViewsClient"/> interface.</param>
public SampleService(
SdkClientSettings sdkClientSettings,
ISystemClient systemClient,
IUserClient userClient,
IUserViewsClient userViewsClient)
{
_sdkClientSettings = sdkClientSettings;
_systemClient = systemClient;
_userClient = userClient;
_userViewsClient = userViewsClient;
}
/// <summary>
/// Run the sample.
/// </summary>
/// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
public async Task RunAsync()
{
var validServer = false;
do
{
// Prompt for server url.
// Url must be proto://host/path
// ex: https://demo.jellyfin.org/stable
Console.Write("Server Url: ");
var host = Console.ReadLine();
_sdkClientSettings.BaseUrl = host;
try
{
// Get public system info to verify that the url points to a Jellyfin server.
var systemInfo = await _systemClient.GetPublicSystemInfoAsync()
.ConfigureAwait(false);
validServer = true;
Console.WriteLine($"Connected to {host}");
Console.WriteLine($"Server Name: {systemInfo.ServerName}");
Console.WriteLine($"Server Version: {systemInfo.Version}");
}
catch (InvalidOperationException ex)
{
await Console.Error.WriteLineAsync("Invalid url").ConfigureAwait(false);
await Console.Error.WriteLineAsync(ex.Message).ConfigureAwait(false);
}
catch (SystemException ex)
{
await Console.Error.WriteLineAsync($"Error connecting to {host}").ConfigureAwait(false);
await Console.Error.WriteLineAsync(ex.Message).ConfigureAwait(false);
}
}
while (!validServer);
var validUser = false;
UserDto userDto = null!;
do
{
try
{
Console.Write("Username: ");
var username = Console.ReadLine();
Console.Write("Password: ");
var password = Console.ReadLine();
Console.WriteLine($"Logging into {_sdkClientSettings.BaseUrl}");
// Authenticate user.
var authenticationResult = await _userClient.AuthenticateUserByNameAsync(new AuthenticateUserByName
{
Username = username,
Pw = password
})
.ConfigureAwait(false);
_sdkClientSettings.AccessToken = authenticationResult.AccessToken;
userDto = authenticationResult.User;
Console.WriteLine("Authentication success.");
Console.WriteLine($"Welcome to Jellyfin - {userDto.Name}");
validUser = true;
}
catch (UserException ex)
{
await Console.Error.WriteLineAsync("Error authenticating.").ConfigureAwait(false);
await Console.Error.WriteLineAsync(ex.Message).ConfigureAwait(false);
}
}
while (!validUser);
await PrintViews(userDto.Id)
.ConfigureAwait(false);
}
private async Task PrintViews(Guid userId)
{
try
{
var views = await _userViewsClient.GetUserViewsAsync(userId)
.ConfigureAwait(false);
Console.WriteLine("Printing Views:");
foreach (var view in views.Items)
{
Console.WriteLine($"{view.Id} - {view.Name}");
}
}
catch (UserViewsException ex)
{
await Console.Error.WriteLineAsync("Error getting user views").ConfigureAwait(false);
await Console.Error.WriteLineAsync(ex.Message).ConfigureAwait(false);
}
}
}
| 36.154412 | 115 | 0.584299 | [
"MIT"
] | crobibero/jellyfin-sdk-csharp | samples/Simple/SampleService.cs | 4,919 | C# |
using System;
using System.Linq;
using GAPoTNumLib.Structures;
namespace GAPoTNumLib.Text.Structured
{
public sealed class PriorityQueueTextComposer<TPriority> : PriorityQueue<TPriority, StructuredTextItem>, IStructuredTextComposer
{
public string Separator { get; set; }
public string ActiveItemPrefix { get; set; }
public string ActiveItemSuffix { get; set; }
public string FinalPrefix { get; set; }
public string FinalSuffix { get; set; }
public bool ReverseItems { get; set; }
public PriorityQueueTextComposer()
{
Separator = string.Empty;
ActiveItemPrefix = string.Empty;
ActiveItemSuffix = string.Empty;
FinalPrefix = string.Empty;
FinalSuffix = string.Empty;
}
public PriorityQueueTextComposer(string separator)
{
Separator = separator ?? string.Empty;
ActiveItemPrefix = string.Empty;
ActiveItemSuffix = string.Empty;
FinalPrefix = string.Empty;
FinalSuffix = string.Empty;
}
public PriorityQueueTextComposer<TPriority> Enqueue(TPriority priority)
{
base.Enqueue(priority, this.ToTextItem(string.Empty));
return this;
}
public PriorityQueueTextComposer<TPriority> Enqueue(TPriority priority, string item)
{
base.Enqueue(priority, this.ToTextItem(item));
return this;
}
public PriorityQueueTextComposer<TPriority> Enqueue<T>(TPriority priority, T item)
{
base.Enqueue(priority, this.ToTextItem(item));
return this;
}
public string Generate()
{
var items = ReverseItems ? this.Reverse() : this;
return items.Select(item => item.Value).Concatenate(Separator, FinalPrefix, FinalSuffix);
}
public string Generate(Func<StructuredTextItem, string> itemFunc)
{
var items = ReverseItems ? this.Reverse() : this;
return items.Select(item => itemFunc(item.Value)).Concatenate(Separator, FinalPrefix, FinalSuffix);
}
public override string ToString()
{
return Generate();
}
}
}
| 27.722892 | 132 | 0.607997 | [
"MIT"
] | ga-explorer/GeometricAlgebraFulcrumLib | GAPoTNumLib/GAPoTNumLib/Text/Structured/PriorityQueueTextComposer.cs | 2,303 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace WebAPIHttp
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
//有cookie时 Access-Control-Allow-Origin 不能为 *
//https://segmentfault.com/a/1190000015552557
//https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Access_control_CORS
services.AddCors(options =>
{
options.AddPolicy("AllowSameDomain", policyBuilder =>
{
policyBuilder.AllowAnyMethod()
.AllowAnyHeader();
//.WithMethods("GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS", "DEBUG");
var cfg = Configuration.GetSection("AllowedHosts").Get<List<string>>();
if (cfg?.Any() ?? false)
//允许任何来源的主机访问
policyBuilder.AllowAnyOrigin();
else if (cfg?.Any() ?? false)
//允许类似http://localhost:8080等主机访问
policyBuilder.AllowCredentials().WithOrigins(cfg.ToArray());
});
});
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(configureOptions =>
{
configureOptions.Cookie.SameSite = Microsoft.AspNetCore.Http.SameSiteMode.None;
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
//https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-3.0
app.UseCors("AllowSameDomain");
app.UseAuthentication();
app.UseMvc();
}
}
}
| 36.932432 | 108 | 0.600805 | [
"MIT"
] | Ran-snow/aspnetcorestudy | WebAPIHttp/Startup.cs | 2,785 | C# |
namespace Debwin.UI.Panels
{
partial class LogViewPanel
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(LogViewPanel));
this.ilLogLevelIcons = new System.Windows.Forms.ImageList(this.components);
this.listviewLayoutTimer = new System.Windows.Forms.Timer(this.components);
this.statusStrip1 = new System.Windows.Forms.StatusStrip();
this.lblReceivedMessages = new System.Windows.Forms.ToolStripStatusLabel();
this.lblReceivedMessageCount = new System.Windows.Forms.ToolStripStatusLabel();
this.lblBufferedMessages = new System.Windows.Forms.ToolStripStatusLabel();
this.lblBufferedMessagesCount = new System.Windows.Forms.ToolStripStatusLabel();
this.lblFilterNameLabel = new System.Windows.Forms.ToolStripStatusLabel();
this.lblFilterNameValue = new System.Windows.Forms.ToolStripStatusLabel();
this.lblVisibleMessages = new System.Windows.Forms.ToolStripStatusLabel();
this.lblVisibleMessageCount = new System.Windows.Forms.ToolStripStatusLabel();
this.lblAttachedFileNotification = new System.Windows.Forms.ToolStripStatusLabel();
this.lblAttachedLogFileName = new System.Windows.Forms.ToolStripStatusLabel();
this.lblLineNumberLabel = new System.Windows.Forms.ToolStripStatusLabel();
this.lblLineNumber = new System.Windows.Forms.ToolStripStatusLabel();
this.panelLogLoader = new System.Windows.Forms.Panel();
this.label1 = new System.Windows.Forms.Label();
this.panelLogView = new System.Windows.Forms.Panel();
this.mnuLogMessageContext = new System.Windows.Forms.ContextMenuStrip(this.components);
this.miSelectInUnfilteredView = new System.Windows.Forms.ToolStripMenuItem();
this.copySelectedMessagesMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.setBaseForRelativeTimeMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.chooseColumnsMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem1 = new System.Windows.Forms.ToolStripSeparator();
this.filterToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.dateFromToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.dateToToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.byThreadToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.includeLoggerInFilterMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.excludeLoggerInFilterMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.includeModuleInFilterMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.excludeModuleInFilterMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.lstLogMessages = new Debwin.UI.Controls.DoubleBufferedListView();
this.toolStrip1 = new System.Windows.Forms.ToolStrip();
this.btnCaptureActive = new System.Windows.Forms.ToolStripButton();
this.btnClearLog = new System.Windows.Forms.ToolStripButton();
this.btnToggleAutoScroll = new System.Windows.Forms.ToolStripButton();
this.autoScrollToolstripSeparator = new System.Windows.Forms.ToolStripSeparator();
this.btnSaveLog = new System.Windows.Forms.ToolStripSplitButton();
this.btnSaveAndEditLog = new System.Windows.Forms.ToolStripMenuItem();
this.btnSaveWithSpecificColumns = new System.Windows.Forms.ToolStripMenuItem();
this.btnCopyLog = new System.Windows.Forms.ToolStripButton();
this.btnAppendMessage = new System.Windows.Forms.ToolStripButton();
this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator();
this.btnSavedFilters = new System.Windows.Forms.ToolStripDropDownButton();
this.btnPopLogView = new System.Windows.Forms.ToolStripButton();
this.toolStripSeparator2 = new System.Windows.Forms.ToolStripSeparator();
this.btnFindLastIssue = new System.Windows.Forms.ToolStripButton();
this.btnFindNextIssue = new System.Windows.Forms.ToolStripButton();
this.toolStripLabel1 = new System.Windows.Forms.ToolStripLabel();
this.txtSearchBox = new System.Windows.Forms.ToolStripComboBox();
this.findTextMenuItem = new System.Windows.Forms.ToolStripSplitButton();
this.findNextMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.findLastMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem2 = new System.Windows.Forms.ToolStripSeparator();
this.caseSensitiveMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.patternsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.errorCodeNegNumberToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.goToLineToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.statusStrip1.SuspendLayout();
this.panelLogLoader.SuspendLayout();
this.panelLogView.SuspendLayout();
this.mnuLogMessageContext.SuspendLayout();
this.toolStrip1.SuspendLayout();
this.SuspendLayout();
//
// ilLogLevelIcons
//
this.ilLogLevelIcons.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("ilLogLevelIcons.ImageStream")));
this.ilLogLevelIcons.TransparentColor = System.Drawing.Color.Transparent;
this.ilLogLevelIcons.Images.SetKeyName(0, "Tip.png");
this.ilLogLevelIcons.Images.SetKeyName(1, "Information.png");
this.ilLogLevelIcons.Images.SetKeyName(2, "Warning.png");
this.ilLogLevelIcons.Images.SetKeyName(3, "Error.png");
this.ilLogLevelIcons.Images.SetKeyName(4, "User-Comment.png");
//
// listviewLayoutTimer
//
this.listviewLayoutTimer.Tick += new System.EventHandler(this.listviewLayoutTimer_Tick);
//
// statusStrip1
//
this.statusStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.lblReceivedMessages,
this.lblReceivedMessageCount,
this.lblBufferedMessages,
this.lblBufferedMessagesCount,
this.lblFilterNameLabel,
this.lblFilterNameValue,
this.lblVisibleMessages,
this.lblVisibleMessageCount,
this.lblAttachedFileNotification,
this.lblAttachedLogFileName,
this.lblLineNumberLabel,
this.lblLineNumber});
this.statusStrip1.Location = new System.Drawing.Point(0, 342);
this.statusStrip1.Name = "statusStrip1";
this.statusStrip1.Size = new System.Drawing.Size(976, 24);
this.statusStrip1.SizingGrip = false;
this.statusStrip1.TabIndex = 7;
this.statusStrip1.Text = "statusStrip1";
//
// lblReceivedMessages
//
this.lblReceivedMessages.Name = "lblReceivedMessages";
this.lblReceivedMessages.Size = new System.Drawing.Size(111, 19);
this.lblReceivedMessages.Text = "Received Messages:";
//
// lblReceivedMessageCount
//
this.lblReceivedMessageCount.BorderSides = ((System.Windows.Forms.ToolStripStatusLabelBorderSides)((((System.Windows.Forms.ToolStripStatusLabelBorderSides.Left | System.Windows.Forms.ToolStripStatusLabelBorderSides.Top)
| System.Windows.Forms.ToolStripStatusLabelBorderSides.Right)
| System.Windows.Forms.ToolStripStatusLabelBorderSides.Bottom)));
this.lblReceivedMessageCount.Name = "lblReceivedMessageCount";
this.lblReceivedMessageCount.Size = new System.Drawing.Size(25, 19);
this.lblReceivedMessageCount.Text = "{0}";
this.lblReceivedMessageCount.ToolTipText = "Number of messages in this view which are currently not displayed until the next " +
"refresh";
//
// lblBufferedMessages
//
this.lblBufferedMessages.Name = "lblBufferedMessages";
this.lblBufferedMessages.Size = new System.Drawing.Size(109, 19);
this.lblBufferedMessages.Text = "Buffered Messages:";
//
// lblBufferedMessagesCount
//
this.lblBufferedMessagesCount.BorderSides = ((System.Windows.Forms.ToolStripStatusLabelBorderSides)((((System.Windows.Forms.ToolStripStatusLabelBorderSides.Left | System.Windows.Forms.ToolStripStatusLabelBorderSides.Top)
| System.Windows.Forms.ToolStripStatusLabelBorderSides.Right)
| System.Windows.Forms.ToolStripStatusLabelBorderSides.Bottom)));
this.lblBufferedMessagesCount.Name = "lblBufferedMessagesCount";
this.lblBufferedMessagesCount.Size = new System.Drawing.Size(25, 19);
this.lblBufferedMessagesCount.Text = "{0}";
this.lblBufferedMessagesCount.ToolTipText = "Number of messages in this view which are currently not displayed until the next " +
"refresh";
//
// lblFilterNameLabel
//
this.lblFilterNameLabel.Name = "lblFilterNameLabel";
this.lblFilterNameLabel.Size = new System.Drawing.Size(36, 19);
this.lblFilterNameLabel.Text = "Filter:";
this.lblFilterNameLabel.Visible = false;
//
// lblFilterNameValue
//
this.lblFilterNameValue.BorderSides = ((System.Windows.Forms.ToolStripStatusLabelBorderSides)((((System.Windows.Forms.ToolStripStatusLabelBorderSides.Left | System.Windows.Forms.ToolStripStatusLabelBorderSides.Top)
| System.Windows.Forms.ToolStripStatusLabelBorderSides.Right)
| System.Windows.Forms.ToolStripStatusLabelBorderSides.Bottom)));
this.lblFilterNameValue.Name = "lblFilterNameValue";
this.lblFilterNameValue.Size = new System.Drawing.Size(51, 19);
this.lblFilterNameValue.Text = "{Name}";
this.lblFilterNameValue.Visible = false;
//
// lblVisibleMessages
//
this.lblVisibleMessages.Name = "lblVisibleMessages";
this.lblVisibleMessages.Size = new System.Drawing.Size(98, 19);
this.lblVisibleMessages.Text = "Visible Messages:";
this.lblVisibleMessages.ToolTipText = "Number of messages in the buffer which match the filter and are currently visible" +
"";
this.lblVisibleMessages.Visible = false;
//
// lblVisibleMessageCount
//
this.lblVisibleMessageCount.BorderSides = ((System.Windows.Forms.ToolStripStatusLabelBorderSides)((((System.Windows.Forms.ToolStripStatusLabelBorderSides.Left | System.Windows.Forms.ToolStripStatusLabelBorderSides.Top)
| System.Windows.Forms.ToolStripStatusLabelBorderSides.Right)
| System.Windows.Forms.ToolStripStatusLabelBorderSides.Bottom)));
this.lblVisibleMessageCount.Name = "lblVisibleMessageCount";
this.lblVisibleMessageCount.Size = new System.Drawing.Size(25, 19);
this.lblVisibleMessageCount.Text = "{0}";
this.lblVisibleMessageCount.ToolTipText = "Number of messages in the buffer which match the filter and are currently visible" +
"";
this.lblVisibleMessageCount.Visible = false;
//
// lblAttachedFileNotification
//
this.lblAttachedFileNotification.Font = new System.Drawing.Font("Segoe UI", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lblAttachedFileNotification.ForeColor = System.Drawing.Color.SteelBlue;
this.lblAttachedFileNotification.Image = ((System.Drawing.Image)(resources.GetObject("lblAttachedFileNotification.Image")));
this.lblAttachedFileNotification.ImageAlign = System.Drawing.ContentAlignment.MiddleRight;
this.lblAttachedFileNotification.Name = "lblAttachedFileNotification";
this.lblAttachedFileNotification.Size = new System.Drawing.Size(139, 19);
this.lblAttachedFileNotification.Spring = true;
this.lblAttachedFileNotification.Text = "{lblAttachedFileNotification}";
this.lblAttachedFileNotification.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
this.lblAttachedFileNotification.Visible = false;
//
// lblAttachedLogFileName
//
this.lblAttachedLogFileName.Font = new System.Drawing.Font("Segoe UI", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lblAttachedLogFileName.ForeColor = System.Drawing.Color.DodgerBlue;
this.lblAttachedLogFileName.IsLink = true;
this.lblAttachedLogFileName.LinkBehavior = System.Windows.Forms.LinkBehavior.AlwaysUnderline;
this.lblAttachedLogFileName.LinkColor = System.Drawing.Color.SteelBlue;
this.lblAttachedLogFileName.Name = "lblAttachedLogFileName";
this.lblAttachedLogFileName.Size = new System.Drawing.Size(151, 19);
this.lblAttachedLogFileName.Text = "{lblAttachedLogFileName}";
this.lblAttachedLogFileName.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
this.lblAttachedLogFileName.Visible = false;
this.lblAttachedLogFileName.Click += new System.EventHandler(this.lblAttachedLogFileName_Click);
//
// lblLineNumberLabel
//
this.lblLineNumberLabel.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
this.lblLineNumberLabel.Name = "lblLineNumberLabel";
this.lblLineNumberLabel.Size = new System.Drawing.Size(139, 19);
this.lblLineNumberLabel.Spring = true;
this.lblLineNumberLabel.Text = "Ln";
this.lblLineNumberLabel.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// lblLineNumber
//
this.lblLineNumber.Name = "lblLineNumber";
this.lblLineNumber.Size = new System.Drawing.Size(21, 19);
this.lblLineNumber.Text = "{0}";
//
// panelLogLoader
//
this.panelLogLoader.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.panelLogLoader.Controls.Add(this.label1);
this.panelLogLoader.Location = new System.Drawing.Point(1013, 22);
this.panelLogLoader.Name = "panelLogLoader";
this.panelLogLoader.Size = new System.Drawing.Size(164, 324);
this.panelLogLoader.TabIndex = 8;
//
// label1
//
this.label1.Dock = System.Windows.Forms.DockStyle.Fill;
this.label1.Font = new System.Drawing.Font("Segoe UI Light", 15.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label1.ForeColor = System.Drawing.SystemColors.ControlDark;
this.label1.Location = new System.Drawing.Point(0, 0);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(164, 324);
this.label1.TabIndex = 0;
this.label1.Text = "Working on it...";
this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
//
// panelLogView
//
this.panelLogView.Controls.Add(this.lstLogMessages);
this.panelLogView.Controls.Add(this.toolStrip1);
this.panelLogView.Controls.Add(this.statusStrip1);
this.panelLogView.Location = new System.Drawing.Point(12, 12);
this.panelLogView.Name = "panelLogView";
this.panelLogView.Size = new System.Drawing.Size(976, 366);
this.panelLogView.TabIndex = 9;
//
// mnuLogMessageContext
//
this.mnuLogMessageContext.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.miSelectInUnfilteredView,
this.copySelectedMessagesMenuItem,
this.setBaseForRelativeTimeMenuItem,
this.chooseColumnsMenuItem,
this.toolStripMenuItem1,
this.filterToolStripMenuItem,
this.dateFromToolStripMenuItem,
this.dateToToolStripMenuItem,
this.byThreadToolStripMenuItem,
this.includeLoggerInFilterMenuItem,
this.excludeLoggerInFilterMenuItem,
this.includeModuleInFilterMenuItem,
this.excludeModuleInFilterMenuItem});
this.mnuLogMessageContext.Name = "mnuLogMessageContext";
this.mnuLogMessageContext.Size = new System.Drawing.Size(269, 274);
this.mnuLogMessageContext.Opening += new System.ComponentModel.CancelEventHandler(this.mnuLogMessageContext_Opening);
//
// miSelectInUnfilteredView
//
this.miSelectInUnfilteredView.Enabled = false;
this.miSelectInUnfilteredView.Image = ((System.Drawing.Image)(resources.GetObject("miSelectInUnfilteredView.Image")));
this.miSelectInUnfilteredView.Name = "miSelectInUnfilteredView";
this.miSelectInUnfilteredView.Size = new System.Drawing.Size(268, 22);
this.miSelectInUnfilteredView.Text = "Undo Filters and Select This Message";
this.miSelectInUnfilteredView.Click += new System.EventHandler(this.miSelectInUnfilteredView_Click);
//
// copySelectedMessagesMenuItem
//
this.copySelectedMessagesMenuItem.Image = global::Debwin.UI.Properties.Resources.Copy;
this.copySelectedMessagesMenuItem.Name = "copySelectedMessagesMenuItem";
this.copySelectedMessagesMenuItem.Size = new System.Drawing.Size(268, 22);
this.copySelectedMessagesMenuItem.Text = "Copy Selected Messages";
this.copySelectedMessagesMenuItem.Click += new System.EventHandler(this.copySelectedMessagesToolStripMenuItem_Click);
//
// setBaseForRelativeTimeMenuItem
//
this.setBaseForRelativeTimeMenuItem.Name = "setBaseForRelativeTimeMenuItem";
this.setBaseForRelativeTimeMenuItem.Size = new System.Drawing.Size(268, 22);
this.setBaseForRelativeTimeMenuItem.Text = "Set as Base for Relative Timestamps";
this.setBaseForRelativeTimeMenuItem.Click += new System.EventHandler(this.setBaseForRelativeTimeMenuItem_Click);
//
// chooseColumnsMenuItem
//
this.chooseColumnsMenuItem.Name = "chooseColumnsMenuItem";
this.chooseColumnsMenuItem.Size = new System.Drawing.Size(268, 22);
this.chooseColumnsMenuItem.Text = "Choose Columns...";
this.chooseColumnsMenuItem.Click += new System.EventHandler(this.chooseColumnsMenuItem_Click);
//
// toolStripMenuItem1
//
this.toolStripMenuItem1.Name = "toolStripMenuItem1";
this.toolStripMenuItem1.Size = new System.Drawing.Size(265, 6);
//
// filterToolStripMenuItem
//
this.filterToolStripMenuItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
this.filterToolStripMenuItem.Enabled = false;
this.filterToolStripMenuItem.Font = new System.Drawing.Font("Segoe UI", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.filterToolStripMenuItem.Name = "filterToolStripMenuItem";
this.filterToolStripMenuItem.Size = new System.Drawing.Size(268, 22);
this.filterToolStripMenuItem.Text = "Filter by";
//
// dateFromToolStripMenuItem
//
this.dateFromToolStripMenuItem.Name = "dateFromToolStripMenuItem";
this.dateFromToolStripMenuItem.Size = new System.Drawing.Size(268, 22);
this.dateFromToolStripMenuItem.Text = "Date/Time (From)";
this.dateFromToolStripMenuItem.Click += new System.EventHandler(this.SetDateFilterToolStripMenuItem_Click);
//
// dateToToolStripMenuItem
//
this.dateToToolStripMenuItem.Name = "dateToToolStripMenuItem";
this.dateToToolStripMenuItem.Size = new System.Drawing.Size(268, 22);
this.dateToToolStripMenuItem.Text = "Date/Time (To)";
this.dateToToolStripMenuItem.Click += new System.EventHandler(this.SetDateFilterToolStripMenuItem_Click);
//
// byThreadToolStripMenuItem
//
this.byThreadToolStripMenuItem.Name = "byThreadToolStripMenuItem";
this.byThreadToolStripMenuItem.Size = new System.Drawing.Size(268, 22);
this.byThreadToolStripMenuItem.Text = "Thread";
this.byThreadToolStripMenuItem.Click += new System.EventHandler(this.byThreadToolStripMenuItem_Click);
//
// includeLoggerInFilterMenuItem
//
this.includeLoggerInFilterMenuItem.Name = "includeLoggerInFilterMenuItem";
this.includeLoggerInFilterMenuItem.Size = new System.Drawing.Size(268, 22);
this.includeLoggerInFilterMenuItem.Text = "Logger (Include)";
this.includeLoggerInFilterMenuItem.Click += new System.EventHandler(this.includeLoggerInFilterMenuItem_Click);
//
// excludeLoggerInFilterMenuItem
//
this.excludeLoggerInFilterMenuItem.Name = "excludeLoggerInFilterMenuItem";
this.excludeLoggerInFilterMenuItem.Size = new System.Drawing.Size(268, 22);
this.excludeLoggerInFilterMenuItem.Text = "Logger (Exclude)";
this.excludeLoggerInFilterMenuItem.Click += new System.EventHandler(this.excludeLoggerInFilterMenuItem_Click);
//
// includeModuleInFilterMenuItem
//
this.includeModuleInFilterMenuItem.Name = "includeModuleInFilterMenuItem";
this.includeModuleInFilterMenuItem.Size = new System.Drawing.Size(268, 22);
this.includeModuleInFilterMenuItem.Text = "Module (Include)";
this.includeModuleInFilterMenuItem.Click += new System.EventHandler(this.includeModuleInFilterMenuItem_Click);
//
// excludeModuleInFilterMenuItem
//
this.excludeModuleInFilterMenuItem.Name = "excludeModuleInFilterMenuItem";
this.excludeModuleInFilterMenuItem.Size = new System.Drawing.Size(268, 22);
this.excludeModuleInFilterMenuItem.Text = "Module (Exclude)";
this.excludeModuleInFilterMenuItem.Click += new System.EventHandler(this.excludeModuleInFilterMenuItem_Click);
//
// lstLogMessages
//
this.lstLogMessages.AllowColumnReorder = true;
this.lstLogMessages.Dock = System.Windows.Forms.DockStyle.Fill;
this.lstLogMessages.Font = new System.Drawing.Font("Consolas", _userPreferences.ListLogMessageFontSize, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lstLogMessages.FullRowSelect = true;
this.lstLogMessages.HideSelection = false;
this.lstLogMessages.Location = new System.Drawing.Point(0, 25);
this.lstLogMessages.Name = "lstLogMessages";
this.lstLogMessages.ShowGroups = false;
this.lstLogMessages.Size = new System.Drawing.Size(976, 317);
this.lstLogMessages.SmallImageList = this.ilLogLevelIcons;
this.lstLogMessages.TabIndex = 6;
this.lstLogMessages.UseCompatibleStateImageBehavior = false;
this.lstLogMessages.View = System.Windows.Forms.View.Details;
this.lstLogMessages.VirtualMode = true;
this.lstLogMessages.Scroll += new System.Windows.Forms.ScrollEventHandler(this.lstLogMessages_Scroll);
this.lstLogMessages.ScrolledToEnd += new System.EventHandler(this.lstLogMessages_ScrolledToEnd);
this.lstLogMessages.ColumnReordered += new System.Windows.Forms.ColumnReorderedEventHandler(this.lstLogMessages_ColumnReordered);
this.lstLogMessages.RetrieveVirtualItem += new System.Windows.Forms.RetrieveVirtualItemEventHandler(this.LstLogMessages_RetrieveVirtualItem);
this.lstLogMessages.SelectedIndexChanged += new System.EventHandler(this.lstLogMessages_SelectedIndexChanged);
this.lstLogMessages.VirtualItemsSelectionRangeChanged += new System.Windows.Forms.ListViewVirtualItemsSelectionRangeChangedEventHandler(this.lstLogMessages_VirtualItemsSelectionRangeChanged);
this.lstLogMessages.KeyDown += new System.Windows.Forms.KeyEventHandler(this.lstLogMessages_KeyDown);
this.lstLogMessages.MouseClick += new System.Windows.Forms.MouseEventHandler(this.lstLogMessages_MouseClick);
this.lstLogMessages.MouseWheel += new System.Windows.Forms.MouseEventHandler(this.lstLogMessages_MouseWheel);
//
// toolStrip1
//
this.toolStrip1.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden;
this.toolStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.btnCaptureActive,
this.btnClearLog,
this.btnToggleAutoScroll,
this.autoScrollToolstripSeparator,
this.btnSaveLog,
this.btnCopyLog,
this.btnAppendMessage,
this.toolStripSeparator1,
this.btnSavedFilters,
this.btnPopLogView,
this.toolStripSeparator2,
this.btnFindLastIssue,
this.btnFindNextIssue,
this.toolStripLabel1,
this.txtSearchBox,
this.findTextMenuItem});
this.toolStrip1.Location = new System.Drawing.Point(0, 0);
this.toolStrip1.Name = "toolStrip1";
this.toolStrip1.RenderMode = System.Windows.Forms.ToolStripRenderMode.Professional;
this.toolStrip1.Size = new System.Drawing.Size(976, 25);
this.toolStrip1.TabIndex = 2;
this.toolStrip1.Text = "toolStrip1";
//
// btnCaptureActive
//
this.btnCaptureActive.Checked = true;
this.btnCaptureActive.CheckState = System.Windows.Forms.CheckState.Checked;
this.btnCaptureActive.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.btnCaptureActive.Image = ((System.Drawing.Image)(resources.GetObject("btnCaptureActive.Image")));
this.btnCaptureActive.ImageTransparentColor = System.Drawing.Color.Magenta;
this.btnCaptureActive.Margin = new System.Windows.Forms.Padding(3, 1, 0, 2);
this.btnCaptureActive.Name = "btnCaptureActive";
this.btnCaptureActive.Size = new System.Drawing.Size(23, 22);
this.btnCaptureActive.Text = "Turn logging on or off";
this.btnCaptureActive.Click += new System.EventHandler(this.btnStartStopReceiver_Click);
//
// btnClearLog
//
this.btnClearLog.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.btnClearLog.Image = global::Debwin.UI.Properties.Resources.Waste_Bin;
this.btnClearLog.ImageTransparentColor = System.Drawing.Color.Magenta;
this.btnClearLog.Name = "btnClearLog";
this.btnClearLog.Size = new System.Drawing.Size(23, 22);
this.btnClearLog.Text = "Clear";
this.btnClearLog.ToolTipText = "Clear all messages in the current view (Ctrl+Del)";
this.btnClearLog.Click += new System.EventHandler(this.btnClearLog_Click);
//
// btnToggleAutoScroll
//
this.btnToggleAutoScroll.Checked = true;
this.btnToggleAutoScroll.CheckState = System.Windows.Forms.CheckState.Checked;
this.btnToggleAutoScroll.Image = global::Debwin.UI.Properties.Resources.Autoscroll_On;
this.btnToggleAutoScroll.ImageTransparentColor = System.Drawing.Color.Magenta;
this.btnToggleAutoScroll.Name = "btnToggleAutoScroll";
this.btnToggleAutoScroll.Size = new System.Drawing.Size(87, 22);
this.btnToggleAutoScroll.Text = "Auto-Scroll";
this.btnToggleAutoScroll.ToolTipText = "Auto-Scroll to the end of the message list (F5)";
this.btnToggleAutoScroll.Click += new System.EventHandler(this.btnToggleAutoScroll_Click);
//
// autoScrollToolstripSeparator
//
this.autoScrollToolstripSeparator.Name = "autoScrollToolstripSeparator";
this.autoScrollToolstripSeparator.Size = new System.Drawing.Size(6, 25);
//
// btnSaveLog
//
this.btnSaveLog.DropDownButtonWidth = 16;
this.btnSaveLog.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.btnSaveAndEditLog, this.btnSaveWithSpecificColumns});
this.btnSaveLog.Image = global::Debwin.UI.Properties.Resources.Save;
this.btnSaveLog.ImageTransparentColor = System.Drawing.Color.Magenta;
this.btnSaveLog.Name = "btnSaveLog";
this.btnSaveLog.Size = new System.Drawing.Size(91, 22);
this.btnSaveLog.Text = "Save Log";
this.btnSaveLog.ToolTipText = "Saves the log to a file (Ctrl+S).\r\nIf multiple messages are selected, only these " +
"messages are saved.";
this.btnSaveLog.ButtonClick += new System.EventHandler(this.btnSaveLog_Click);
//
// btnSaveAndEditLog
//
this.btnSaveAndEditLog.Name = "btnSaveAndEditLog";
this.btnSaveAndEditLog.Size = new System.Drawing.Size(200, 22);
this.btnSaveAndEditLog.Text = "Save and Open in Editor";
this.btnSaveAndEditLog.Click += new System.EventHandler(this.btnSaveLog_Click);
//
// btnSaveWithSpecificColumns
//
this.btnSaveWithSpecificColumns.Name = "btnSaveWithSpecificColumns";
this.btnSaveWithSpecificColumns.Size = new System.Drawing.Size(200, 22);
this.btnSaveWithSpecificColumns.Text = "Save Log with Specific Columns";
this.btnSaveWithSpecificColumns.Click += new System.EventHandler(this.btnSaveWithSpecificColumns_Click);
//
// btnCopyLog
//
this.btnCopyLog.Image = global::Debwin.UI.Properties.Resources.Copy;
this.btnCopyLog.ImageTransparentColor = System.Drawing.Color.Magenta;
this.btnCopyLog.Name = "btnCopyLog";
this.btnCopyLog.Size = new System.Drawing.Size(78, 22);
this.btnCopyLog.Text = "Copy Log";
this.btnCopyLog.ToolTipText = "Copies the log to the clipboard (Ctrl+C)\r\nIf multiple messages are selected, only" +
" these messages are copied.";
this.btnCopyLog.Click += new System.EventHandler(this.btnSaveLog_Click);
//
// btnAppendMessage
//
this.btnAppendMessage.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.btnAppendMessage.Image = ((System.Drawing.Image)(resources.GetObject("btnAppendMessage.Image")));
this.btnAppendMessage.ImageTransparentColor = System.Drawing.Color.Magenta;
this.btnAppendMessage.Name = "btnAppendMessage";
this.btnAppendMessage.Size = new System.Drawing.Size(23, 22);
this.btnAppendMessage.Text = "Add Comment";
this.btnAppendMessage.ToolTipText = "Adds a custom message to the log";
this.btnAppendMessage.Click += new System.EventHandler(this.btnAppendMessage_Click);
//
// toolStripSeparator1
//
this.toolStripSeparator1.Name = "toolStripSeparator1";
this.toolStripSeparator1.Size = new System.Drawing.Size(6, 25);
//
// btnSavedFilters
//
this.btnSavedFilters.Image = ((System.Drawing.Image)(resources.GetObject("btnSavedFilters.Image")));
this.btnSavedFilters.ImageTransparentColor = System.Drawing.Color.Magenta;
this.btnSavedFilters.Name = "btnSavedFilters";
this.btnSavedFilters.Size = new System.Drawing.Size(76, 22);
this.btnSavedFilters.Text = "Filters...";
this.btnSavedFilters.ToolTipText = "Load a saved filter";
//
// btnPopLogView
//
this.btnPopLogView.Enabled = false;
this.btnPopLogView.Image = ((System.Drawing.Image)(resources.GetObject("btnPopLogView.Image")));
this.btnPopLogView.ImageTransparentColor = System.Drawing.Color.Magenta;
this.btnPopLogView.Name = "btnPopLogView";
this.btnPopLogView.Size = new System.Drawing.Size(83, 22);
this.btnPopLogView.Text = "Clear Filter";
this.btnPopLogView.ToolTipText = "Disables any filters so all messages are visible (Ctrl+Z)";
this.btnPopLogView.Click += new System.EventHandler(this.btnPopLogView_ButtonClick);
//
// toolStripSeparator2
//
this.toolStripSeparator2.Name = "toolStripSeparator2";
this.toolStripSeparator2.Size = new System.Drawing.Size(6, 25);
//
// btnFindLastIssue
//
this.btnFindLastIssue.Image = global::Debwin.UI.Properties.Resources.Arrow_Up_Orange;
this.btnFindLastIssue.ImageTransparentColor = System.Drawing.Color.Magenta;
this.btnFindLastIssue.Name = "btnFindLastIssue";
this.btnFindLastIssue.Size = new System.Drawing.Size(101, 22);
this.btnFindLastIssue.Text = "Previous Issue";
this.btnFindLastIssue.ToolTipText = "Go to previous warning/error (Ctrl+Up)";
this.btnFindLastIssue.Click += new System.EventHandler(this.btnFindIssue_Click);
//
// btnFindNextIssue
//
this.btnFindNextIssue.Image = global::Debwin.UI.Properties.Resources.Arrow_Down_Orange;
this.btnFindNextIssue.ImageTransparentColor = System.Drawing.Color.Magenta;
this.btnFindNextIssue.Name = "btnFindNextIssue";
this.btnFindNextIssue.Size = new System.Drawing.Size(80, 22);
this.btnFindNextIssue.Text = "Next Issue";
this.btnFindNextIssue.ToolTipText = "Go to next warning/error (Ctrl+Down)";
this.btnFindNextIssue.Click += new System.EventHandler(this.btnFindIssue_Click);
//
// toolStripLabel1
//
this.toolStripLabel1.Name = "toolStripLabel1";
this.toolStripLabel1.Size = new System.Drawing.Size(45, 22);
this.toolStripLabel1.Text = "Search:";
//
// txtSearchBox
//
this.txtSearchBox.BackColor = System.Drawing.SystemColors.Window;
this.txtSearchBox.Name = "txtSearchBox";
this.txtSearchBox.Size = new System.Drawing.Size(150, 25);
this.txtSearchBox.ToolTipText = "Find next item containg a text (Ctrl+F)\r\nEnclose in slashes to enable regex searc" +
"h: /regex/";
this.txtSearchBox.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.txtSearchBox_KeyPress);
this.txtSearchBox.KeyUp += new System.Windows.Forms.KeyEventHandler(this.txtSearchBox_KeyUp);
this.txtSearchBox.TextChanged += new System.EventHandler(this.txtSearchBox_TextChanged);
this.txtSearchBox.Click += new System.EventHandler(this.txtSearchBox_Click);
//
// findTextMenuItem
//
this.findTextMenuItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.findTextMenuItem.DropDownButtonWidth = 16;
this.findTextMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.findNextMenuItem,
this.findLastMenuItem,
this.toolStripMenuItem2,
this.caseSensitiveMenuItem,
this.patternsToolStripMenuItem,
this.goToLineToolStripMenuItem});
this.findTextMenuItem.Image = global::Debwin.UI.Properties.Resources.Find;
this.findTextMenuItem.ImageTransparentColor = System.Drawing.Color.Magenta;
this.findTextMenuItem.Name = "findTextMenuItem";
this.findTextMenuItem.Size = new System.Drawing.Size(37, 22);
this.findTextMenuItem.Text = "Search Text";
this.findTextMenuItem.ButtonClick += new System.EventHandler(this.findTextMenuItem_ButtonClick);
//
// findNextMenuItem
//
this.findNextMenuItem.Name = "findNextMenuItem";
this.findNextMenuItem.ShortcutKeys = System.Windows.Forms.Keys.F3;
this.findNextMenuItem.Size = new System.Drawing.Size(222, 22);
this.findNextMenuItem.Text = "Find Next (Down)";
this.findNextMenuItem.Click += new System.EventHandler(this.findTextMenuItem_ButtonClick);
//
// findLastMenuItem
//
this.findLastMenuItem.Name = "findLastMenuItem";
this.findLastMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Shift | System.Windows.Forms.Keys.F3)));
this.findLastMenuItem.Size = new System.Drawing.Size(222, 22);
this.findLastMenuItem.Text = "Find Previous (Up)";
this.findLastMenuItem.Click += new System.EventHandler(this.findTextMenuItem_ButtonClick);
//
// toolStripMenuItem2
//
this.toolStripMenuItem2.Name = "toolStripMenuItem2";
this.toolStripMenuItem2.Size = new System.Drawing.Size(219, 6);
//
// caseSensitiveMenuItem
//
this.caseSensitiveMenuItem.CheckOnClick = true;
this.caseSensitiveMenuItem.Name = "caseSensitiveMenuItem";
this.caseSensitiveMenuItem.Size = new System.Drawing.Size(222, 22);
this.caseSensitiveMenuItem.Text = "Case Sensitive";
//
// patternsToolStripMenuItem
//
this.patternsToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.errorCodeNegNumberToolStripMenuItem});
this.patternsToolStripMenuItem.Name = "patternsToolStripMenuItem";
this.patternsToolStripMenuItem.Size = new System.Drawing.Size(222, 22);
this.patternsToolStripMenuItem.Text = "Regex Patterns";
//
// errorCodeNegNumberToolStripMenuItem
//
this.errorCodeNegNumberToolStripMenuItem.Name = "errorCodeNegNumberToolStripMenuItem";
this.errorCodeNegNumberToolStripMenuItem.Size = new System.Drawing.Size(213, 22);
this.errorCodeNegNumberToolStripMenuItem.Text = "Error Code (Neg. Number)";
this.errorCodeNegNumberToolStripMenuItem.Click += new System.EventHandler(this.errorCodeNegNumberToolStripMenuItem_Click);
//
// goToLineToolStripMenuItem
//
this.goToLineToolStripMenuItem.Name = "goToLineToolStripMenuItem";
this.goToLineToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.G)));
this.goToLineToolStripMenuItem.Size = new System.Drawing.Size(222, 22);
this.goToLineToolStripMenuItem.Text = "Go to Line";
this.goToLineToolStripMenuItem.Click += new System.EventHandler(this.goToLineToolStripMenuItem_Click);
//
// LogViewPanel
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1206, 391);
this.Controls.Add(this.panelLogView);
this.Controls.Add(this.panelLogLoader);
this.Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.Name = "LogViewPanel";
this.Text = "LogPanel";
this.Load += new System.EventHandler(this.LogViewPanel_Load);
this.statusStrip1.ResumeLayout(false);
this.statusStrip1.PerformLayout();
this.panelLogLoader.ResumeLayout(false);
this.panelLogView.ResumeLayout(false);
this.panelLogView.PerformLayout();
this.mnuLogMessageContext.ResumeLayout(false);
this.toolStrip1.ResumeLayout(false);
this.toolStrip1.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.ToolStrip toolStrip1;
private System.Windows.Forms.ToolStripButton btnToggleAutoScroll;
private System.Windows.Forms.ToolStripButton btnClearLog;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator1;
private Controls.DoubleBufferedListView lstLogMessages;
private System.Windows.Forms.ImageList ilLogLevelIcons;
private System.Windows.Forms.Timer listviewLayoutTimer;
private System.Windows.Forms.StatusStrip statusStrip1;
private System.Windows.Forms.ToolStripStatusLabel lblVisibleMessageCount;
private System.Windows.Forms.Panel panelLogLoader;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Panel panelLogView;
private System.Windows.Forms.ContextMenuStrip mnuLogMessageContext;
private System.Windows.Forms.ToolStripMenuItem filterToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem dateFromToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem dateToToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripMenuItem1;
private System.Windows.Forms.ToolStripMenuItem miSelectInUnfilteredView;
private System.Windows.Forms.ToolStripButton btnPopLogView;
private System.Windows.Forms.ToolStripMenuItem byThreadToolStripMenuItem;
private System.Windows.Forms.ToolStripButton btnFindNextIssue;
private System.Windows.Forms.ToolStripButton btnFindLastIssue;
private System.Windows.Forms.ToolStripButton btnAppendMessage;
private System.Windows.Forms.ToolStripSeparator autoScrollToolstripSeparator;
private System.Windows.Forms.ToolStripLabel toolStripLabel1;
private System.Windows.Forms.ToolStripComboBox txtSearchBox;
private System.Windows.Forms.ToolStripButton btnCopyLog;
private System.Windows.Forms.ToolStripMenuItem caseSensitiveMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripMenuItem2;
private System.Windows.Forms.ToolStripMenuItem findLastMenuItem;
private System.Windows.Forms.ToolStripMenuItem findNextMenuItem;
private System.Windows.Forms.ToolStripSplitButton findTextMenuItem;
private System.Windows.Forms.ToolStripMenuItem copySelectedMessagesMenuItem;
private System.Windows.Forms.ToolStripMenuItem patternsToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem errorCodeNegNumberToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem btnSaveAndEditLog;
private System.Windows.Forms.ToolStripMenuItem btnSaveWithSpecificColumns;
private System.Windows.Forms.ToolStripSplitButton btnSaveLog;
private System.Windows.Forms.ToolStripStatusLabel lblVisibleMessages;
private System.Windows.Forms.ToolStripStatusLabel lblBufferedMessagesCount;
private System.Windows.Forms.ToolStripStatusLabel lblBufferedMessages;
private System.Windows.Forms.ToolStripMenuItem setBaseForRelativeTimeMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator2;
private System.Windows.Forms.ToolStripMenuItem includeLoggerInFilterMenuItem;
private System.Windows.Forms.ToolStripMenuItem excludeLoggerInFilterMenuItem;
private System.Windows.Forms.ToolStripMenuItem includeModuleInFilterMenuItem;
private System.Windows.Forms.ToolStripMenuItem excludeModuleInFilterMenuItem;
private System.Windows.Forms.ToolStripMenuItem chooseColumnsMenuItem;
private System.Windows.Forms.ToolStripDropDownButton btnSavedFilters;
private System.Windows.Forms.ToolStripStatusLabel lblFilterNameLabel;
private System.Windows.Forms.ToolStripStatusLabel lblFilterNameValue;
private System.Windows.Forms.ToolStripStatusLabel lblAttachedFileNotification;
private System.Windows.Forms.ToolStripStatusLabel lblAttachedLogFileName;
private System.Windows.Forms.ToolStripStatusLabel lblReceivedMessages;
private System.Windows.Forms.ToolStripStatusLabel lblReceivedMessageCount;
private System.Windows.Forms.ToolStripButton btnCaptureActive;
private System.Windows.Forms.ToolStripMenuItem goToLineToolStripMenuItem;
private System.Windows.Forms.ToolStripStatusLabel lblLineNumberLabel;
private System.Windows.Forms.ToolStripStatusLabel lblLineNumber;
}
} | 62.052632 | 232 | 0.673198 | [
"MIT"
] | combit/Debwin | Debwin.UI/Panels/LogViewPanel.Designer.cs | 47,162 | 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.AzureNextGen.Compute.V20180601.Outputs
{
[OutputType]
public sealed class RollingUpgradePolicyResponse
{
/// <summary>
/// The maximum percent of total virtual machine instances that will be upgraded simultaneously by the rolling upgrade in one batch. As this is a maximum, unhealthy instances in previous or future batches can cause the percentage of instances in a batch to decrease to ensure higher reliability. The default value for this parameter is 20%.
/// </summary>
public readonly int? MaxBatchInstancePercent;
/// <summary>
/// The maximum percentage of the total virtual machine instances in the scale set that can be simultaneously unhealthy, either as a result of being upgraded, or by being found in an unhealthy state by the virtual machine health checks before the rolling upgrade aborts. This constraint will be checked prior to starting any batch. The default value for this parameter is 20%.
/// </summary>
public readonly int? MaxUnhealthyInstancePercent;
/// <summary>
/// The maximum percentage of upgraded virtual machine instances that can be found to be in an unhealthy state. This check will happen after each batch is upgraded. If this percentage is ever exceeded, the rolling update aborts. The default value for this parameter is 20%.
/// </summary>
public readonly int? MaxUnhealthyUpgradedInstancePercent;
/// <summary>
/// The wait time between completing the update for all virtual machines in one batch and starting the next batch. The time duration should be specified in ISO 8601 format. The default value is 0 seconds (PT0S).
/// </summary>
public readonly string? PauseTimeBetweenBatches;
[OutputConstructor]
private RollingUpgradePolicyResponse(
int? maxBatchInstancePercent,
int? maxUnhealthyInstancePercent,
int? maxUnhealthyUpgradedInstancePercent,
string? pauseTimeBetweenBatches)
{
MaxBatchInstancePercent = maxBatchInstancePercent;
MaxUnhealthyInstancePercent = maxUnhealthyInstancePercent;
MaxUnhealthyUpgradedInstancePercent = maxUnhealthyUpgradedInstancePercent;
PauseTimeBetweenBatches = pauseTimeBetweenBatches;
}
}
}
| 53.24 | 384 | 0.722765 | [
"Apache-2.0"
] | pulumi/pulumi-azure-nextgen | sdk/dotnet/Compute/V20180601/Outputs/RollingUpgradePolicyResponse.cs | 2,662 | C# |
namespace PageFeatures;
public class PagingEntity
{
private class PageNumberData
{
public const int Start_Page = 1;
public const int Quantity_Per_Page = 3;
public const int Page_Size = 8;
}
private const int max_Page_Size = 50;
public int PageNumber { get; set; } = 1;
private int pageSize = PageNumberData.Page_Size;
public int PageSize
{
get => this.pageSize;
set => this.pageSize = (value > max_Page_Size) ? max_Page_Size : value;
}
public string SearchTerm { get; set; } = string.Empty;
public string OrderBy { get; set; } = "name";
}
| 24.192308 | 79 | 0.63434 | [
"MIT"
] | pragmatic-applications/MAK.Lib.CoreLite | PageFeatures/PagingEntity.cs | 631 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DataSource.Employees;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Internal;
namespace DataSource.Seeds
{
public class EmployeeSourceSeeding
{
public static async Task Run()
{
Console.WriteLine("Creating employee source seed....");
using (var context = new AuditorDbContext(ContextProvider.ContextOptions))
{
List<EmployeeSource> sources = new List<EmployeeSource>()
{
new EmployeeSource()
{
SocialSecurityNumber = "01010101",
FirstName = "Kari",
LastName = "Nordmann",
Department = "Sales"
},
new EmployeeSource()
{
SocialSecurityNumber = "01010102",
FirstName = "Jack",
LastName = "Jackson",
Department = "Support"
},
new EmployeeSource()
{
SocialSecurityNumber = "01010103",
FirstName = "Nils",
LastName = "Nilsen",
Department = "Sales"
},
};
foreach (var source in sources)
{
var employeeSource = await context.EmployeeSources.FirstOrDefaultAsync(x => x.SocialSecurityNumber == source.SocialSecurityNumber);
if (employeeSource == null)
{
context.EmployeeSources.Add(source);
}
else
{
employeeSource.FirstName = source.FirstName;
employeeSource.LastName = source.LastName;
employeeSource.Department = source.Department;
context.EmployeeSources.Update(employeeSource);
}
}
await context.SaveChangesAsync();
}
}
}
}
| 34.283582 | 151 | 0.463648 | [
"MIT"
] | sabbiryan/entity-auditor | Auditor/DataSource/Seeds/EmployeeSourceSeeding.cs | 2,299 | C# |
using System.Data.Entity;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
namespace AspNetWebApp1.DotNetFramework.SPA.Models
{
// You can add profile data for the user by adding more properties to your ApplicationUser class, please visit https://go.microsoft.com/fwlink/?LinkID=317594 to learn more.
public class ApplicationUser : IdentityUser
{
public string Hometown { get; set; }
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
return userIdentity;
}
}
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
}
} | 36.485714 | 176 | 0.70556 | [
"MIT"
] | iwhp/AspNetIdentitySideBySide | AspNetWebApp1.DotNetFramework.SPA/Models/IdentityModels.cs | 1,279 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using Microsoft.Azure.Amqp;
using Microsoft.Azure.Amqp.Encoding;
namespace Azure.Messaging.ServiceBus.Amqp
{
internal class AmqpClientConstants
{
// AMQP Management Operation
public const string ManagementAddress = "$management";
public const string EntityTypeManagement = "entity-mgmt";
public const string EntityNameKey = "name";
public const string PartitionNameKey = "partition";
public const string ManagementOperationKey = "operation";
public const string ReadOperationValue = "READ";
public const string ManagementEntityTypeKey = "type";
public const string ManagementSecurityTokenKey = "security_token";
// Filters
public const string FilterOffsetPartName = "amqp.annotation.x-opt-offset";
public const string FilterOffset = FilterOffsetPartName + " > ";
public const string FilterInclusiveOffset = FilterOffsetPartName + " >= ";
public const string FilterOffsetFormatString = FilterOffset + "'{0}'";
public const string FilterInclusiveOffsetFormatString = FilterInclusiveOffset + "'{0}'";
public const string FilterReceivedAtPartNameV1 = "amqp.annotation.x-opt-enqueuedtimeutc";
public const string FilterReceivedAtPartNameV2 = "amqp.annotation.x-opt-enqueued-time";
public const string FilterReceivedAt = FilterReceivedAtPartNameV2 + " > ";
public const string FilterReceivedAtFormatString = FilterReceivedAt + "{0}";
public static readonly AmqpSymbol SessionFilterName = AmqpConstants.Vendor + ":session-filter";
public static readonly AmqpSymbol MessageReceiptsFilterName = AmqpConstants.Vendor + ":message-receipts-filter";
public static readonly AmqpSymbol ClientSideCursorFilterName = AmqpConstants.Vendor + ":client-side-filter";
public static readonly TimeSpan ClientMinimumTokenRefreshInterval = TimeSpan.FromMinutes(4);
// Properties
public static readonly AmqpSymbol AttachEpoch = AmqpConstants.Vendor + ":epoch";
public static readonly AmqpSymbol BatchFlushIntervalName = AmqpConstants.Vendor + ":batch-flush-interval";
public static readonly AmqpSymbol EntityTypeName = AmqpConstants.Vendor + ":entity-type";
public static readonly AmqpSymbol TransferDestinationAddress = AmqpConstants.Vendor + ":transfer-destination-address";
public static readonly AmqpSymbol TimeoutName = AmqpConstants.Vendor + ":timeout";
public static readonly AmqpSymbol TrackingIdName = AmqpConstants.Vendor + ":tracking-id";
// Error codes
public static readonly AmqpSymbol DeadLetterName = AmqpConstants.Vendor + ":dead-letter";
public static readonly AmqpSymbol TimeoutError = AmqpConstants.Vendor + ":timeout";
public static readonly AmqpSymbol AddressAlreadyInUseError = AmqpConstants.Vendor + ":address-already-in-use";
public static readonly AmqpSymbol AuthorizationFailedError = AmqpConstants.Vendor + ":auth-failed";
public static readonly AmqpSymbol MessageLockLostError = AmqpConstants.Vendor + ":message-lock-lost";
public static readonly AmqpSymbol SessionLockLostError = AmqpConstants.Vendor + ":session-lock-lost";
public static readonly AmqpSymbol StoreLockLostError = AmqpConstants.Vendor + ":store-lock-lost";
public static readonly AmqpSymbol SessionCannotBeLockedError = AmqpConstants.Vendor + ":session-cannot-be-locked";
public static readonly AmqpSymbol NoMatchingSubscriptionError = AmqpConstants.Vendor + ":no-matching-subscription";
public static readonly AmqpSymbol ServerBusyError = AmqpConstants.Vendor + ":server-busy";
public static readonly AmqpSymbol ArgumentError = AmqpConstants.Vendor + ":argument-error";
public static readonly AmqpSymbol ArgumentOutOfRangeError = AmqpConstants.Vendor + ":argument-out-of-range";
public static readonly AmqpSymbol PartitionNotOwnedError = AmqpConstants.Vendor + ":partition-not-owned";
public static readonly AmqpSymbol EntityDisabledError = AmqpConstants.Vendor + ":entity-disabled";
public static readonly AmqpSymbol PublisherRevokedError = AmqpConstants.Vendor + ":publisher-revoked";
public static readonly AmqpSymbol OperationCancelledError = AmqpConstants.Vendor + ":operation-cancelled";
public static readonly AmqpSymbol EntityAlreadyExistsError = AmqpConstants.Vendor + ":entity-already-exists";
public static readonly AmqpSymbol RelayNotFoundError = AmqpConstants.Vendor + ":relay-not-found";
public static readonly AmqpSymbol MessageNotFoundError = AmqpConstants.Vendor + ":message-not-found";
public static readonly AmqpSymbol LockedUntilUtc = AmqpConstants.Vendor + ":locked-until-utc";
}
}
| 72.176471 | 126 | 0.746944 | [
"MIT"
] | 0rland0Wats0n/azure-sdk-for-net | sdk/servicebus/Azure.Messaging.ServiceBus/src/Amqp/AmqpClientConstants.cs | 4,910 | C# |
using UnityEngine;
public class Rotate : MonoBehaviour
{
public float x = 0;
public float y = 0.0624f;
public float z = 0;
void Update()
{
transform.Rotate(new Vector3(x, y, z));
}
}
| 15.571429 | 47 | 0.587156 | [
"MIT"
] | MarkHerdt/SpaceInvader-Unity-2020 | Unity Project/Assets/Scripts/Rotate.cs | 220 | C# |
using System.Linq;
using Api.Analysers;
using Api.Utility;
using DataAccess;
using DataAccess.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Shared;
using Shared.Dtos;
namespace Api.Controllers {
[Route("api/[controller]")]
[ApiController]
[Authorize]
public class RidesController : ControllerBase {
private readonly DbFactory dbFactory;
public RidesController(DbFactory dbFactory) {
this.dbFactory = dbFactory;
}
[HttpGet]
[Route("{id}")]
public ActionResult<RideDto> Get(int id) {
int userId = this.GetCurrentUserId();
using (Transaction transaction = dbFactory.CreateReadOnlyTransaction()) {
var ride = RideHelper.GetRideDto(transaction, id, userId);
if (ride == null) {
return NotFound();
}
return ride;
}
}
[HttpPost]
[Route("add")]
public ActionResult<RideFeedDto> Add(CreateRideDto model) {
if (!ModelState.IsValid) {
return BadRequest(ModelState);
}
int userId = this.GetCurrentUserId();
int rideId;
using (Transaction transaction = dbFactory.CreateTransaction()) {
rideId = SaveRide(transaction, userId, model);
Analyser.AnalyseRide(transaction, userId, rideId);
transaction.Commit();
}
using (Transaction transaction = dbFactory.CreateReadOnlyTransaction()) {
return GetRideOverview(transaction, rideId);
}
}
private RideFeedDto GetRideOverview(Transaction transaction, int rideId) {
using (ModelDataContext context = transaction.CreateDataContext()) {
var medals = context.TrailAttempts
.Where(row => row.RideId == rideId)
.Where(row => row.Medal != (int)Medal.None)
.Select(row => (Medal)row.Medal)
.ToList();
return context.Rides
.Where(row => row.RideId == rideId)
.Select(row => new RideFeedDto {
UserId = row.UserId,
UserName = row.User.Name,
UserProfileImageUrl = row.User.ProfileImageUrl,
RideId = row.RideId,
Name = row.Name,
Date = row.StartUtc,
DistanceMiles = row.DistanceMiles,
EndUtc = row.EndUtc,
MaxSpeedMph = row.MaxSpeedMph,
Medals = medals,
RouteSvgPath = row.RouteSvgPath,
})
.SingleOrDefault();
}
}
private int SaveRide(Transaction transaction, int userId, CreateRideDto model) {
using (ModelDataContext context = transaction.CreateDataContext()) {
Ride ride = new Ride();
ride.StartUtc = model.StartUtc;
ride.EndUtc = model.EndUtc;
ride.UserId = userId;
ride.AverageSpeedMph = 0;
ride.MaxSpeedMph = 0;
ride.DistanceMiles = 0;
ride.RouteSvgPath = "-";
ride.AnalyserVersion = Analyser.AnalyserVersion;
ride.RideLocations = model.Locations
.Select(i => new RideLocation {
AccuracyInMetres = i.AccuracyInMetres,
Altitude = i.Altitude,
Latitude = i.Latitude,
Longitude = i.Longitude,
Mph = i.Mph,
Timestamp = i.Timestamp,
})
.ToList();
ride.Jumps = model.Jumps
.Select(i => new Jump {
Airtime = i.Airtime,
Number = i.Number,
Timestamp = i.Timestamp,
Latitude = i.Latitude,
Longitude = i.Longitude,
})
.ToList();
ride.AccelerometerReadings = model.AccelerometerReadings
.Select(i => new AccelerometerReading {
Time = i.Timestamp,
X = i.X,
Y = i.Y,
Z = i.Z,
})
.ToList();
context.Rides.Add(ride);
context.SaveChanges();
return ride.RideId;
}
}
[HttpPost]
[Route("reanalyse")]
public ActionResult Analyse([FromBody] int rideId) {
if (!ModelState.IsValid) {
return BadRequest(ModelState);
}
int userId = this.GetCurrentUserId();
using (Transaction transaction = dbFactory.CreateTransaction()) {
RideHelper.ThrowIfNotOwner(transaction, rideId, userId);
using (ModelDataContext context = transaction.CreateDataContext()) {
var attempts = context.TrailAttempts.Where(row => row.RideId == rideId);
var jumpAchievements = context.UserJumpAchievements.Where(row => row.RideId == rideId);
var speedAchievements = context.UserSpeedAchievements.Where(row => row.RideId == rideId);
var distanceAchievements = context.UserDistanceAchievements.Where(row => row.RideId == rideId);
context.SaveChanges();
}
Analyser.AnalyseRide(transaction, userId, rideId);
transaction.Commit();
}
return Ok();
}
[HttpPost]
[Route("delete")]
public ActionResult<bool> Delete([FromBody] int rideId) {
int userId = this.GetCurrentUserId();
using (Transaction transaction = dbFactory.CreateTransaction()) {
using (ModelDataContext context = transaction.CreateDataContext()) {
var ride = context.Rides
.Where(row => row.RideId == rideId)
.Where(row => row.UserId == userId)
.SingleOrDefault();
if (ride == null) {
return NotFound();
}
var locations = context.RideLocations.Where(row => row.RideId == rideId);
var jumps = context.Jumps.Where(row => row.RideId == rideId);
var attempts = context.TrailAttempts.Where(row => row.RideId == rideId);
var jumpAchievements = context.UserJumpAchievements.Where(row => row.RideId == rideId);
var speedAchievements = context.UserSpeedAchievements.Where(row => row.RideId == rideId);
var distanceAchievements = context.UserDistanceAchievements.Where(row => row.RideId == rideId);
var accelerometerReadings = context.AccelerometerReadings.Where(row => row.RideId == rideId);
context.RideLocations.RemoveRange(locations);
context.Jumps.RemoveRange(jumps);
context.TrailAttempts.RemoveRange(attempts);
context.UserJumpAchievements.RemoveRange(jumpAchievements);
context.UserSpeedAchievements.RemoveRange(speedAchievements);
context.UserDistanceAchievements.RemoveRange(distanceAchievements);
context.AccelerometerReadings.RemoveRange(accelerometerReadings);
context.Rides.Remove(ride);
context.SaveChanges();
}
transaction.Commit();
}
return true;
}
[HttpGet]
[Route("latest-analyser-version")]
public ActionResult<int> LatestAnalyserVersion() {
return Analyser.AnalyserVersion;
}
}
} | 37.990698 | 115 | 0.513345 | [
"MIT"
] | ormesam/mtb-mate | src/Api/Controllers/RidesController.cs | 8,170 | C# |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// <auto-generated/>
// Template Source: EntityRequestBuilder.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
/// <summary>
/// The type RoleManagementRequestBuilder.
/// </summary>
public partial class RoleManagementRequestBuilder : BaseRequestBuilder, IRoleManagementRequestBuilder
{
/// <summary>
/// Constructs a new RoleManagementRequestBuilder.
/// </summary>
/// <param name="requestUrl">The URL for the built request.</param>
/// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param>
public RoleManagementRequestBuilder(
string requestUrl,
IBaseClient client)
: base(requestUrl, client)
{
}
/// <summary>
/// Builds the request.
/// </summary>
/// <returns>The built request.</returns>
public IRoleManagementRequest Request()
{
return this.Request(null);
}
/// <summary>
/// Builds the request.
/// </summary>
/// <param name="options">The query and header options for the request.</param>
/// <returns>The built request.</returns>
public IRoleManagementRequest Request(IEnumerable<Option> options)
{
return new RoleManagementRequest(this.RequestUrl, this.Client, options);
}
/// <summary>
/// Gets the request builder for Directory.
/// </summary>
/// <returns>The <see cref="IRbacApplicationRequestBuilder"/>.</returns>
public IRbacApplicationRequestBuilder Directory
{
get
{
return new RbacApplicationRequestBuilder(this.AppendSegmentToRequestUrl("directory"), this.Client);
}
}
/// <summary>
/// Gets the request builder for CloudPC.
/// </summary>
/// <returns>The <see cref="IRbacApplicationMultipleRequestBuilder"/>.</returns>
public IRbacApplicationMultipleRequestBuilder CloudPC
{
get
{
return new RbacApplicationMultipleRequestBuilder(this.AppendSegmentToRequestUrl("cloudPC"), this.Client);
}
}
/// <summary>
/// Gets the request builder for EntitlementManagement.
/// </summary>
/// <returns>The <see cref="IRbacApplicationRequestBuilder"/>.</returns>
public IRbacApplicationRequestBuilder EntitlementManagement
{
get
{
return new RbacApplicationRequestBuilder(this.AppendSegmentToRequestUrl("entitlementManagement"), this.Client);
}
}
/// <summary>
/// Gets the request builder for DeviceManagement.
/// </summary>
/// <returns>The <see cref="IRbacApplicationMultipleRequestBuilder"/>.</returns>
public IRbacApplicationMultipleRequestBuilder DeviceManagement
{
get
{
return new RbacApplicationMultipleRequestBuilder(this.AppendSegmentToRequestUrl("deviceManagement"), this.Client);
}
}
}
}
| 35.174757 | 153 | 0.577422 | [
"MIT"
] | ScriptBox99/msgraph-beta-sdk-dotnet | src/Microsoft.Graph/Generated/requests/RoleManagementRequestBuilder.cs | 3,623 | C# |
// Copyright 2017 the original author or 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
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Hosting;
using Steeltoe.Common.Diagnostics;
using Steeltoe.Extensions.Logging;
using Steeltoe.Management.Census.Trace;
using System;
using System.Linq;
using Xunit;
namespace Steeltoe.Management.Tracing.Test
{
public class TracingServiceCollectionExtensionsTest : TestBase
{
[Fact]
public void AddDistributedTracing_ThrowsOnNulls()
{
// Arrange
IServiceCollection services = null;
IServiceCollection services2 = new ServiceCollection();
IConfiguration config = null;
// Act and Assert
var ex = Assert.Throws<ArgumentNullException>(() => TracingServiceCollectionExtensions.AddDistributedTracing(services, config));
Assert.Contains(nameof(services), ex.Message);
var ex2 = Assert.Throws<ArgumentNullException>(() => TracingServiceCollectionExtensions.AddDistributedTracing(services2, config));
Assert.Contains(nameof(config), ex2.Message);
}
[Fact]
public void AddDistributedTracing_AddsCorrectServices()
{
ServiceCollection services = new ServiceCollection();
var config = GetConfiguration();
services.AddOptions();
services.AddSingleton<Microsoft.AspNetCore.Hosting.IHostingEnvironment>(new TestHost());
services.AddDistributedTracing(config);
var serviceProvider = services.BuildServiceProvider();
var mgr = serviceProvider.GetService<IDiagnosticsManager>();
Assert.NotNull(mgr);
var hst = serviceProvider.GetService<IHostedService>();
Assert.NotNull(hst);
var opts = serviceProvider.GetService<ITracingOptions>();
Assert.NotNull(opts);
var observers = serviceProvider.GetServices<IDiagnosticObserver>();
var list = observers.ToList();
Assert.Equal(5, list.Count);
var tracing = serviceProvider.GetService<ITracing>();
Assert.NotNull(tracing);
var processer = serviceProvider.GetService<IDynamicMessageProcessor>();
Assert.NotNull(processer);
}
private class TestHost : Microsoft.AspNetCore.Hosting.IHostingEnvironment
{
public string EnvironmentName { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
public string ApplicationName { get => "foobar"; set => throw new NotImplementedException(); }
public string WebRootPath { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
public IFileProvider WebRootFileProvider { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
public string ContentRootPath { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
public IFileProvider ContentRootFileProvider { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
}
}
}
| 42.241758 | 148 | 0.690947 | [
"Apache-2.0"
] | budorcas/steeltoe | src/Management/test/TracingCore.Test/TracingServiceCollectionExtensionsTest.cs | 3,846 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Management.Automation.Internal;
using Dbg = System.Management.Automation.Diagnostics;
namespace System.Management.Automation
{
/// <summary>
/// Used to enumerate the commands on the system that match the specified
/// command name.
/// </summary>
internal class CommandSearcher : IEnumerable<CommandInfo>, IEnumerator<CommandInfo>
{
/// <summary>
/// Constructs a command searching enumerator that resolves the location
/// to a command using a standard algorithm.
/// </summary>
/// <param name="commandName">
/// The name of the command to look for.
/// </param>
/// <param name="options">
/// Determines which types of commands glob resolution of the name will take place on.
/// </param>
/// <param name="commandTypes">
/// The types of commands to look for.
/// </param>
/// <param name="context">
/// The execution context for this engine instance...
/// </param>
/// <exception cref="ArgumentNullException">
/// If <paramref name="context"/> is null.
/// </exception>
/// <exception cref="PSArgumentException">
/// If <paramref name="commandName"/> is null or empty.
/// </exception>
internal CommandSearcher(
string commandName,
SearchResolutionOptions options,
CommandTypes commandTypes,
ExecutionContext context)
{
Diagnostics.Assert(context != null, "caller to verify context is not null");
Diagnostics.Assert(!string.IsNullOrEmpty(commandName), "caller to verify commandName is valid");
_commandName = commandName;
_context = context;
_commandResolutionOptions = options;
_commandTypes = commandTypes;
// Initialize the enumerators
this.Reset();
}
/// <summary>
/// Gets an instance of a command enumerator.
/// </summary>
/// <returns>
/// An instance of this class as IEnumerator.
/// </returns>
IEnumerator<CommandInfo> IEnumerable<CommandInfo>.GetEnumerator()
{
return this;
}
IEnumerator IEnumerable.GetEnumerator()
{
return this;
}
/// <summary>
/// Moves the enumerator to the next command match. Public for IEnumerable.
/// </summary>
/// <returns>
/// true if there was another command that matches, false otherwise.
/// </returns>
public bool MoveNext()
{
_currentMatch = null;
if (_currentState == SearchState.SearchingAliases)
{
_currentMatch = SearchForAliases();
// Why don't we check IsVisible on other scoped items?
if (_currentMatch != null && SessionState.IsVisible(_commandOrigin, _currentMatch))
{
return true;
}
// Make sure Current doesn't return an alias that isn't visible
_currentMatch = null;
// Advance the state
_currentState = SearchState.SearchingFunctions;
}
if (_currentState == SearchState.SearchingFunctions)
{
_currentMatch = SearchForFunctions();
// Return the alias info only if it is visible. If not, then skip to the next
// stage of command resolution...
if (_currentMatch != null)
{
return true;
}
// Advance the state
_currentState = SearchState.SearchingCmdlets;
}
if (_currentState == SearchState.SearchingCmdlets)
{
_currentMatch = SearchForCmdlets();
if (_currentMatch != null)
{
return true;
}
// Advance the state
_currentState = SearchState.StartSearchingForExternalCommands;
}
if (_currentState == SearchState.StartSearchingForExternalCommands)
{
if ((_commandTypes & (CommandTypes.Application | CommandTypes.ExternalScript)) == 0)
{
// Since we are not requiring any path lookup in this search, just return false now
// because all the remaining searches do path lookup.
return false;
}
// For security reasons, if the command is coming from outside the runspace and it looks like a path,
// we want to pre-check that path before doing any probing of the network or drives
if (_commandOrigin == CommandOrigin.Runspace && _commandName.IndexOfAny(Utils.Separators.DirectoryOrDrive) >= 0)
{
bool allowed = false;
// Ok - it looks like it might be a path, so we're going to check to see if the command is prefixed
// by any of the allowed paths. If so, then we allow the search to proceed...
// If either the Applications or Script lists contain just '*' the command is allowed
// at this point.
if ((_context.EngineSessionState.Applications.Count == 1 &&
_context.EngineSessionState.Applications[0].Equals("*", StringComparison.OrdinalIgnoreCase)) ||
(_context.EngineSessionState.Scripts.Count == 1 &&
_context.EngineSessionState.Scripts[0].Equals("*", StringComparison.OrdinalIgnoreCase)))
{
allowed = true;
}
else
{
// Ok see it it's in the applications list
foreach (string path in _context.EngineSessionState.Applications)
{
if (checkPath(path, _commandName))
{
allowed = true;
break;
}
}
// If it wasn't in the applications list, see it's in the script list
if (!allowed)
{
foreach (string path in _context.EngineSessionState.Scripts)
{
if (checkPath(path, _commandName))
{
allowed = true;
break;
}
}
}
}
if (!allowed)
{
return false;
}
}
// Advance the state
_currentState = SearchState.PowerShellPathResolution;
_currentMatch = ProcessBuiltinScriptState();
if (_currentMatch != null)
{
// Set the current state to QualifiedFileSystemPath since
// we want to skip the qualified file system path search
// in the case where we found a PowerShell qualified path.
_currentState = SearchState.QualifiedFileSystemPath;
return true;
}
}
if (_currentState == SearchState.PowerShellPathResolution)
{
_currentState = SearchState.QualifiedFileSystemPath;
_currentMatch = ProcessPathResolutionState();
if (_currentMatch != null)
{
return true;
}
}
// Search using CommandPathSearch
if (_currentState == SearchState.QualifiedFileSystemPath ||
_currentState == SearchState.PathSearch)
{
_currentMatch = ProcessQualifiedFileSystemState();
if (_currentMatch != null)
{
return true;
}
}
if (_currentState == SearchState.PathSearch)
{
_currentState = SearchState.PowerShellRelativePath;
_currentMatch = ProcessPathSearchState();
if (_currentMatch != null)
{
return true;
}
}
return false;
}
private CommandInfo SearchForAliases()
{
CommandInfo currentMatch = null;
if (_context.EngineSessionState != null &&
(_commandTypes & CommandTypes.Alias) != 0)
{
currentMatch = GetNextAlias();
}
return currentMatch;
}
private CommandInfo SearchForFunctions()
{
CommandInfo currentMatch = null;
if (_context.EngineSessionState != null &&
(_commandTypes & (CommandTypes.Function | CommandTypes.Filter | CommandTypes.Configuration)) != 0)
{
currentMatch = GetNextFunction();
}
return currentMatch;
}
private CommandInfo SearchForCmdlets()
{
CommandInfo currentMatch = null;
if ((_commandTypes & CommandTypes.Cmdlet) != 0)
{
currentMatch = GetNextCmdlet();
}
return currentMatch;
}
private CommandInfo ProcessBuiltinScriptState()
{
CommandInfo currentMatch = null;
// Check to see if the path is qualified
if (_context.EngineSessionState != null &&
_context.EngineSessionState.ProviderCount > 0 &&
IsQualifiedPSPath(_commandName))
{
currentMatch = GetNextFromPath();
}
return currentMatch;
}
private CommandInfo ProcessPathResolutionState()
{
CommandInfo currentMatch = null;
try
{
// Check to see if the path is a file system path that
// is rooted. If so that is the next match
if (Path.IsPathRooted(_commandName) &&
File.Exists(_commandName))
{
try
{
currentMatch = GetInfoFromPath(_commandName);
}
catch (FileLoadException)
{
}
catch (FormatException)
{
}
catch (MetadataException)
{
}
}
}
catch (ArgumentException)
{
// If the path contains illegal characters that
// weren't caught by the other APIs, IsPathRooted
// will throw an exception.
// For example, looking for a command called
// `abcdef
// The `a will be translated into the beep control character
// which is not a legal file system character, though
// Path.InvalidPathChars does not contain it as an invalid
// character.
}
return currentMatch;
}
private CommandInfo ProcessQualifiedFileSystemState()
{
try
{
setupPathSearcher();
}
catch (ArgumentException)
{
_currentState = SearchState.NoMoreMatches;
throw;
}
catch (PathTooLongException)
{
_currentState = SearchState.NoMoreMatches;
throw;
}
CommandInfo currentMatch = null;
_currentState = SearchState.PathSearch;
if (_canDoPathLookup)
{
try
{
while (currentMatch == null && _pathSearcher.MoveNext())
{
currentMatch = GetInfoFromPath(((IEnumerator<string>)_pathSearcher).Current);
}
}
catch (InvalidOperationException)
{
// The enumerator may throw if there are no more matches
}
}
return currentMatch;
}
private CommandInfo ProcessPathSearchState()
{
CommandInfo currentMatch = null;
string path = DoPowerShellRelativePathLookup();
if (!string.IsNullOrEmpty(path))
{
currentMatch = GetInfoFromPath(path);
}
return currentMatch;
}
/// <summary>
/// Gets the CommandInfo representing the current command match.
/// </summary>
/// <value></value>
/// <exception cref="InvalidOperationException">
/// The enumerator is positioned before the first element of
/// the collection or after the last element.
/// </exception>
CommandInfo IEnumerator<CommandInfo>.Current
{
get
{
if ((_currentState == SearchState.SearchingAliases && _currentMatch == null) ||
_currentState == SearchState.NoMoreMatches ||
_currentMatch == null)
{
throw PSTraceSource.NewInvalidOperationException();
}
return _currentMatch;
}
}
object IEnumerator.Current
{
get
{
return ((IEnumerator<CommandInfo>)this).Current;
}
}
/// <summary>
/// Required by the IEnumerator generic interface.
/// Resets the searcher.
/// </summary>
public void Dispose()
{
if (_pathSearcher != null)
{
_pathSearcher.Dispose();
_pathSearcher = null;
}
Reset();
GC.SuppressFinalize(this);
}
#region private members
/// <summary>
/// Gets the next command info using the command name as a path.
/// </summary>
/// <returns>
/// A CommandInfo for the next command if it exists as a path, or null otherwise.
/// </returns>
private CommandInfo GetNextFromPath()
{
CommandInfo result = null;
do // false loop
{
CommandDiscovery.discoveryTracer.WriteLine(
"The name appears to be a qualified path: {0}",
_commandName);
CommandDiscovery.discoveryTracer.WriteLine(
"Trying to resolve the path as an PSPath");
// Find the match if it is.
// Try literal path resolution if it is set to run first
if (_commandResolutionOptions.HasFlag(SearchResolutionOptions.ResolveLiteralThenPathPatterns))
{
var path = GetNextLiteralPathThatExistsAndHandleExceptions(_commandName, out _);
if (path != null)
{
return GetInfoFromPath(path);
}
}
Collection<string> resolvedPaths = new Collection<string>();
if (WildcardPattern.ContainsWildcardCharacters(_commandName))
{
resolvedPaths = GetNextFromPathUsingWildcards(_commandName, out _);
}
// Try literal path resolution if wildcards are enable first and wildcard search failed
if (!_commandResolutionOptions.HasFlag(SearchResolutionOptions.ResolveLiteralThenPathPatterns) &&
resolvedPaths.Count == 0)
{
string path = GetNextLiteralPathThatExistsAndHandleExceptions(_commandName, out _);
if (path != null)
{
return GetInfoFromPath(path);
}
}
if (resolvedPaths.Count > 1)
{
CommandDiscovery.discoveryTracer.TraceError(
"The path resolved to more than one result so this path cannot be used.");
break;
}
// If the path was resolved, and it exists
if (resolvedPaths.Count == 1 &&
File.Exists(resolvedPaths[0]))
{
string path = resolvedPaths[0];
CommandDiscovery.discoveryTracer.WriteLine(
"Path resolved to: {0}",
path);
result = GetInfoFromPath(path);
}
} while (false);
return result;
}
/// <summary>
/// Gets the next path using WildCards.
/// </summary>
/// <param name="command">
/// The command to search for.
/// </param>
/// <param name="provider">The provider that the command was found in.</param>
/// <returns>
/// A collection of full paths to the commands which were found.
/// </returns>
private Collection<string> GetNextFromPathUsingWildcards(string command, out ProviderInfo provider)
{
try
{
return _context.LocationGlobber.GetGlobbedProviderPathsFromMonadPath(path: command, allowNonexistingPaths: false, provider: out provider, providerInstance: out _);
}
catch (ItemNotFoundException)
{
CommandDiscovery.discoveryTracer.TraceError(
"The path could not be found: {0}",
command);
}
catch (DriveNotFoundException)
{
CommandDiscovery.discoveryTracer.TraceError(
"A drive could not be found for the path: {0}",
command);
}
catch (ProviderNotFoundException)
{
CommandDiscovery.discoveryTracer.TraceError(
"A provider could not be found for the path: {0}",
command);
}
catch (InvalidOperationException)
{
CommandDiscovery.discoveryTracer.TraceError(
"The path specified a home directory, but the provider home directory was not set. {0}",
command);
}
catch (ProviderInvocationException providerException)
{
CommandDiscovery.discoveryTracer.TraceError(
"The provider associated with the path '{0}' encountered an error: {1}",
command,
providerException.Message);
}
catch (PSNotSupportedException)
{
CommandDiscovery.discoveryTracer.TraceError(
"The provider associated with the path '{0}' does not implement ContainerCmdletProvider",
command);
}
provider = null;
return new Collection<string>();
}
private static bool checkPath(string path, string commandName)
{
return path.StartsWith(commandName, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Gets the appropriate CommandInfo instance given the specified path.
/// </summary>
/// <param name="path">
/// The path to create the CommandInfo for.
/// </param>
/// <returns>
/// An instance of the appropriate CommandInfo derivative given the specified path.
/// </returns>
/// <exception cref="FileLoadException">
/// The <paramref name="path"/> refers to a cmdlet, or cmdletprovider
/// and it could not be loaded as an XML document.
/// </exception>
/// <exception cref="FormatException">
/// The <paramref name="path"/> refers to a cmdlet, or cmdletprovider
/// that does not adhere to the appropriate file format for its extension.
/// </exception>
/// <exception cref="MetadataException">
/// If <paramref name="path"/> refers to a cmdlet file that
/// contains invalid metadata.
/// </exception>
private CommandInfo GetInfoFromPath(string path)
{
CommandInfo result = null;
do // false loop
{
if (!File.Exists(path))
{
CommandDiscovery.discoveryTracer.TraceError("The path does not exist: {0}", path);
break;
}
// Now create the appropriate CommandInfo using the extension
string extension = null;
try
{
extension = Path.GetExtension(path);
}
catch (ArgumentException)
{
// If the path contains illegal characters that
// weren't caught by the other APIs, GetExtension
// will throw an exception.
// For example, looking for a command called
// `abcdef
// The `a will be translated into the beep control character
// which is not a legal file system character.
}
if (extension == null)
{
result = null;
break;
}
if (string.Equals(extension, StringLiterals.PowerShellScriptFileExtension, StringComparison.OrdinalIgnoreCase))
{
if ((_commandTypes & CommandTypes.ExternalScript) != 0)
{
string scriptName = Path.GetFileName(path);
CommandDiscovery.discoveryTracer.WriteLine(
"Command Found: path ({0}) is a script with name: {1}",
path,
scriptName);
// The path is to a PowerShell script
result = new ExternalScriptInfo(scriptName, path, _context);
break;
}
break;
}
if ((_commandTypes & CommandTypes.Application) != 0)
{
// Anything else is treated like an application
string appName = Path.GetFileName(path);
CommandDiscovery.discoveryTracer.WriteLine(
"Command Found: path ({0}) is an application with name: {1}",
path,
appName);
result = new ApplicationInfo(appName, path, _context);
break;
}
} while (false);
// Verify that this script is not untrusted, if we aren't constrained.
if (ShouldSkipCommandResolutionForConstrainedLanguage(result, _context))
{
result = null;
}
return result;
}
/// <summary>
/// Gets the next matching alias.
/// </summary>
/// <returns>
/// A CommandInfo representing the next matching alias if found, otherwise null.
/// </returns>
private CommandInfo GetNextAlias()
{
CommandInfo result = null;
if ((_commandResolutionOptions & SearchResolutionOptions.ResolveAliasPatterns) != 0)
{
if (_matchingAlias == null)
{
// Generate the enumerator of matching alias names
Collection<AliasInfo> matchingAliases = new Collection<AliasInfo>();
WildcardPattern aliasMatcher =
WildcardPattern.Get(
_commandName,
WildcardOptions.IgnoreCase);
foreach (KeyValuePair<string, AliasInfo> aliasEntry in _context.EngineSessionState.GetAliasTable())
{
if (aliasMatcher.IsMatch(aliasEntry.Key) ||
(_commandResolutionOptions.HasFlag(SearchResolutionOptions.FuzzyMatch) &&
FuzzyMatcher.IsFuzzyMatch(aliasEntry.Key, _commandName)))
{
matchingAliases.Add(aliasEntry.Value);
}
}
// Process alias from modules
AliasInfo c = GetAliasFromModules(_commandName);
if (c != null)
{
matchingAliases.Add(c);
}
_matchingAlias = matchingAliases.GetEnumerator();
}
if (!_matchingAlias.MoveNext())
{
// Advance the state
_currentState = SearchState.SearchingFunctions;
_matchingAlias = null;
}
else
{
result = _matchingAlias.Current;
}
}
else
{
// Advance the state
_currentState = SearchState.SearchingFunctions;
result = _context.EngineSessionState.GetAlias(_commandName) ?? GetAliasFromModules(_commandName);
}
// Verify that this alias was not created by an untrusted constrained language,
// if we aren't constrained.
if (ShouldSkipCommandResolutionForConstrainedLanguage(result, _context))
{
result = null;
}
if (result != null)
{
CommandDiscovery.discoveryTracer.WriteLine(
"Alias found: {0} {1}",
result.Name,
result.Definition);
}
return result;
}
/// <summary>
/// Gets the next matching function.
/// </summary>
/// <returns>
/// A CommandInfo representing the next matching function if found, otherwise null.
/// </returns>
private CommandInfo GetNextFunction()
{
CommandInfo result = null;
if (_commandResolutionOptions.HasFlag(SearchResolutionOptions.ResolveFunctionPatterns))
{
if (_matchingFunctionEnumerator == null)
{
Collection<CommandInfo> matchingFunction = new Collection<CommandInfo>();
// Generate the enumerator of matching function names
WildcardPattern functionMatcher =
WildcardPattern.Get(
_commandName,
WildcardOptions.IgnoreCase);
foreach (DictionaryEntry functionEntry in _context.EngineSessionState.GetFunctionTable())
{
if (functionMatcher.IsMatch((string)functionEntry.Key) ||
(_commandResolutionOptions.HasFlag(SearchResolutionOptions.FuzzyMatch) &&
FuzzyMatcher.IsFuzzyMatch(functionEntry.Key.ToString(), _commandName)))
{
matchingFunction.Add((CommandInfo)functionEntry.Value);
}
else if (_commandResolutionOptions.HasFlag(SearchResolutionOptions.UseAbbreviationExpansion))
{
if (_commandName.Equals(ModuleUtils.AbbreviateName((string)functionEntry.Key), StringComparison.OrdinalIgnoreCase))
{
matchingFunction.Add((CommandInfo)functionEntry.Value);
}
}
}
// Process functions from modules
CommandInfo cmdInfo = GetFunctionFromModules(_commandName);
if (cmdInfo != null)
{
matchingFunction.Add(cmdInfo);
}
_matchingFunctionEnumerator = matchingFunction.GetEnumerator();
}
if (!_matchingFunctionEnumerator.MoveNext())
{
// Advance the state
_currentState = SearchState.SearchingCmdlets;
_matchingFunctionEnumerator = null;
}
else
{
result = _matchingFunctionEnumerator.Current;
}
}
else
{
// Advance the state
_currentState = SearchState.SearchingCmdlets;
result = GetFunction(_commandName);
}
// Verify that this function was not created by an untrusted constrained language,
// if we aren't constrained.
if (ShouldSkipCommandResolutionForConstrainedLanguage(result, _context))
{
result = null;
}
return result;
}
// Don't return commands to the user if that might result in:
// - Trusted commands calling untrusted functions that the user has overridden
// - Debug prompts calling internal functions that are likely to have code injection
private bool ShouldSkipCommandResolutionForConstrainedLanguage(CommandInfo result, ExecutionContext executionContext)
{
if (result == null)
{
return false;
}
// Don't return untrusted commands to trusted functions
if ((result.DefiningLanguageMode == PSLanguageMode.ConstrainedLanguage) &&
(executionContext.LanguageMode == PSLanguageMode.FullLanguage))
{
return true;
}
// Don't allow invocation of trusted functions from debug breakpoints.
// They were probably defined within a trusted script, and could be
// susceptible to injection attacks. However, we do allow execution
// of functions defined in the global scope (i.e.: "more",) as those
// are intended to be exposed explicitly to users.
if ((result is FunctionInfo) &&
(executionContext.LanguageMode == PSLanguageMode.ConstrainedLanguage) &&
(result.DefiningLanguageMode == PSLanguageMode.FullLanguage) &&
(executionContext.Debugger != null) &&
(executionContext.Debugger.InBreakpoint) &&
(!(executionContext.TopLevelSessionState.GetFunctionTableAtScope("GLOBAL").ContainsKey(result.Name))))
{
return true;
}
return false;
}
private AliasInfo GetAliasFromModules(string command)
{
AliasInfo result = null;
if (command.IndexOf('\\') > 0)
{
// See if it's a module qualified alias...
PSSnapinQualifiedName qualifiedName = PSSnapinQualifiedName.GetInstance(command);
if (qualifiedName != null && !string.IsNullOrEmpty(qualifiedName.PSSnapInName))
{
PSModuleInfo module = GetImportedModuleByName(qualifiedName.PSSnapInName);
if (module != null)
{
module.ExportedAliases.TryGetValue(qualifiedName.ShortName, out result);
}
}
}
return result;
}
private CommandInfo GetFunctionFromModules(string command)
{
FunctionInfo result = null;
if (command.IndexOf('\\') > 0)
{
// See if it's a module qualified function call...
PSSnapinQualifiedName qualifiedName = PSSnapinQualifiedName.GetInstance(command);
if (qualifiedName != null && !string.IsNullOrEmpty(qualifiedName.PSSnapInName))
{
PSModuleInfo module = GetImportedModuleByName(qualifiedName.PSSnapInName);
if (module != null)
{
module.ExportedFunctions.TryGetValue(qualifiedName.ShortName, out result);
}
}
}
return result;
}
private PSModuleInfo GetImportedModuleByName(string moduleName)
{
PSModuleInfo module = null;
List<PSModuleInfo> modules = _context.Modules.GetModules(new string[] { moduleName }, false);
if (modules != null && modules.Count > 0)
{
foreach (PSModuleInfo m in modules)
{
if (_context.previousModuleImported.ContainsKey(m.Name) && ((string)_context.previousModuleImported[m.Name] == m.Path))
{
module = m;
break;
}
}
if (module == null)
{
module = modules[0];
}
}
return module;
}
/// <summary>
/// Gets the FunctionInfo or FilterInfo for the specified function name.
/// </summary>
/// <param name="function">
/// The name of the function/filter to retrieve.
/// </param>
/// <returns>
/// A FunctionInfo if the function name exists and is a function, a FilterInfo if
/// the filter name exists and is a filter, or null otherwise.
/// </returns>
private CommandInfo GetFunction(string function)
{
CommandInfo result = _context.EngineSessionState.GetFunction(function);
if (result != null)
{
if (result is FilterInfo)
{
CommandDiscovery.discoveryTracer.WriteLine(
"Filter found: {0}",
function);
}
else if (result is ConfigurationInfo)
{
CommandDiscovery.discoveryTracer.WriteLine(
"Configuration found: {0}",
function);
}
else
{
CommandDiscovery.discoveryTracer.WriteLine(
"Function found: {0} {1}",
function);
}
}
else
{
result = GetFunctionFromModules(function);
}
return result;
}
/// <summary>
/// Gets the next cmdlet from the collection of matching cmdlets.
/// If the collection doesn't exist yet it is created and the
/// enumerator is moved to the first item in the collection.
/// </summary>
/// <returns>
/// A CmdletInfo for the next matching Cmdlet or null if there are
/// no more matches.
/// </returns>
private CmdletInfo GetNextCmdlet()
{
CmdletInfo result = null;
bool useAbbreviationExpansion = _commandResolutionOptions.HasFlag(SearchResolutionOptions.UseAbbreviationExpansion);
if (_matchingCmdlet == null)
{
if (_commandResolutionOptions.HasFlag(SearchResolutionOptions.CommandNameIsPattern) || useAbbreviationExpansion)
{
Collection<CmdletInfo> matchingCmdletInfo = new Collection<CmdletInfo>();
PSSnapinQualifiedName PSSnapinQualifiedCommandName =
PSSnapinQualifiedName.GetInstance(_commandName);
if (!useAbbreviationExpansion && PSSnapinQualifiedCommandName == null)
{
return null;
}
WildcardPattern cmdletMatcher =
WildcardPattern.Get(
PSSnapinQualifiedCommandName.ShortName,
WildcardOptions.IgnoreCase);
SessionStateInternal ss = _context.EngineSessionState;
foreach (List<CmdletInfo> cmdletList in ss.GetCmdletTable().Values)
{
foreach (CmdletInfo cmdlet in cmdletList)
{
if (cmdletMatcher.IsMatch(cmdlet.Name) ||
(_commandResolutionOptions.HasFlag(SearchResolutionOptions.FuzzyMatch) &&
FuzzyMatcher.IsFuzzyMatch(cmdlet.Name, _commandName)))
{
if (string.IsNullOrEmpty(PSSnapinQualifiedCommandName.PSSnapInName) ||
(PSSnapinQualifiedCommandName.PSSnapInName.Equals(
cmdlet.ModuleName, StringComparison.OrdinalIgnoreCase)))
{
// If PSSnapin is specified, make sure they match
matchingCmdletInfo.Add(cmdlet);
}
}
else if (useAbbreviationExpansion)
{
if (_commandName.Equals(ModuleUtils.AbbreviateName(cmdlet.Name), StringComparison.OrdinalIgnoreCase))
{
matchingCmdletInfo.Add(cmdlet);
}
}
}
}
_matchingCmdlet = matchingCmdletInfo.GetEnumerator();
}
else
{
_matchingCmdlet = _context.CommandDiscovery.GetCmdletInfo(_commandName,
_commandResolutionOptions.HasFlag(SearchResolutionOptions.SearchAllScopes));
}
}
if (!_matchingCmdlet.MoveNext())
{
// Advance the state
_currentState = SearchState.StartSearchingForExternalCommands;
_matchingCmdlet = null;
}
else
{
result = _matchingCmdlet.Current;
}
return traceResult(result);
}
private IEnumerator<CmdletInfo> _matchingCmdlet;
private static CmdletInfo traceResult(CmdletInfo result)
{
if (result != null)
{
CommandDiscovery.discoveryTracer.WriteLine(
"Cmdlet found: {0} {1}",
result.Name,
result.ImplementingType);
}
return result;
}
private string DoPowerShellRelativePathLookup()
{
string result = null;
if (_context.EngineSessionState != null &&
_context.EngineSessionState.ProviderCount > 0)
{
// NTRAID#Windows OS Bugs-1009294-2004/02/04-JeffJon
// This is really slow. Maybe since we are only allowing FS paths right
// now we should use the file system APIs to verify the existence of the file.
// Since the path to the command was not found using the PATH variable,
// maybe it is relative to the current location. Try resolving the
// path.
// Relative Path: ".\command.exe"
// Home Path: "~\command.exe"
// Drive Relative Path: "\Users\User\AppData\Local\Temp\command.exe"
if (_commandName[0] == '.' || _commandName[0] == '~' || _commandName[0] == '\\')
{
using (CommandDiscovery.discoveryTracer.TraceScope(
"{0} appears to be a relative path. Trying to resolve relative path",
_commandName))
{
result = ResolvePSPath(_commandName);
}
}
}
return result;
}
/// <summary>
/// Resolves the given path as an PSPath and ensures that it was resolved
/// by the FileSystemProvider.
/// </summary>
/// <param name="path">
/// The path to resolve.
/// </param>
/// <returns>
/// The path that was resolved. Null if the path couldn't be resolved or was
/// not resolved by the FileSystemProvider.
/// </returns>
private string ResolvePSPath(string path)
{
string result = null;
try
{
ProviderInfo provider = null;
string resolvedPath = null;
// Try literal path resolution if it is set to run first
if (_commandResolutionOptions.HasFlag(SearchResolutionOptions.ResolveLiteralThenPathPatterns))
{
// Cannot return early as this code path only expects
// The file system provider and the final check for that
// must verify this before we return.
resolvedPath = GetNextLiteralPathThatExists(path, out provider);
}
if (WildcardPattern.ContainsWildcardCharacters(path) &&
((resolvedPath == null) || (provider == null)))
{
// Let PowerShell resolve relative path with wildcards.
Collection<string> resolvedPaths = GetNextFromPathUsingWildcards(path, out provider);
if (resolvedPaths.Count == 0)
{
resolvedPath = null;
CommandDiscovery.discoveryTracer.TraceError(
"The relative path with wildcard did not resolve to valid path. {0}",
path);
}
else if (resolvedPaths.Count > 1)
{
resolvedPath = null;
CommandDiscovery.discoveryTracer.TraceError(
"The relative path with wildcard resolved to multiple paths. {0}",
path);
}
else
{
resolvedPath = resolvedPaths[0];
}
}
// Try literal path resolution if wildcards are enabled first and wildcard search failed
if (!_commandResolutionOptions.HasFlag(SearchResolutionOptions.ResolveLiteralThenPathPatterns) &&
((resolvedPath == null) || (provider == null)))
{
resolvedPath = GetNextLiteralPathThatExists(path, out provider);
}
// Verify the path was resolved to a file system path
if (provider != null && provider.NameEquals(_context.ProviderNames.FileSystem))
{
result = resolvedPath;
CommandDiscovery.discoveryTracer.WriteLine(
"The relative path was resolved to: {0}",
result);
}
else
{
// The path was not to the file system
CommandDiscovery.discoveryTracer.TraceError(
"The relative path was not a file system path. {0}",
path);
}
}
catch (InvalidOperationException)
{
CommandDiscovery.discoveryTracer.TraceError(
"The home path was not specified for the provider. {0}",
path);
}
catch (ProviderInvocationException providerInvocationException)
{
CommandDiscovery.discoveryTracer.TraceError(
"While resolving the path, \"{0}\", an error was encountered by the provider: {1}",
path,
providerInvocationException.Message);
}
catch (ItemNotFoundException)
{
CommandDiscovery.discoveryTracer.TraceError(
"The path does not exist: {0}",
path);
}
catch (DriveNotFoundException driveNotFound)
{
CommandDiscovery.discoveryTracer.TraceError(
"The drive does not exist: {0}",
driveNotFound.ItemName);
}
return result;
}
/// <summary>
/// Gets the next literal path.
/// Filtering to ones that exist for the filesystem.
/// Handles Exceptions
/// </summary>
/// <param name="command">
/// The command to search for.
/// </param>
/// <param name="provider">The provider that the command was found in.</param>
/// <returns>
/// Full path to the command.
/// </returns>
private string GetNextLiteralPathThatExistsAndHandleExceptions(string command, out ProviderInfo provider)
{
try
{
return GetNextLiteralPathThatExists(command, out provider);
}
catch (ItemNotFoundException)
{
CommandDiscovery.discoveryTracer.TraceError(
"The path could not be found: {0}",
_commandName);
}
catch (DriveNotFoundException)
{
// This can be because we think a scope or a url is a drive
// and need to continue searching.
// Although, scope does not work through get-command
CommandDiscovery.discoveryTracer.TraceError(
"A drive could not be found for the path: {0}",
_commandName);
}
catch (ProviderNotFoundException)
{
CommandDiscovery.discoveryTracer.TraceError(
"A provider could not be found for the path: {0}",
_commandName);
}
catch (InvalidOperationException)
{
CommandDiscovery.discoveryTracer.TraceError(
"The path specified a home directory, but the provider home directory was not set. {0}",
_commandName);
}
catch (ProviderInvocationException providerException)
{
CommandDiscovery.discoveryTracer.TraceError(
"The provider associated with the path '{0}' encountered an error: {1}",
_commandName,
providerException.Message);
}
catch (PSNotSupportedException)
{
CommandDiscovery.discoveryTracer.TraceError(
"The provider associated with the path '{0}' does not implement ContainerCmdletProvider",
_commandName);
}
provider = null;
return null;
}
/// <summary>
/// Gets the next literal path.
/// Filtering to ones that exist for the filesystem.
/// </summary>
/// <param name="command">
/// The command to search for.
/// </param>
/// <param name="provider">The provider that the command was found in.</param>
/// <returns>
/// Full path to the command.
/// </returns>
private string GetNextLiteralPathThatExists(string command, out ProviderInfo provider)
{
string resolvedPath = _context.LocationGlobber.GetProviderPath(command, out provider);
if (provider.NameEquals(_context.ProviderNames.FileSystem)
&& !File.Exists(resolvedPath)
&& !Directory.Exists(resolvedPath))
{
provider = null;
return null;
}
return resolvedPath;
}
/// <summary>
/// Creates a collection of patterns used to find the command.
/// </summary>
/// <param name="name">
/// The name of the command to search for.
/// </param>
/// <param name="commandDiscovery">Get names for command discovery.</param>
/// <returns>
/// A collection of the patterns used to find the command.
/// The patterns are as follows:
/// 1. [commandName].cmdlet
/// 2. [commandName].ps1
/// 3..x
/// foreach (extension in PATHEXT)
/// [commandName].[extension]
/// x+1. [commandName]
/// </returns>
/// <exception cref="ArgumentException">
/// If <paramref name="name"/> contains one or more of the
/// invalid characters defined in InvalidPathChars.
/// </exception>
internal LookupPathCollection ConstructSearchPatternsFromName(string name, bool commandDiscovery = false)
{
Dbg.Assert(
!string.IsNullOrEmpty(name),
"Caller should verify name");
var result = new LookupPathCollection();
// First check to see if the commandName has an extension, if so
// look for that first
bool commandNameAddedFirst = Path.HasExtension(name);
if (commandNameAddedFirst)
{
result.Add(name);
}
// Add the extensions for script, module and data files in that order...
if (_commandTypes.HasFlag(CommandTypes.ExternalScript))
{
result.Add(name + StringLiterals.PowerShellScriptFileExtension);
if (!commandDiscovery)
{
// psd1 and psm1 are not executable, so don't add them
result.Add(name + StringLiterals.PowerShellModuleFileExtension);
result.Add(name + StringLiterals.PowerShellDataFileExtension);
}
}
#if !UNIX
if (_commandTypes.HasFlag(CommandTypes.Application))
{
// Now add each extension from the PATHEXT environment variable
foreach (string extension in CommandDiscovery.PathExtensions)
{
result.Add(name + extension);
}
}
#endif
// Now add the commandName by itself if it wasn't added as the first pattern
if (!commandNameAddedFirst)
{
result.Add(name);
}
return result;
}
/// <summary>
/// Determines if the given command name is a qualified PowerShell path.
/// </summary>
/// <param name="commandName">
/// The name of the command.
/// </param>
/// <returns>
/// True if the command name is either a provider-qualified or PowerShell drive-qualified
/// path. False otherwise.
/// </returns>
private static bool IsQualifiedPSPath(string commandName)
{
Dbg.Assert(
!string.IsNullOrEmpty(commandName),
"The caller should have verified the commandName");
bool result =
LocationGlobber.IsAbsolutePath(commandName) ||
LocationGlobber.IsProviderQualifiedPath(commandName) ||
LocationGlobber.IsHomePath(commandName) ||
LocationGlobber.IsProviderDirectPath(commandName);
return result;
}
private enum CanDoPathLookupResult
{
Yes,
PathIsRooted,
WildcardCharacters,
DirectorySeparator,
IllegalCharacters
}
/// <summary>
/// Determines if the command name has any path special
/// characters which would require resolution. If so,
/// path lookup will not succeed.
/// </summary>
/// <param name="possiblePath">
/// The command name (or possible path) to look for the special characters.
/// </param>
/// <returns>
/// True if the command name does not contain any special
/// characters. False otherwise.
/// </returns>
private static CanDoPathLookupResult CanDoPathLookup(string possiblePath)
{
CanDoPathLookupResult result = CanDoPathLookupResult.Yes;
do // false loop
{
// If the command name contains any wildcard characters
// we can't do the path lookup
if (WildcardPattern.ContainsWildcardCharacters(possiblePath))
{
result = CanDoPathLookupResult.WildcardCharacters;
break;
}
try
{
if (Path.IsPathRooted(possiblePath))
{
result = CanDoPathLookupResult.PathIsRooted;
break;
}
}
catch (ArgumentException)
{
result = CanDoPathLookupResult.IllegalCharacters;
break;
}
// If the command contains any path separators, we can't
// do the path lookup
if (possiblePath.IndexOfAny(Utils.Separators.Directory) != -1)
{
result = CanDoPathLookupResult.DirectorySeparator;
break;
}
// If the command contains any invalid path characters, we can't
// do the path lookup
if (possiblePath.IndexOfAny(Path.GetInvalidPathChars()) != -1)
{
result = CanDoPathLookupResult.IllegalCharacters;
break;
}
} while (false);
return result;
}
/// <summary>
/// The command name to search for.
/// </summary>
private string _commandName;
/// <summary>
/// Determines which command types will be globbed.
/// </summary>
private SearchResolutionOptions _commandResolutionOptions;
/// <summary>
/// Determines which types of commands to look for.
/// </summary>
private CommandTypes _commandTypes = CommandTypes.All;
/// <summary>
/// The enumerator that uses the Path to
/// search for commands.
/// </summary>
private CommandPathSearch _pathSearcher;
/// <summary>
/// The execution context instance for the current engine...
/// </summary>
private ExecutionContext _context;
/// <summary>
/// A routine to initialize the path searcher...
/// </summary>
/// <exception cref="ArgumentException">
/// If the commandName used to construct this object
/// contains one or more of the invalid characters defined
/// in InvalidPathChars.
/// </exception>
private void setupPathSearcher()
{
// If it's already set up, just return...
if (_pathSearcher != null)
{
return;
}
// We are never going to look for non-executable commands in CommandSearcher.
// Even though file types like .DOC, .LOG,.TXT, etc. can be opened / invoked, users think of these as files, not applications.
// So I don't think we should show applications with the additional extensions at all.
// Applications should only include files whose extensions are in the PATHEXT list and these would only be returned with the All parameter.
if ((_commandResolutionOptions & SearchResolutionOptions.CommandNameIsPattern) != 0)
{
_canDoPathLookup = true;
_canDoPathLookupResult = CanDoPathLookupResult.Yes;
_pathSearcher =
new CommandPathSearch(
_commandName,
_context.CommandDiscovery.GetLookupDirectoryPaths(),
_context,
acceptableCommandNames: null,
useFuzzyMatch: _commandResolutionOptions.HasFlag(SearchResolutionOptions.FuzzyMatch));
}
else
{
_canDoPathLookupResult = CanDoPathLookup(_commandName);
if (_canDoPathLookupResult == CanDoPathLookupResult.Yes)
{
_canDoPathLookup = true;
_commandName = _commandName.TrimEnd(Utils.Separators.PathSearchTrimEnd);
_pathSearcher =
new CommandPathSearch(
_commandName,
_context.CommandDiscovery.GetLookupDirectoryPaths(),
_context,
ConstructSearchPatternsFromName(_commandName, commandDiscovery: true),
useFuzzyMatch: false);
}
else if (_canDoPathLookupResult == CanDoPathLookupResult.PathIsRooted)
{
_canDoPathLookup = true;
string directory = Path.GetDirectoryName(_commandName);
var directoryCollection = new LookupPathCollection { directory };
CommandDiscovery.discoveryTracer.WriteLine(
"The path is rooted, so only doing the lookup in the specified directory: {0}",
directory);
string fileName = Path.GetFileName(_commandName);
if (!string.IsNullOrEmpty(fileName))
{
fileName = fileName.TrimEnd(Utils.Separators.PathSearchTrimEnd);
_pathSearcher =
new CommandPathSearch(
fileName,
directoryCollection,
_context,
ConstructSearchPatternsFromName(fileName, commandDiscovery: true),
useFuzzyMatch: false);
}
else
{
_canDoPathLookup = false;
}
}
else if (_canDoPathLookupResult == CanDoPathLookupResult.DirectorySeparator)
{
_canDoPathLookup = true;
// We must try to resolve the path as an PSPath or else we can't do
// path lookup for relative paths.
string directory = Path.GetDirectoryName(_commandName);
directory = ResolvePSPath(directory);
CommandDiscovery.discoveryTracer.WriteLine(
"The path is relative, so only doing the lookup in the specified directory: {0}",
directory);
if (directory == null)
{
_canDoPathLookup = false;
}
else
{
var directoryCollection = new LookupPathCollection { directory };
string fileName = Path.GetFileName(_commandName);
if (!string.IsNullOrEmpty(fileName))
{
fileName = fileName.TrimEnd(Utils.Separators.PathSearchTrimEnd);
_pathSearcher =
new CommandPathSearch(
fileName,
directoryCollection,
_context,
ConstructSearchPatternsFromName(fileName, commandDiscovery: true),
useFuzzyMatch: false);
}
else
{
_canDoPathLookup = false;
}
}
}
}
}
/// <summary>
/// Resets the enumerator to before the first command match, public for IEnumerable.
/// </summary>
public void Reset()
{
// If this is a command coming from outside the runspace and there are no
// permitted scripts or applications,
// remove them from the set of things to search for...
if (_commandOrigin == CommandOrigin.Runspace)
{
if (_context.EngineSessionState.Applications.Count == 0)
_commandTypes &= ~CommandTypes.Application;
if (_context.EngineSessionState.Scripts.Count == 0)
_commandTypes &= ~CommandTypes.ExternalScript;
}
if (_pathSearcher != null)
{
_pathSearcher.Reset();
}
_currentMatch = null;
_currentState = SearchState.SearchingAliases;
_matchingAlias = null;
_matchingCmdlet = null;
}
internal CommandOrigin CommandOrigin
{
get { return _commandOrigin; }
set { _commandOrigin = value; }
}
private CommandOrigin _commandOrigin = CommandOrigin.Internal;
/// <summary>
/// An enumerator of the matching aliases.
/// </summary>
private IEnumerator<AliasInfo> _matchingAlias;
/// <summary>
/// An enumerator of the matching functions.
/// </summary>
private IEnumerator<CommandInfo> _matchingFunctionEnumerator;
/// <summary>
/// The CommandInfo that references the command that matches the pattern.
/// </summary>
private CommandInfo _currentMatch;
private bool _canDoPathLookup;
private CanDoPathLookupResult _canDoPathLookupResult = CanDoPathLookupResult.Yes;
/// <summary>
/// The current state of the enumerator.
/// </summary>
private SearchState _currentState = SearchState.SearchingAliases;
private enum SearchState
{
// the searcher has been reset or has not been advanced since being created.
SearchingAliases,
// the searcher has finished alias resolution and is now searching for functions.
SearchingFunctions,
// the searcher has finished function resolution and is now searching for cmdlets
SearchingCmdlets,
// the search has finished builtin script resolution and is now searching for external commands
StartSearchingForExternalCommands,
// the searcher has moved to
PowerShellPathResolution,
// the searcher has moved to a qualified file system path
QualifiedFileSystemPath,
// the searcher has moved to using a CommandPathSearch object
// for resolution
PathSearch,
// the searcher has moved to using a CommandPathSearch object
// with get prepended to the command name for resolution
GetPathSearch,
// the searcher has moved to resolving the command as a
// relative PowerShell path
PowerShellRelativePath,
// No more matches can be found
NoMoreMatches,
}
#endregion private members
}
/// <summary>
/// Determines which types of commands should be globbed using the specified
/// pattern. Any flag that is not specified will only match if exact.
/// </summary>
[Flags]
internal enum SearchResolutionOptions
{
None = 0x0,
ResolveAliasPatterns = 0x01,
ResolveFunctionPatterns = 0x02,
CommandNameIsPattern = 0x04,
SearchAllScopes = 0x08,
/// <summary>Use fuzzy matching.</summary>
FuzzyMatch = 0x10,
/// <summary>
/// Enable searching for cmdlets/functions by abbreviation expansion.
/// </summary>
UseAbbreviationExpansion = 0x20,
/// <summary>
/// Enable resolving wildcard in paths.
/// </summary>
ResolveLiteralThenPathPatterns = 0x40
}
}
| 37.459475 | 179 | 0.506209 | [
"MIT"
] | Babuyvmware/PowerShell | src/System.Management.Automation/engine/CommandSearcher.cs | 65,629 | C# |
namespace NelitaBeautyStudio.Data.Unit_of_Work
{
using System;
using System.Collections.Generic;
using System.Data.Entity;
using Microsoft.AspNet.Identity.EntityFramework;
using NelitaBeautyStudio.Data.Repositories;
using NelitaBeautyStudio.Models;
public class ApplicationData : IApplicationData
{
private readonly DbContext context;
private readonly Dictionary<Type, object> repositories = new Dictionary<Type, object>();
public ApplicationData()
: this(new ApplicationDbContext())
{
}
public ApplicationData(ApplicationDbContext context)
{
this.context = context;
}
public IRepository<Contact> Contacts
{
get { return this.GetRepository<Contact>(); }
}
public IRepository<IdentityRole> Roles
{
get { return this.GetRepository<IdentityRole>(); }
}
public IRepository<IdentityUserRole> UserRoles
{
get { return this.GetRepository<IdentityUserRole>(); }
}
public IRepository<User> Users
{
get { return this.GetRepository<User>(); }
}
public IRepository<PriceList> PriceLists
{
get { return this.GetRepository<PriceList>(); }
}
public IRepository<Service> Services
{
get { return this.GetRepository<Service>(); }
}
public IRepository<News> News
{
get { return this.GetRepository<News>(); }
}
public DbContext Context
{
get
{
return this.context;
}
}
/// <summary>
/// Saves all changes made in this context to the underlying database.
/// </summary>
/// <returns>
/// The number of objects written to the underlying database.
/// </returns>
/// <exception cref="T:System.InvalidOperationException">Thrown if the context has been disposed.</exception>
public int SaveChanges()
{
return this.context.SaveChanges();
}
public void Dispose()
{
this.Dispose(true);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
if (this.context != null)
{
this.context.Dispose();
}
}
}
private IRepository<T> GetRepository<T>() where T : class
{
if (!this.repositories.ContainsKey(typeof(T)))
{
var type = typeof(GenericRepository<T>);
this.repositories.Add(typeof(T), Activator.CreateInstance(type, this.context));
}
return (IRepository<T>)this.repositories[typeof(T)];
}
}
}
| 25.964286 | 117 | 0.544017 | [
"MIT"
] | DimitarBakardzhiev/NelitaBeautyStudio | NelitaBeautyStudio.Data/Unit of Work/ApplicationData.cs | 2,910 | C# |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
using System.Collections.Generic;
using Aliyun.Acs.Core;
namespace Aliyun.Acs.dcdn.Model.V20180115
{
public class CreateDcdnDeliverTaskResponse : AcsResponse
{
private string requestId;
public string RequestId
{
get
{
return requestId;
}
set
{
requestId = value;
}
}
}
}
| 26.488372 | 63 | 0.719052 | [
"Apache-2.0"
] | AxiosCros/aliyun-openapi-net-sdk | aliyun-net-sdk-dcdn/Dcdn/Model/V20180115/CreateDcdnDeliverTaskResponse.cs | 1,139 | 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("IncludeSpec.Test.Utility")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("IncludeSpec.Test.Utility")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("6d8e882a-2343-43c8-92df-ef176f52d004")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.405405 | 84 | 0.746657 | [
"MIT"
] | VasiliyNovikov/IncludeSpecification | Sources/IncludeSpec.Test.Utility/Properties/AssemblyInfo.cs | 1,424 | C# |
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using Xunit;
using Xunit.Sdk;
using Xunit.v3;
public class EqualityAssertsTests
{
public class Equal
{
[Fact]
public void Success()
{
Assert.Equal(42, 42);
}
[Fact]
public void Failure()
{
var ex = Assert.Throws<EqualException>(() => Assert.Equal(42, 2112));
Assert.Equal("42", ex.Expected);
Assert.Equal("2112", ex.Actual);
}
[Fact]
public void Comparable()
{
var obj1 = new SpyComparable();
var obj2 = new SpyComparable();
Assert.Equal(obj1, obj2);
Assert.True(obj1.CompareCalled);
}
[Fact]
public void Comparable_NonGeneric_SameType_Equal()
{
var expected = new MultiComparable(1);
var actual = new MultiComparable(1);
Assert.Equal(expected, actual);
Assert.Equal(expected, (IComparable)actual);
Assert.Equal(expected, (object)actual);
}
[Fact]
public void Comparable_NonGeneric_SameType_NotEqual()
{
var expected = new MultiComparable(1);
var actual = new MultiComparable(2);
Assert.NotEqual(expected, actual);
Assert.NotEqual(expected, (IComparable)actual);
Assert.NotEqual(expected, (object)actual);
}
[Fact]
public void Comparable_NonGeneric_DifferentType_Equal()
{
var expected = new MultiComparable(1);
var actual = 1;
Assert.Equal(expected, (IComparable)actual);
Assert.Equal(expected, (object)actual);
}
[Fact]
public void Comparable_NonGeneric_DifferentType_NotEqual()
{
var expected = new MultiComparable(1);
var actual = 2;
Assert.NotEqual(expected, (IComparable)actual);
Assert.NotEqual(expected, (object)actual);
}
class MultiComparable : IComparable
{
private int Value { get; }
public MultiComparable(int value)
{
Value = value;
}
public int CompareTo(object? obj)
{
if (obj is int intObj)
return Value.CompareTo(intObj);
else if (obj is MultiComparable multiObj)
return Value.CompareTo(multiObj.Value);
throw new InvalidOperationException();
}
}
[Fact]
public void Comparable_Generic()
{
var obj1 = new SpyComparable_Generic();
var obj2 = new SpyComparable_Generic();
Assert.Equal(obj1, obj2);
Assert.True(obj1.CompareCalled);
}
[Fact]
public void Comparable_SubClass_SubClass_Equal()
{
var expected = new ComparableSubClassA(1);
var actual = new ComparableSubClassB(1);
Assert.Equal<ComparableBaseClass>(expected, actual);
}
[Fact]
public void Comparable_SubClass_SubClass_NotEqual()
{
var expected = new ComparableSubClassA(1);
var actual = new ComparableSubClassB(2);
Assert.NotEqual<ComparableBaseClass>(expected, actual);
}
[Fact]
public void Comparable_BaseClass_SubClass_Equal()
{
var expected = new ComparableBaseClass(1);
var actual = new ComparableSubClassA(1);
Assert.Equal(expected, actual);
}
[Fact]
public void Comparable_SubClass_BaseClass_Equal()
{
var expected = new ComparableSubClassA(1);
var actual = new ComparableBaseClass(1);
Assert.Equal(expected, actual);
}
class ComparableBaseClass : IComparable<ComparableBaseClass>
{
private int Value { get; }
public ComparableBaseClass(int value)
{
Value = value;
}
public int CompareTo(ComparableBaseClass? other) => Value.CompareTo(other!.Value);
}
class ComparableSubClassA : ComparableBaseClass
{
public ComparableSubClassA(int value) : base(value)
{ }
}
class ComparableSubClassB : ComparableBaseClass
{
public ComparableSubClassB(int value) : base(value)
{ }
}
[Fact]
public void Comparable_Generic_ThrowsException_Equal()
{
var expected = new ComparableThrower(1);
var actual = new ComparableThrower(1);
Assert.Equal(expected, actual);
Assert.Equal(expected, (IComparable<ComparableThrower>)actual);
Assert.Equal(expected, (object)actual);
}
[Fact]
public void Comparable_Generic_ThrowsException_NotEqual()
{
var expected = new ComparableThrower(1);
var actual = new ComparableThrower(2);
Assert.NotEqual(expected, actual);
Assert.NotEqual(expected, (IComparable<ComparableThrower>)actual);
Assert.NotEqual(expected, (object)actual);
}
class ComparableThrower : IComparable<ComparableThrower>
{
public int Value { get; }
public ComparableThrower(int value)
{
Value = value;
}
public int CompareTo(ComparableThrower? other)
{
throw new InvalidOperationException();
}
public override bool Equals(object? obj) => Value == ((ComparableThrower?)obj)!.Value;
public override int GetHashCode() => Value;
}
[Fact]
public void Equatable()
{
var obj1 = new SpyEquatable();
var obj2 = new SpyEquatable();
Assert.Equal(obj1, obj2);
Assert.True(obj1.Equals__Called);
Assert.Same(obj2, obj1.Equals_Other);
}
[Fact]
public void Equatable_SubClass_SubClass_Equal()
{
var expected = new EquatableSubClassA(1);
var actual = new EquatableSubClassB(1);
Assert.Equal<EquatableBaseClass>(expected, actual);
}
[Fact]
public void Equatable_SubClass_SubClass_NotEqual()
{
var expected = new EquatableSubClassA(1);
var actual = new EquatableSubClassB(2);
Assert.NotEqual<EquatableBaseClass>(expected, actual);
}
[Fact]
public void Equatable_BaseClass_SubClass_Equal()
{
var expected = new EquatableBaseClass(1);
var actual = new EquatableSubClassA(1);
Assert.Equal(expected, actual);
}
[Fact]
public void Equatable_SubClass_BaseClass_Equal()
{
var expected = new EquatableSubClassA(1);
var actual = new EquatableBaseClass(1);
Assert.Equal(expected, actual);
}
class EquatableBaseClass : IEquatable<EquatableBaseClass>
{
private int Value { get; }
public EquatableBaseClass(int value)
{
Value = value;
}
public bool Equals(EquatableBaseClass? other) => Value == other!.Value;
}
class EquatableSubClassA : EquatableBaseClass
{
public EquatableSubClassA(int value) : base(value) { }
}
class EquatableSubClassB : EquatableBaseClass
{
public EquatableSubClassB(int value) : base(value) { }
}
[Fact]
public void NonComparable()
{
var nco1 = new NonComparableObject();
var nco2 = new NonComparableObject();
Assert.Equal(nco1, nco2);
}
[Fact]
public void IStructuralEquatable_Equal()
{
var expected = new Tuple<StringWrapper>(new StringWrapper("a"));
var actual = new Tuple<StringWrapper>(new StringWrapper("a"));
Assert.Equal(expected, actual);
Assert.Equal(expected, (IStructuralEquatable)actual);
Assert.Equal(expected, (object)actual);
}
[Fact]
public void IStructuralEquatable_NotEqual()
{
var expected = new Tuple<StringWrapper>(new StringWrapper("a"));
var actual = new Tuple<StringWrapper>(new StringWrapper("b"));
Assert.NotEqual(expected, actual);
Assert.NotEqual(expected, (IStructuralEquatable)actual);
Assert.NotEqual(expected, (object)actual);
}
[Fact]
public void IStructuralEquatable_ExpectedNull_ActualNull()
{
var expected = new Tuple<StringWrapper?>(null);
var actual = new Tuple<StringWrapper?>(null);
Assert.Equal(expected, actual);
Assert.Equal(expected, (IStructuralEquatable)actual);
Assert.Equal(expected, (object)actual);
}
[Fact]
public void IStructuralEquatable_ExpectedNull_ActualNonNull()
{
var expected = new Tuple<StringWrapper?>(null);
var actual = new Tuple<StringWrapper?>(new StringWrapper("a"));
Assert.NotEqual(expected, actual);
Assert.NotEqual(expected, (IStructuralEquatable)actual);
Assert.NotEqual(expected, (object)actual);
}
[Fact]
public void IStructuralEquatable_ExpectedNonNull_ActualNull()
{
var expected = new Tuple<StringWrapper?>(new StringWrapper("a"));
var actual = new Tuple<StringWrapper?>(null);
Assert.NotEqual(expected, actual);
Assert.NotEqual(expected, (IStructuralEquatable)actual);
Assert.NotEqual(expected, (object)actual);
}
class StringWrapper : IEquatable<StringWrapper>
{
public string Value { get; }
public StringWrapper(string value)
{
Value = value;
}
bool IEquatable<StringWrapper>.Equals(StringWrapper? other) => Value == other!.Value;
}
[Fact]
public void DepthExample()
{
var x = new List<object> { new List<object> { new List<object> { new List<object>() } } };
var y = new List<object> { new List<object> { new List<object> { new List<object>() } } };
Assert.Equal(x, y);
}
[Fact]
public void IReadOnlyCollection_IEnumerable()
{
var expected = new string[] { "foo", "bar" };
var actual = (IReadOnlyCollection<string>)new ReadOnlyCollection<string>(expected);
Assert.Equal(expected, actual);
Assert.Equal(expected, (object)actual);
Assert.Equal(actual, expected);
Assert.Equal(actual, (object)expected);
}
[Fact]
public void StringArray_ObjectArray()
{
var expected = new string[] { "foo", "bar" };
var actual = new object[] { "foo", "bar" };
Assert.Equal(expected, actual);
Assert.Equal(expected, (object)actual);
Assert.Equal(actual, expected);
Assert.Equal(actual, (object)expected);
}
[Fact]
public void IDictionary_SameTypes()
{
var expected = new Dictionary<string, string> { ["foo"] = "bar" };
var actual = new Dictionary<string, string> { ["foo"] = "bar" };
Assert.Equal(expected, actual);
Assert.Equal(expected, (IDictionary)actual);
Assert.Equal(expected, (object)actual);
}
[Fact]
public void IDictionary_DifferentTypes()
{
var expected = new Dictionary<string, string> { ["foo"] = "bar" };
var actual = new ConcurrentDictionary<string, string>(expected);
Assert.Equal(expected, (IDictionary)actual);
Assert.Equal(expected, (object)actual);
}
[Fact]
public void ISet_SameTypes()
{
var expected = new HashSet<string> { "foo", "bar" };
var actual = new HashSet<string> { "foo", "bar" };
Assert.Equal(expected, actual);
Assert.Equal(expected, (ISet<string>)actual);
Assert.Equal(expected, (object)actual);
}
[Fact]
public void ISet_DifferentTypes()
{
var expected = new HashSet<string> { "bar", "foo" };
var actual = new SortedSet<string> { "foo", "bar" };
Assert.Equal(expected, (ISet<string>)actual);
Assert.Equal(expected, (object)actual);
}
[Fact]
public void ISet_NonGenericSubClass_Equal()
{
var expected = new NonGenericSet { "bar", "foo" };
var actual = new NonGenericSet { "bar", "foo" };
Assert.Equal(expected, actual);
Assert.Equal(expected, (ISet<string>)actual);
Assert.Equal(expected, (object)actual);
}
[Fact]
public void ISet_NonGenericSubClass_NotEqual()
{
var expected = new NonGenericSet { "bar", "foo" };
var actual = new NonGenericSet { "bar", "baz" };
Assert.NotEqual(expected, actual);
Assert.NotEqual(expected, (ISet<string>)actual);
Assert.NotEqual(expected, (object)actual);
}
[Fact]
public void ISet_NonGenericSubClass_DifferentCounts()
{
var expected = new NonGenericSet { "bar" };
var actual = new NonGenericSet { "bar", "foo" };
Assert.NotEqual(expected, actual);
Assert.NotEqual(expected, (ISet<string>)actual);
Assert.NotEqual(expected, (object)actual);
}
[Fact]
public void ISet_NonGenericSubClass_DifferentTypesEqual()
{
var expected = new NonGenericSet { "bar" };
var actual = new HashSet<string> { "bar" };
Assert.Equal(expected, actual);
Assert.Equal(expected, (ISet<string>)actual);
Assert.Equal(expected, (object)actual);
}
[Fact]
public void ISet_NonGenericSubClass_DifferentTypesNotEqual()
{
var expected = new NonGenericSet { "bar" };
var actual = new HashSet<int> { 1 };
Assert.NotEqual(expected, (object)actual);
}
class NonGenericSet : HashSet<string> { }
[Fact]
public void ISet_TwoGenericSubClass_Equal()
{
var expected = new TwoGenericSet<string, int> { "foo", "bar" };
var actual = new TwoGenericSet<string, int> { "foo", "bar" };
Assert.Equal(expected, actual);
Assert.Equal(expected, (ISet<string>)actual);
Assert.Equal(expected, (object)actual);
}
[Fact]
public void ISet_TwoGenericSubClass_NotEqual()
{
var expected = new TwoGenericSet<string, int> { "foo", "bar" };
var actual = new TwoGenericSet<string, int> { "foo", "baz" };
Assert.NotEqual(expected, actual);
Assert.NotEqual(expected, (ISet<string>)actual);
Assert.NotEqual(expected, (object)actual);
}
[Fact]
public void ISet_TwoGenericSubClass_DifferentCounts()
{
var expected = new TwoGenericSet<string, int> { "bar" };
var actual = new TwoGenericSet<string, int> { "foo", "bar" };
Assert.NotEqual(expected, actual);
Assert.NotEqual(expected, (ISet<string>)actual);
Assert.NotEqual(expected, (object)actual);
}
class TwoGenericSet<T, U> : HashSet<T> { }
[Fact]
public void IEquatableActual_Implicit_Equal()
{
var expected = new ImplicitIEquatableExpected(1);
var actual = new IntWrapper(1);
Assert.Equal(expected, (object)actual);
}
[Fact]
public void IEquatableActual_Implicit_NotEqual()
{
var expected = new ImplicitIEquatableExpected(1);
var actual = new IntWrapper(2);
Assert.NotEqual(expected, (object)actual);
}
class ImplicitIEquatableExpected : IEquatable<IntWrapper>
{
public int Value { get; }
public ImplicitIEquatableExpected(int value)
{
Value = value;
}
public bool Equals(IntWrapper? other) => Value == other!.Value;
}
[Fact]
public void IEquatableActual_Explicit_Equal()
{
var expected = new ExplicitIEquatableExpected(1);
var actual = new IntWrapper(1);
Assert.Equal(expected, (object)actual);
}
[Fact]
public void IEquatableActual_Explicit_NotEqual()
{
var expected = new ExplicitIEquatableExpected(1);
var actual = new IntWrapper(2);
Assert.NotEqual(expected, (object)actual);
}
class ExplicitIEquatableExpected : IEquatable<IntWrapper>
{
public int Value { get; }
public ExplicitIEquatableExpected(int value)
{
Value = value;
}
bool IEquatable<IntWrapper>.Equals(IntWrapper? other) => Value == other!.Value;
}
[Fact]
public void IComparableActual_Implicit_Equal()
{
var expected = new ImplicitIComparableExpected(1);
var actual = new IntWrapper(1);
Assert.Equal(expected, (object)actual);
}
[Fact]
public void IComparableActual_Implicit_NotEqual()
{
var expected = new ImplicitIComparableExpected(1);
var actual = new IntWrapper(2);
Assert.NotEqual(expected, (object)actual);
}
class ImplicitIComparableExpected : IComparable<IntWrapper>
{
public int Value { get; }
public ImplicitIComparableExpected(int value)
{
Value = value;
}
public int CompareTo(IntWrapper? other) => Value.CompareTo(other!.Value);
}
[Fact]
public void IComparableActual_Explicit_Equal()
{
var expected = new ExplicitIComparableActual(1);
var actual = new IntWrapper(1);
Assert.Equal(expected, (object)actual);
}
[Fact]
public void IComparableActual_Explicit_NotEqual()
{
var expected = new ExplicitIComparableActual(1);
var actual = new IntWrapper(2);
Assert.NotEqual(expected, (object)actual);
}
class ExplicitIComparableActual : IComparable<IntWrapper>
{
public int Value { get; }
public ExplicitIComparableActual(int value)
{
Value = value;
}
int IComparable<IntWrapper>.CompareTo(IntWrapper? other) => Value.CompareTo(other!.Value);
}
[Fact]
public void IComparableActual_ThrowsException_Equal()
{
var expected = new IComparableActualThrower(1);
var actual = new IntWrapper(1);
Assert.Equal(expected, (object)actual);
}
[Fact]
public void IComparableActual_ThrowsException_NotEqual()
{
var expected = new IComparableActualThrower(1);
var actual = new IntWrapper(2);
Assert.NotEqual(expected, (object)actual);
}
class IComparableActualThrower : IComparable<IntWrapper>
{
public int Value { get; }
public IComparableActualThrower(int value)
{
Value = value;
}
public int CompareTo(IntWrapper? other)
{
throw new NotSupportedException();
}
public override bool Equals(object? obj) => Value == ((IntWrapper?)obj)!.Value;
public override int GetHashCode() => Value;
}
class IntWrapper
{
public int Value { get; }
public IntWrapper(int value)
{
Value = value;
}
}
class SpyComparable : IComparable
{
public bool CompareCalled;
public int CompareTo(object? obj)
{
CompareCalled = true;
return 0;
}
}
class SpyComparable_Generic : IComparable<SpyComparable_Generic>
{
public bool CompareCalled;
public int CompareTo(SpyComparable_Generic? other)
{
CompareCalled = true;
return 0;
}
}
public class SpyEquatable : IEquatable<SpyEquatable>
{
public bool Equals__Called;
public SpyEquatable? Equals_Other;
public bool Equals(SpyEquatable? other)
{
Equals__Called = true;
Equals_Other = other;
return true;
}
}
class NonComparableObject
{
public override bool Equals(object? obj) => true;
public override int GetHashCode() => 42;
}
}
public class Equal_WithComparer
{
[Fact]
public void Success()
{
Assert.Equal(42, 21, new Comparer<int>(true));
}
[Fact]
public void Failure()
{
var ex = Assert.Throws<EqualException>(() => Assert.Equal(42, 42, new Comparer<int>(false)));
Assert.Equal("42", ex.Expected);
Assert.Equal("42", ex.Actual);
}
class Comparer<T> : IEqualityComparer<T>
{
readonly bool result;
public Comparer(bool result)
{
this.result = result;
}
public bool Equals([AllowNull] T x, [AllowNull] T y) => result;
public int GetHashCode(T obj) => throw new NotImplementedException();
}
}
public class Equal_Decimal
{
[Fact]
public void Success()
{
Assert.Equal(0.11111M, 0.11444M, 2);
}
[CulturedFact]
public void Failure()
{
var ex = Assert.Throws<EqualException>(() => Assert.Equal(0.11111M, 0.11444M, 3));
Assert.Equal($"{0.111M} (rounded from {0.11111M})", ex.Expected);
Assert.Equal($"{0.114M} (rounded from {0.11444M})", ex.Actual);
}
}
public class Equal_Double
{
[Fact]
public void Success()
{
Assert.Equal(0.11111, 0.11444, 2);
}
[Fact]
public void Success_Zero()
{
Assert.Equal(0.0, 0.0);
Assert.Equal(0.0, (object)0.0);
}
[Fact]
public void Success_PositiveZero_NegativeZero()
{
Assert.Equal(0.0, -0.0);
}
[CulturedFact]
public void Failure()
{
var ex = Assert.Throws<EqualException>(() => Assert.Equal(0.11111, 0.11444, 3));
Assert.Equal($"{0.111M} (rounded from {0.11111})", ex.Expected);
Assert.Equal($"{0.114M} (rounded from {0.11444})", ex.Actual);
}
}
public class Equal_Double_MidPointRounding
{
[Fact]
public void Success()
{
Assert.Equal(10.566, 10.565, 2, MidpointRounding.AwayFromZero);
}
[Fact]
public void Success_Zero()
{
Assert.Equal(0.00, 0.05, 1, MidpointRounding.ToEven);
}
[CulturedFact]
public void Failure()
{
var ex = Assert.Throws<EqualException>(() => Assert.Equal(0.11113, 0.11115, 4, MidpointRounding.ToEven));
Assert.Equal($"{0.1111} (rounded from {0.11113})", ex.Expected);
Assert.Equal($"{0.1112} (rounded from {0.11115})", ex.Actual);
}
}
public class Equal_Double_Tolerance
{
[Fact]
public void Success()
{
Assert.Equal(10.566, 10.565, 0.01);
}
[Fact]
public void Success_Zero()
{
Assert.Equal(0.00, 0.05, 0.1);
}
[Fact]
public void Success_NaN()
{
Assert.Equal(double.NaN, double.NaN, 1000.0);
}
[Fact]
public void Success_Infinite()
{
Assert.Equal(double.MinValue, double.MaxValue, double.PositiveInfinity);
}
[CulturedFact]
public void Failure()
{
var ex = Assert.Throws<EqualException>(() => Assert.Equal(0.11113, 0.11115, 0.00001));
Assert.Equal($"{0.11113:G17}", ex.Expected);
Assert.Equal($"{0.11115:G17}", ex.Actual);
}
[CulturedFact]
public void Failure_NaN()
{
var ex = Assert.Throws<EqualException>(() => Assert.Equal(20210102.2208, double.NaN, 20000000.0));
Assert.Equal($"{20210102.2208:G17}", ex.Expected);
Assert.Equal($"NaN", ex.Actual);
}
[CulturedFact]
public void Failure_PositiveInfinity()
{
var ex = Assert.Throws<EqualException>(() => Assert.Equal(double.PositiveInfinity, 77.7, 1.0));
Assert.Equal($"∞", ex.Expected);
Assert.Equal($"{77.7:G17}", ex.Actual);
}
[CulturedFact]
public void Failure_NegativeInfinity()
{
var ex = Assert.Throws<EqualException>(() => Assert.Equal(0.0, double.NegativeInfinity, 1.0));
Assert.Equal($"{0.0:G17}", ex.Expected);
Assert.Equal($"-∞", ex.Actual);
}
[CulturedFact]
public void Failure_InvalidTolerance()
{
var ex = Assert.Throws<ArgumentException>(() => Assert.Equal(0.0, 1.0, double.NegativeInfinity));
Assert.Equal($"Tolerance must be greater than or equal to zero{Environment.NewLine}Parameter name: tolerance", ex.Message);
Assert.Equal("tolerance", ex.ParamName);
}
}
public class StrictEqual
{
[Fact]
public static void Success()
{
Assert.StrictEqual(42, 42);
}
[Fact]
public static void Equals()
{
Assert.StrictEqual(new DerivedClass(), new BaseClass());
}
[Fact]
public static void Failure()
{
var ex = Assert.Throws<EqualException>(() => Assert.StrictEqual(42, 2112));
Assert.Equal("42", ex.Expected);
Assert.Equal("2112", ex.Actual);
}
[Fact]
public static void Collection_Failure()
{
var expected = new EnumerableClass("ploeh");
var actual = new EnumerableClass("fnaah");
var ex = Assert.Throws<EqualException>(() => Assert.StrictEqual(expected, actual));
Assert.Equal("EnumerableClass []", ex.Expected);
Assert.Equal("EnumerableClass []", ex.Actual);
}
}
public class NotEqual
{
[Fact]
public void Success()
{
Assert.NotEqual("bob", "jim");
}
[Fact]
public void String_Double_Failure()
{
Assert.NotEqual("0", (object)0.0);
Assert.NotEqual((object)0.0, "0");
}
[Fact]
public void IReadOnlyCollection_IEnumerable_Success()
{
var expected = new string[] { "foo", "bar" };
IReadOnlyCollection<string> actual = new ReadOnlyCollection<string>(new string[] { "foo", "baz" });
Assert.NotEqual(expected, actual);
Assert.NotEqual(expected, (object)actual);
}
[Fact]
public void IReadOnlyCollection_IEnumerable_Failure()
{
var expected = new string[] { "foo", "bar" };
IReadOnlyCollection<string> actual = new ReadOnlyCollection<string>(expected);
Assert.Throws<NotEqualException>(() => Assert.NotEqual(expected, actual));
Assert.Throws<NotEqualException>(() => Assert.NotEqual(expected, (object)actual));
}
[Fact]
public void StringArray_ObjectArray_Success()
{
var expected = new string[] { "foo", "bar" };
var actual = new object[] { "foo", "baz" };
Assert.NotEqual(expected, actual);
Assert.NotEqual(expected, (object)actual);
}
[Fact]
public void StringArray_ObjectArray_Failure()
{
var expected = new string[] { "foo", "bar" };
var actual = new object[] { "foo", "bar" };
Assert.Throws<NotEqualException>(() => Assert.NotEqual(expected, actual));
Assert.Throws<NotEqualException>(() => Assert.NotEqual(expected, (object)actual));
}
[Fact]
public void MultidimensionalArrays()
{
var expected = new string[] { "foo", "bar" };
var actual = new string[,] { { "foo" }, { "baz" } };
Assert.NotEqual(expected, (object)actual);
}
[Fact]
public void IDictionary_SameTypes()
{
var expected = new Dictionary<string, string> { ["foo"] = "bar" };
var actual = new Dictionary<string, string> { ["foo"] = "baz" };
Assert.NotEqual(expected, actual);
Assert.NotEqual(expected, (IDictionary)actual);
Assert.NotEqual(expected, (object)actual);
}
[Fact]
public void IDictionary_DifferentTypes()
{
var expected = new Dictionary<string, string> { ["foo"] = "bar" };
var actual = new ConcurrentDictionary<string, string> { ["foo"] = "baz" };
Assert.NotEqual(expected, (IDictionary)actual);
Assert.NotEqual(expected, (object)actual);
}
[Fact]
public void ISet_SameTypes()
{
var expected = new HashSet<string> { "foo", "bar" };
var actual = new HashSet<string> { "foo", "baz" };
Assert.NotEqual(expected, actual);
Assert.NotEqual(expected, (ISet<string>)actual);
Assert.NotEqual(expected, (object)actual);
}
[Fact]
public void ISet_DifferentTypes()
{
var expected = new HashSet<string> { "bar", "foo" };
var actual = new SortedSet<string> { "foo", "baz" };
Assert.NotEqual(expected, (ISet<string>)actual);
Assert.NotEqual(expected, (object)actual);
}
[Fact]
public void Failure()
{
var ex = Record.Exception(() => Assert.NotEqual("actual", "actual"));
Assert.IsType<NotEqualException>(ex);
Assert.Equal(
@"Assert.NotEqual() Failure" + Environment.NewLine +
@"Expected: Not ""actual""" + Environment.NewLine +
@"Actual: ""actual""",
ex.Message
);
}
}
public class NotEqual_WithComparer
{
[Fact]
public void Success()
{
Assert.NotEqual("TestString", "testString", StringComparer.InvariantCulture);
}
[Fact]
public void NotEqualWithCustomComparer()
{
var ex = Record.Exception(
() => Assert.NotEqual("TestString", "testString", StringComparer.InvariantCultureIgnoreCase));
Assert.IsType<NotEqualException>(ex);
Assert.Equal(
@"Assert.NotEqual() Failure" + Environment.NewLine +
@"Expected: Not ""TestString""" + Environment.NewLine +
@"Actual: ""testString""",
ex.Message
);
}
}
public class NotEqual_Decimal
{
[Fact]
public void Success()
{
Assert.NotEqual(0.11111M, 0.11444M, 3);
}
[CulturedFact]
public void Failure()
{
var ex = Assert.Throws<NotEqualException>(() => Assert.NotEqual(0.11111M, 0.11444M, 2));
Assert.Equal(
"Assert.NotEqual() Failure" + Environment.NewLine +
$"Expected: Not {0.11M} (rounded from {0.11111})" + Environment.NewLine +
$"Actual: {0.11M} (rounded from {0.11444})",
ex.Message
);
}
}
public class NotEqual_Double
{
[Fact]
public void Success()
{
Assert.NotEqual(0.11111, 0.11444, 3);
}
[CulturedFact]
public void Failure()
{
var ex = Assert.Throws<NotEqualException>(() => Assert.NotEqual(0.11111, 0.11444, 2));
Assert.Equal(
"Assert.NotEqual() Failure" + Environment.NewLine +
$"Expected: Not {0.11M} (rounded from {0.11111})" + Environment.NewLine +
$"Actual: {0.11M} (rounded from {0.11444})",
ex.Message
);
}
}
public class NotStrictEqual
{
[Fact]
public static void Success()
{
Assert.NotStrictEqual("bob", "jim");
}
[Fact]
public static void Equals()
{
Assert.NotStrictEqual(new EnumerableClass("ploeh"), new EnumerableClass("fnaah"));
}
[Fact]
public static void Failure()
{
var ex = Record.Exception(() => Assert.NotStrictEqual("actual", "actual"));
Assert.IsType<NotEqualException>(ex);
Assert.Equal(
@"Assert.NotEqual() Failure" + Environment.NewLine +
@"Expected: Not ""actual""" + Environment.NewLine +
@"Actual: ""actual""",
ex.Message
);
}
[Fact]
public static void Collection()
{
var ex = Assert.Throws<NotEqualException>(() => Assert.NotStrictEqual(new DerivedClass(), new BaseClass()));
Assert.Equal(
@"Assert.NotEqual() Failure" + Environment.NewLine +
@"Expected: Not DerivedClass { }" + Environment.NewLine +
@"Actual: BaseClass { }",
ex.Message
);
}
}
private class BaseClass { }
private class DerivedClass : BaseClass
{
public override bool Equals(object? obj) =>
obj is BaseClass || base.Equals(obj);
public override int GetHashCode() => 0;
}
private class EnumerableClass : IEnumerable<BaseClass>
{
private readonly IEnumerable<BaseClass> bars;
public EnumerableClass(string baz, params BaseClass[] bars)
{
this.bars = bars;
}
public IEnumerator<BaseClass> GetEnumerator() => bars.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
}
| 23.731933 | 126 | 0.676676 | [
"Apache-2.0"
] | MichaelTrikergiotis/xun | src/xunit.v3.assert.tests/Asserts/EqualityAssertsTests.cs | 28,247 | C# |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
namespace KSAGrinder.ValueConverters
{
public class TextToVisibility : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is string text)
{
if (String.IsNullOrEmpty(text)) return Visibility.Visible;
else return Visibility.Hidden;
}
return null;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
| 27.032258 | 103 | 0.659905 | [
"MIT"
] | A-H4NU/KSAGrinder | KSAGrinder/ValueConverters/TextToVisibility.cs | 840 | C# |
# CS_ARCH_MIPS, CS_MODE_32+CS_MODE_MICRO, None
0x00,0x94,0x9a,0x02 = b 1332
0xc9,0x94,0x9a,0x02 = beq $9, $6, 1332
0x46,0x40,0x9a,0x02 = bgez $6, 1332
0x66,0x40,0x9a,0x02 = bgezal $6, 1332
0x26,0x40,0x9a,0x02 = bltzal $6, 1332
0xc6,0x40,0x9a,0x02 = bgtz $6, 1332
0x86,0x40,0x9a,0x02 = blez $6, 1332
0xc9,0xb4,0x9a,0x02 = bne $9, $6, 1332
0x60,0x40,0x9a,0x02 = bal 1332
0x06,0x40,0x9a,0x02 = bltz $6, 1332
| 33.75 | 46 | 0.708642 | [
"BSD-3-Clause"
] | luismiras/capstone | suite/MC/Mips/micromips-branch-instructions.s.cs | 405 | C# |
using Mastonet.Entities;
using System;
using System.Collections.Generic;
using System.Text;
namespace Mastonet
{
public class StreamUpdateEventArgs : EventArgs
{
public StreamUpdateEventArgs(Status status)
{
Status = status;
}
public Status Status { get; set; }
}
public class StreamNotificationEventArgs : EventArgs
{
public StreamNotificationEventArgs(Notification notification)
{
this.Notification = notification;
}
public Notification Notification { get; set; }
}
public class StreamDeleteEventArgs : EventArgs
{
public StreamDeleteEventArgs(long statusId)
{
StatusId = statusId;
}
public long StatusId { get; set; }
}
public class StreamFiltersChangedEventArgs : EventArgs
{
}
public class StreamConversationEvenTargs : EventArgs
{
public StreamConversationEvenTargs(Conversation conversation)
{
Conversation = conversation;
}
public Conversation Conversation { get; set; }
}
}
| 21.711538 | 69 | 0.628875 | [
"MIT"
] | glacasa/Mastonet | Mastonet/StreamEventArgs.cs | 1,131 | C# |
using System.Collections.Generic;
using Newtonsoft.Json;
namespace TMDbLib.Objects.General
{
public class TranslationsContainer
{
[JsonProperty("id")]
public int Id { get; set; }
[JsonProperty("translations")]
public List<Translation> Translations { get; set; }
}
} | 22.285714 | 59 | 0.653846 | [
"MIT"
] | 1337joe/TMDbLib | TMDbLib/Objects/General/TranslationsContainer.cs | 314 | C# |
namespace CoinChallenge.Api.CSharp.Domain
{
public enum AmountValidation
{
Valid,
InValidNegativeAmount,
InValidExceedsMaxAmount
}
public enum OperationResult
{
Ok,
Fail,
Error
}
public enum Coin
{
SilverDollar,
HalfDollar,
Quarter,
Dime,
Nickel,
Penny
}
} | 15.038462 | 42 | 0.526854 | [
"MIT"
] | srpeterson/fsharp-csharp-developers | Code/CoinChallenge.Api.CSharp/Domain/Enums.cs | 393 | C# |
// *****************************************************************************
// BSD 3-Clause License (https://github.com/ComponentFactory/Krypton/blob/master/LICENSE)
// © Component Factory Pty Ltd, 2006 - 2016, All rights reserved.
// The software and associated documentation supplied hereunder are the
// proprietary information of Component Factory Pty Ltd, 13 Swallows Close,
// Mornington, Vic 3931, Australia and are supplied subject to license terms.
//
// Modifications by Peter Wagner(aka Wagnerp) & Simon Coghlan(aka Smurf-IV) 2017 - 2020. All rights reserved. (https://github.com/Wagnerp/Krypton-NET-5.490)
// Version 5.490.0.0 www.ComponentFactory.com
// *****************************************************************************
using System;
using System.Collections;
using System.Drawing;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Windows.Forms;
using System.Windows.Forms.Design;
using ComponentFactory.Krypton.Toolkit;
namespace ComponentFactory.Krypton.Navigator
{
/// <summary>
/// Designer for the navigator instance.
/// </summary>
public class KryptonNavigatorDesigner : ParentControlDesigner
{
#region Instance Fields
private bool _lastHitTest;
private bool _ignoreOnAddPage;
private DesignerVerbCollection _verbs;
private DesignerVerb _verbAddPage;
private DesignerVerb _verbRemovePage;
private DesignerVerb _verbClearPages;
private IDesignerHost _designerHost;
private IComponentChangeService _changeService;
private ISelectionService _selectionService;
#endregion
#region Public Overrides
/// <summary>
/// Initializes the designer with the specified component.
/// </summary>
/// <param name="component">The IComponent to associate the designer with.</param>
public override void Initialize(IComponent component)
{
// Let base class do standard stuff
base.Initialize(component);
// The resizing handles around the control need to change depending on the
// value of the AutoSize and AutoSizeMode properties. When in AutoSize you
// do not get the resizing handles, otherwise you do.
AutoResizeHandles = true;
// Cast to correct type
Navigator = (KryptonNavigator)component;
// Must enable the child panel so that copy and paste of navigator
// correctly copies across copies of the child pages. Also allows the
// child panel to be viewed in the document outline and modified.
EnableDesignMode(Navigator.ChildPanel, "PageContainer");
// Make sure that all the pages in control can be designed
foreach (KryptonPage page in Navigator.Pages)
{
EnableDesignMode(page, page.Name);
}
// Monitor navigator events
Navigator.GetViewManager().MouseDownProcessed += OnNavigatorMouseUp;
Navigator.GetViewManager().DoubleClickProcessed += OnNavigatorDoubleClick;
Navigator.Pages.Inserted += OnPageInserted;
Navigator.Pages.Removed += OnPageRemoved;
Navigator.Pages.Cleared += OnPagesCleared;
Navigator.SelectedPageChanged += OnSelectedPageChanged;
// Get access to the services
_designerHost = (IDesignerHost)GetService(typeof(IDesignerHost));
_changeService = (IComponentChangeService)GetService(typeof(IComponentChangeService));
_selectionService = (ISelectionService)GetService(typeof(ISelectionService));
// We need to know when we are being removed
_changeService.ComponentRemoving += OnComponentRemoving;
}
/// <summary>
/// Initializes a newly created component.
/// </summary>
/// <param name="defaultValues">A name/value dictionary of default values to apply to properties.</param>
public override void InitializeNewComponent(IDictionary defaultValues)
{
// Let base class set the initial position and parent
base.InitializeNewComponent(defaultValues);
// Add a couple of pages
_ignoreOnAddPage = true;
OnAddPage(this, EventArgs.Empty);
OnAddPage(this, EventArgs.Empty);
_ignoreOnAddPage = false;
// Get access to the Pages property
MemberDescriptor propertyPages = TypeDescriptor.GetProperties(Navigator)["Pages"];
// Notify that the pages collection has been updated
RaiseComponentChanging(propertyPages);
RaiseComponentChanged(propertyPages, null, null);
}
/// <summary>
/// Gets the design-time action lists supported by the component associated with the designer.
/// </summary>
public override DesignerActionListCollection ActionLists
{
get
{
// Create a collection of action lists
DesignerActionListCollection actionLists = new DesignerActionListCollection
{
// Add the navigator specific list
new KryptonNavigatorActionList(this)
};
return actionLists;
}
}
/// <summary>
/// Gets the design-time verbs supported by the component that is associated with the designer.
/// </summary>
public override DesignerVerbCollection Verbs
{
get
{
// First time around we create the verb collection
if (_verbs == null)
{
// Cache verb instances so enabled state can be updated in future
_verbAddPage = new DesignerVerb("Add Page", OnAddPage);
_verbRemovePage = new DesignerVerb("Remove Page", OnRemovePage);
_verbClearPages = new DesignerVerb("Clear Pages", OnClearPages);
_verbs = new DesignerVerbCollection(new DesignerVerb[] { _verbAddPage, _verbRemovePage, _verbClearPages });
// Set correct initial state of the verbs
UpdateVerbStatus();
}
return _verbs;
}
}
/// <summary>
/// Gets the collection of components associated with the component managed by the designer.
/// </summary>
public override ICollection AssociatedComponents
{
get
{
// Create a new compound array
ArrayList compound = new ArrayList();
// Add all the navigator components
compound.AddRange(Navigator.Button.ButtonSpecs);
compound.AddRange(Navigator.Pages);
return compound;
}
}
/// <summary>
/// Indicates whether the specified control can be a child of the control managed by a designer.
/// </summary>
/// <param name="control">The Control to test.</param>
/// <returns>true if the specified control can be a child of the control managed by this designer; otherwise, false.</returns>
public override bool CanParent(Control control)
{
// Only a KryptonPage can be added as a child
if (control is KryptonPage)
{
// Cannot add the same page more than once
return !Navigator.Controls.Contains(control);
}
return false;
}
/// <summary>
/// Returns the internal control designer with the specified index in the ControlDesigner.
/// </summary>
/// <param name="internalControlIndex">A specified index to select the internal control designer. This index is zero-based.</param>
/// <returns>A ControlDesigner at the specified index.</returns>
public override ControlDesigner InternalControlDesigner(int internalControlIndex)
{
return (ControlDesigner)_designerHost.GetDesigner(Navigator.Pages[internalControlIndex]);
}
/// <summary>
/// Returns the number of internal control designers in the ControlDesigner.
/// </summary>
/// <returns>The number of internal control designers in the ControlDesigner.</returns>
public override int NumberOfInternalControlDesigners()
{
return Navigator.Pages.Count;
}
/// <summary>
/// Add a new page to the navigator.
/// </summary>
public void AddPage()
{
OnAddPage(this, EventArgs.Empty);
}
/// <summary>
/// Remove the current page from the navigator.
/// </summary>
public void RemovePage()
{
OnRemovePage(this, EventArgs.Empty);
}
/// <summary>
/// Remove all pages from the navigator.
/// </summary>
public void ClearPages()
{
OnClearPages(this, EventArgs.Empty);
}
#endregion
#region Protected Overrides
/// <summary>
/// Releases all resources used by the component.
/// </summary>
/// <param name="disposing">true to release both managed and unmanaged resources; false to release only unmanaged resources.</param>
protected override void Dispose(bool disposing)
{
try
{
if (disposing)
{
// Unhook from navigator events
Navigator.GetViewManager().MouseUpProcessed -= OnNavigatorMouseUp;
Navigator.GetViewManager().DoubleClickProcessed -= OnNavigatorDoubleClick;
Navigator.Pages.Inserted -= OnPageInserted;
Navigator.Pages.Removed -= OnPageRemoved;
Navigator.Pages.Cleared -= OnPagesCleared;
Navigator.SelectedPageChanged -= OnSelectedPageChanged;
// Unhook from designer events
_changeService.ComponentRemoving -= OnComponentRemoving;
}
}
finally
{
// Must let base class do standard stuff
base.Dispose(disposing);
}
}
/// <summary>
/// Indicates whether a mouse click at the specified point should be handled by the control.
/// </summary>
/// <param name="point">A Point indicating the position at which the mouse was clicked, in screen coordinates.</param>
/// <returns>true if a click at the specified point is to be handled by the control; otherwise, false.</returns>
protected override bool GetHitTest(Point point)
{
// Ask the control if it wants to process the point
bool ret = Navigator.DesignerGetHitTest(Navigator.PointToClient(point));
// If the navigator does not want the mouse point then make sure the
// tracking element is informed that the mouse has left the control
if (!ret && _lastHitTest)
{
Navigator.DesignerMouseLeave();
}
// Cache the last answer recovered
_lastHitTest = ret;
return ret;
}
/// <summary>
/// Receives a call when the mouse leaves the control.
/// </summary>
protected override void OnMouseLeave()
{
Navigator.DesignerMouseLeave();
base.OnMouseLeave();
}
/// <summary>
/// Called when a drag-and-drop operation enters the control designer view.
/// </summary>
/// <param name="de">A DragEventArgs that provides data for the event.</param>
protected override void OnDragEnter(DragEventArgs de)
{
de.Effect = DragDropEffects.None;
}
/// <summary>
/// Called when a drag-and-drop object is dragged over the control designer view.
/// </summary>
/// <param name="de">A DragEventArgs that provides data for the event.</param>
protected override void OnDragOver(DragEventArgs de)
{
de.Effect = DragDropEffects.None;
}
/// <summary>
/// Called when a drag-and-drop object is dropped onto the control designer view.
/// </summary>
/// <param name="de">A DragEventArgs that provides data for the event.</param>
protected override void OnDragDrop(DragEventArgs de)
{
de.Effect = DragDropEffects.None;
}
#endregion
#region Protected Virtual
// ReSharper disable VirtualMemberNeverOverridden.Global
/// <summary>
/// Gets access to the associated navigator instance.
/// </summary>
protected virtual KryptonNavigator Navigator { get; private set; }
/// <summary>
/// Occurs when the component is being removed from the designer.
/// </summary>
/// <param name="sender">Source of the event.</param>
/// <param name="e">A ComponentEventArgs containing event data.</param>
protected virtual void OnComponentRemoving(object sender, ComponentEventArgs e)
{
// If our control is being removed
if (e.Component == Navigator)
{
// Need access to host in order to delete a component
IDesignerHost host = (IDesignerHost)GetService(typeof(IDesignerHost));
// We need to remove all the button spec instances
for (int i = Navigator.Button.ButtonSpecs.Count - 1; i >= 0; i--)
{
ButtonSpec spec = Navigator.Button.ButtonSpecs[i];
_changeService.OnComponentChanging(Navigator, null);
Navigator.Button.ButtonSpecs.Remove(spec);
host.DestroyComponent(spec);
_changeService.OnComponentChanged(Navigator, null, null, null);
}
// We need to remove all the page instances
for (int i = Navigator.Pages.Count - 1; i >= 0; i--)
{
KryptonPage page = Navigator.Pages[i];
_changeService.OnComponentChanging(Navigator, null);
Navigator.Pages.Remove(page);
host.DestroyComponent(page);
_changeService.OnComponentChanged(Navigator, null, null, null);
}
}
}
// ReSharper restore VirtualMemberNeverOverridden.Global
#endregion
#region Implementation
private void OnAddPage(object sender, EventArgs e)
{
// Use a transaction to support undo/redo actions
DesignerTransaction transaction = _designerHost.CreateTransaction("KryptonNavigator AddPage");
try
{
// Get access to the Pages property
MemberDescriptor propertyPages = TypeDescriptor.GetProperties(Navigator)["Pages"];
// Do we need to raise the changing notification?
if (!_ignoreOnAddPage)
{
RaiseComponentChanging(propertyPages);
}
// Get designer to create the new page component
KryptonPage page = (KryptonPage)_designerHost.CreateComponent(typeof(KryptonPage));
// Get access to the Name and Text propertues of the new page
PropertyDescriptor propertyName = TypeDescriptor.GetProperties(page)["Name"];
PropertyDescriptor propertyText = TypeDescriptor.GetProperties(page)["Text"];
// If we managed to get the property and it is the string we are expecting
if ((propertyName != null) && (propertyName.PropertyType == typeof(string)) &&
(propertyText != null) && (propertyText.PropertyType == typeof(string)))
{
// Grab the design time name
string name = (string)propertyName.GetValue(page);
// If the name is valid
if ((name != null) && (name.Length > 0))
{
// Use the design time name as the page text
propertyText.SetValue(page, name);
}
}
// Add a new defaulted page to the navigator
Navigator.Pages.Add(page);
// Do we need to raise the changed notification?
if (!_ignoreOnAddPage)
{
RaiseComponentChanged(propertyPages, null, null);
}
}
finally
{
// If we managed to create the transaction, then do it
transaction?.Commit();
}
}
private void OnRemovePage(object sender, EventArgs e)
{
// Use a transaction to support undo/redo actions
DesignerTransaction transaction = _designerHost.CreateTransaction("KryptonNavigator RemovePage");
try
{
// Get access to the Pages property
MemberDescriptor propertyPages = TypeDescriptor.GetProperties(Navigator)["Pages"];
// Remove the selected page from the navigator
RaiseComponentChanging(propertyPages);
// Get the page we are going to remove
KryptonPage removePage = Navigator.SelectedPage;
// Get designer to destroy it
_designerHost.DestroyComponent(removePage);
RaiseComponentChanged(propertyPages, null, null);
}
finally
{
// If we managed to create the transaction, then do it
transaction?.Commit();
}
}
private void OnClearPages(object sender, EventArgs e)
{
if (MessageBox.Show("Are you sure that all pages should be removed?",
"Clear Pages",
MessageBoxButtons.YesNo,
MessageBoxIcon.Warning) == DialogResult.Yes)
{
// Use a transaction to support undo/redo actions
DesignerTransaction transaction = _designerHost.CreateTransaction("KryptonNavigator RemovePage");
try
{
// Get access to the Pages property
MemberDescriptor propertyPages = TypeDescriptor.GetProperties(Navigator)["Pages"];
// Remove all pages from the navigator
RaiseComponentChanging(propertyPages);
// Get the designer to destroy each page in turn
for(int i=Navigator.Pages.Count; i>0; i--)
{
_designerHost.DestroyComponent(Navigator.Pages[0]);
}
RaiseComponentChanged(propertyPages, null, null);
}
finally
{
// If we managed to create the transaction, then do it
transaction?.Commit();
}
}
}
private void OnPageInserted(object sender, TypedCollectionEventArgs<KryptonPage> e)
{
// Let the user design the new page surface
EnableDesignMode(e.Item, e.Item.Name);
UpdateVerbStatus();
}
private void OnPageRemoved(object sender, TypedCollectionEventArgs<KryptonPage> e)
{
UpdateVerbStatus();
}
private void OnPagesCleared(object sender, EventArgs e)
{
UpdateVerbStatus();
}
private void OnSelectedPageChanged(object sender, EventArgs e)
{
MarkSelectionAsChanged();
UpdateVerbStatus();
}
private void OnNavigatorMouseUp(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
// Get any component associated with the current mouse position
Component component = Navigator.DesignerComponentFromPoint(new Point(e.X, e.Y));
if (component != null)
{
// Force the layout to be update for any change in selection
Navigator.PerformLayout();
// Select the component
ArrayList selectionList = new ArrayList
{
component
};
_selectionService.SetSelectedComponents(selectionList, SelectionTypes.Auto);
}
}
}
private void OnNavigatorDoubleClick(object sender, Point pt)
{
// Get any component associated with the current mouse position
Component component = Navigator.DesignerComponentFromPoint(pt);
// We are only interested in the button spec components and not the tab/check buttons
if ((component != null) && !(component is Control))
{
// Get the designer for the component
IDesigner designer = _designerHost.GetDesigner(component);
// Request code for the default event be generated
designer.DoDefaultAction();
}
}
private void UpdateVerbStatus()
{
// Can only update verbs, if the verbs have been created
if (_verbs != null)
{
_verbRemovePage.Enabled = (Navigator.SelectedPage != null);
_verbClearPages.Enabled = (Navigator.Pages.Count > 0);
}
}
private void MarkSelectionAsChanged()
{
// Get access to the SelectedPage property
MemberDescriptor propertyPage = TypeDescriptor.GetProperties(Navigator)["SelectedPage"];
// Notify that the selected page has been updated
RaiseComponentChanging(propertyPage);
RaiseComponentChanged(propertyPage, null, null);
}
#endregion
}
}
| 39.753982 | 157 | 0.571479 | [
"BSD-3-Clause"
] | Carko/Krypton-Toolkit-Suite-NET-Core | Source/Krypton Components/ComponentFactory.Krypton.Navigator/Navigator/KryptonNavigatorDesigner.cs | 22,464 | C# |
using System.Text.Json.Serialization;
namespace Essensoft.AspNetCore.Payment.Alipay.Domain
{
/// <summary>
/// AlipayUserCertifyInfoApplyModel Data Structure.
/// </summary>
public class AlipayUserCertifyInfoApplyModel : AlipayObject
{
/// <summary>
/// 委托书图片数据,根据biz_from参数确定是传base64字符串,还是传oss地址
/// </summary>
[JsonPropertyName("agent_auth_letter_picture")]
public string AgentAuthLetterPicture { get; set; }
/// <summary>
/// 代理人证件图片辅助页图片,对应二代身份证就是国徽页,根据biz_from参数确定是传base64字符串,还是传oss地址
/// </summary>
[JsonPropertyName("agent_cert_card_assist_picture")]
public string AgentCertCardAssistPicture { get; set; }
/// <summary>
/// 代理人证件信息页图片数据,对应二代身份证为带人脸页图片,根据biz_from参数确定是传base64字符串,还是传oss地址
/// </summary>
[JsonPropertyName("agent_cert_card_info_picture")]
public string AgentCertCardInfoPicture { get; set; }
/// <summary>
/// 代理人证件图片有效期截止日期,"yyyy-MM-dd"格式,若为长期,则填“长期”
/// </summary>
[JsonPropertyName("agent_cert_expired_date")]
public string AgentCertExpiredDate { get; set; }
/// <summary>
/// 代理人证件号码,若认证申请人不是法人而是代理人,则需要填写代理人相关信息
/// </summary>
[JsonPropertyName("agent_cert_no")]
public string AgentCertNo { get; set; }
/// <summary>
/// 代理人证件类型,目前仅支持二代身份证:RESIDENT,不支持其他证件类型
/// </summary>
[JsonPropertyName("agent_cert_type")]
public string AgentCertType { get; set; }
/// <summary>
/// 代理人姓名,若申请认证者非法人而是由代理人,则将代理人姓名填到此字段
/// </summary>
[JsonPropertyName("agent_name")]
public string AgentName { get; set; }
/// <summary>
/// 外部系统请求申请认证的业务来源,例如DingTalk,具体值请向认证开发同学确定
/// </summary>
[JsonPropertyName("biz_from")]
public string BizFrom { get; set; }
/// <summary>
/// 联系人手机号,用于认证过程中对用户进行短信通知的号码,11位数字
/// </summary>
[JsonPropertyName("contact_mobile")]
public string ContactMobile { get; set; }
/// <summary>
/// 法人证件图片辅助页图片数据,若为身份证,则为国徽页图片,根据biz_from参数确定是传base64字符串,还是传oss地址
/// </summary>
[JsonPropertyName("legal_cert_card_assist_picture")]
public string LegalCertCardAssistPicture { get; set; }
/// <summary>
/// 法定代表人的证件图片信息页数据,若为身份证,则为带人脸图片的那一页照片,根据biz_from参数确定是传base64字符串,还是传oss地址
/// </summary>
[JsonPropertyName("legal_cert_card_info_picture")]
public string LegalCertCardInfoPicture { get; set; }
/// <summary>
/// 法定代表人证件有效期截止日期 “yyyy-MM-dd” 格式,若为长期,则填“长期”
/// </summary>
[JsonPropertyName("legal_cert_expired_date")]
public string LegalCertExpiredDate { get; set; }
/// <summary>
/// 法定代表人证件号码
/// </summary>
[JsonPropertyName("legal_cert_no")]
public string LegalCertNo { get; set; }
/// <summary>
/// 法定代表人证件类型 二代身份证:RESIDENT 护照:PASSPORT 港澳来往内地通行证:HONGKONG_MACAO 台湾同胞往来大陆通行证:TAIWAN
/// </summary>
[JsonPropertyName("legal_cert_type")]
public string LegalCertType { get; set; }
/// <summary>
/// 法定代理人姓名,要按照营业执照上的姓名填写,必须一致,不能有错别字。
/// </summary>
[JsonPropertyName("legal_name")]
public string LegalName { get; set; }
/// <summary>
/// 住所,填写营业执照号上的住所(经营地址)信息
/// </summary>
[JsonPropertyName("org_address")]
public string OrgAddress { get; set; }
/// <summary>
/// 填写营业执照上的经营范围
/// </summary>
[JsonPropertyName("org_business_scope")]
public string OrgBusinessScope { get; set; }
/// <summary>
/// 企业所在市,城市的中文完整描述
/// </summary>
[JsonPropertyName("org_city")]
public string OrgCity { get; set; }
/// <summary>
/// 企业所在国家,目前只支持 中国
/// </summary>
[JsonPropertyName("org_country")]
public string OrgCountry { get; set; }
/// <summary>
/// 营业执照上的经营期限截止日期,日期为10位格式"yyyy-MM-dd“ 若为长期,则填“长期”
/// </summary>
[JsonPropertyName("org_main_cert_expired_date")]
public string OrgMainCertExpiredDate { get; set; }
/// <summary>
/// 填企业营业执照上的注册号(一般为15位数字)或社会信用代码(18位数字加字母格式大写),如果有信用代码则优先填写社会信用代码
/// </summary>
[JsonPropertyName("org_main_cert_no")]
public string OrgMainCertNo { get; set; }
/// <summary>
/// 营业执照图片信息,根据biz_from参数确定是要传base64编码格式的string字符串,还是传oss地址
/// </summary>
[JsonPropertyName("org_main_cert_picture")]
public string OrgMainCertPicture { get; set; }
/// <summary>
/// 申请认证的公司的名字,要与营业执照上面一致,包括全半角字符
/// </summary>
[JsonPropertyName("org_name")]
public string OrgName { get; set; }
/// <summary>
/// 企业所在省份,填写省份中文完整信息
/// </summary>
[JsonPropertyName("org_province")]
public string OrgProvince { get; set; }
/// <summary>
/// 公司: ENTERPRISE,事业单位:PUBLIC_INST,社会团体:SOCIAL_ORG,民办非企业组织:PRIVATE_NON_ENTERPRISE,党政国家机关:PARTY_AND_STATE_ORGANS,个体工商户:INDIVIDUAL
/// </summary>
[JsonPropertyName("org_type")]
public string OrgType { get; set; }
/// <summary>
/// 注册资本
/// </summary>
[JsonPropertyName("register_capital")]
public string RegisterCapital { get; set; }
/// <summary>
/// 蚂蚁统一会员ID
/// </summary>
[JsonPropertyName("user_id")]
public string UserId { get; set; }
}
}
| 32.531792 | 137 | 0.590085 | [
"MIT"
] | LuohuaRain/payment | src/Essensoft.AspNetCore.Payment.Alipay/Domain/AlipayUserCertifyInfoApplyModel.cs | 7,214 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Threading;
using System.Threading.Tasks;
using Azure.Core;
namespace Microsoft.Azure.WebJobs.Extensions.WebPubSub
{
internal class WebPubSubAsyncCollector : IAsyncCollector<WebPubSubOperation>
{
private readonly IWebPubSubService _service;
internal WebPubSubAsyncCollector(IWebPubSubService service)
{
_service = service;
}
public async Task AddAsync(WebPubSubOperation item, CancellationToken cancellationToken = default)
{
if (item == null)
{
throw new ArgumentNullException(nameof(item));
}
switch (item)
{
case SendToAll sendToAll:
await _service.Client.SendToAllAsync(RequestContent.Create(sendToAll.Message),
Utilities.GetContentType(sendToAll.DataType), sendToAll.Excluded).ConfigureAwait(false);
break;
case SendToConnection sendToConnection:
await _service.Client.SendToConnectionAsync(sendToConnection.ConnectionId, RequestContent.Create(sendToConnection.Message),
Utilities.GetContentType(sendToConnection.DataType)).ConfigureAwait(false);
break;
case SendToUser sendToUser:
await _service.Client.SendToUserAsync(sendToUser.UserId, RequestContent.Create(sendToUser.Message),
Utilities.GetContentType(sendToUser.DataType)).ConfigureAwait(false);
break;
case SendToGroup sendToGroup:
await _service.Client.SendToGroupAsync(sendToGroup.Group, RequestContent.Create(sendToGroup.Message),
Utilities.GetContentType(sendToGroup.DataType), sendToGroup.Excluded).ConfigureAwait(false);
break;
case AddUserToGroup addUserToGroup:
await _service.Client.AddUserToGroupAsync(addUserToGroup.Group, addUserToGroup.UserId).ConfigureAwait(false);
break;
case RemoveUserFromGroup removeUserFromGroup:
await _service.Client.RemoveUserFromGroupAsync(removeUserFromGroup.Group, removeUserFromGroup.UserId).ConfigureAwait(false);
break;
case RemoveUserFromAllGroups removeUserFromAllGroups:
await _service.Client.RemoveUserFromAllGroupsAsync(removeUserFromAllGroups.UserId).ConfigureAwait(false);
break;
case AddConnectionToGroup addConnectionToGroup:
await _service.Client.AddConnectionToGroupAsync(addConnectionToGroup.Group, addConnectionToGroup.ConnectionId).ConfigureAwait(false);
break;
case RemoveConnectionFromGroup removeConnectionFromGroup:
await _service.Client.RemoveConnectionFromGroupAsync(removeConnectionFromGroup.Group, removeConnectionFromGroup.ConnectionId).ConfigureAwait(false);
break;
case CloseAllConnections closeAllConnections:
await _service.Client.CloseAllConnectionsAsync(closeAllConnections.Excluded, closeAllConnections.Reason).ConfigureAwait(false);
break;
case CloseClientConnection closeClientConnection:
await _service.Client.CloseConnectionAsync(closeClientConnection.ConnectionId, closeClientConnection.Reason).ConfigureAwait(false);
break;
case CloseGroupConnections closeGroupConnections:
await _service.Client.CloseGroupConnectionsAsync(closeGroupConnections.Group, closeGroupConnections.Excluded, closeGroupConnections.Reason).ConfigureAwait(false);
break;
case GrantPermission grantPermission:
await _service.Client.GrantPermissionAsync(grantPermission.Permission, grantPermission.ConnectionId, grantPermission.TargetName).ConfigureAwait(false);
break;
case RevokePermission revokePermission:
await _service.Client.RevokePermissionAsync(revokePermission.Permission, revokePermission.ConnectionId, revokePermission.TargetName).ConfigureAwait(false);
break;
default:
throw new ArgumentException($"Not supported WebPubSubOperation: {nameof(item)}.");
}
}
public Task FlushAsync(CancellationToken cancellationToken = default)
{
return Task.CompletedTask;
}
}
}
| 55.081395 | 182 | 0.659278 | [
"MIT"
] | frank-pang-msft/azure-sdk-for-net | sdk/webpubsub/Microsoft.Azure.WebJobs.Extensions.WebPubSub/src/Bindings/WebPubSubAsyncCollector.cs | 4,739 | C# |
using System;
using System.Collections.Generic;
using System.Reactive.Linq;
using FluentAssertions;
using NSubstitute;
using Toggl.Foundation.Analytics;
using Toggl.Foundation.DataSources.Interfaces;
using Toggl.Foundation.Extensions;
using Toggl.Foundation.Models;
using Toggl.Foundation.Models.Interfaces;
using Toggl.Foundation.Sync;
using Toggl.Foundation.Sync.States.Push;
using Toggl.Foundation.Tests.Sync.States.Push.BaseStates;
using Toggl.PrimeRadiant;
using Toggl.Ultrawave.ApiClients;
using Xunit;
using static Toggl.Foundation.Sync.PushSyncOperation;
namespace Toggl.Foundation.Tests.Sync.States.Push
{
public sealed class CreateEntityStateTests : BasePushEntityStateTests
{
private readonly ICreatingApiClient<ITestModel> api
= Substitute.For<ICreatingApiClient<ITestModel>>();
private readonly IDataSource<IThreadSafeTestModel, IDatabaseTestModel> dataSource;
private readonly ITestAnalyticsService analyticsService
= Substitute.For<ITestAnalyticsService>();
protected override PushSyncOperation Operation => PushSyncOperation.Create;
public CreateEntityStateTests()
: this(Substitute.For<IDataSource<IThreadSafeTestModel, IDatabaseTestModel>>())
{
}
private CreateEntityStateTests(IDataSource<IThreadSafeTestModel, IDatabaseTestModel> dataSource)
{
this.dataSource = dataSource;
SyncAnalyticsExtensions.SearchStrategy = TestSyncAnalyticsExtensionsSearchStrategy;
}
[Fact, LogIfTooSlow]
public void ReturnsSuccessfulTransitionWhenEverythingWorks()
{
var state = (CreateEntityState<ITestModel, IDatabaseTestModel, IThreadSafeTestModel>)CreateState();
var entity = new TestModel(-1, SyncStatus.SyncFailed);
var withPositiveId = new TestModel(13, SyncStatus.InSync);
api.Create(Arg.Any<ITestModel>())
.Returns(Observable.Return(withPositiveId));
dataSource.OverwriteIfOriginalDidNotChange(Arg.Any<IThreadSafeTestModel>(), Arg.Any<IThreadSafeTestModel>())
.Returns(x => Observable.Return(new[] {
new UpdateResult<IThreadSafeTestModel>(entity.Id, entityWithId((IThreadSafeTestModel)x[1], entity.Id))
}));
dataSource.ChangeId(entity.Id, withPositiveId.Id).Returns(Observable.Return(withPositiveId));
var transition = state.Start(entity).SingleAsync().Wait();
var persistedEntity = ((Transition<IThreadSafeTestModel>)transition).Parameter;
dataSource.Received().ChangeId(entity.Id, withPositiveId.Id);
transition.Result.Should().Be(state.Finished);
persistedEntity.Id.Should().Be(withPositiveId.Id);
persistedEntity.SyncStatus.Should().Be(SyncStatus.InSync);
}
private static IThreadSafeTestModel entityWithId(IThreadSafeTestModel testModel, long id)
{
var newModel = TestModel.From(testModel);
newModel.Id = id;
return newModel;
}
[Fact, LogIfTooSlow]
public void TriesToSafelyOverwriteLocalDataWithDataFromTheServer()
{
var state = (CreateEntityState<ITestModel, IDatabaseTestModel, IThreadSafeTestModel>)CreateState();
var entity = new TestModel(-1, SyncStatus.SyncFailed);
var withPositiveId = new TestModel(Math.Abs(entity.Id), SyncStatus.InSync);
api.Create(entity)
.Returns(Observable.Return(withPositiveId));
state.Start(entity).SingleAsync().Wait();
dataSource
.Received()
.OverwriteIfOriginalDidNotChange(
Arg.Is<IThreadSafeTestModel>(original => original.Id == entity.Id),
Arg.Is<IThreadSafeTestModel>(fromServer => fromServer.Id == withPositiveId.Id));
}
[Fact, LogIfTooSlow]
public void UpdateIsCalledWithCorrectParameters()
{
var state = (CreateEntityState<ITestModel, IDatabaseTestModel, IThreadSafeTestModel>)CreateState();
var entity = new TestModel(-1, SyncStatus.SyncFailed);
var withPositiveId = new TestModel(Math.Abs(entity.Id), SyncStatus.InSync);
api.Create(entity)
.Returns(Observable.Return(withPositiveId));
state.Start(entity).SingleAsync().Wait();
dataSource
.Received()
.OverwriteIfOriginalDidNotChange(Arg.Is<IThreadSafeTestModel>(model => model.Id == entity.Id), Arg.Is<IThreadSafeTestModel>(model => model.Id == withPositiveId.Id));
}
[Fact, LogIfTooSlow]
public void ReturnsTheEntityChangedTransitionWhenEntityChangesLocally()
{
var state = (CreateEntityState<ITestModel, IDatabaseTestModel, IThreadSafeTestModel>)CreateState();
var at = new DateTimeOffset(2017, 9, 1, 12, 34, 56, TimeSpan.Zero);
var entity = new TestModel { Id = 1, At = at, SyncStatus = SyncStatus.SyncNeeded };
api.Create(Arg.Any<ITestModel>())
.Returns(Observable.Return(entity));
dataSource
.OverwriteIfOriginalDidNotChange(Arg.Any<IThreadSafeTestModel>(), Arg.Any<IThreadSafeTestModel>())
.Returns(Observable.Return(new[] { new IgnoreResult<IThreadSafeTestModel>(entity.Id) }));
dataSource.ChangeId(Arg.Any<long>(), entity.Id).Returns(Observable.Return(entity));
var transition = state.Start(entity).SingleAsync().Wait();
var parameter = ((Transition<IThreadSafeTestModel>)transition).Parameter;
transition.Result.Should().Be(state.EntityChanged);
parameter.Id.Should().Be(entity.Id);
}
[Fact, LogIfTooSlow]
public void ChangesIdIfTheEntityChangedLocally()
{
var state = (CreateEntityState<ITestModel, IDatabaseTestModel, IThreadSafeTestModel>)CreateState();
var at = new DateTimeOffset(2017, 9, 1, 12, 34, 56, TimeSpan.Zero);
var entity = new TestModel { Id = -1, At = at, SyncStatus = SyncStatus.SyncNeeded };
var updatedEntity = new TestModel { Id = 13, At = at, SyncStatus = SyncStatus.SyncNeeded };
api.Create(Arg.Any<ITestModel>())
.Returns(Observable.Return(updatedEntity));
dataSource
.OverwriteIfOriginalDidNotChange(Arg.Any<IThreadSafeTestModel>(), Arg.Any<IThreadSafeTestModel>())
.Returns(Observable.Return(new[] { new IgnoreResult<IThreadSafeTestModel>(entity.Id) }));
dataSource.ChangeId(Arg.Any<long>(), updatedEntity.Id).Returns(Observable.Return(entity));
_ = state.Start(entity).SingleAsync().Wait();
dataSource.Received().ChangeId(entity.Id, updatedEntity.Id);
}
[Fact, LogIfTooSlow]
public void TracksEntitySyncStatusInCaseOfSuccess()
{
var exception = new Exception();
var state = CreateState();
var entity = new TestModel(-1, SyncStatus.SyncFailed);
var withPositiveId = new TestModel(Math.Abs(entity.Id), SyncStatus.InSync);
api.Create(Arg.Any<ITestModel>())
.Returns(Observable.Return(withPositiveId));
dataSource.OverwriteIfOriginalDidNotChange(Arg.Any<IThreadSafeTestModel>(), Arg.Any<IThreadSafeTestModel>())
.Returns(x => Observable.Return(new[] { new UpdateResult<IThreadSafeTestModel>(entity.Id, (IThreadSafeTestModel)x[1]) }));
state.Start(entity).Wait();
analyticsService.EntitySyncStatus.Received().Track(
entity.GetSafeTypeName(),
$"{Create}:{Resources.Success}");
}
[Fact, LogIfTooSlow]
public void TracksEntitySyncedInCaseOfSuccess()
{
var exception = new Exception();
var state = CreateState();
var entity = new TestModel(-1, SyncStatus.SyncFailed);
var withPositiveId = new TestModel(Math.Abs(entity.Id), SyncStatus.InSync);
api.Create(Arg.Any<ITestModel>())
.Returns(Observable.Return(withPositiveId));
dataSource.OverwriteIfOriginalDidNotChange(Arg.Any<IThreadSafeTestModel>(), Arg.Any<IThreadSafeTestModel>())
.Returns(x => Observable.Return(new[] { new UpdateResult<IThreadSafeTestModel>(entity.Id, (IThreadSafeTestModel)x[1]) }));
state.Start(entity).Wait();
analyticsService.EntitySynced.Received().Track(Create, entity.GetSafeTypeName());
}
[Fact, LogIfTooSlow]
public void TracksEntitySyncStatusInCaseOfFailure()
{
var exception = new Exception();
var state = CreateState();
var entity = Substitute.For<IThreadSafeTestModel>();
PrepareApiCallFunctionToThrow(exception);
state.Start(entity).Wait();
analyticsService.EntitySyncStatus.Received().Track(
entity.GetSafeTypeName(),
$"{Create}:{Resources.Failure}");
}
[Theory, LogIfTooSlow]
[MemberData(nameof(EntityTypes), MemberType = typeof(BasePushEntityStateTests))]
public void TracksEntitySyncErrorInCaseOfFailure(Type entityType)
{
var exception = new Exception("SomeRandomMessage");
var entity = (IThreadSafeTestModel)Substitute.For(new[] { entityType }, new object[0]);
var state = new CreateEntityState<ITestModel, IDatabaseTestModel, IThreadSafeTestModel>(api, dataSource, analyticsService, _ => null);
var expectedMessage = $"{Create}:{exception.Message}";
var analyticsEvent = entity.GetType().ToSyncErrorAnalyticsEvent(analyticsService);
PrepareApiCallFunctionToThrow(exception);
state.Start(entity).Wait();
analyticsEvent.Received().Track(expectedMessage);
}
protected override BasePushEntityState<IThreadSafeTestModel> CreateState()
=> new CreateEntityState<ITestModel, IDatabaseTestModel, IThreadSafeTestModel>(api, dataSource, analyticsService, TestModel.From);
protected override void PrepareApiCallFunctionToThrow(Exception e)
{
api.Create(Arg.Any<ITestModel>())
.Returns(_ => Observable.Throw<ITestModel>(e));
}
protected override void PrepareDatabaseOperationToThrow(Exception e)
{
dataSource.OverwriteIfOriginalDidNotChange(Arg.Any<IThreadSafeTestModel>(), Arg.Any<IThreadSafeTestModel>())
.Returns(_ => Observable.Throw<IEnumerable<IConflictResolutionResult<IThreadSafeTestModel>>>(e));
}
}
}
| 47.095652 | 181 | 0.655465 | [
"BSD-3-Clause"
] | AzureMentor/mobileapp | Toggl.Foundation.Tests/Sync/States/Push/CreateEntityStateTests.cs | 10,834 | C# |
namespace Atc.Tests.Helpers.Enums;
public class EnumHelperTests
{
[Theory]
[InlineData("On", OnOffType.On)]
[InlineData("Off", OnOffType.Off)]
public void GetName(string expected, Enum input)
{
// Act
var actual = EnumHelper.GetName(input);
// Assert
Assert.Equal(expected, actual);
}
[Theory]
[InlineData("On", "On")]
[InlineData("Off", "Off")]
public void GetEnumValue_OnOffType(string expected, string input)
{
// Act
var actual = EnumHelper.GetEnumValue<OnOffType>(input);
// Assert
Assert.Equal(expected, actual.ToString());
}
[Theory]
[InlineData("On", "On", true)]
[InlineData("Off", "Off", true)]
[InlineData("On", "on", true)]
[InlineData("Off", "off", true)]
[InlineData("None", "on", false)]
[InlineData("None", "off", false)]
public void GetEnumValue_OnOffType_IgnoreCase(string expected, string input, bool ignoreCase)
{
// Act
var actual = EnumHelper.GetEnumValue<OnOffType>(input, ignoreCase);
// Assert
Assert.Equal(expected, actual.ToString());
}
[Theory]
[InlineData("Monday", DayOfWeek.Monday)]
public void GetDescription(string expected, DayOfWeek value)
{
Assert.Equal(expected, EnumHelper.GetDescription(value));
}
[Theory]
[InlineData(GlobalizationLcidConstants.Invariant, ForwardReverseType.Forward, "Forward")]
[InlineData(GlobalizationLcidConstants.Invariant, ForwardReverseType.Forward, "forward")]
[InlineData(GlobalizationLcidConstants.UnitedStates, ForwardReverseType.Forward, "Forward")]
[InlineData(GlobalizationLcidConstants.UnitedStates, ForwardReverseType.Forward, "forward")]
[InlineData(GlobalizationLcidConstants.Denmark, ForwardReverseType.Forward, "Fremad")]
[InlineData(GlobalizationLcidConstants.Denmark, ForwardReverseType.Forward, "fremad")]
public void GetValueFromDescription_ForwardReverseType(int arrangeUiLcid, ForwardReverseType expected, string input)
{
// Arrange
if (arrangeUiLcid > 0)
{
Thread.CurrentThread.CurrentUICulture = new CultureInfo(arrangeUiLcid);
}
// Act
var actual = EnumHelper.GetValueFromDescription<ForwardReverseType>(input);
// Assert
Assert.Equal(expected, actual);
}
[Theory]
[MemberData(nameof(TestMemberDataForEnum.DayOfWeekData), MemberType = typeof(TestMemberDataForEnum), DisableDiscoveryEnumeration = true)]
public void ConvertEnumToArray<T>(
T dummyForT,
int expectedCount,
DropDownFirstItemType dropDownFirstItemType,
bool useDescriptionAttribute,
bool includeDefault,
SortDirectionType sortDirectionType,
bool byFlagIncludeBase,
bool byFlagIncludeCombined)
where T : Enum
{
// Arrange
var enumType = dummyForT.GetType();
// Act
var actual = EnumHelper.ConvertEnumToArray(
enumType,
dropDownFirstItemType,
useDescriptionAttribute,
includeDefault,
sortDirectionType,
byFlagIncludeBase,
byFlagIncludeCombined);
// Assert
actual.Cast<string>().Should().NotBeNull().And.HaveCount(expectedCount);
}
[Theory]
[MemberData(nameof(TestMemberDataForEnum.DayOfWeekData), MemberType = typeof(TestMemberDataForEnum), DisableDiscoveryEnumeration = true)]
public void ConvertEnumToDictionary<T>(
T dummyForT,
int expectedCount,
DropDownFirstItemType dropDownFirstItemType,
bool useDescriptionAttribute,
bool includeDefault,
SortDirectionType sortDirectionType,
bool byFlagIncludeBase,
bool byFlagIncludeCombined)
where T : Enum
{
// Arrange
var enumType = dummyForT.GetType();
// Act
var actual = EnumHelper.ConvertEnumToDictionary(
enumType,
dropDownFirstItemType,
useDescriptionAttribute,
includeDefault,
sortDirectionType,
byFlagIncludeBase,
byFlagIncludeCombined);
// Assert
actual.Should().NotBeNull().And.HaveCount(expectedCount);
}
[Theory]
[MemberData(nameof(TestMemberDataForEnum.DayOfWeekData), MemberType = typeof(TestMemberDataForEnum), DisableDiscoveryEnumeration = true)]
public void ConvertEnumToDictionaryWithStringKey<T>(
T dummyForT,
int expectedCount,
DropDownFirstItemType dropDownFirstItemType,
bool useDescriptionAttribute,
bool includeDefault,
SortDirectionType sortDirectionType,
bool byFlagIncludeBase,
bool byFlagIncludeCombined)
where T : Enum
{
// Arrange
var enumType = dummyForT.GetType();
// Act
var actual = EnumHelper.ConvertEnumToDictionaryWithStringKey(
enumType,
dropDownFirstItemType,
useDescriptionAttribute,
includeDefault,
sortDirectionType,
byFlagIncludeBase,
byFlagIncludeCombined);
// Assert
actual.Should().NotBeNull().And.HaveCount(expectedCount);
}
} | 32.411043 | 141 | 0.654363 | [
"MIT"
] | atc-net/atc-common | test/Atc.Tests/Helpers/Enums/EnumHelperTests.cs | 5,283 | C# |
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
#if DNXCORE50
using System.Collections.Generic;
using System.Diagnostics;
using System.Net.Http.Headers;
using Microsoft.AspNet.Mvc;
namespace System.Net.Http.Formatting
{
/// <summary>
/// Extension methods for <see cref="MediaTypeHeaderValue"/>.
/// </summary>
internal static class MediaTypeHeaderValueExtensions
{
/// <summary>
/// Determines whether two <see cref="MediaTypeHeaderValue"/> instances match. The instance
/// <paramref name="mediaType1"/> is said to match <paramref name="mediaType2"/> if and only if
/// <paramref name="mediaType1"/> is a strict subset of the values and parameters of
/// <paramref name="mediaType2"/>.
/// That is, if the media type and media type parameters of <paramref name="mediaType1"/> are all present
/// and match those of <paramref name="mediaType2"/> then it is a match even though
/// <paramref name="mediaType2"/> may have additional parameters.
/// </summary>
/// <param name="mediaType1">The first media type.</param>
/// <param name="mediaType2">The second media type.</param>
/// <returns><c>true</c> if this is a subset of <paramref name="mediaType2"/>; false otherwise.</returns>
public static bool IsSubsetOf(this MediaTypeHeaderValue mediaType1, MediaTypeHeaderValue mediaType2)
{
MediaTypeFormatterMatchRanking mediaType2Range;
return IsSubsetOf(mediaType1, mediaType2, out mediaType2Range);
}
/// <summary>
/// Determines whether two <see cref="MediaTypeHeaderValue"/> instances match. The instance
/// <paramref name="mediaType1"/> is said to match <paramref name="mediaType2"/> if and only if
/// <paramref name="mediaType1"/> is a strict subset of the values and parameters of
/// <paramref name="mediaType2"/>.
/// That is, if the media type and media type parameters of <paramref name="mediaType1"/> are all present
/// and match those of <paramref name="mediaType2"/> then it is a match even though
/// <paramref name="mediaType2"/> may have additional parameters.
/// </summary>
/// <param name="mediaType1">The first media type.</param>
/// <param name="mediaType2">The second media type.</param>
/// <param name="mediaType2Range">
/// Indicates whether <paramref name="mediaType2"/> is a regular media type, a subtype media range, or a full
/// media range.
/// </param>
/// <returns><c>true</c> if this is a subset of <paramref name="mediaType2"/>; false otherwise.</returns>
public static bool IsSubsetOf(
this MediaTypeHeaderValue mediaType1,
MediaTypeHeaderValue mediaType2,
out MediaTypeFormatterMatchRanking mediaType2Range)
{
// Performance-sensitive
Debug.Assert(mediaType1 != null);
if (mediaType2 == null)
{
mediaType2Range = MediaTypeFormatterMatchRanking.None;
return false;
}
var parsedMediaType1 = new ParsedMediaTypeHeaderValue(mediaType1);
var parsedMediaType2 = new ParsedMediaTypeHeaderValue(mediaType2);
mediaType2Range = parsedMediaType2.IsAllMediaRange ? MediaTypeFormatterMatchRanking.MatchOnRequestAcceptHeaderAllMediaRange :
parsedMediaType2.IsSubtypeMediaRange ? MediaTypeFormatterMatchRanking.MatchOnRequestAcceptHeaderSubtypeMediaRange :
MediaTypeFormatterMatchRanking.None;
if (!parsedMediaType1.TypesEqual(ref parsedMediaType2))
{
if (mediaType2Range != MediaTypeFormatterMatchRanking.MatchOnRequestAcceptHeaderAllMediaRange)
{
return false;
}
}
else if (!parsedMediaType1.SubTypesEqual(ref parsedMediaType2))
{
if (mediaType2Range != MediaTypeFormatterMatchRanking.MatchOnRequestAcceptHeaderSubtypeMediaRange)
{
return false;
}
}
else
{
mediaType2Range = MediaTypeFormatterMatchRanking.MatchOnRequestAcceptHeaderLiteral;
}
// So far we either have a full match or a subset match. Now check that all of
// mediaType1's parameters are present and equal in mediatype2
// Optimize for the common case where the parameters inherit from Collection<T> and cache the count which
// is faster for Collection<T>.
var parameters1 = mediaType1.Parameters.AsCollection();
var parameterCount1 = parameters1.Count;
var parameters2 = mediaType2.Parameters.AsCollection();
var parameterCount2 = parameters2.Count;
for (var i = 0; i < parameterCount1; i++)
{
var parameter1 = parameters1[i];
var found = false;
for (var j = 0; j < parameterCount2; j++)
{
var parameter2 = parameters2[j];
if (parameter1.Equals(parameter2))
{
found = true;
break;
}
}
if (!found)
{
return false;
}
}
return true;
}
}
}
#endif
| 46.540984 | 137 | 0.607432 | [
"Apache-2.0"
] | walkeeperY/ManagementSystem | src/Microsoft.AspNet.Mvc.WebApiCompatShim/ContentNegotiator/MediaTypeHeaderValueExtensions.cs | 5,680 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace IdentityTest.WebApp.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
} | 42.765351 | 261 | 0.553305 | [
"MIT"
] | Code-Inside/Samples | 2016/IdentityTest/IdentityTest.WebApp/Areas/HelpPage/SampleGeneration/ObjectGenerator.cs | 19,501 | C# |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// <auto-generated/>
// Template Source: MethodRequestBuilder.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
/// <summary>
/// The type PrintJobStartPrintJobRequestBuilder.
/// </summary>
public partial class PrintJobStartPrintJobRequestBuilder : BaseActionMethodRequestBuilder<IPrintJobStartPrintJobRequest>, IPrintJobStartPrintJobRequestBuilder
{
/// <summary>
/// Constructs a new <see cref="PrintJobStartPrintJobRequestBuilder"/>.
/// </summary>
/// <param name="requestUrl">The URL for the request.</param>
/// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param>
public PrintJobStartPrintJobRequestBuilder(
string requestUrl,
IBaseClient client)
: base(requestUrl, client)
{
}
/// <summary>
/// A method used by the base class to construct a request class instance.
/// </summary>
/// <param name="functionUrl">The request URL to </param>
/// <param name="options">The query and header options for the request.</param>
/// <returns>An instance of a specific request class.</returns>
protected override IPrintJobStartPrintJobRequest CreateRequest(string functionUrl, IEnumerable<Option> options)
{
var request = new PrintJobStartPrintJobRequest(functionUrl, this.Client, options);
return request;
}
}
}
| 41.021277 | 162 | 0.610477 | [
"MIT"
] | GeertVL/msgraph-beta-sdk-dotnet | src/Microsoft.Graph/Generated/requests/PrintJobStartPrintJobRequestBuilder.cs | 1,928 | C# |
using System.Diagnostics.Contracts;
using System.Runtime.CompilerServices;
namespace SadRogue.Primitives
{
/// <summary>
/// Contains set of operators that match ones defined by other packages for interoperability,
/// so syntax may be uniform. Functionality is similar to the corresponding actual operators for Point.
/// </summary>
public static class PointExtensions
{
/// <summary>
/// Adds the given Point's x/y values to the current Point's x/y values.
/// </summary>
/// <param name="self"/>
/// <param name="other"/>
/// <returns>Position (self.X + other.X, self.Y + other.Y).</returns>
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Point Add(this Point self, Point other) => self + other;
/// <summary>
/// Adds the given scalar to the current Point's x/y values.
/// </summary>
/// <param name="self"/>
/// <param name="i"/>
/// <returns>Position (self.X + i, self.Y + i).</returns>
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Point Add(this Point self, int i) => self + i;
/// <summary>
/// Translates the current position by one unit in the given direction.
/// </summary>
/// <param name="self"/>
/// <param name="dir"/>
/// <returns>Position (self.X + dir.DeltaX, self.Y + dir.DeltaY)</returns>
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Point Add(this Point self, Direction dir) => self + dir;
/// <summary>
/// Subtracts the given Point's x/y values from the current Point's x/y values.
/// </summary>
/// <param name="self"/>
/// <param name="other"/>
/// <returns>Position (self.X - other.X, self.Y - other.Y).</returns>
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Point Subtract(this Point self, Point other) => self - other;
/// <summary>
/// Subtracts the given scalar from the current Point's x/y values.
/// </summary>
/// <param name="self"/>
/// <param name="i"/>
/// <returns>Position (self.X - i, self.Y - i).</returns>
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Point Subtract(this Point self, int i) => self - i;
/// <summary>
/// Translates the current position by one unit in the opposite of the given direction.
/// </summary>
/// <param name="self"/>
/// <param name="dir"/>
/// <returns>Position (self.X - dir.DeltaX, self.Y - dir.DeltaY)</returns>
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Point Subtract(this Point self, Direction dir) => self - dir;
/// <summary>
/// Multiplies the current Point's x/y values by the given Point's x/y values.
/// </summary>
/// <param name="self"/>
/// <param name="other"/>
/// <returns>Position (self.X * other.X, self.Y * other.Y).</returns>
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Point Multiply(this Point self, Point other) => self * other;
/// <summary>
/// Multiplies the current Point's x/y values by the given scalar.
/// </summary>
/// <param name="self"/>
/// <param name="i"/>
/// <returns>Position (self.X * i, self.Y * i).</returns>
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Point Multiply(this Point self, int i) => self * i;
/// <summary>
/// Multiplies the current Point's x/y values by the given scalar, rounding to the nearest integer.
/// </summary>
/// <param name="self"/>
/// <param name="d"/>
/// <returns>Position (self.X * d, self.Y * d), with each value rounded to the nearest integer.</returns>
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Point Multiply(this Point self, double d) => self * d;
/// <summary>
/// Divides the current Point's x/y values by the given Point's x/y values, rounding to the nearest integer.
/// </summary>
/// <param name="self"/>
/// <param name="other"/>
/// <returns>Position (self.X / other.X, self.Y / other.Y), with each value rounded to the nearest integer.</returns>
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Point Divide(this Point self, Point other) => self / other;
/// <summary>
/// Divides the current Point's x/y values by the given scalar, rounding to the nearest integer.
/// </summary>
/// <param name="self"/>
/// <param name="i"/>
/// <returns>Position(self.X / i, self.Y / i), with each value rounded to the nearest integer.</returns>
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Point Divide(this Point self, int i) => self / i;
/// <summary>
/// Divides the current Point's x/y values by the given scalar, rounding to the nearest integer.
/// </summary>
/// <param name="self"/>
/// <param name="d"/>
/// <returns>Position(self.X / d, self.Y / d), with each value rounded to the nearest integer.</returns>
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Point Divide(this Point self, double d) => self / d;
/// <summary>
/// Compares the two points for equality; equivalent to <see cref="Point.Equals(Point)"/>.
/// </summary>
/// <param name="self"/>
/// <param name="other"/>
/// <returns>True if the two points are equal; false otherwise.</returns>
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool Matches(this Point self, Point other) => self.Equals(other);
}
}
| 43.090909 | 125 | 0.586011 | [
"MIT"
] | Thecentury/TheSadRogue.Primitives | TheSadRogue.Primitives/PointExtensions.cs | 6,164 | C# |
using System.Collections.Generic;
using System.Linq;
namespace AsyncGenerator.Tests.LocalFunctions.Input
{
public class ExtensionMethod
{
public void Test()
{
TType GetFirstOrDefault<TType>(TType item) where TType : class
{
return (from e in new EnumerableQuery<TType>(new List<TType>())
where e.Equals(item)
select e
).FirstOrDefault();
}
var result = GetFirstOrDefault("test");
}
}
}
| 19.590909 | 67 | 0.689095 | [
"MIT"
] | bubdm/AsyncGenerator | Source/AsyncGenerator.Tests/LocalFunctions/Input/ExtensionMethod.cs | 433 | C# |
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CQRSPipeline.DemoAPI.Data;
namespace CQRSPipeline.DemoAPI.Dispatch
{
public class CommandDispatcher
{
private readonly DispatchHandlers handlers;
private readonly Func<AdventureWorksDbContext> dbContextFactory;
private readonly FastContainer iocContainer;
public CommandDispatcher(DispatchHandlers handlers, FastContainer iocContainer, Func<AdventureWorksDbContext> dbContextFactory)
{
this.handlers = handlers;
this.iocContainer = iocContainer;
this.dbContextFactory = dbContextFactory;
}
public TResult Dispatch<TResult>(IAPICommand command)
{
var sw = Stopwatch.StartNew();
var commandContext = new CommandContext();
commandContext.CurrentCommand = command;
using (var childContainer = iocContainer.Clone())
{
childContainer.Register(commandContext);
try
{
OnDispatching(commandContext);
var handler = handlers.FindHandler(command.GetType());
var result = (TResult)handler.Execute(ResolveParameters(handler, command, childContainer));
OnDispatched(commandContext);
// TODO: logging and other instrumentation
sw.Stop();
return result;
}
catch (Exception e)
{
OnDispatched(commandContext, e);
sw.Stop();
// TODO: logging
throw;
}
}
}
private object[] ResolveParameters(ActionMethodDispatcher handler, object command, FastContainer childContainer)
{
var parameters = new object[handler.ParameterTypes.Count];
for (int i = 0; i < parameters.Length; i++)
{
var parameterType = handler.ParameterTypes[i];
if (parameterType == command.GetType())
{
parameters[i] = command; // shortcut for command, it's a known type
continue;
}
parameters[i] = childContainer.Resolve(parameterType);
}
return parameters;
}
private void OnDispatching(CommandContext commandContext)
{
// TODO: begin unit of work, other pipeline operations here
commandContext.DbContext = dbContextFactory();
commandContext.DbContext.Database.BeginTransaction(IsolationLevel.RepeatableRead);
}
private void OnDispatched(CommandContext commandContext, Exception exception = null)
{
try
{
if (exception == null)
{
// TODO: commit unit of work
commandContext.DbContext.SaveChanges();
commandContext.DbContext.Database.CurrentTransaction.Commit();
}
else
{
try
{
if (commandContext.DbContext != null && commandContext.DbContext.Database.CurrentTransaction != null)
{
commandContext.DbContext.Database.CurrentTransaction.Rollback();
}
}
catch (Exception)
{
// do not throw;
// TODO: logging if necessary
}
}
}
finally
{
if (commandContext.DbContext != null)
{
commandContext.DbContext.Dispose();
commandContext.DbContext = null;
}
}
}
}
} | 37.176991 | 136 | 0.508926 | [
"MIT"
] | jdaigle/CQRSPipelineDemo | CQRSPipeline.DemoAPI/Dispatch/CommandDispatcher.cs | 4,203 | C# |
////////////////////////////////////////////////////////////////////////////////
//NUnit tests for "EF Core Provider for LCPI OLE DB"
// IBProvider and Contributors. 13.05.2021.
using System;
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.NullableTimeSpan.NullableTimeSpan{
////////////////////////////////////////////////////////////////////////////////
using T_DATA1 =System.Nullable<System.TimeSpan>;
using T_DATA2 =System.Nullable<System.TimeSpan>;
using T_DATA1_U=System.TimeSpan;
using T_DATA2_U=System.TimeSpan;
using DB_TABLE=LocalDbObjNames.TEST_MODIFY_ROW2;
////////////////////////////////////////////////////////////////////////////////
//class TestSet_001__fields__02__VN
public static class TestSet_001__fields__02__VN
{
private const string c_NameOf__TABLE =DB_TABLE.Name;
private const string c_NameOf__COL_DATA1 =DB_TABLE.Columns.COL_for_TimeSpan;
private const string c_NameOf__COL_DATA2 =DB_TABLE.Columns.COL2_for_TimeSpan;
private sealed class MyContext:TestBaseDbContext
{
[Table(c_NameOf__TABLE)]
public sealed class TEST_RECORD
{
[Key]
[Column("TEST_ID")]
public System.Int64? TEST_ID { get; set; }
[Column(c_NameOf__COL_DATA1)]
public T_DATA1 COL_DATA1 { get; set; }
[Column(c_NameOf__COL_DATA2)]
public T_DATA2 COL_DATA2 { 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 c_value1=new T_DATA1_U(12,14,34).Add(new System.TimeSpan(1000*1234)).Add(new System.TimeSpan(100));
System.Int64? testID=Helper__InsertRow(db,c_value1,null);
var recs=db.testTable.Where(r => (r.COL_DATA1 /*OP{*/ >= /*}OP*/ r.COL_DATA2) && r.TEST_ID==testID);
foreach(var r in recs)
{
TestServices.ThrowSelectedRow();
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("t","TEST_ID").T(", ").N("t",c_NameOf__COL_DATA1).T(", ").N("t",c_NameOf__COL_DATA2).EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("t").EOL()
.T("WHERE (").N("t",c_NameOf__COL_DATA1).T(" >= ").N("t",c_NameOf__COL_DATA2).T(") AND (").N("t","TEST_ID").T(" = ").P_ID("__testID_0").T(")"));
}//using db
tr.Rollback();
}//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 c_value1=new T_DATA1_U(12,14,34).Add(new System.TimeSpan(1000*1234)).Add(new System.TimeSpan(100));
System.Int64? testID=Helper__InsertRow(db,c_value1,null);
var recs=db.testTable.Where(r => !(r.COL_DATA1 /*OP{*/ >= /*}OP*/ r.COL_DATA2) && r.TEST_ID==testID);
foreach(var r in recs)
{
TestServices.ThrowSelectedRow();
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("t","TEST_ID").T(", ").N("t",c_NameOf__COL_DATA1).T(", ").N("t",c_NameOf__COL_DATA2).EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("t").EOL()
.T("WHERE NOT (").N("t",c_NameOf__COL_DATA1).T(" >= ").N("t",c_NameOf__COL_DATA2).T(") AND (").N("t","TEST_ID").T(" = ").P_ID("__testID_0").T(")"));
}//using db
tr.Rollback();
}//using tr
}//using cn
}//Test_002
//Helper methods --------------------------------------------------------
private static System.Int64 Helper__InsertRow(MyContext db,
T_DATA1 valueForColData1,
T_DATA2 valueForColData2)
{
var newRecord=new MyContext.TEST_RECORD();
newRecord.COL_DATA1 =valueForColData1;
newRecord.COL_DATA2 =valueForColData2;
db.testTable.Add(newRecord);
db.SaveChanges();
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("INSERT INTO ").N(c_NameOf__TABLE).T(" (").N(c_NameOf__COL_DATA1).T(", ").N(c_NameOf__COL_DATA2).T(")").EOL()
.T("VALUES (").P("p0").T(", ").P("p1").T(")").EOL()
.T("RETURNING ").N("TEST_ID").EOL()
.T("INTO ").P("p2").T(";"));
Assert.IsTrue
(newRecord.TEST_ID.HasValue);
Console.WriteLine("TEST_ID: {0}",newRecord.TEST_ID.Value);
return newRecord.TEST_ID.Value;
}//Helper__InsertRow
};//class TestSet_001__fields__02__VN
////////////////////////////////////////////////////////////////////////////////
}//namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D1.Query.Operators.SET_001.GreaterThanOrEqual.Complete.NullableTimeSpan.NullableTimeSpan
| 33.993865 | 159 | 0.584732 | [
"MIT"
] | ibprovider/Lcpi.EFCore.LcpiOleDb | Tests/General/Source/Work/DBMS/Firebird/V03_0_0/D1/Query/Operators/SET_001/GreaterThanOrEqual/Complete/NullableTimeSpan/NullableTimeSpan/TestSet_001__fields__02__VN.cs | 5,543 | C# |
using Godot;
using System.Data.SQLite;
public class world : Node2D
{
public override void _Ready()
{
string dataSource = "SQLiteDemo.db";
SQLiteConnection connection = new SQLiteConnection
{
ConnectionString = "Data Source=" + dataSource
};
connection.Open();
SQLiteCommand command = new SQLiteCommand(connection);
// Erstellen der Tabelle, sofern diese noch nicht existiert.
command.CommandText = "CREATE TABLE IF NOT EXISTS beispiel ( id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, name VARCHAR(100) NOT NULL);";
command.ExecuteNonQuery();
// Einfügen eines Test-Datensatzes.
command.CommandText = "INSERT INTO beispiel (id, name) VALUES(NULL, 'Test-Datensatz!')";
command.ExecuteNonQuery();
// Freigabe der Ressourcen.
command.Dispose();
command = new SQLiteCommand(connection);
// Auslesen des zuletzt eingefügten Datensatzes.
command.CommandText = "SELECT id, name FROM beispiel ORDER BY id DESC LIMIT 0, 1";
SQLiteDataReader reader = command.ExecuteReader();
while (reader.Read())
{
GD.Print("Dies ist der " + reader[0].ToString() + ". eingefügte Datensatz mit dem Wert: \"{" + reader[1].ToString() + "}\"");
}
// Beenden des Readers und Freigabe aller Ressourcen.
reader.Close();
reader.Dispose();
command.Dispose();
connection.Close();
connection.Dispose();
}
}
| 31.490196 | 146 | 0.594645 | [
"MIT"
] | pwab/godot-testbed | sqlite_test/world.cs | 1,609 | C# |
namespace Interpreter
{
/// <summary>
/// The thousand expression.
/// </summary>
public class ThousandExpression : AnAbstractExpression
{
/// <summary>
/// The one.
/// </summary>
/// <returns>
/// The <see cref="string"/>.
/// </returns>
public override string One()
{
return "M";
}
/// <summary>
/// The four.
/// </summary>
/// <returns>
/// The <see cref="string"/>.
/// </returns>
public override string Four()
{
return " ";
}
/// <summary>
/// The five.
/// </summary>
/// <returns>
/// The <see cref="string"/>.
/// </returns>
public override string Five()
{
return " ";
}
/// <summary>
/// The nine.
/// </summary>
/// <returns>
/// The <see cref="string"/>.
/// </returns>
public override string Nine()
{
return " ";
}
/// <summary>
/// The multiplier.
/// </summary>
/// <returns>
/// The <see cref="int"/>.
/// </returns>
public override int Multiplier()
{
return 1000;
}
}
} | 21.206349 | 58 | 0.387725 | [
"MIT"
] | enriqueescobar-askida/Kinito.Patterns.Behavioral | Interpreter/ThousandExpression.cs | 1,338 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace DLaB.Xrm.Entities
{
[System.Runtime.Serialization.DataContractAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("CrmSvcUtil", "8.0.1.7297")]
public enum Incident_PriorityCode
{
[System.Runtime.Serialization.EnumMemberAttribute()]
High = 1,
[System.Runtime.Serialization.EnumMemberAttribute()]
Low = 3,
[System.Runtime.Serialization.EnumMemberAttribute()]
Normal = 2,
}
} | 28.777778 | 80 | 0.570142 | [
"MIT"
] | Bhawk90/DLaB.Xrm.XrmToolBoxTools | DLaB.Xrm.Entities/OptionSets/Incident_PriorityCode.cs | 777 | C# |
using Abp.Authorization.Users;
using Abp.Domain.Repositories;
using Abp.Domain.Uow;
using Abp.Linq;
using RomarizIT.PostFromFacebookData.Authorization.Roles;
namespace RomarizIT.PostFromFacebookData.Authorization.Users
{
public class UserStore : AbpUserStore<Role, User>
{
public UserStore(
IUnitOfWorkManager unitOfWorkManager,
IRepository<User, long> userRepository,
IRepository<Role> roleRepository,
IAsyncQueryableExecuter asyncQueryableExecuter,
IRepository<UserRole, long> userRoleRepository,
IRepository<UserLogin, long> userLoginRepository,
IRepository<UserClaim, long> userClaimRepository,
IRepository<UserPermissionSetting, long> userPermissionSettingRepository)
: base(
unitOfWorkManager,
userRepository,
roleRepository,
asyncQueryableExecuter,
userRoleRepository,
userLoginRepository,
userClaimRepository,
userPermissionSettingRepository)
{
}
}
}
| 35.212121 | 86 | 0.635112 | [
"MIT"
] | romariz/postfacebookdata | aspnet-core/src/RomarizIT.PostFromFacebookData.Core/Authorization/Users/UserStore.cs | 1,162 | C# |
//-----------------------------------------------------------------------
// <copyright file="Address.cs" company="Akka.NET Project">
// Copyright (C) 2009-2016 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Akka.Util;
namespace Akka.Actor
{
/// <summary>
/// The address specifies the physical location under which an Actor can be
/// reached. Examples are local addresses, identified by the <see cref="ActorSystem"/>'s
/// name, and remote addresses, identified by protocol, host and port.
///
/// This class is sealed to allow use as a case class (copy method etc.); if
/// for example a remote transport would want to associate additional
/// information with an address, then this must be done externally.
/// </summary>
public sealed class Address : ICloneable, IEquatable<Address>, ISurrogated
{
/// <summary>
/// Pseudo address for all systems
/// </summary>
public static readonly Address AllSystems = new Address("akka", "all-systems");
private readonly Lazy<string> _toString;
private readonly string _host;
private readonly int? _port;
private readonly string _system;
private readonly string _protocol;
/// <summary>
/// TBD
/// </summary>
/// <param name="protocol">TBD</param>
/// <param name="system">TBD</param>
/// <param name="host">TBD</param>
/// <param name="port">TBD</param>
public Address(string protocol, string system, string host = null, int? port = null)
{
_protocol = protocol;
_system = system;
_host = host != null ? host.ToLowerInvariant() : null;
_port = port;
_toString = CreateLazyToString();
}
/// <summary>
/// TBD
/// </summary>
public string Host
{
get { return _host; }
}
/// <summary>
/// TBD
/// </summary>
public int? Port
{
get { return _port; }
}
/// <summary>
/// TBD
/// </summary>
public string System
{
get { return _system; }
}
/// <summary>
/// TBD
/// </summary>
public string Protocol
{
get { return _protocol; }
}
/// <summary>
/// Returns true if this Address is only defined locally. It is not safe to send locally scoped addresses to remote
/// hosts. See also <see cref="HasGlobalScope"/>
/// </summary>
public bool HasLocalScope
{
get { return string.IsNullOrEmpty(Host); }
}
/// <summary>
/// Returns true if this Address is usable globally. Unlike locally defined addresses <see cref="HasLocalScope"/>
/// addresses of global scope are safe to sent to other hosts, as they globally and uniquely identify an addressable
/// entity.
/// </summary>
public bool HasGlobalScope
{
get { return !string.IsNullOrEmpty(Host); }
}
private Lazy<string> CreateLazyToString()
{
return new Lazy<string>(() =>
{
var sb = new StringBuilder();
sb.AppendFormat("{0}://{1}", Protocol, System);
if (!string.IsNullOrWhiteSpace(Host))
sb.AppendFormat("@{0}", Host);
if (Port.HasValue)
sb.AppendFormat(":{0}", Port.Value);
return sb.ToString();
}, true);
}
/// <summary>
/// TBD
/// </summary>
/// <returns>TBD</returns>
public override string ToString()
{
return _toString.Value;
}
/// <summary>
/// TBD
/// </summary>
/// <param name="other">TBD</param>
/// <returns>TBD</returns>
public bool Equals(Address other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return string.Equals(Host, other.Host) && Port == other.Port && string.Equals(System, other.System) && string.Equals(Protocol, other.Protocol);
}
/// <summary>
/// TBD
/// </summary>
/// <param name="obj">TBD</param>
/// <returns>TBD</returns>
public override bool Equals(object obj) => obj is Address && Equals((Address)obj);
/// <summary>
/// TBD
/// </summary>
/// <returns>TBD</returns>
public override int GetHashCode()
{
unchecked
{
var hashCode = (Host != null ? Host.GetHashCode() : 0);
hashCode = (hashCode * 397) ^ Port.GetHashCode();
hashCode = (hashCode * 397) ^ (System != null ? System.GetHashCode() : 0);
hashCode = (hashCode * 397) ^ (Protocol != null ? Protocol.GetHashCode() : 0);
return hashCode;
}
}
/// <summary>
/// TBD
/// </summary>
/// <returns>TBD</returns>
public object Clone()
{
return new Address(Protocol, System, Host, Port);
}
/// <summary>
/// TBD
/// </summary>
/// <param name="protocol">TBD</param>
/// <returns>TBD</returns>
public Address WithProtocol(string protocol)
{
return new Address(protocol, System, Host, Port);
}
/// <summary>
/// TBD
/// </summary>
/// <param name="system">TBD</param>
/// <returns>TBD</returns>
public Address WithSystem(string system)
{
return new Address(Protocol, system, Host, Port);
}
/// <summary>
/// TBD
/// </summary>
/// <param name="host">TBD</param>
/// <returns>TBD</returns>
public Address WithHost(string host = null)
{
return new Address(Protocol, System, host, Port);
}
/// <summary>
/// TBD
/// </summary>
/// <param name="port">TBD</param>
/// <returns>TBD</returns>
public Address WithPort(int? port = null)
{
return new Address(Protocol, System, Host, port);
}
/// <summary>
/// TBD
/// </summary>
/// <param name="left">TBD</param>
/// <param name="right">TBD</param>
/// <returns>TBD</returns>
public static bool operator ==(Address left, Address right)
{
return Equals(left, right);
}
/// <summary>
/// TBD
/// </summary>
/// <param name="left">TBD</param>
/// <param name="right">TBD</param>
/// <returns>TBD</returns>
public static bool operator !=(Address left, Address right)
{
return !Equals(left, right);
}
/// <summary>
/// TBD
/// </summary>
/// <returns>TBD</returns>
public string HostPort()
{
return ToString().Substring(Protocol.Length + 3);
}
/// <summary>
/// Parses a new <see cref="Address"/> from a given string
/// </summary>
/// <param name="address">The address to parse</param>
/// <returns>A populated <see cref="Address"/> object with host and port included, if available</returns>
/// <exception cref="UriFormatException">Thrown if the address is not able to be parsed</exception>
public static Address Parse(string address)
{
var uri = new Uri(address);
var protocol = uri.Scheme;
if (string.IsNullOrEmpty(uri.UserInfo))
{
var systemName = uri.Host;
return new Address(protocol, systemName);
}
else
{
var systemName = uri.UserInfo;
var host = uri.Host;
/*
* Aaronontheweb: in the event that an Address is passed in with port 0, the Uri converts it to -1 (which is invalid.)
*/
var port = uri.Port;
return new Address(protocol, systemName, host, port);
}
}
/// <summary>
/// TBD
/// </summary>
public class AddressSurrogate : ISurrogate
{
/// <summary>
/// TBD
/// </summary>
public string Protocol { get; set; }
/// <summary>
/// TBD
/// </summary>
public string System { get; set; }
/// <summary>
/// TBD
/// </summary>
public string Host { get; set; }
/// <summary>
/// TBD
/// </summary>
public int? Port { get; set; }
/// <summary>
/// TBD
/// </summary>
/// <param name="system">TBD</param>
/// <returns>TBD</returns>
public ISurrogated FromSurrogate(ActorSystem system)
{
return new Address(Protocol, System, Host, Port);
}
}
/// <summary>
/// TBD
/// </summary>
/// <param name="system">TBD</param>
/// <returns>TBD</returns>
public ISurrogate ToSurrogate(ActorSystem system)
{
return new AddressSurrogate()
{
Host = Host,
Port = Port,
System = System,
Protocol = Protocol
};
}
}
/// <summary>
/// Extractor class for so-called "relative actor paths" - as in "relative URI", not
/// "relative to some other actors."
///
/// Examples:
///
/// * "grand/child"
/// * "/user/hello/world"
/// </summary>
public static class RelativeActorPath
{
/// <summary>
/// TBD
/// </summary>
/// <param name="addr">TBD</param>
/// <returns>TBD</returns>
public static IEnumerable<string> Unapply(string addr)
{
try
{
Uri uri;
bool isRelative = Uri.TryCreate(addr, UriKind.Relative, out uri);
if (!isRelative) return null;
var finalAddr = addr;
if (!addr.StartsWith("/"))
{
//hack to cause the URI not to explode when we're only given an actor name
finalAddr = "/" + addr;
}
return finalAddr.Split('/').SkipWhile(string.IsNullOrEmpty);
}
catch (UriFormatException)
{
return null;
}
}
}
}
| 30.676712 | 155 | 0.483344 | [
"Apache-2.0"
] | corefan/akka.net | src/core/Akka/Actor/Address.cs | 11,199 | C# |
using Microsoft.Coyote;
using System;
using System.Runtime;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using Plang.CSharpRuntime;
using Plang.CSharpRuntime.Values;
using System.Threading;
using System.Threading.Tasks;
namespace PImplementation {
internal partial class Main : PMachine
{
public void ForeignFun()
{
Main currentMachine = this;
}
}
public static partial class GlobalFunctions
{
public static void GlobalForeignFun(PMachine currentMachine)
{
}
}
public partial class T : IPrtValue
{
public IPrtValue Clone()
{
return this;
}
public bool Equals(IPrtValue other)
{
return this == other;
}
}
} | 19.52381 | 68 | 0.606098 | [
"MIT"
] | HuaixiLu/P | Tst/RegressionTests/Feature1SMLevelDecls/Correct/ForeignFun/Foreign.cs | 820 | C# |
using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using arch.dal.intf;
using MySql.Data.MySqlClient;
using arch.crl;
using System.Collections.Generic;
namespace arch.dal.impl
{
/// <summary>
/// Implementation du service facture
/// </summary>
public class ImplDalFacture : IntfDalFacture
{
#region declaration variable
IntfDalConnectBase serviceConnectBase = null;
IntfDalServiceRessource serviceRessource = null;
MySqlDataReader reader = null;
string strCommande = "";
#endregion
#region constructeur
public ImplDalFacture(string strConnection)
{
serviceConnectBase = new ImplDalConnectBase(strConnection);
}
public ImplDalFacture()
{
serviceRessource = new ImplDalServiceRessource();
serviceConnectBase = new ImplDalConnectBase(serviceRessource.getDefaultStrConnection());
}
#endregion
#region IntfDalFacture Members
string IntfDalFacture.insertFacture(crlFacture Facture)
{
#region declaration
IntfDalFacture serviceFacture = new ImplDalFacture();
int nombreInsertion = 0;
string numFacture = "";
#endregion
#region implementation
if (Facture != null)
{
Facture.NumFacture = serviceFacture.getNumFacture(Facture.agent.agence.SigleAgence);
this.strCommande = "INSERT INTO `facture` (`numFacture`,`libele`,`montant`,`dateFacturation`,`matriculeAgent`)";
this.strCommande += " VALUES ('" + Facture.NumFacture + "', '" + Facture.Libele + "', ";
this.strCommande += " '" + Facture.Montant + "', '" + Facture.DateFacturation.ToString("yyyy-MM-dd") + "','" + Facture.MatriculeAgent + "')";
this.serviceConnectBase.openConnection();
nombreInsertion = this.serviceConnectBase.requete(this.strCommande);
if (nombreInsertion == 1)
numFacture = Facture.NumFacture;
this.serviceConnectBase.closeConnection();
}
#endregion
return numFacture;
}
string IntfDalFacture.insertFactureAssoc(crlFacture Facture)
{
#region declaration
string numFacture = "";
IntfDalFacture serviceFacture = new ImplDalFacture();
IntfDalAutorisationDepart serviceAutorisationDepart = new ImplDalAutorisationDepart();
#endregion
#region implementation
if (Facture != null)
{
if (Facture.autorisationDeparts != null)
{
Facture.NumFacture = serviceFacture.insertFacture(Facture);
if (Facture.NumFacture != "")
{
for (int i = 0; i < Facture.autorisationDeparts.Count; i++)
{
serviceFacture.insertAssocFactureAD(Facture.NumFacture, Facture.autorisationDeparts[i].NumAutorisationDepart);
Facture.autorisationDeparts[i].ResteRegle = 0;
serviceAutorisationDepart.updateAutorisationDepart(Facture.autorisationDeparts[i]);
}
numFacture = Facture.NumFacture;
}
}
}
#endregion
return numFacture;
}
bool IntfDalFacture.insertAssocFactureAD(string numFacture, string numAutorisationDepart)
{
#region declaration
bool isInsert = false;
int nbInsert = 0;
#endregion
#region implementation
if (numAutorisationDepart != "" && numFacture != "")
{
this.strCommande = "INSERT INTO `assocautorisationdepartfacture` (`numFacture`,`numAutorisationDepart`)";
this.strCommande += " VALUES ('" + numFacture + "','" + numAutorisationDepart + "')";
this.serviceConnectBase.openConnection();
nbInsert = this.serviceConnectBase.requete(this.strCommande);
if (nbInsert == 1)
isInsert = true;
this.serviceConnectBase.closeConnection();
}
#endregion
return isInsert;
}
bool IntfDalFacture.deleteFacture(crlFacture Facture)
{
#region declaration
bool isDelete = false;
int nombreDelete = 0;
#endregion
#region implementation
if (Facture != null)
{
if (Facture.NumFacture != "")
{
this.strCommande = "DELETE FROM `facture` WHERE (`numFacture` = '" + Facture.NumFacture + "')";
this.serviceConnectBase.openConnection();
nombreDelete = this.serviceConnectBase.requete(this.strCommande);
if (nombreDelete == 1)
isDelete = true;
this.serviceConnectBase.closeConnection();
}
}
#endregion
return isDelete;
}
bool IntfDalFacture.deleteFacture(string numFacture)
{
#region declaration
bool isDelete = false;
int nombreDelete = 0;
#endregion
#region implementation
if (numFacture != "")
{
this.strCommande = "DELETE FROM `facture` WHERE (`numFacture` = '" + numFacture + "')";
this.serviceConnectBase.openConnection();
nombreDelete = this.serviceConnectBase.requete(this.strCommande);
if (nombreDelete == 1)
isDelete = true;
this.serviceConnectBase.closeConnection();
}
#endregion
return isDelete;
}
bool IntfDalFacture.updateFacture(crlFacture Facture)
{
#region declaration
bool isUpdate = false;
int nombreUpdate = 0;
#endregion
#region implementation
if (Facture != null)
{
if (Facture.NumFacture != "")
{
this.strCommande = "UPDATE `facture` SET `libele`='" + Facture.Libele + "', ";
this.strCommande += "`montant`='" + Facture.Montant + "', `dateFacturation`='" + Facture.DateFacturation.ToString("yyyy-MM-dd") + "'";
this.strCommande += ",`matriculeAgent`='" + Facture.MatriculeAgent + "' WHERE (`numFacture`='" + Facture.NumFacture + "')";
this.serviceConnectBase.openConnection();
nombreUpdate = this.serviceConnectBase.requete(this.strCommande);
if (nombreUpdate == 1)
isUpdate = true;
this.serviceConnectBase.closeConnection();
}
}
#endregion
return isUpdate;
}
crlFacture IntfDalFacture.selectFacture(string numFacture)
{
#region declaration
crlFacture Facture = null;
IntfDalAgent serviceAgent = new ImplDalAgent();
IntfDalFacture serviceFacture = new ImplDalFacture();
#endregion
#region implementation
if (numFacture != "")
{
this.strCommande = "SELECT * FROM `facture` WHERE (`numFacture`='" + numFacture + "')";
this.serviceConnectBase.openConnection();
this.reader = this.serviceConnectBase.select(this.strCommande);
if (reader != null)
{
if (reader.HasRows)
{
Facture = new crlFacture();
reader.Read();
Facture.NumFacture = reader["numFacture"].ToString();
Facture.Libele = reader["libele"].ToString();
Facture.Montant = reader["montant"].ToString();
Facture.MatriculeAgent = reader["matriculeAgent"].ToString();
try
{
Facture.DateFacturation = Convert.ToDateTime(reader["dateFacturation"].ToString());
}
catch (Exception)
{
}
}
reader.Dispose();
}
this.serviceConnectBase.closeConnection();
if (Facture != null)
{
if (Facture.MatriculeAgent != "")
{
Facture.agent = serviceAgent.selectAgent(Facture.MatriculeAgent);
}
Facture.autorisationDeparts = serviceFacture.selectADForFacture(Facture.NumFacture);
}
}
#endregion
return Facture;
}
string IntfDalFacture.getNumFacture(string sigleAgence)
{
#region declaration
double numTemp = 0;
string numFacture = "00001";
string[] tempNumFacture = null;
string strDate = "FA" + DateTime.Now.ToString("yyMM");
#endregion
#region implementation
this.strCommande = "SELECT facture.numFacture AS maxNum FROM facture";
this.strCommande += " WHERE facture.numFacture LIKE '%" + sigleAgence + "%'";
this.strCommande += " ORDER BY maxNum DESC";
this.serviceConnectBase.openConnection();
reader = this.serviceConnectBase.select(strCommande);
if (reader != null)
{
if (reader.HasRows)
{
if (reader.Read())
{
tempNumFacture = reader["maxNum"].ToString().ToString().Split('/');
numFacture = tempNumFacture[tempNumFacture.Length - 1];
}
numTemp = double.Parse(numFacture) + 1;
if (numTemp < 10)
numFacture = "0000" + numTemp.ToString("0");
if (numTemp < 100 && numTemp >= 10)
numFacture = "000" + numTemp.ToString("0");
if (numTemp < 1000 && numTemp >= 100)
numFacture = "00" + numTemp.ToString("0");
if (numTemp < 10000 && numTemp >= 1000)
numFacture = "0" + numTemp.ToString("0");
if (numTemp >= 10000)
numFacture = "" + numTemp.ToString("0");
}
reader.Dispose();
}
this.serviceConnectBase.closeConnection();
numFacture = strDate + "/" + sigleAgence + "/" + numFacture;
#endregion
return numFacture;
}
void IntfDalFacture.loadDdlTri(DropDownList ddlTri)
{
throw new NotImplementedException();
}
double IntfDalFacture.getTotalPrixBillet(string numFacture)
{
#region declaration
double prixTotal = 0.00;
#endregion
#region implementation
if (numFacture != "")
{
this.strCommande = "SELECT Sum(billet.prixBillet) AS prixTotal FROM billet";
this.strCommande += " Inner Join voyage ON voyage.numBillet = billet.numBillet";
this.strCommande += " Inner Join fichebord ON fichebord.numerosFB = voyage.numerosFB";
this.strCommande += " Inner Join autorisationdepart ON autorisationdepart.numerosFB = fichebord.numerosFB";
this.strCommande += " Inner Join assocautorisationdepartfacture ON assocautorisationdepartfacture.numAutorisationDepart = autorisationdepart.numAutorisationDepart";
this.strCommande += " WHERE assocautorisationdepartfacture.numFacture = '" + numFacture + "'";
this.serviceConnectBase.openConnection();
this.reader = serviceConnectBase.select(this.strCommande);
if (this.reader != null)
{
if (this.reader.HasRows)
{
if (this.reader.Read())
{
try
{
prixTotal = double.Parse(this.reader["prixTotal"].ToString());
}
catch (Exception)
{
}
}
}
this.reader.Dispose();
}
this.serviceConnectBase.closeConnection();
}
#endregion
return prixTotal;
}
double IntfDalFacture.getTotalPrixBagage(string numFacture)
{
#region declaration
double prixTotal = 0.00;
#endregion
#region implementation
if (numFacture != "")
{
this.strCommande = "SELECT Sum(recu.montant) AS prixTotal FROM recu";
this.strCommande += " Inner Join bagage ON bagage.numRecu = recu.numRecu";
this.strCommande += " Inner Join associationvoyagebagage ON associationvoyagebagage.idBagage = bagage.idBagage";
this.strCommande += " Inner Join voyage ON voyage.idVoyage = associationvoyagebagage.idVoyage";
this.strCommande += " Inner Join fichebord ON fichebord.numerosFB = voyage.numerosFB";
this.strCommande += " Inner Join autorisationdepart ON autorisationdepart.numerosFB = fichebord.numerosFB";
this.strCommande += " Inner Join assocautorisationdepartfacture ON assocautorisationdepartfacture.numAutorisationDepart = autorisationdepart.numAutorisationDepart";
this.strCommande += " WHERE assocautorisationdepartfacture.numFacture = '" + numFacture + "'";
this.serviceConnectBase.openConnection();
this.reader = serviceConnectBase.select(this.strCommande);
if (this.reader != null)
{
if (this.reader.HasRows)
{
if (this.reader.Read())
{
try
{
prixTotal = double.Parse(this.reader["prixTotal"].ToString());
}
catch (Exception)
{
}
}
}
this.reader.Dispose();
}
this.serviceConnectBase.closeConnection();
}
#endregion
return prixTotal;
}
double IntfDalFacture.getTotalPrixCommission(string numFacture)
{
#region declaration
double prixTotal = 0.00;
#endregion
#region implementation
if (numFacture != "")
{
this.strCommande = "SELECT Sum(recu.montant) AS prixTotal FROM recu";
this.strCommande += " Inner Join commission ON commission.numRecu = recu.numRecu";
this.strCommande += " Inner Join associationfichebordcommission ON associationfichebordcommission.idCommission = commission.idCommission";
this.strCommande += " Inner Join fichebord ON fichebord.numerosFB = associationfichebordcommission.numerosFB";
this.strCommande += " Inner Join autorisationdepart ON autorisationdepart.numerosFB = fichebord.numerosFB";
this.strCommande += " Inner Join assocautorisationdepartfacture ON assocautorisationdepartfacture.numAutorisationDepart = autorisationdepart.numAutorisationDepart";
this.strCommande += " WHERE assocautorisationdepartfacture.numFacture = '" + numFacture + "'";
this.serviceConnectBase.openConnection();
this.reader = serviceConnectBase.select(this.strCommande);
if (this.reader != null)
{
if (this.reader.HasRows)
{
if (this.reader.Read())
{
try
{
prixTotal = double.Parse(this.reader["prixTotal"].ToString());
}
catch (Exception)
{
}
}
}
this.reader.Dispose();
}
this.serviceConnectBase.closeConnection();
}
#endregion
return prixTotal;
}
double IntfDalFacture.getTotalMontantRecu(string numFacture)
{
#region declaration
double prixTotal = 0.00;
#endregion
#region implementation
if (numFacture != "")
{
this.strCommande = "SELECT Sum(recuad.montant) AS prixTotal FROM recuad";
this.strCommande += " Inner Join asociationautorisationdepartrecu ON asociationautorisationdepartrecu.numRecuAD = recuad.numRecuAD";
this.strCommande += " Inner Join autorisationdepart ON autorisationdepart.numAutorisationDepart = asociationautorisationdepartrecu.numAutorisationDepart";
this.strCommande += " Inner Join assocautorisationdepartfacture ON assocautorisationdepartfacture.numAutorisationDepart = autorisationdepart.numAutorisationDepart";
this.strCommande += " WHERE assocautorisationdepartfacture.numFacture = '" + numFacture + "'";
this.serviceConnectBase.openConnection();
this.reader = serviceConnectBase.select(this.strCommande);
if (this.reader != null)
{
if (this.reader.HasRows)
{
if (this.reader.Read())
{
try
{
prixTotal = double.Parse(this.reader["prixTotal"].ToString());
}
catch (Exception)
{
}
}
}
this.reader.Dispose();
}
this.serviceConnectBase.closeConnection();
}
#endregion
return prixTotal;
}
double IntfDalFacture.getMontantRecette(string numFacture)
{
#region declaration
double prixTotal = 0.00;
#endregion
#region implementation
if (numFacture != "")
{
this.strCommande = "SELECT Sum(autorisationdepart.recetteTotale) AS prixTotal FROM autorisationdepart";
this.strCommande += " Inner Join assocautorisationdepartfacture ON assocautorisationdepartfacture.numAutorisationDepart = autorisationdepart.numAutorisationDepart";
this.strCommande += " WHERE assocautorisationdepartfacture.numFacture = '" + numFacture + "'";
this.serviceConnectBase.openConnection();
this.reader = serviceConnectBase.select(this.strCommande);
if (this.reader != null)
{
if (this.reader.HasRows)
{
if (this.reader.Read())
{
try
{
prixTotal = double.Parse(this.reader["prixTotal"].ToString());
}
catch (Exception)
{
}
}
}
this.reader.Dispose();
}
this.serviceConnectBase.closeConnection();
}
#endregion
return prixTotal;
}
double IntfDalFacture.getMontantRecu(string numFacture)
{
#region declaration
double prixTotal = 0.00;
#endregion
#region implementation
if (numFacture != "")
{
this.strCommande = "SELECT Sum(recuad.montant) AS prixTotal FROM recuad";
this.strCommande += " Inner Join prelevement ON prelevement.numPrelevement = recuad.numPrelevement";
this.strCommande += " Inner Join autorisationdepart ON autorisationdepart.numAutorisationDepart = prelevement.numAutorisationDepart";
this.strCommande += " Inner Join assocautorisationdepartfacture ON assocautorisationdepartfacture.numAutorisationDepart = autorisationdepart.numAutorisationDepart";
this.strCommande += " WHERE assocautorisationdepartfacture.numFacture = '" + numFacture + "'";
this.serviceConnectBase.openConnection();
this.reader = serviceConnectBase.select(this.strCommande);
if (this.reader != null)
{
if (this.reader.HasRows)
{
if (this.reader.Read())
{
try
{
prixTotal = double.Parse(this.reader["prixTotal"].ToString());
}
catch (Exception)
{
}
}
}
this.reader.Dispose();
}
this.serviceConnectBase.closeConnection();
}
#endregion
return prixTotal;
}
List<crlAutorisationDepart> IntfDalFacture.selectADForFacture(string numFacture)
{
#region declaration
List<crlAutorisationDepart> autorisationDeparts = null;
IntfDalAutorisationDepart serviceAutorisationDepart = new ImplDalAutorisationDepart();
#endregion
#region implementation
if (numFacture != "")
{
this.strCommande = "SELECT autorisationdepart.numAutorisationDepart FROM autorisationdepart";
this.strCommande += " Inner Join assocautorisationdepartfacture ON assocautorisationdepartfacture.numAutorisationDepart = autorisationdepart.numAutorisationDepart";
this.strCommande += " WHERE assocautorisationdepartfacture.numFacture = '" + numFacture + "'";
this.serviceConnectBase.openConnection();
this.reader = this.serviceConnectBase.select(this.strCommande);
if (this.reader != null)
{
if (this.reader.HasRows)
{
autorisationDeparts = new List<crlAutorisationDepart>();
while (this.reader.Read())
{
autorisationDeparts.Add(serviceAutorisationDepart.selectAutorisationDepart(this.reader["numAutorisationDepart"].ToString()));
}
}
this.reader.Dispose();
}
this.serviceConnectBase.closeConnection();
}
#endregion
return autorisationDeparts;
}
#endregion
#region insert to grid
void IntfDalFacture.insertToGridFactureNotRecu(GridView gridView, string param, string paramLike, string valueLike)
{
#region declaration
IntfDalFacture serviceFacture = new ImplDalFacture();
#endregion
#region implementation
this.strCommande = "SELECT facture.numFacture, facture.libele, facture.montant, facture.dateFacturation, facture.matriculeAgent,";
this.strCommande += " Individu.nomIndividu, Individu.prenomIndividu, societe.nomSociete, organisme.nomOrganisme, Individu.civiliteIndividu,";
this.strCommande += " Individu.cinIndividu, Individu.adresse, organisme.adresseOrganisme, societe.adresseSociete FROM facture";
this.strCommande += " Left Join recuad ON recuad.numFacture = facture.numFacture";
this.strCommande += " Inner Join assocautorisationdepartfacture ON assocautorisationdepartfacture.numFacture = facture.numFacture";
this.strCommande += " Inner Join autorisationdepart ON autorisationdepart.numAutorisationDepart = assocautorisationdepartfacture.numAutorisationDepart";
this.strCommande += " Inner Join fichebord ON fichebord.numerosFB = autorisationdepart.numerosFB";
this.strCommande += " Inner Join autorisationvoyage ON autorisationvoyage.numerosAV = fichebord.numerosAV";
this.strCommande += " Inner Join verification ON verification.idVerification = autorisationvoyage.idVerification";
this.strCommande += " Inner Join licence ON licence.numLicence = verification.numLicence";
this.strCommande += " Inner Join vehicule ON vehicule.numVehicule = licence.numVehicule";
this.strCommande += " Inner Join proprietaire ON proprietaire.numProprietaire = vehicule.numProprietaire";
this.strCommande += " Left Join Individu ON Individu.numIndividu = proprietaire.numIndividu";
this.strCommande += " Left Join societe ON societe.numSociete = proprietaire.numSociete";
this.strCommande += " Left Join organisme ON organisme.numOrganisme = proprietaire.numOrganisme";
this.strCommande += " WHERE recuad.numRecuAD IS NULL AND";
this.strCommande += " " + paramLike + " LIKE '%" + valueLike + "%'";
this.strCommande += " GROUP BY facture.numFacture ORDER BY " + param + " ASC";
gridView.DataSource = serviceFacture.getDataTableFactureNotRecu(this.strCommande);
gridView.DataBind();
#endregion
}
DataTable IntfDalFacture.getDataTableFactureNotRecu(string strRqst)
{
#region declaration
DataTable dataTable = new DataTable();
//IntfDalVille serviceVille = new ImplDalVille();
//IntfDalFicheBord serviceFicheBord = new ImplDalFicheBord();
IntfDalGeneral serviceGeneral = new ImplDalGeneral();
#endregion
#region implementation
#region initialisation du dataTable
dataTable = new DataTable();
dataTable.Columns.Add("numFacture", typeof(string));
dataTable.Columns.Add("montant", typeof(string));
dataTable.Columns.Add("dateFacturation", typeof(DateTime));
dataTable.Columns.Add("Individu", typeof(string));
dataTable.Columns.Add("societe", typeof(string));
dataTable.Columns.Add("organisme", typeof(string));
DataRow dr;
#endregion
this.serviceConnectBase.openConnection();
this.reader = this.serviceConnectBase.select(strRqst);
if (this.reader != null)
{
if (this.reader.HasRows)
{
while (this.reader.Read())
{
dr = dataTable.NewRow();
dr["numFacture"] = reader["numFacture"].ToString();
dr["montant"] = serviceGeneral.separateurDesMilles(reader["montant"].ToString()) + "Ar";
try
{
dr["dateFacturation"] = Convert.ToDateTime(reader["dateFacturation"].ToString());
}
catch (Exception)
{
}
dr["Individu"] = reader["prenomIndividu"].ToString() + " " + reader["nomIndividu"].ToString() + " / " + reader["cinIndividu"] + " / " + reader["adresse"].ToString();
dr["societe"] = reader["nomSociete"] + " / " + reader["adresseSociete"].ToString();
dr["organisme"] = reader["nomOrganisme"].ToString() + " / " + reader["adresseOrganisme"].ToString();
dataTable.Rows.Add(dr);
}
}
this.reader.Dispose();
}
this.serviceConnectBase.closeConnection();
#endregion
return dataTable;
}
#endregion
}
} | 42.412446 | 189 | 0.527928 | [
"MIT"
] | Natolotra/App | AppDal/dal/impl/ImplDalFacture.cs | 29,309 | 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.AzureNextGen.Network.V20190801.Outputs
{
[OutputType]
public sealed class ReferencedPublicIpAddressResponse
{
/// <summary>
/// The PublicIPAddress Reference.
/// </summary>
public readonly string? Id;
[OutputConstructor]
private ReferencedPublicIpAddressResponse(string? id)
{
Id = id;
}
}
}
| 25.107143 | 81 | 0.664296 | [
"Apache-2.0"
] | pulumi/pulumi-azure-nextgen | sdk/dotnet/Network/V20190801/Outputs/ReferencedPublicIpAddressResponse.cs | 703 | 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("AddressBookTests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("AddressBookTests")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("b3eceb40-6a28-494a-9aa1-4faec464818d")]
// 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.972973 | 84 | 0.746619 | [
"MIT"
] | ZTMowrer947/csharp-address-book | AddressBookTests/Properties/AssemblyInfo.cs | 1,408 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using Microsoft.EntityFrameworkCore;
#nullable disable
namespace assignment3.Models
{
[Table("skills")]
public partial class Skill
{
public Skill()
{
People = new HashSet<Person>();
}
[Key]
[Column("skill_level")]
[StringLength(1)]
public string SkillLevel { get; set; }
[Column("skill_description")]
[StringLength(50)]
public string SkillDescription { get; set; }
[InverseProperty(nameof(Person.SkillLevelNavigation))]
public virtual ICollection<Person> People { get; set; }
}
}
| 24.322581 | 63 | 0.647215 | [
"MIT"
] | Andytule/comp-CO884 | assignment3/assignment3/Models/Skill.cs | 756 | C# |
using System;
namespace MultiplicationTable
{
class MultiplicationTable
{
static void Main(string[] args)
{
int a = Convert.ToInt32(Console.ReadLine());
for (int b = 0; b <= 9; b++)
{
Console.WriteLine($"{a} x {b} = {a * b}");
}
}
}
}
| 19.823529 | 58 | 0.451039 | [
"MIT"
] | VelesovZmei/Homework1 | MultiplicationTable/Multiple.cs | 339 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
namespace KinematicCharacterController.Examples
{
public class StressTestManager : MonoBehaviour
{
public Camera Camera;
public LayerMask UIMask;
public InputField CountField;
public Image RenderOn;
public Image SimOn;
public Image InterpOn;
public ExampleCharacterController CharacterPrefab;
public ExampleAIController AIController;
public int SpawnCount = 100;
public float SpawnDistance = 2f;
private void Start()
{
CountField.text = SpawnCount.ToString();
UpdateOnImages();
}
private void UpdateOnImages()
{
RenderOn.enabled = Camera.cullingMask == -1;
SimOn.enabled = Physics.autoSimulation;
InterpOn.enabled = KinematicCharacterSystem.Interpolate;
}
public void SetSpawnCount(string count)
{
if (int.TryParse(count, out int result))
{
SpawnCount = result;
}
}
public void ToggleRendering()
{
if(Camera.cullingMask == -1)
{
Camera.cullingMask = UIMask;
}
else
{
Camera.cullingMask = -1;
}
UpdateOnImages();
}
public void TogglePhysicsSim()
{
Physics.autoSimulation = !Physics.autoSimulation;
UpdateOnImages();
}
public void ToggleInterpolation()
{
KinematicCharacterSystem.Interpolate = !KinematicCharacterSystem.Interpolate;
UpdateOnImages();
}
public void Spawn()
{
for (int i = 0; i < AIController.Characters.Count; i++)
{
Destroy(AIController.Characters[i].gameObject);
}
AIController.Characters.Clear();
int charsPerRow = Mathf.CeilToInt(Mathf.Sqrt(SpawnCount));
Vector3 firstPos = ((charsPerRow * SpawnDistance) * 0.5f) * -Vector3.one;
firstPos.y = 0f;
for (int i = 0; i < SpawnCount; i++)
{
int row = i / charsPerRow;
int col = i % charsPerRow;
Vector3 pos = firstPos + (Vector3.right * row * SpawnDistance) + (Vector3.forward * col * SpawnDistance);
ExampleCharacterController newChar = Instantiate(CharacterPrefab);
newChar.Motor.SetPosition(pos);
AIController.Characters.Add(newChar);
}
}
}
} | 28.924731 | 121 | 0.550929 | [
"Unlicense"
] | AceofGrades/Cert4Programming | Artificial-Intelligence/FirstPersonShooter/Assets/KinematicCharacterController/Examples/Scripts/StressTestManager.cs | 2,692 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Reflection;
[assembly: System.Reflection.AssemblyCompanyAttribute("more_operations")]
[assembly: System.Reflection.AssemblyConfigurationAttribute("Release")]
[assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")]
[assembly: System.Reflection.AssemblyProductAttribute("more_operations")]
[assembly: System.Reflection.AssemblyTitleAttribute("more_operations")]
[assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")]
// Generated by the MSBuild WriteCodeFragment class.
| 41.541667 | 80 | 0.652959 | [
"MIT"
] | wuweisage/Softuni-Svetlina-Projects-and-Code | C#/archive/repos/more_operations/more_operations/obj/Release/netcoreapp3.1/more_operations.AssemblyInfo.cs | 997 | C# |
using Sniper.Common;
using Sniper.Http;
using Sniper.TargetProcess.Routes;
using Xunit;
namespace Sniper.Tests.CRUD.Delete.Common.RoleEfforts
{
public class DeleteRoleEffortTests
{
[Fact]
public void RoleEffortThrowsError()
{
var client = new TargetProcessClient
{
ApiSiteInfo = new ApiSiteInfo(TargetProcessRoutes.Route.RoleEfforts)
};
var roleEffort = new RoleEffort
{
};
}
}
}
| 23 | 85 | 0.572779 | [
"MIT"
] | amenkes/sniper | Sniper.Tests/CRUD/Delete/Common/RoleEfforts/DeleteRoleEffortTests.cs | 529 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Recipe.Web")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Recipe.Web")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("45381abf-68b1-45a2-906c-69c384ff1f2e")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.648649 | 84 | 0.743001 | [
"MIT"
] | caronyan/CSharpRecipe | CSharpRecipe/Recipe.Web/Properties/AssemblyInfo.cs | 1,396 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.