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 |
|---|---|---|---|---|---|---|---|---|
/*
* 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 lightsail-2016-11-28.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Amazon.Lightsail.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.Lightsail.Model.Internal.MarshallTransformations
{
/// <summary>
/// CreateRelationalDatabase Request Marshaller
/// </summary>
public class CreateRelationalDatabaseRequestMarshaller : IMarshaller<IRequest, CreateRelationalDatabaseRequest> , IMarshaller<IRequest,AmazonWebServiceRequest>
{
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public IRequest Marshall(AmazonWebServiceRequest input)
{
return this.Marshall((CreateRelationalDatabaseRequest)input);
}
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="publicRequest"></param>
/// <returns></returns>
public IRequest Marshall(CreateRelationalDatabaseRequest publicRequest)
{
IRequest request = new DefaultRequest(publicRequest, "Amazon.Lightsail");
string target = "Lightsail_20161128.CreateRelationalDatabase";
request.Headers["X-Amz-Target"] = target;
request.Headers["Content-Type"] = "application/x-amz-json-1.1";
request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2016-11-28";
request.HttpMethod = "POST";
request.ResourcePath = "/";
request.MarshallerVersion = 2;
using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture))
{
JsonWriter writer = new JsonWriter(stringWriter);
writer.WriteObjectStart();
var context = new JsonMarshallerContext(request, writer);
if(publicRequest.IsSetAvailabilityZone())
{
context.Writer.WritePropertyName("availabilityZone");
context.Writer.Write(publicRequest.AvailabilityZone);
}
if(publicRequest.IsSetMasterDatabaseName())
{
context.Writer.WritePropertyName("masterDatabaseName");
context.Writer.Write(publicRequest.MasterDatabaseName);
}
if(publicRequest.IsSetMasterUsername())
{
context.Writer.WritePropertyName("masterUsername");
context.Writer.Write(publicRequest.MasterUsername);
}
if(publicRequest.IsSetMasterUserPassword())
{
context.Writer.WritePropertyName("masterUserPassword");
context.Writer.Write(publicRequest.MasterUserPassword);
}
if(publicRequest.IsSetPreferredBackupWindow())
{
context.Writer.WritePropertyName("preferredBackupWindow");
context.Writer.Write(publicRequest.PreferredBackupWindow);
}
if(publicRequest.IsSetPreferredMaintenanceWindow())
{
context.Writer.WritePropertyName("preferredMaintenanceWindow");
context.Writer.Write(publicRequest.PreferredMaintenanceWindow);
}
if(publicRequest.IsSetPubliclyAccessible())
{
context.Writer.WritePropertyName("publiclyAccessible");
context.Writer.Write(publicRequest.PubliclyAccessible);
}
if(publicRequest.IsSetRelationalDatabaseBlueprintId())
{
context.Writer.WritePropertyName("relationalDatabaseBlueprintId");
context.Writer.Write(publicRequest.RelationalDatabaseBlueprintId);
}
if(publicRequest.IsSetRelationalDatabaseBundleId())
{
context.Writer.WritePropertyName("relationalDatabaseBundleId");
context.Writer.Write(publicRequest.RelationalDatabaseBundleId);
}
if(publicRequest.IsSetRelationalDatabaseName())
{
context.Writer.WritePropertyName("relationalDatabaseName");
context.Writer.Write(publicRequest.RelationalDatabaseName);
}
if(publicRequest.IsSetTags())
{
context.Writer.WritePropertyName("tags");
context.Writer.WriteArrayStart();
foreach(var publicRequestTagsListValue in publicRequest.Tags)
{
context.Writer.WriteObjectStart();
var marshaller = TagMarshaller.Instance;
marshaller.Marshall(publicRequestTagsListValue, context);
context.Writer.WriteObjectEnd();
}
context.Writer.WriteArrayEnd();
}
writer.WriteObjectEnd();
string snippet = stringWriter.ToString();
request.Content = System.Text.Encoding.UTF8.GetBytes(snippet);
}
return request;
}
private static CreateRelationalDatabaseRequestMarshaller _instance = new CreateRelationalDatabaseRequestMarshaller();
internal static CreateRelationalDatabaseRequestMarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static CreateRelationalDatabaseRequestMarshaller Instance
{
get
{
return _instance;
}
}
}
} | 38.697143 | 163 | 0.597608 | [
"Apache-2.0"
] | PureKrome/aws-sdk-net | sdk/src/Services/Lightsail/Generated/Model/Internal/MarshallTransformations/CreateRelationalDatabaseRequestMarshaller.cs | 6,772 | C# |
using Il2CppSystem.Collections.Generic;
using DataHelper;
namespace GunfireLib.Data
{
public static class DrugData
{
public static Dictionary<int, itemdataclass> drugList;
public static System.Collections.Generic.Dictionary<int, Classes.ItemDataClass> parsedDrugList =
new System.Collections.Generic.Dictionary<int, Classes.ItemDataClass>();
internal static void Setup()
{
drugList = drugdata.GetData();
foreach (KeyValuePair<int, itemdataclass> drug in drugList)
{
parsedDrugList.Add(drug.Key, new Classes.ItemDataClass(drug.Key, drugList));
}
}
}
} | 31 | 104 | 0.651026 | [
"MIT"
] | ardittristan/GunfireMod | GunfireLib/Data/DrugsData.cs | 684 | C# |
using ClForms.Core;
using ClForms.Loader;
namespace PanelsApp
{
internal class Program
{
private static void Main(string[] args)
=> AppLoader.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build()
.Start(new MainWindow());
}
}
| 20.8 | 51 | 0.564103 | [
"Apache-2.0"
] | Ahatornn/clforms | Examples/Elements/PanelsApp/Program.cs | 312 | C# |
using System;
using System.Runtime.CompilerServices;
/// <summary>
/// InternalsVisibleToAttribute.AssemblyName [v-yaduoj]
/// </summary>
public class InternalsVisibleToAttributeAssemblyName
{
public static int Main()
{
InternalsVisibleToAttributeAssemblyName testObj = new InternalsVisibleToAttributeAssemblyName();
TestLibrary.TestFramework.BeginTestCase("for property: InternalsVisibleToAttribute.AssemblyName");
if (testObj.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
return retVal;
}
#region Positive tests
public bool PosTest1()
{
bool retVal = true;
const string c_TEST_ID = "P001";
string c_TEST_DESC = "PosTest1: Get a normal friend assembly name.";
string errorDesc;
string assemblyName;
string actualFriendAssemblyName;
assemblyName = "myTestCase.dll";
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
InternalsVisibleToAttribute internalIsVisibleTo = new InternalsVisibleToAttribute(assemblyName);
actualFriendAssemblyName = internalIsVisibleTo.AssemblyName;
if (actualFriendAssemblyName != assemblyName)
{
errorDesc = "The friend assembly name is not the value \"" + assemblyName +
"\" as expected, Actually\"" + actualFriendAssemblyName + "\"";
TestLibrary.TestFramework.LogError("001" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
errorDesc = "Unexpected exception: " + e;
TestLibrary.TestFramework.LogError("002" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
const string c_TEST_ID = "P002";
string c_TEST_DESC = "PosTest2: Get a friend assembly name that is an emtpy string.";
string errorDesc;
string assemblyName;
string actualFriendAssemblyName;
assemblyName = string.Empty;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
InternalsVisibleToAttribute internalIsVisibleTo = new InternalsVisibleToAttribute(assemblyName);
actualFriendAssemblyName = internalIsVisibleTo.AssemblyName;
if (actualFriendAssemblyName != assemblyName)
{
errorDesc = "The friend assembly name is not an empty string as expected, Actually\"" +
actualFriendAssemblyName + "\"";
TestLibrary.TestFramework.LogError("003" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
errorDesc = "Unexpected exception: " + e;
TestLibrary.TestFramework.LogError("004" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
const string c_TEST_ID = "P003";
string c_TEST_DESC = "PosTest3: Get a friend assembly name that is a null reference.";
string errorDesc;
string assemblyName;
string actualFriendAssemblyName;
assemblyName = null;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
InternalsVisibleToAttribute internalIsVisibleTo = new InternalsVisibleToAttribute(assemblyName);
actualFriendAssemblyName = internalIsVisibleTo.AssemblyName;
if (actualFriendAssemblyName != assemblyName)
{
errorDesc = "The friend assembly name is not a null reference as expected, Actually\"" +
actualFriendAssemblyName + "\"";
TestLibrary.TestFramework.LogError("005" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
errorDesc = "Unexpected exception: " + e;
TestLibrary.TestFramework.LogError("006" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
const string c_TEST_ID = "P004";
string c_TEST_DESC = "PosTest4: Get a friend assembly name containing special characters.";
string errorDesc;
string assemblyName;
string actualFriendAssemblyName;
assemblyName = "::B:" + System.IO.Path.DirectorySeparatorChar + "\n\v\r\t\0myTestCase.dll";
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
InternalsVisibleToAttribute internalIsVisibleTo = new InternalsVisibleToAttribute(assemblyName);
actualFriendAssemblyName = internalIsVisibleTo.AssemblyName;
if (actualFriendAssemblyName != assemblyName)
{
errorDesc = "The friend assembly name is not the value \"" + assemblyName +
"\" as expected, Actually\"" + actualFriendAssemblyName + "\"";
TestLibrary.TestFramework.LogError("007" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
errorDesc = "Unexpected exception: " + e;
TestLibrary.TestFramework.LogError("008" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
return retVal;
}
#endregion
}
| 34.659218 | 108 | 0.594778 | [
"MIT"
] | corefan/coreclr | tests/src/CoreMangLib/cti/system/runtime/compilerservices/internalsvisibletoattribute/internalsvisibletoattributeassemblyname.cs | 6,204 | C# |
using System;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace Scraper.Net.Facebook
{
internal class DateTimeConverterUsingDateTimeParse : JsonConverter<DateTime>
{
public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
return DateTime.Parse(reader.GetString());
}
public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
{
writer.WriteStringValue(value.ToString());
}
}
} | 30.368421 | 115 | 0.701906 | [
"MIT"
] | Scraper-Net/Scraper.Net | src/Scraper.Net.Facebook/DateTimeConverterUsingDateTimeParse.cs | 579 | C# |
using System.Collections;
using UnityEngine;
using UnityEngine.SceneManagement;
public class Level_6 : ALevel
{
protected override IEnumerator Startup()
{
yield return new WaitForSeconds(0.5f);
eventsSystem.OnNewMessage.Invoke("There are more and more houses", 0, 2, 1);
}
protected override IEnumerator Closing()
{
yield return new WaitForSeconds(0.5f);
eventsSystem.OnNewMessage.Invoke("Well Done :)", 0, 2, 1);
yield return new WaitForSeconds(3);
eventsSystem.OnNewMessage.Invoke("However there are no more levels :(", 0, 2, 1);
yield return new WaitForSeconds(3);
SceneManager.LoadSceneAsync(NextLevel, LoadSceneMode.Single);
}
}
| 30.208333 | 89 | 0.684138 | [
"MIT"
] | TomKauffeld/GMTK-2021 | Assets/Scenes/Levels/Level_6.cs | 725 | C# |
using Panuon.UI.Silver.Core;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
namespace Panuon.UI.Silver
{
/// <summary>
/// ColorPicker.xaml 的交互逻辑
/// </summary>
public partial class ColorPicker : ContentControl
{
#region Constructor
public ColorPicker()
{
InitializeComponent();
Foreground = "#3E3E3E".ToColor().ToBrush();
Background = "#FFFFFF".ToColor().ToBrush();
Padding = new Thickness(5, 0, 0, 0);
ShadowColor = "#888888".ToColor();
CornerRadius = new CornerRadius(2);
VerticalContentAlignment = VerticalAlignment.Center;
Loaded += delegate
{
UpdateText();
};
}
#endregion
#region RoutedEvent
public static readonly RoutedEvent SelectedBrushChangedEvent = EventManager.RegisterRoutedEvent("SelectedBrushChanged", RoutingStrategy.Bubble, typeof(SelectedBrushChangedEventHandler), typeof(ColorPicker));
public event SelectedBrushChangedEventHandler SelectedBrushChanged
{
add { AddHandler(SelectedBrushChangedEvent, value); }
remove { RemoveHandler(SelectedBrushChangedEvent, value); }
}
void RaiseSelectedBrushChanged(Brush brush)
{
var arg = new SelectedBrushChangedEventArgs(brush, SelectedBrushChangedEvent);
RaiseEvent(arg);
}
#endregion
#region Property
/// <summary>
/// Gets or sets text.
/// </summary>
public string Text
{
get { return (string)GetValue(TextProperty); }
set { SetValue(TextProperty, value); }
}
public static readonly DependencyProperty TextProperty =
DependencyProperty.Register("Text", typeof(string), typeof(ColorPicker));
/// <summary>
/// Gets or sets shadow color.
/// </summary>
public Color ShadowColor
{
get { return (Color)GetValue(ShadowColorProperty); }
set { SetValue(ShadowColorProperty, value); }
}
public static readonly DependencyProperty ShadowColorProperty =
DependencyProperty.Register("ShadowColor", typeof(Color), typeof(ColorPicker));
/// <summary>
/// Gets or sets selected brush.
/// </summary>
public SolidColorBrush SelectedBrush
{
get { return (SolidColorBrush)GetValue(SelectedBrushProperty); }
set { SetValue(SelectedBrushProperty, value); }
}
public static readonly DependencyProperty SelectedBrushProperty =
DependencyProperty.Register("SelectedBrush", typeof(SolidColorBrush), typeof(ColorPicker), new PropertyMetadata(Colors.White.ToBrush(), OnSelectedBrushChanged));
private static void OnSelectedBrushChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var picker = d as ColorPicker;
picker.UpdateText();
picker.RaiseSelectedBrushChanged(picker.SelectedBrush);
}
/// <summary>
/// Gets or sets is opacity enabled.
/// </summary>
public bool IsOpacityEnabled
{
get { return (bool)GetValue(IsOpacityEnabledProperty); }
set { SetValue(IsOpacityEnabledProperty, value); }
}
public static readonly DependencyProperty IsOpacityEnabledProperty =
DependencyProperty.Register("IsOpacityEnabled", typeof(bool), typeof(ColorPicker), new PropertyMetadata(true, OnIsOpacityEnabled));
private static void OnIsOpacityEnabled(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var picker = d as ColorPicker;
picker.UpdateText();
}
/// <summary>
/// Gets or sets corner radius.
/// </summary>
public CornerRadius CornerRadius
{
get { return (CornerRadius)GetValue(CornerRadiusProperty); }
set { SetValue(CornerRadiusProperty, value); }
}
public static readonly DependencyProperty CornerRadiusProperty =
DependencyProperty.Register("CornerRadius", typeof(CornerRadius), typeof(ColorPicker));
/// <summary>
/// Gets or sets is text visible.
/// </summary>
public bool IsTextVisible
{
get { return (bool)GetValue(IsTextVisibleProperty); }
set { SetValue(IsTextVisibleProperty, value); }
}
public static readonly DependencyProperty IsTextVisibleProperty =
DependencyProperty.Register("IsTextVisible", typeof(bool), typeof(ColorPicker), new PropertyMetadata(true));
/// <summary>
/// Gets or sets header.
/// </summary>
public object Header
{
get { return (object)GetValue(HeaderProperty); }
set { SetValue(HeaderProperty, value); }
}
public static readonly DependencyProperty HeaderProperty =
DependencyProperty.Register("Header", typeof(object), typeof(ColorPicker));
/// <summary>
/// Gets or sets is measured value visible.
/// </summary>
public bool IsMeasuredValueVisible
{
get { return (bool)GetValue(IsMeasuredValueVisibleProperty); }
set { SetValue(IsMeasuredValueVisibleProperty, value); }
}
public static readonly DependencyProperty IsMeasuredValueVisibleProperty =
DependencyProperty.Register("IsMeasuredValueVisible", typeof(bool), typeof(ColorPicker), new PropertyMetadata(true, OnIsMeasuredValueVisibleChanged));
private static void OnIsMeasuredValueVisibleChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var picker = d as ColorPicker;
picker.ColorSelector.Height = 340 - (picker.IsMeasuredValueVisible ? 0 : 50) - (picker.IsDefaultColorPanelVisible ? 0 : 70);
}
/// <summary>
/// Gets or sets is default color panel visible.
/// </summary>
public bool IsDefaultColorPanelVisible
{
get { return (bool)GetValue(IsDefaultColorPanelVisibleProperty); }
set { SetValue(IsDefaultColorPanelVisibleProperty, value); }
}
public static readonly DependencyProperty IsDefaultColorPanelVisibleProperty =
DependencyProperty.Register("IsDefaultColorPanelVisible", typeof(bool), typeof(ColorPicker), new PropertyMetadata(true, OnIsDefaultColorPanelVisibleChanged));
private static void OnIsDefaultColorPanelVisibleChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var picker = d as ColorPicker;
picker.ColorSelector.Height = 340 - (picker.IsMeasuredValueVisible ? 0 : 50) - (picker.IsDefaultColorPanelVisible ? 0 : 70);
}
#endregion
#region Function
private void UpdateText()
{
var color = SelectedBrush.ToColor();
if (IsOpacityEnabled)
Text = string.Format("#{0:X2}{1:X2}{2:X2}{3:X2}", color.A, color.R, color.G, color.B);
else
Text = string.Format("#{0:X2}{1:X2}{2:X2}", color.R, color.G, color.B);
}
#endregion
}
}
| 38.338542 | 215 | 0.627225 | [
"MIT"
] | MANLONE/PanuonUI.Silver | SharedResources/Panuon.UI.Silver/Controls/ColorPicker.xaml.cs | 7,373 | C# |
//-----------------------------------------------------------------------------
// Copyright : (c) Chris Moore, 2020
// License : MIT
//-----------------------------------------------------------------------------
namespace Z0
{
using System;
using System.Runtime.CompilerServices;
using static Root;
using static core;
partial class ByteBlocks
{
/// <summary>
/// Fills a span with data from a memory block
/// </summary>
/// <param name="src">The stack storage source</param>
/// <typeparam name="T">The span cell type</typeparam>
[MethodImpl(Inline), Op, Closures(Closure)]
public static unsafe Span<T> span<T>(ref ByteBlock8 src)
where T : unmanaged
=> recover<T>(cover(u8(src), ByteBlock8.Size));
/// <summary>
/// Fills a span with data from a memory block
/// </summary>
/// <param name="src">The stack storage source</param>
/// <typeparam name="T">The span cell type</typeparam>
[MethodImpl(Inline), Op, Closures(Closure)]
public static Span<T> span<T>(ref ByteBlock16 src)
where T : unmanaged
=> recover<T>(cover(u8(src), ByteBlock16.Size));
/// <summary>
/// Fills a span with data from a memory block
/// </summary>
/// <param name="src">The stack storage source</param>
/// <typeparam name="T">The span cell type</typeparam>
[MethodImpl(Inline), Op, Closures(Closure)]
public static Span<T> span<T>(ref ByteBlock32 src)
where T : unmanaged
=> recover<T>(cover(u8(src), ByteBlock32.Size));
/// <summary>
/// Fills a span with data from a memory block
/// </summary>
/// <param name="src">The stack storage source</param>
/// <typeparam name="T">The span cell type</typeparam>
[MethodImpl(Inline), Op, Closures(Closure)]
public static unsafe Span<T> span<T>(ref ByteBlock64 src)
where T : unmanaged
=> recover<T>(cover(u8(src), ByteBlock64.Size));
}
} | 38.890909 | 79 | 0.527349 | [
"BSD-3-Clause"
] | 0xCM/z0 | src/blocks/src/ops/byteblocks/span.cs | 2,139 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SeleniumStoneSoup
{
public enum TagAttributes
{
[Description("id")]
Id,
[Description("name")]
Name,
[Description("class")]
Class,
[Description("value")]
Value,
[Description("onclick")]
OnClick,
[Description("src")]
Src,
[Description("title")]
Title,
[Description("href")]
Href,
[Description("type")]
Type,
[Description("style")]
Style,
[Description("rel")]
Rel,
[Description("data-policy-id")]
DataPolicyId
}
}
| 16.66 | 40 | 0.503001 | [
"MIT"
] | GregFinzer/SeleniumStoneSoup | SeleniumStoneSoup/TagAttributes.cs | 835 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Fluid.ViewEngine;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ViewEngines;
using Microsoft.Extensions.Options;
namespace Fluid.MvcViewEngine
{
public class FluidViewEngine : IFluidViewEngine
{
private IFluidRendering _fluidRendering;
private readonly IWebHostEnvironment _hostingEnvironment;
public static readonly string ViewExtension = ".liquid";
private const string ControllerKey = "controller";
private const string AreaKey = "area";
private FluidViewEngineOptions _options;
public FluidViewEngine(IFluidRendering fluidRendering,
IOptions<FluidViewEngineOptions> optionsAccessor,
IWebHostEnvironment hostingEnvironment)
{
_options = optionsAccessor.Value;
_fluidRendering = fluidRendering;
_hostingEnvironment = hostingEnvironment;
}
public ViewEngineResult FindView(ActionContext context, string viewName, bool isMainPage)
{
return LocatePageFromViewLocations(context, viewName, isMainPage);
}
private ViewEngineResult LocatePageFromViewLocations(
ActionContext actionContext,
string viewName,
bool isMainPage)
{
var controllerName = GetNormalizedRouteValue(actionContext, ControllerKey);
var areaName = GetNormalizedRouteValue(actionContext, AreaKey);
var fileProvider = _options.ViewsFileProvider ?? _hostingEnvironment.ContentRootFileProvider;
var checkedLocations = new List<string>();
foreach (var location in _options.ViewLocationFormats)
{
var view = string.Format(location, viewName, controllerName);
if(fileProvider.GetFileInfo(view).Exists)
return ViewEngineResult.Found("Default", new FluidView(view, _fluidRendering));
checkedLocations.Add(view);
}
return ViewEngineResult.NotFound(viewName, checkedLocations);
}
public ViewEngineResult GetView(string executingFilePath, string viewPath, bool isMainPage)
{
var applicationRelativePath = GetAbsolutePath(executingFilePath, viewPath);
if (!(IsApplicationRelativePath(viewPath) || IsRelativePath(viewPath)))
{
// Not a path this method can handle.
return ViewEngineResult.NotFound(applicationRelativePath, Enumerable.Empty<string>());
}
return ViewEngineResult.Found("Default", new FluidView(applicationRelativePath, _fluidRendering));
}
public string GetAbsolutePath(string executingFilePath, string pagePath)
{
if (string.IsNullOrEmpty(pagePath))
{
// Path is not valid; no change required.
return pagePath;
}
if (IsApplicationRelativePath(pagePath))
{
// An absolute path already; no change required.
return pagePath.Replace("~/", "");
}
if (!IsRelativePath(pagePath))
{
// A page name; no change required.
return pagePath;
}
// Given a relative path i.e. not yet application-relative (starting with "~/" or "/"), interpret
// path relative to currently-executing view, if any.
if (string.IsNullOrEmpty(executingFilePath))
{
// Not yet executing a view. Start in app root.
return "/" + pagePath;
}
// Get directory name (including final slash) but do not use Path.GetDirectoryName() to preserve path
// normalization.
var index = executingFilePath.LastIndexOf('/');
Debug.Assert(index >= 0);
return executingFilePath.Substring(0, index + 1) + pagePath;
}
private static bool IsApplicationRelativePath(string name)
{
Debug.Assert(!string.IsNullOrEmpty(name));
return name[0] == '~' || name[0] == '/';
}
private static bool IsRelativePath(string name)
{
Debug.Assert(!string.IsNullOrEmpty(name));
// Though ./ViewName looks like a relative path, framework searches for that view using view locations.
return name.EndsWith(ViewExtension, StringComparison.OrdinalIgnoreCase);
}
public static string GetNormalizedRouteValue(ActionContext context, string key)
{
if (context == null)
{
ExceptionHelper.ThrowArgumentNullException(nameof(context));
}
if (key == null)
{
ExceptionHelper.ThrowArgumentNullException(nameof(key));
}
if (!context.RouteData.Values.TryGetValue(key, out object routeValue))
{
return null;
}
var actionDescriptor = context.ActionDescriptor;
string normalizedValue = null;
if (actionDescriptor.RouteValues.TryGetValue(key, out string value) &&
!string.IsNullOrEmpty(value))
{
normalizedValue = value;
}
var stringRouteValue = routeValue?.ToString();
if (string.Equals(normalizedValue, stringRouteValue, StringComparison.OrdinalIgnoreCase))
{
return normalizedValue;
}
return stringRouteValue;
}
}
}
| 36.653846 | 115 | 0.610178 | [
"MIT"
] | MichaelPetrinolis/fluid | Fluid.MvcViewEngine/FluidViewEngine.cs | 5,720 | C# |
using System;
using Hrimsoft.Core.ValueObjects;
namespace Hrimsoft.Core.Extensions
{
/// <summary>
/// Methods that extend DateTime functionality
/// </summary>
public static class DateTimeExtensions
{
/// <summary>
/// Truncate DateTime to milliseconds, seconds, etc that is depends on TimeSpan
/// </summary>
/// <param name="dateTime">date and time that must be truncated</param>
/// <param name="timeSpan">a period to which it will truncate. If it is needed to cut all micro and nano seconds Time span should be 1 millisecond</param>
public static DateTime Truncate(this DateTime dateTime, TimeSpan timeSpan)
{
if (timeSpan == TimeSpan.Zero)
return dateTime;
if (dateTime == DateTime.MinValue || dateTime == DateTime.MaxValue)
return dateTime;
return dateTime.AddTicks(-(dateTime.Ticks % timeSpan.Ticks));
}
/// <summary>
/// Cut micro and nano seconds from DateTime
/// </summary>
/// <param name="dateTime">date and time that must be cut</param>
public static DateTime TruncateToMilliseconds(this DateTime dateTime)
=> dateTime.Truncate(TimeSpan.FromMilliseconds(1));
/// <summary>
/// Cut micro-, nano- and milli- seconds from DateTime
/// </summary>
/// <param name="dateTime">date and time that must be cut</param>
public static DateTime TruncateToSeconds(this DateTime dateTime)
=> dateTime.Truncate(TimeSpan.FromSeconds(1));
/// <summary> Converts DateTime to Date </summary>
public static Date ToDate(this DateTime dateTime) => new Date(dateTime);
}
} | 41.857143 | 162 | 0.624573 | [
"MIT"
] | Basim108/hrimsoft.core | Hrimsoft.Core/Extensions/DateTimeExtensions.cs | 1,758 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
#if HAS_IOPERATION
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Operations;
namespace Analyzer.Utilities.Extensions
{
internal static class OperationBlockAnalysisContextExtension
{
public static bool IsMethodNotImplementedOrSupported(this OperationBlockAnalysisContext context)
{
// Note that VB method bodies with 1 action have 3 operations.
// The first is the actual operation, the second is a label statement, and the third is a return
// statement. The last two are implicit in these scenarios.
var operationBlocks = context.OperationBlocks.WhereAsArray(operation => !operation.IsOperationNoneRoot());
IBlockOperation? methodBlock = null;
if (operationBlocks.Length == 1 && operationBlocks[0].Kind == OperationKind.Block)
{
methodBlock = (IBlockOperation)operationBlocks[0];
}
else if (operationBlocks.Length > 1)
{
foreach (var block in operationBlocks)
{
if (block.Kind == OperationKind.Block)
{
methodBlock = (IBlockOperation)block;
break;
}
}
}
if (methodBlock != null)
{
static bool IsSingleStatementBody(IBlockOperation body)
{
return body.Operations.Length == 1 ||
(body.Operations.Length == 3 && body.Syntax.Language == LanguageNames.VisualBasic &&
body.Operations[1] is ILabeledOperation labeledOp && labeledOp.IsImplicit &&
body.Operations[2] is IReturnOperation returnOp && returnOp.IsImplicit);
}
if (IsSingleStatementBody(methodBlock))
{
var innerOperation = methodBlock.Operations.First();
// Because of https://github.com/dotnet/roslyn/issues/23152, there can be an expression-statement
// wrapping expression-bodied throw operations. Compensate by unwrapping if necessary.
if (innerOperation.Kind == OperationKind.ExpressionStatement &&
innerOperation is IExpressionStatementOperation exprStatement)
{
innerOperation = exprStatement.Operation;
}
if (innerOperation.Kind == OperationKind.Throw &&
innerOperation is IThrowOperation throwOperation &&
throwOperation.GetThrownExceptionType() is ITypeSymbol createdExceptionType)
{
if (Equals(context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemNotImplementedException), createdExceptionType.OriginalDefinition)
|| Equals(context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemNotSupportedException), createdExceptionType.OriginalDefinition))
{
return true;
}
}
}
}
return false;
}
}
}
#endif
| 44.15 | 178 | 0.582106 | [
"Apache-2.0"
] | RussKie/roslyn-analyzers | src/Utilities/Compiler/Extensions/OperationBlockAnalysisContextExtension.cs | 3,534 | C# |
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("AWSSDK.AWSSupport")]
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - AWS Support. The AWS Support API provides methods for creating and managing AWS Support cases and for retrieving the results of AWS Trusted Advisor checks.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyProduct("Amazon Web Services SDK for .NET")]
[assembly: AssemblyCompany("Amazon.com, Inc")]
[assembly: AssemblyCopyright("Copyright 2009-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("3.3")]
[assembly: AssemblyFileVersion("3.3.100.137")] | 47.25 | 235 | 0.752646 | [
"Apache-2.0"
] | lukeenterprise/aws-sdk-net | sdk/code-analysis/ServiceAnalysis/AWSSupport/Properties/AssemblyInfo.cs | 1,512 | C# |
//---------------------------------------------------------------------------
//
// <copyright file="Point3DConverter.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved.
// </copyright>
//
// This file was generated, please do not edit it directly.
//
// Please see http://wiki/default.aspx/Microsoft.Projects.Avalon/MilCodeGen.html for more information.
//
//---------------------------------------------------------------------------
using MS.Internal;
using MS.Internal.Collections;
using MS.Internal.PresentationCore;
using MS.Utility;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.Design.Serialization;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Markup;
using System.Windows.Media.Media3D.Converters;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Composition;
using System.Security;
using System.Security.Permissions;
using SR=MS.Internal.PresentationCore.SR;
using SRID=MS.Internal.PresentationCore.SRID;
using System.Windows.Media.Imaging;
#pragma warning disable 1634, 1691 // suppressing PreSharp warnings
namespace System.Windows.Media.Media3D
{
/// <summary>
/// Point3DConverter - Converter class for converting instances of other types to and from Point3D instances
/// </summary>
public sealed class Point3DConverter : TypeConverter
{
/// <summary>
/// Returns true if this type converter can convert from a given type.
/// </summary>
/// <returns>
/// bool - True if this converter can convert from the provided type, false if not.
/// </returns>
/// <param name="context"> The ITypeDescriptorContext for this call. </param>
/// <param name="sourceType"> The Type being queried for support. </param>
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
if (sourceType == typeof(string))
{
return true;
}
return base.CanConvertFrom(context, sourceType);
}
/// <summary>
/// Returns true if this type converter can convert to the given type.
/// </summary>
/// <returns>
/// bool - True if this converter can convert to the provided type, false if not.
/// </returns>
/// <param name="context"> The ITypeDescriptorContext for this call. </param>
/// <param name="destinationType"> The Type being queried for support. </param>
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
if (destinationType == typeof(string))
{
return true;
}
return base.CanConvertTo(context, destinationType);
}
/// <summary>
/// Attempts to convert to a Point3D from the given object.
/// </summary>
/// <returns>
/// The Point3D which was constructed.
/// </returns>
/// <exception cref="NotSupportedException">
/// A NotSupportedException is thrown if the example object is null or is not a valid type
/// which can be converted to a Point3D.
/// </exception>
/// <param name="context"> The ITypeDescriptorContext for this call. </param>
/// <param name="culture"> The requested CultureInfo. Note that conversion uses "en-US" rather than this parameter. </param>
/// <param name="value"> The object to convert to an instance of Point3D. </param>
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
if (value == null)
{
throw GetConvertFromException(value);
}
String source = value as string;
if (source != null)
{
return Point3D.Parse(source);
}
return base.ConvertFrom(context, culture, value);
}
/// <summary>
/// ConvertTo - Attempt to convert an instance of Point3D to the given type
/// </summary>
/// <returns>
/// The object which was constructoed.
/// </returns>
/// <exception cref="NotSupportedException">
/// A NotSupportedException is thrown if "value" is null or not an instance of Point3D,
/// or if the destinationType isn't one of the valid destination types.
/// </exception>
/// <param name="context"> The ITypeDescriptorContext for this call. </param>
/// <param name="culture"> The CultureInfo which is respected when converting. </param>
/// <param name="value"> The object to convert to an instance of "destinationType". </param>
/// <param name="destinationType"> The type to which this will convert the Point3D instance. </param>
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
{
if (destinationType != null && value is Point3D)
{
Point3D instance = (Point3D)value;
if (destinationType == typeof(string))
{
// Delegate to the formatting/culture-aware ConvertToString method.
#pragma warning suppress 6506 // instance is obviously not null
return instance.ConvertToString(null, culture);
}
}
// Pass unhandled cases to base class (which will throw exceptions for null value or destinationType.)
return base.ConvertTo(context, culture, value, destinationType);
}
}
}
| 40.020408 | 133 | 0.618562 | [
"Apache-2.0"
] | 295007712/295007712.github.io | sourceCode/dotNet4.6/wpf/src/Core/CSharp/System/Windows/Media3D/Generated/Point3DConverter.cs | 5,883 | C# |
namespace BankFileParsers
{
public enum CategoryTypeCodes
{
UniformBankAdministrationInstituteBalance,
SummaryAndDetailCredits,
Lockbox,
Concentration,
PreauthorizedAutomatedClearingHouse,
OtherDeposits,
MoneyTransfer,
Security,
ZeroBalanceAccountDisbursing,
Other,
CorrespondentBankFederalReserve,
Miscellaneous,
SummaryAndDetailDebits,
PayableThroughDraft,
AutomatedClearingHouse,
ChecksPaid,
DepositedItemsReturned,
LoanTransactions,
NonMonetaryInformation
}
} | 25.12 | 50 | 0.659236 | [
"MIT"
] | JLineaweaver/BankFileParsers | BankFileParsers/Enums/CategoryTypeCodes.cs | 630 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System.Collections.Generic;
using Microsoft.Recognizers.Text.DataDrivenTests;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Microsoft.Recognizers.Text.DateTime.Tests
{
[TestClass]
public class TestDateTime_Swedish : TestBase
{
public static IDictionary<string, IDateTimeExtractor> Extractors { get; private set; }
public static IDictionary<string, IDateTimeParser> Parsers { get; private set; }
[ClassInitialize]
public static void ClassInitialize(TestContext context)
{
Extractors = new Dictionary<string, IDateTimeExtractor>();
Parsers = new Dictionary<string, IDateTimeParser>();
}
/*
[NetCoreTestDataSource]
[TestMethod]
public void DateExtractor(TestModel testSpec)
{
ExtractorInitialize(Extractors);
TestDateTimeExtractor(testSpec);
}
[NetCoreTestDataSource]
[TestMethod]
public void TimeExtractor(TestModel testSpec)
{
ExtractorInitialize(Extractors);
TestDateTimeExtractor(testSpec);
}
[NetCoreTestDataSource]
[TestMethod]
public void DatePeriodExtractor(TestModel testSpec)
{
ExtractorInitialize(Extractors);
TestDateTimeExtractor(testSpec);
}
[NetCoreTestDataSource]
[TestMethod]
public void TimePeriodExtractor(TestModel testSpec)
{
ExtractorInitialize(Extractors);
TestDateTimeExtractor(testSpec);
}
[NetCoreTestDataSource]
[TestMethod]
public void DateTimeExtractor(TestModel testSpec)
{
ExtractorInitialize(Extractors);
TestDateTimeExtractor(testSpec);
}
[NetCoreTestDataSource]
[TestMethod]
public void DateTimePeriodExtractor(TestModel testSpec)
{
ExtractorInitialize(Extractors);
TestDateTimeExtractor(testSpec);
}
[NetCoreTestDataSource]
[TestMethod]
public void HolidayExtractor(TestModel testSpec)
{
ExtractorInitialize(Extractors);
TestDateTimeExtractor(testSpec);
}
[NetCoreTestDataSource]
[TestMethod]
public void TimeZoneExtractor(TestModel testSpec)
{
ExtractorInitialize(Extractors);
TestDateTimeExtractor(testSpec);
}
[NetCoreTestDataSource]
[TestMethod]
public void DurationExtractor(TestModel testSpec)
{
ExtractorInitialize(Extractors);
TestDateTimeExtractor(testSpec);
}
[NetCoreTestDataSource]
[TestMethod]
public void SetExtractor(TestModel testSpec)
{
ExtractorInitialize(Extractors);
TestDateTimeExtractor(testSpec);
}
[NetCoreTestDataSource]
[TestMethod]
public void MergedExtractor(TestModel testSpec)
{
ExtractorInitialize(Extractors);
TestDateTimeExtractor(testSpec);
}
[NetCoreTestDataSource]
[TestMethod]
public void MergedExtractorSkipFromTo(TestModel testSpec)
{
ExtractorInitialize(Extractors);
TestDateTimeExtractor(testSpec);
}
[NetCoreTestDataSource]
[TestMethod]
public void DateParser(TestModel testSpec)
{
ExtractorInitialize(Extractors);
ParserInitialize(Parsers);
TestDateTimeParser(testSpec);
}
[NetCoreTestDataSource]
[TestMethod]
public void TimeParser(TestModel testSpec)
{
ExtractorInitialize(Extractors);
ParserInitialize(Parsers);
TestDateTimeParser(testSpec);
}
[NetCoreTestDataSource]
[TestMethod]
public void DatePeriodParser(TestModel testSpec)
{
ExtractorInitialize(Extractors);
ParserInitialize(Parsers);
TestDateTimeParser(testSpec);
}
[NetCoreTestDataSource]
[TestMethod]
public void TimePeriodParser(TestModel testSpec)
{
ExtractorInitialize(Extractors);
ParserInitialize(Parsers);
TestDateTimeParser(testSpec);
}
[NetCoreTestDataSource]
[TestMethod]
public new void DateTimeParser(TestModel testSpec)
{
ExtractorInitialize(Extractors);
ParserInitialize(Parsers);
TestDateTimeParser(testSpec);
}
[NetCoreTestDataSource]
[TestMethod]
public void DateTimePeriodParser(TestModel testSpec)
{
ExtractorInitialize(Extractors);
ParserInitialize(Parsers);
TestDateTimeParser(testSpec);
}
[NetCoreTestDataSource]
[TestMethod]
public void HolidayParser(TestModel testSpec)
{
ExtractorInitialize(Extractors);
ParserInitialize(Parsers);
TestDateTimeParser(testSpec);
}
[NetCoreTestDataSource]
[TestMethod]
public void TimeZoneParser(TestModel testSpec)
{
ExtractorInitialize(Extractors);
ParserInitialize(Parsers);
TestDateTimeParser(testSpec);
}
[NetCoreTestDataSource]
[TestMethod]
public void DurationParser(TestModel testSpec)
{
ExtractorInitialize(Extractors);
ParserInitialize(Parsers);
TestDateTimeParser(testSpec);
}
[NetCoreTestDataSource]
[TestMethod]
public void SetParser(TestModel testSpec)
{
ExtractorInitialize(Extractors);
ParserInitialize(Parsers);
TestDateTimeParser(testSpec);
}
[NetCoreTestDataSource]
[TestMethod]
public void MergedParser(TestModel testSpec)
{
ExtractorInitialize(Extractors);
ParserInitialize(Parsers);
TestDateTimeMergedParser(testSpec);
}
[NetCoreTestDataSource]
[TestMethod]
public void DateTimeModel(TestModel testSpec)
{
TestDateTime(testSpec);
}
[NetCoreTestDataSource]
[TestMethod]
public void DateTimeModelSplitDateAndTime(TestModel testSpec)
{
TestDateTime(testSpec);
}
[NetCoreTestDataSource]
[TestMethod]
public void DateTimeModelCalendarMode(TestModel testSpec)
{
TestDateTimeAlt(testSpec);
}
[NetCoreTestDataSource]
[TestMethod]
public void DateTimeModelExtendedTypes(TestModel testSpec)
{
TestDateTimeAlt(testSpec);
}
[NetCoreTestDataSource]
[TestMethod]
public void DateTimeModelComplexCalendar(TestModel testSpec)
{
TestDateTimeAlt(testSpec);
}
[NetCoreTestDataSource]
[TestMethod]
public void DateTimeModelExperimentalMode(TestModel testSpec)
{
TestDateTimeAlt(testSpec);
}
*/
}
}
| 27.003774 | 94 | 0.622275 | [
"MIT"
] | G-arj/Recognizers-Text | .NET/Microsoft.Recognizers.Text.DataDrivenTests/DateTime/TestDateTime_Swedish.cs | 7,158 | C# |
namespace Hangfire.Storage.EntityFramework.JobQueue
{
internal class FetchedJob
{
public int Id { get; set; }
public int JobId { get; set; }
public string Queue { get; set; }
}
}
| 21.6 | 52 | 0.601852 | [
"MIT"
] | TrieBr/Hangfire.Storage.EntityFramework | src/Hangfire.Storage.EntityFramework/JobQueue/FetchedJob.cs | 218 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using SharpCompress.Common;
using SharpCompress.Common.Zip;
using SharpCompress.Common.Zip.Headers;
using SharpCompress.Compressors.Deflate;
using SharpCompress.Readers;
using SharpCompress.Readers.Zip;
using SharpCompress.Writers;
using SharpCompress.Writers.Zip;
namespace SharpCompress.Archives.Zip
{
public class ZipArchive : AbstractWritableArchive<ZipArchiveEntry, ZipVolume>
{
private readonly SeekableZipHeaderFactory headerFactory;
/// <summary>
/// Gets or sets the compression level applied to files added to the archive,
/// if the compression method is set to deflate
/// </summary>
public CompressionLevel DeflateCompressionLevel { get; set; }
#if !NO_FILE
/// <summary>
/// Constructor expects a filepath to an existing file.
/// </summary>
/// <param name="filePath"></param>
/// <param name="readerOptions"></param>
public static ZipArchive Open(string filePath, ReaderOptions readerOptions = null)
{
filePath.CheckNotNullOrEmpty("filePath");
return Open(new FileInfo(filePath), readerOptions ?? new ReaderOptions());
}
/// <summary>
/// Constructor with a FileInfo object to an existing file.
/// </summary>
/// <param name="fileInfo"></param>
/// <param name="readerOptions"></param>
public static ZipArchive Open(FileInfo fileInfo, ReaderOptions readerOptions = null)
{
fileInfo.CheckNotNull("fileInfo");
return new ZipArchive(fileInfo, readerOptions ?? new ReaderOptions());
}
#endif
/// <summary>
/// Takes a seekable Stream as a source
/// </summary>
/// <param name="stream"></param>
/// <param name="readerOptions"></param>
public static ZipArchive Open(Stream stream, ReaderOptions readerOptions = null)
{
stream.CheckNotNull("stream");
return new ZipArchive(stream, readerOptions ?? new ReaderOptions());
}
#if !NO_FILE
public static bool IsZipFile(string filePath, string password = null)
{
return IsZipFile(new FileInfo(filePath), password);
}
public static bool IsZipFile(FileInfo fileInfo, string password = null)
{
if (!fileInfo.Exists)
{
return false;
}
using (Stream stream = fileInfo.OpenRead())
{
return IsZipFile(stream, password);
}
}
#endif
public static bool IsZipFile(Stream stream, string password = null)
{
StreamingZipHeaderFactory headerFactory = new StreamingZipHeaderFactory(password, new ArchiveEncoding());
try
{
ZipHeader header =
headerFactory.ReadStreamHeader(stream).FirstOrDefault(x => x.ZipHeaderType != ZipHeaderType.Split);
if (header == null)
{
return false;
}
return Enum.IsDefined(typeof(ZipHeaderType), header.ZipHeaderType);
}
catch (CryptographicException)
{
return true;
}
catch
{
return false;
}
}
#if !NO_FILE
/// <summary>
/// Constructor with a FileInfo object to an existing file.
/// </summary>
/// <param name="fileInfo"></param>
/// <param name="readerOptions"></param>
internal ZipArchive(FileInfo fileInfo, ReaderOptions readerOptions)
: base(ArchiveType.Zip, fileInfo, readerOptions)
{
headerFactory = new SeekableZipHeaderFactory(readerOptions.Password, readerOptions.ArchiveEncoding);
}
protected override IEnumerable<ZipVolume> LoadVolumes(FileInfo file)
{
return new ZipVolume(file.OpenRead(), ReaderOptions).AsEnumerable();
}
#endif
internal ZipArchive()
: base(ArchiveType.Zip)
{
}
/// <summary>
/// Takes multiple seekable Streams for a multi-part archive
/// </summary>
/// <param name="stream"></param>
/// <param name="readerOptions"></param>
internal ZipArchive(Stream stream, ReaderOptions readerOptions)
: base(ArchiveType.Zip, stream, readerOptions)
{
headerFactory = new SeekableZipHeaderFactory(readerOptions.Password, readerOptions.ArchiveEncoding);
}
protected override IEnumerable<ZipVolume> LoadVolumes(IEnumerable<Stream> streams)
{
return new ZipVolume(streams.First(), ReaderOptions).AsEnumerable();
}
protected override IEnumerable<ZipArchiveEntry> LoadEntries(IEnumerable<ZipVolume> volumes)
{
var volume = volumes.Single();
Stream stream = volume.Stream;
foreach (ZipHeader h in headerFactory.ReadSeekableHeader(stream))
{
if (h != null)
{
switch (h.ZipHeaderType)
{
case ZipHeaderType.DirectoryEntry:
{
yield return new ZipArchiveEntry(this,
new SeekableZipFilePart(headerFactory,
h as DirectoryEntryHeader,
stream));
}
break;
case ZipHeaderType.DirectoryEnd:
{
byte[] bytes = (h as DirectoryEndHeader).Comment;
volume.Comment = ReaderOptions.ArchiveEncoding.Decode(bytes);
yield break;
}
}
}
}
}
public void SaveTo(Stream stream)
{
SaveTo(stream, new WriterOptions(CompressionType.Deflate));
}
protected override void SaveTo(Stream stream, WriterOptions options,
IEnumerable<ZipArchiveEntry> oldEntries,
IEnumerable<ZipArchiveEntry> newEntries)
{
using (var writer = new ZipWriter(stream, new ZipWriterOptions(options)))
{
foreach (var entry in oldEntries.Concat(newEntries)
.Where(x => !x.IsDirectory))
{
using (var entryStream = entry.OpenEntryStream())
{
writer.Write(entry.Key, entryStream, entry.LastModifiedTime);
}
}
}
}
protected override ZipArchiveEntry CreateEntryInternal(string filePath, Stream source, long size, DateTime? modified,
bool closeStream)
{
return new ZipWritableArchiveEntry(this, source, filePath, size, modified, closeStream);
}
public static ZipArchive Create()
{
return new ZipArchive();
}
protected override IReader CreateReaderForSolidExtraction()
{
var stream = Volumes.Single().Stream;
stream.Position = 0;
return ZipReader.Open(stream);
}
}
} | 36.238318 | 125 | 0.536557 | [
"MIT"
] | weijie01011/Win10-Explorer | Explorer/Libs/sharpcompress-0.18/src/SharpCompress/Archives/Zip/ZipArchive.cs | 7,757 | C# |
using UnityEngine;
namespace Imoet.Unity
{
public struct SizeF
{
public int width;
public int height;
public SizeF(int width, int height) {
this.width = width;
this.height = height;
}
public SizeF(int value) {
this.width = this.height = value;
}
#region Property
public float ratio {
get { return (float)width / (float)height; }
}
#endregion
#region Basic Operator
public static SizeF operator +(SizeF a, SizeF b)
{
return new SizeF(a.width + b.width, a.height + b.height);
}
public static SizeF operator -(SizeF a, SizeF b)
{
return new SizeF(a.width - b.width, a.height - b.height);
}
public static SizeF operator *(SizeF a, int b)
{
return new SizeF(a.width * b, a.height * b);
}
public static SizeF operator *(int a, SizeF b)
{
return new SizeF(a * b.width, a * b.height);
}
public static SizeF operator *(SizeF a, float b)
{
return a * (int)b;
}
public static SizeF operator *(float a, SizeF b)
{
return b * (int)a;
}
public static SizeF operator /(SizeF a, int b)
{
return new SizeF(a.width / b, a.height / b);
}
public static SizeF operator /(SizeF a, float b)
{
return a / (int)b;
}
public static SizeF operator -(SizeF a)
{
return a * -1;
}
#endregion
#region Implicit Operator
public static implicit operator Vector2(SizeF p)
{
return new Vector2(p.width, p.height);
}
public static implicit operator SizeF(Vector2 p)
{
return new SizeF((int)p.x, (int)p.y);
}
#if UNITY_2017_1_OR_NEWER
public static implicit operator Vector2Int(SizeF p)
{
return new Vector2Int(p.width, p.height);
}
public static implicit operator SizeF(Vector2Int p)
{
return new SizeF(p.x, p.y);
}
#endif
#endregion
#region Equal Operator
public static bool operator ==(SizeF left, SizeF right)
{
return left.width == right.width && left.height == right.height;
}
public static bool operator !=(SizeF left, SizeF right)
{
return left.width != right.width || left.height == right.height;
}
#endregion
public override bool Equals(object obj)
{
if (obj is SizeF)
return this == (SizeF)obj;
return false;
}
public override int GetHashCode()
{
return this.width.GetHashCode() + this.height.GetHashCode();
}
public override string ToString()
{
return string.Format("x:{0} y:{1}", this.width, this.height);
}
}
}
| 26.626087 | 76 | 0.510777 | [
"MIT"
] | m4s4m0r1/Imoet.Unity | Plugins/Imoet.Unity/Common/SizeF.cs | 3,064 | 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.
// ------------------------------------------------------------------------------
// Changes to this file must follow the http://aka.ms/api-review process.
// ------------------------------------------------------------------------------
namespace Microsoft.Win32.SafeHandles
{
public sealed partial class SafeProcessHandle : Microsoft.Win32.SafeHandles.SafeHandleZeroOrMinusOneIsInvalid
{
public SafeProcessHandle(System.IntPtr existingHandle, bool ownsHandle) : base (default(bool)) { }
protected override bool ReleaseHandle() { throw null; }
}
}
namespace System.Diagnostics
{
public partial class DataReceivedEventArgs : System.EventArgs
{
internal DataReceivedEventArgs() { }
public string? Data { get { throw null; } }
}
public delegate void DataReceivedEventHandler(object sender, System.Diagnostics.DataReceivedEventArgs e);
[System.AttributeUsageAttribute(System.AttributeTargets.All)]
public partial class MonitoringDescriptionAttribute : System.ComponentModel.DescriptionAttribute
{
public MonitoringDescriptionAttribute(string description) { }
public override string Description { get { throw null; } }
}
public partial class Process : System.ComponentModel.Component, System.IDisposable
{
public Process() { }
public int BasePriority { get { throw null; } }
public bool EnableRaisingEvents { get { throw null; } set { } }
public int ExitCode { get { throw null; } }
public System.DateTime ExitTime { get { throw null; } }
public System.IntPtr Handle { get { throw null; } }
public int HandleCount { get { throw null; } }
public bool HasExited { get { throw null; } }
public int Id { get { throw null; } }
public string MachineName { get { throw null; } }
public System.Diagnostics.ProcessModule? MainModule { get { throw null; } }
public System.IntPtr MainWindowHandle { get { throw null; } }
public string MainWindowTitle { get { throw null; } }
public System.IntPtr MaxWorkingSet { get { throw null; } set { } }
public System.IntPtr MinWorkingSet { get { throw null; } set { } }
public System.Diagnostics.ProcessModuleCollection Modules { get { throw null; } }
[System.ObsoleteAttribute("This property has been deprecated. Please use System.Diagnostics.Process.NonpagedSystemMemorySize64 instead. https://go.microsoft.com/fwlink/?linkid=14202")]
public int NonpagedSystemMemorySize { get { throw null; } }
public long NonpagedSystemMemorySize64 { get { throw null; } }
[System.ObsoleteAttribute("This property has been deprecated. Please use System.Diagnostics.Process.PagedMemorySize64 instead. https://go.microsoft.com/fwlink/?linkid=14202")]
public int PagedMemorySize { get { throw null; } }
public long PagedMemorySize64 { get { throw null; } }
[System.ObsoleteAttribute("This property has been deprecated. Please use System.Diagnostics.Process.PagedSystemMemorySize64 instead. https://go.microsoft.com/fwlink/?linkid=14202")]
public int PagedSystemMemorySize { get { throw null; } }
public long PagedSystemMemorySize64 { get { throw null; } }
[System.ObsoleteAttribute("This property has been deprecated. Please use System.Diagnostics.Process.PeakPagedMemorySize64 instead. https://go.microsoft.com/fwlink/?linkid=14202")]
public int PeakPagedMemorySize { get { throw null; } }
public long PeakPagedMemorySize64 { get { throw null; } }
[System.ObsoleteAttribute("This property has been deprecated. Please use System.Diagnostics.Process.PeakVirtualMemorySize64 instead. https://go.microsoft.com/fwlink/?linkid=14202")]
public int PeakVirtualMemorySize { get { throw null; } }
public long PeakVirtualMemorySize64 { get { throw null; } }
[System.ObsoleteAttribute("This property has been deprecated. Please use System.Diagnostics.Process.PeakWorkingSet64 instead. https://go.microsoft.com/fwlink/?linkid=14202")]
public int PeakWorkingSet { get { throw null; } }
public long PeakWorkingSet64 { get { throw null; } }
public bool PriorityBoostEnabled { get { throw null; } set { } }
public System.Diagnostics.ProcessPriorityClass PriorityClass { get { throw null; } set { } }
[System.ObsoleteAttribute("This property has been deprecated. Please use System.Diagnostics.Process.PrivateMemorySize64 instead. https://go.microsoft.com/fwlink/?linkid=14202")]
public int PrivateMemorySize { get { throw null; } }
public long PrivateMemorySize64 { get { throw null; } }
public System.TimeSpan PrivilegedProcessorTime { get { throw null; } }
public string ProcessName { get { throw null; } }
public System.IntPtr ProcessorAffinity { get { throw null; } set { } }
public bool Responding { get { throw null; } }
public Microsoft.Win32.SafeHandles.SafeProcessHandle SafeHandle { get { throw null; } }
public int SessionId { get { throw null; } }
public System.IO.StreamReader StandardError { get { throw null; } }
public System.IO.StreamWriter StandardInput { get { throw null; } }
public System.IO.StreamReader StandardOutput { get { throw null; } }
public System.Diagnostics.ProcessStartInfo StartInfo { get { throw null; } set { } }
public System.DateTime StartTime { get { throw null; } }
public System.ComponentModel.ISynchronizeInvoke? SynchronizingObject { get { throw null; } set { } }
public System.Diagnostics.ProcessThreadCollection Threads { get { throw null; } }
public System.TimeSpan TotalProcessorTime { get { throw null; } }
public System.TimeSpan UserProcessorTime { get { throw null; } }
[System.ObsoleteAttribute("This property has been deprecated. Please use System.Diagnostics.Process.VirtualMemorySize64 instead. https://go.microsoft.com/fwlink/?linkid=14202")]
public int VirtualMemorySize { get { throw null; } }
public long VirtualMemorySize64 { get { throw null; } }
[System.ObsoleteAttribute("This property has been deprecated. Please use System.Diagnostics.Process.WorkingSet64 instead. https://go.microsoft.com/fwlink/?linkid=14202")]
public int WorkingSet { get { throw null; } }
public long WorkingSet64 { get { throw null; } }
public event System.Diagnostics.DataReceivedEventHandler? ErrorDataReceived { add { } remove { } }
public event System.EventHandler Exited { add { } remove { } }
public event System.Diagnostics.DataReceivedEventHandler? OutputDataReceived { add { } remove { } }
public void BeginErrorReadLine() { }
public void BeginOutputReadLine() { }
public void CancelErrorRead() { }
public void CancelOutputRead() { }
public void Close() { }
public bool CloseMainWindow() { throw null; }
protected override void Dispose(bool disposing) { }
public static void EnterDebugMode() { }
public static System.Diagnostics.Process GetCurrentProcess() { throw null; }
public static System.Diagnostics.Process GetProcessById(int processId) { throw null; }
public static System.Diagnostics.Process GetProcessById(int processId, string machineName) { throw null; }
public static System.Diagnostics.Process[] GetProcesses() { throw null; }
public static System.Diagnostics.Process[] GetProcesses(string machineName) { throw null; }
public static System.Diagnostics.Process[] GetProcessesByName(string? processName) { throw null; }
public static System.Diagnostics.Process[] GetProcessesByName(string? processName, string machineName) { throw null; }
public void Kill() { }
public void Kill(bool entireProcessTree) { }
public static void LeaveDebugMode() { }
protected void OnExited() { }
public void Refresh() { }
public bool Start() { throw null; }
public static System.Diagnostics.Process? Start(System.Diagnostics.ProcessStartInfo startInfo) { throw null; }
public static System.Diagnostics.Process Start(string fileName) { throw null; }
public static System.Diagnostics.Process Start(string fileName, string arguments) { throw null; }
[System.CLSCompliantAttribute(false)]
public static System.Diagnostics.Process Start(string fileName, string userName, System.Security.SecureString password, string domain) { throw null; }
[System.CLSCompliantAttribute(false)]
public static System.Diagnostics.Process Start(string fileName, string arguments, string userName, System.Security.SecureString password, string domain) { throw null; }
public override string ToString() { throw null; }
public void WaitForExit() { }
public bool WaitForExit(int milliseconds) { throw null; }
public System.Threading.Tasks.Task WaitForExitAsync(System.Threading.CancellationToken cancellationToken = default) { throw null; }
public bool WaitForInputIdle() { throw null; }
public bool WaitForInputIdle(int milliseconds) { throw null; }
}
public partial class ProcessModule : System.ComponentModel.Component
{
internal ProcessModule() { }
public System.IntPtr BaseAddress { get { throw null; } }
public System.IntPtr EntryPointAddress { get { throw null; } }
public string? FileName { get { throw null; } }
public System.Diagnostics.FileVersionInfo FileVersionInfo { get { throw null; } }
public int ModuleMemorySize { get { throw null; } }
public string? ModuleName { get { throw null; } }
public override string ToString() { throw null; }
}
public partial class ProcessModuleCollection : System.Collections.ReadOnlyCollectionBase
{
protected ProcessModuleCollection() { }
public ProcessModuleCollection(System.Diagnostics.ProcessModule[] processModules) { }
public System.Diagnostics.ProcessModule this[int index] { get { throw null; } }
public bool Contains(System.Diagnostics.ProcessModule module) { throw null; }
public void CopyTo(System.Diagnostics.ProcessModule[] array, int index) { }
public int IndexOf(System.Diagnostics.ProcessModule module) { throw null; }
}
public enum ProcessPriorityClass
{
Normal = 32,
Idle = 64,
High = 128,
RealTime = 256,
BelowNormal = 16384,
AboveNormal = 32768,
}
public sealed partial class ProcessStartInfo
{
public ProcessStartInfo() { }
public ProcessStartInfo(string fileName) { }
public ProcessStartInfo(string fileName, string arguments) { }
public System.Collections.ObjectModel.Collection<string> ArgumentList { get { throw null; } }
public string Arguments { get { throw null; } set { } }
public bool CreateNoWindow { get { throw null; } set { } }
public string Domain { get { throw null; } set { } }
public System.Collections.Generic.IDictionary<string, string?> Environment { get { throw null; } }
public System.Collections.Specialized.StringDictionary EnvironmentVariables { get { throw null; } }
public bool ErrorDialog { get { throw null; } set { } }
public System.IntPtr ErrorDialogParentHandle { get { throw null; } set { } }
public string FileName { get { throw null; } set { } }
public bool LoadUserProfile { get { throw null; } set { } }
[System.CLSCompliantAttribute(false)]
public System.Security.SecureString? Password { get { throw null; } set { } }
public string? PasswordInClearText { get { throw null; } set { } }
public bool RedirectStandardError { get { throw null; } set { } }
public bool RedirectStandardInput { get { throw null; } set { } }
public bool RedirectStandardOutput { get { throw null; } set { } }
public System.Text.Encoding? StandardErrorEncoding { get { throw null; } set { } }
public System.Text.Encoding? StandardInputEncoding { get { throw null; } set { } }
public System.Text.Encoding? StandardOutputEncoding { get { throw null; } set { } }
public string UserName { get { throw null; } set { } }
public bool UseShellExecute { get { throw null; } set { } }
[System.ComponentModel.DefaultValueAttribute("")]
public string Verb { get { throw null; } set { } }
public string[] Verbs { get { throw null; } }
[System.ComponentModel.DefaultValueAttribute(System.Diagnostics.ProcessWindowStyle.Normal)]
public System.Diagnostics.ProcessWindowStyle WindowStyle { get { throw null; } set { } }
public string WorkingDirectory { get { throw null; } set { } }
}
public partial class ProcessThread : System.ComponentModel.Component
{
internal ProcessThread() { }
public int BasePriority { get { throw null; } }
public int CurrentPriority { get { throw null; } }
public int Id { get { throw null; } }
public int IdealProcessor { set { } }
public bool PriorityBoostEnabled { get { throw null; } set { } }
public System.Diagnostics.ThreadPriorityLevel PriorityLevel { get { throw null; } set { } }
public System.TimeSpan PrivilegedProcessorTime { get { throw null; } }
public System.IntPtr ProcessorAffinity { set { } }
public System.IntPtr StartAddress { get { throw null; } }
public System.DateTime StartTime { get { throw null; } }
public System.Diagnostics.ThreadState ThreadState { get { throw null; } }
public System.TimeSpan TotalProcessorTime { get { throw null; } }
public System.TimeSpan UserProcessorTime { get { throw null; } }
public System.Diagnostics.ThreadWaitReason WaitReason { get { throw null; } }
public void ResetIdealProcessor() { }
}
public partial class ProcessThreadCollection : System.Collections.ReadOnlyCollectionBase
{
protected ProcessThreadCollection() { }
public ProcessThreadCollection(System.Diagnostics.ProcessThread[] processThreads) { }
public System.Diagnostics.ProcessThread this[int index] { get { throw null; } }
public int Add(System.Diagnostics.ProcessThread thread) { throw null; }
public bool Contains(System.Diagnostics.ProcessThread thread) { throw null; }
public void CopyTo(System.Diagnostics.ProcessThread[] array, int index) { }
public int IndexOf(System.Diagnostics.ProcessThread thread) { throw null; }
public void Insert(int index, System.Diagnostics.ProcessThread thread) { }
public void Remove(System.Diagnostics.ProcessThread thread) { }
}
public enum ProcessWindowStyle
{
Normal = 0,
Hidden = 1,
Minimized = 2,
Maximized = 3,
}
public enum ThreadPriorityLevel
{
Idle = -15,
Lowest = -2,
BelowNormal = -1,
Normal = 0,
AboveNormal = 1,
Highest = 2,
TimeCritical = 15,
}
public enum ThreadState
{
Initialized = 0,
Ready = 1,
Running = 2,
Standby = 3,
Terminated = 4,
Wait = 5,
Transition = 6,
Unknown = 7,
}
public enum ThreadWaitReason
{
Executive = 0,
FreePage = 1,
PageIn = 2,
SystemAllocation = 3,
ExecutionDelay = 4,
Suspended = 5,
UserRequest = 6,
EventPairHigh = 7,
EventPairLow = 8,
LpcReceive = 9,
LpcReply = 10,
VirtualMemory = 11,
PageOut = 12,
Unknown = 13,
}
}
| 59.490706 | 194 | 0.665938 | [
"MIT"
] | lewurm/runtime | src/libraries/System.Diagnostics.Process/ref/System.Diagnostics.Process.cs | 16,003 | C# |
using System.Collections.Generic;
namespace RazorLight
{
public class TemplateCompilationException : RazorLightException
{
private readonly List<string> compilationErrors;
public IReadOnlyList<string> CompilationErrors => compilationErrors;
public TemplateCompilationException(string message, IEnumerable<string> errors) : base(message)
{
this.compilationErrors = new List<string>();
if (errors != null)
compilationErrors.AddRange(errors);
}
}
}
| 24.894737 | 97 | 0.77167 | [
"Apache-2.0"
] | mcintyre321/RazorLight | src/RazorLight/TemplateCompilationException.cs | 475 | C# |
// Copyright (c) Frandi Dwi 2020. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using TakNotify;
namespace WebApi
{
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.AddControllers();
services
.AddTakNotify()
.AddProvider<TwilioProvider, TwilioOptions>(options =>
{
options.AccountSid = Configuration["Twilio:AccountSid"];
options.AuthToken = Configuration["Twilio:AuthToken"];
}, true);
}
// 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();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
| 29.126984 | 106 | 0.629428 | [
"MIT"
] | TakNotify/TakNotify.Provider.Twilio | samples/WebApi/Startup.cs | 1,835 | C# |
//
// Copyright (c) 2004-2019 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
using NLog.Layouts;
using Xunit;
namespace NLog.UnitTests.LayoutRenderers.Wrappers
{
public class LeftLayoutRendererWrapperTests
{
[Theory]
[InlineData(":length=2", "12")]
[InlineData(":length=1000", "1234567890")]
[InlineData(":length=-1", "")]
[InlineData(":length=0", "")]
public void LeftWrapperTest(string options, string expected)
{
SimpleLayout l = $"${{left:${{message}}{options}}}";
var result = l.Render(LogEventInfo.Create(LogLevel.Debug, "substringTest", "1234567890"));
Assert.Equal(expected, result);
}
}
} | 43.377358 | 102 | 0.712919 | [
"BSD-3-Clause"
] | ajitpeter/NLog | tests/NLog.UnitTests/LayoutRenderers/Wrappers/LeftLayoutRendererWrapperTests.cs | 2,299 | C# |
using Sharpen;
namespace junit.framework
{
[Sharpen.NakedStub]
public class TestResult
{
}
}
| 9.8 | 25 | 0.734694 | [
"Apache-2.0"
] | Conceptengineai/XobotOS | android/generated/junit/framework/TestResult.cs | 98 | C# |
#region License
/*
Copyright © 2014-2021 European Support Limited
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 Amdocs.Ginger.Common;
using Amdocs.Ginger.Repository;
using GingerCoreNET.SolutionRepositoryLib.RepositoryObjectsLib.PlatformsLib;
using System;
using System.Collections.Generic;
using System.Linq;
using Amdocs.Ginger.Common.InterfacesLib;
using Amdocs.Ginger.CoreNET;
using GingerCore.Actions.WebServices;
using Amdocs.Ginger.Common.Enums;
namespace GingerCore.Actions
{
public class ActWebService : Act, IObsoleteAction
{
public override string ActionDescription { get { return "Web Service Action"; } }
public override string ActionUserDescription { get { return string.Empty; } }
public override List<ePlatformType> LegacyActionPlatformsList { get { return Platforms; } }
public override void ActionUserRecommendedUseCase(ITextBoxFormatter TBH)
{
}
public override string ActionEditPage { get { return "WebServices.ActWebServiceEditPage"; } }
public override bool ObjectLocatorConfigsNeeded { get { return false; } }
public override bool ValueConfigsNeeded { get { return false; } }
// return the list of platforms this action is supported on
public override List<ePlatformType> Platforms
{
get
{
if (mPlatforms.Count == 0)
{
mPlatforms.Add(ePlatformType.WebServices);
}
return mPlatforms;
}
}
public new static partial class Fields
{
public static string URL = "URL";
public static string SOAPAction = "SOAPAction";
public static string XMLfileName = "XMLfileName";
public static string URLUser = "URLUser";
public static string URLPass = "URLPass";
public static string URLDomain = "URLDomain";
public static string DoValidationChkbox = "DoValidationChkbox";
}
public override List<ObservableList<ActInputValue>> GetInputValueListForVEProcessing()
{
List<ObservableList<ActInputValue>> list = new List<ObservableList<ActInputValue>>();
list.Add(DynamicXMLElements);
return list;
}
bool IObsoleteAction.IsObsoleteForPlatform(ePlatformType actionPlatform)
{
if (actionPlatform == ePlatformType.WebServices || actionPlatform == ePlatformType.NA)
{
return true;
}
else
{
return false;
}
}
Act IObsoleteAction.GetNewAction()
{
AutoMapper.MapperConfiguration mapperConfiguration = new AutoMapper.MapperConfiguration(cfg => { cfg.CreateMap<Act, ActWebAPISoap>(); });
ActWebAPISoap convertedActWebAPISoap = mapperConfiguration.CreateMapper().Map<Act, ActWebAPISoap>(this);
convertedActWebAPISoap.AddOrUpdateInputParamValueAndCalculatedValue(ActWebAPIBase.Fields.EndPointURL, this.URL.Value);
convertedActWebAPISoap.AddOrUpdateInputParamValueAndCalculatedValue(ActWebAPIBase.Fields.AuthorizationType, ApplicationAPIUtils.eAuthType.NoAuthentication.ToString());
convertedActWebAPISoap.AddOrUpdateInputParamValueAndCalculatedValue(ActWebAPIBase.Fields.SecurityType, ApplicationAPIUtils.eSercurityType.None.ToString());
convertedActWebAPISoap.AddOrUpdateInputParamValueAndCalculatedValue(ActWebAPIBase.Fields.CertificateTypeRadioButton, ApplicationAPIUtils.eCretificateType.AllSSL.ToString());
if(!string.IsNullOrEmpty(this.URLDomain.Value) || (!string.IsNullOrEmpty(this.URLUser.Value) && !string.IsNullOrEmpty(this.URLPass.Value )))
{
convertedActWebAPISoap.AddOrUpdateInputParamValueAndCalculatedValue(ActWebAPIBase.Fields.NetworkCredentialsRadioButton, ApplicationAPIUtils.eNetworkCredentials.Custom.ToString());
convertedActWebAPISoap.AddOrUpdateInputParamValueAndCalculatedValue(ActWebAPIBase.Fields.URLDomain, this.URLDomain.Value);
convertedActWebAPISoap.AddOrUpdateInputParamValueAndCalculatedValue(ActWebAPIBase.Fields.URLUser, this.URLUser.Value);
convertedActWebAPISoap.AddOrUpdateInputParamValueAndCalculatedValue(ActWebAPIBase.Fields.URLPass, this.URLPass.Value);
}
else
{
convertedActWebAPISoap.AddOrUpdateInputParamValueAndCalculatedValue(ActWebAPIBase.Fields.NetworkCredentialsRadioButton, ApplicationAPIUtils.eNetworkCredentials.Default.ToString());
}
if (!string.IsNullOrEmpty(this.XMLfileName.ToString()))
{
convertedActWebAPISoap.AddOrUpdateInputParamValueAndCalculatedValue(ActWebAPIBase.Fields.RequestBodyTypeRadioButton, ApplicationAPIUtils.eRequestBodyType.TemplateFile.ToString());
convertedActWebAPISoap.AddOrUpdateInputParamValueAndCalculatedValue(ActWebAPIBase.Fields.TemplateFileNameFileBrowser, this.XMLfileName.Value);
}
if (convertedActWebAPISoap.ReturnValues != null && convertedActWebAPISoap.ReturnValues.Count != 0)
{
//Old web service action add response as --> FullReponseXML
//And new adds it as Response:
// so we update it when converting from old action to new
ActReturnValue ARC = convertedActWebAPISoap.ReturnValues.Where(x => x.Param == "FullReponseXML").FirstOrDefault();
if (ARC != null)
{
ARC.Param = "Response:";
if(!string.IsNullOrEmpty(ARC.Expected))
{
ARC.Expected = XMLDocExtended.PrettyXml(ARC.Expected);
}
}
}
convertedActWebAPISoap.DynamicElements = this.DynamicXMLElements;
return convertedActWebAPISoap;
}
Type IObsoleteAction.TargetAction()
{
return typeof(ActWebAPISoap);
}
string IObsoleteAction.TargetActionTypeName()
{
ActWebAPISoap newActApiSoap = new ActWebAPISoap();
return newActApiSoap.ActionDescription;
}
ePlatformType IObsoleteAction.GetTargetPlatform()
{
return ePlatformType.WebServices;
}
public ActInputValue URL { get { return GetOrCreateInputParam(Fields.URL); } }
[IsSerializedForLocalRepository]
public ObservableList<ActInputValue> DynamicXMLElements = new ObservableList<ActInputValue>();
public ActInputValue SOAPAction { get { return GetOrCreateInputParam(Fields.SOAPAction); } }
public ActInputValue XMLfileName { get { return GetOrCreateInputParam(Fields.XMLfileName); } }
public ActInputValue URLUser { get { return GetOrCreateInputParam(Fields.URLUser); } }
public ActInputValue URLPass { get { return GetOrCreateInputParam(Fields.URLPass); } }
public ActInputValue URLDomain { get { return GetOrCreateInputParam(Fields.URLDomain); } }
[IsSerializedForLocalRepository]
public bool DoValidationChkbox { get; set; }
public override String ActionType
{
get
{
return "ActWebService";
}
}
public override eImageType Image { get { return eImageType.Exchange; } }
}
}
| 43.219251 | 196 | 0.670502 | [
"Apache-2.0"
] | Ginger-Automation/Ginger | Ginger/GingerCoreNET/ActionsLib/Webservices/ActWebService.cs | 8,083 | C# |
using Microsoft.Xrm.Sdk.Messages;
using System;
namespace AlbanianXrm.SolutionPackager.Models
{
internal class ImportSolutionRequest
{
public Guid ImportJobId { get; set; }
public ExecuteAsyncResponse ExecuteAsyncResponse { get; set; }
}
}
| 22.5 | 70 | 0.718519 | [
"MIT"
] | albanian-xrm/Solution-Packager | AlbanianXrm.SolutionPackager.Tool/Models/ImportSolutionRequest.cs | 272 | C# |
using OpenBots.Core.Script;
using OpenBots.Core.UI.Forms;
using OpenBots.UI.Forms.Supplement_Forms;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Windows.Forms;
namespace OpenBots.UI.Forms
{
public partial class frmScriptElements : UIForm
{
public List<ScriptElement> ScriptElements { get; set; }
public string ScriptName { get; set; }
private TreeNode _userElementParentNode;
private string _emptyValue = "(no default value)";
#region Initialization and Form Load
public frmScriptElements()
{
InitializeComponent();
}
private void frmScriptElements_Load(object sender, EventArgs e)
{
//initialize
ScriptElements = ScriptElements.OrderBy(x => x.ElementName).ToList();
_userElementParentNode = InitializeNodes("My Task Elements", ScriptElements);
ExpandUserElementNode();
lblMainLogo.Text = ScriptName + " elements";
}
private TreeNode InitializeNodes(string parentName, List<ScriptElement> elements)
{
//create a root node (parent)
TreeNode parentNode = new TreeNode(parentName);
//add each item to parent
foreach (var item in elements)
AddUserElementNode(parentNode, item.ElementName, item.ElementValue);
//add parent to treeview
tvScriptElements.Nodes.Add(parentNode);
//return parent and utilize if needed
return parentNode;
}
#endregion
#region Add/Cancel Buttons
private void uiBtnOK_Click(object sender, EventArgs e)
{
//return success result
DialogResult = DialogResult.OK;
}
private void uiBtnCancel_Click(object sender, EventArgs e)
{
//cancel and close
DialogResult = DialogResult.Cancel;
}
#endregion
#region Add/Edit Elements
private void uiBtnNew_Click(object sender, EventArgs e)
{
//create element editing form
frmAddElement addElementForm = new frmAddElement();
addElementForm.ScriptElements = ScriptElements;
ExpandUserElementNode();
//validate if user added element
if (addElementForm.ShowDialog() == DialogResult.OK)
{
//add newly edited node
AddUserElementNode(_userElementParentNode, addElementForm.txtElementName.Text, addElementForm.ElementValueDT);
ScriptElements.Add(new ScriptElement
{
ElementName = addElementForm.txtElementName.Text,
ElementValue = addElementForm.ElementValueDT
});
}
addElementForm.Dispose();
}
private void tvScriptElements_DoubleClick(object sender, EventArgs e)
{
//handle double clicks outside
if (tvScriptElements.SelectedNode == null)
return;
//if parent was selected return
if (tvScriptElements.SelectedNode.Parent == null)
return;
//top node check
var topNode = GetSelectedTopNode();
if (topNode.Text != "My Task Elements")
return;
ScriptElement element;
string elementName;
DataTable elementValue;
TreeNode parentNode;
if(tvScriptElements.SelectedNode.Nodes.Count == 0)
{
parentNode = tvScriptElements.SelectedNode.Parent;
elementName = tvScriptElements.SelectedNode.Parent.Text;
}
else
{
parentNode = tvScriptElements.SelectedNode;
elementName = tvScriptElements.SelectedNode.Text;
}
element = ScriptElements.Where(x => x.ElementName == elementName).FirstOrDefault();
elementValue = element.ElementValue;
//create element editing form
frmAddElement addElementForm = new frmAddElement(elementName, elementValue);
addElementForm.ScriptElements = ScriptElements;
ExpandUserElementNode();
//validate if user added element
if (addElementForm.ShowDialog() == DialogResult.OK)
{
//remove parent
parentNode.Remove();
AddUserElementNode(_userElementParentNode, addElementForm.txtElementName.Text, addElementForm.ElementValueDT);
}
addElementForm.Dispose();
}
private void AddUserElementNode(TreeNode parentNode, string elementName, DataTable elementValue)
{
//add new node
var childNode = new TreeNode(elementName);
for (int i = 0; i < elementValue.Rows.Count; i++)
{
if (!string.IsNullOrEmpty(elementValue.Rows[i][2].ToString()))
{
TreeNode elementValueNode = new TreeNode($"ValueNode{i}");
string enabled = elementValue.Rows[i][0].ToString();
enabled = enabled == "True" ? "Enabled" : "Disabled";
elementValueNode.Text = $"{enabled} - {elementValue.Rows[i][1]} - {elementValue.Rows[i][2]}";
childNode.Nodes.Add(elementValueNode);
}
}
if (childNode.Nodes.Count == 0)
{
TreeNode elementValueNode = new TreeNode($"ValueNodeEmpty");
elementValueNode.Text = _emptyValue;
childNode.Nodes.Add(elementValueNode);
}
parentNode.Nodes.Add(childNode);
ExpandUserElementNode();
}
private void ExpandUserElementNode()
{
if (_userElementParentNode != null)
_userElementParentNode.Expand();
}
private void tvScriptElements_KeyDown(object sender, KeyEventArgs e)
{
//handling outside
if (tvScriptElements.SelectedNode == null)
return;
//if parent was selected return
if (tvScriptElements.SelectedNode.Parent == null)
{
//user selected top parent
return;
}
//top node check
var topNode = GetSelectedTopNode();
if (topNode.Text != "My Task Elements")
return;
//if user selected delete
if (e.KeyCode == Keys.Delete)
{
//determine which node is the parent
TreeNode parentNode;
if (tvScriptElements.SelectedNode.Nodes.Count == 0)
parentNode = tvScriptElements.SelectedNode.Parent;
else
parentNode = tvScriptElements.SelectedNode;
//remove parent node
string elementName = parentNode.Text;
ScriptElement element = ScriptElements.Where(x => x.ElementName == elementName).FirstOrDefault();
ScriptElements.Remove(element);
parentNode.Remove();
}
}
private TreeNode GetSelectedTopNode()
{
TreeNode node = tvScriptElements.SelectedNode;
while (node.Parent != null)
node = node.Parent;
return node;
}
#endregion
}
} | 33.742222 | 126 | 0.56362 | [
"Apache-2.0"
] | arenabilgisayar/OpenBots.Studio | OpenBots.Studio/UI/Forms/frmScriptElements.cs | 7,594 | C# |
using System;
using System.Threading.Tasks;
namespace R5T.Dunbar.D001.DatabaseConnectionConfiguration
{
public interface IJsonFilePathProvider
{
Task<string> GetJsonFilePath();
}
}
| 17 | 57 | 0.735294 | [
"MIT"
] | SafetyCone/R5T.Dunbar | source/R5T.Dunbar.D001.Base/Code/Services/Definitions/DatabaseConnectionConfiguration/IJsonFilePathProvider.cs | 206 | C# |
namespace TimeRecorder.Core.Models
{
public class EmailMessage
{
public string To { get; set; }
public string Subject { get; set; }
public string Body { get; set; }
}
}
| 20.6 | 43 | 0.587379 | [
"MIT"
] | g-child/serverless-timerecorder | TimeRecorder.Core/Models/EmailMessage.cs | 208 | C# |
using System;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CommandDotNet.Diagnostics.Parse;
using CommandDotNet.Directives;
using CommandDotNet.Execution;
using CommandDotNet.Tokens;
namespace CommandDotNet.Diagnostics
{
internal static class ParseDirective
{
internal static AppRunner UseParseDirective(this AppRunner appRunner)
{
return appRunner.Configure(c =>
{
c.UseMiddleware(ConfigureParseReportByTokenTransform, MiddlewareSteps.ParseDirective);
c.UseMiddleware(ParseReportByArg, MiddlewareSteps.BindValues + 100);
});
}
// adapted from https://github.com/dotnet/command-line-api directives
private static Task<int> ConfigureParseReportByTokenTransform(CommandContext commandContext, ExecutionDelegate next)
{
if (!commandContext.Tokens.TryGetDirective(Resources.A.ParseDirective_parse_lc, out string? value))
{
return next(commandContext);
}
var parseContext = ParseContext.Parse(value!);
commandContext.Services.AddOrUpdate(parseContext);
CaptureTransformations(commandContext, parseContext);
var writer = commandContext.Console.Out;
void WriteLine(string? line)
{
if (writer == null)
{
throw new ArgumentNullException(nameof(writer));
}
// avoid extra new lines
writer.Write(line);
if (!line?.EndsWith(Environment.NewLine) ?? false)
{
writer.Write(Environment.NewLine);
}
}
try
{
// ParseReportByArg is run within this pipeline
var result = next(commandContext);
if (!parseContext.Reported)
{
// in case ParseReportByArg wasn't run due to parsing errors,
// output this the transformations as a temporary aid
writer.WriteLine();
writer.WriteLine(commandContext.ParseResult!.HelpWasRequested()
? Resources.A.ParseDirective_Help_was_requested
: Resources.A.ParseDirective_Unable_to_map_tokens_to_arguments);
WriteLine(parseContext.Transformations.ToString());
}
else if (parseContext.IncludeTokenization || parseContext.IncludeRawCommandLine)
{
if (parseContext.IncludeTokenization)
{
WriteLine(parseContext.Transformations.ToString());
}
if (parseContext.IncludeRawCommandLine)
{
WriteLine(commandContext.Environment.CommandLine);
}
}
else
{
writer.WriteLine();
writer.WriteLine(Resources.A.ParseDirective_Usage(
ParseContext.IncludeTransformationsArgName,
ParseContext.IncludeRawCommandLineArgName));
}
return result;
}
catch (Exception) when (!parseContext.Reported)
{
// in case ParseReportByArg wasn't run due to parsing errors,
// output this the transformations as a temporary aid
writer.WriteLine();
writer.WriteLine(Resources.A.ParseDirective_Unable_to_map_tokens_to_arguments);
WriteLine(parseContext.Transformations.ToString());
throw;
}
}
private static Task<int> ParseReportByArg(CommandContext commandContext, ExecutionDelegate next)
{
var parseContext = commandContext.Services.GetOrDefault<ParseContext>();
if (parseContext != null)
{
ParseReporter.Report(
commandContext,
includeRawCommandLine: parseContext.IncludeRawCommandLine,
writeln: s => commandContext.Console.Out.WriteLine(s));
parseContext.Reported = true;
return ExitCodes.Success;
}
return next(commandContext);
}
private static void CaptureTransformations(CommandContext commandContext, ParseContext parseContext)
{
void WriteLine(string? ln) => parseContext.Transformations.AppendLine(ln);
WriteLine(null);
WriteLine($"{Resources.A.ParseDirective_token_transformations_lc}:");
WriteLine(null);
CaptureTransformation(WriteLine, commandContext.Tokens, $">>> {Resources.A.ParseDirective_from_shell_lc}");
commandContext.AppConfig.TokenizationEvents.OnTokenTransformation += args =>
{
if (args.PreTransformTokens.Count == args.PostTransformTokens.Count &&
Enumerable.Range(0, args.PreTransformTokens.Count)
.All(i => args.PreTransformTokens[i] == args.PostTransformTokens[i]))
{
CaptureTransformation(WriteLine, null,
$">>> {Resources.A.ParseDirective_after_no_changes(args.Transformation.Name)}");
}
else
{
CaptureTransformation(WriteLine, args.PostTransformTokens,
$">>> {Resources.A.ParseDirective_after(args.Transformation.Name)}");
}
};
}
private static void CaptureTransformation(Action<string> writeLine, TokenCollection? args, string description)
{
writeLine(description);
if (args is { })
{
var maxTokenTypeNameLength = Enum.GetNames(typeof(TokenType)).Max(n => n.Length);
foreach (var arg in args)
{
var outputFormat = $" {{0, -{maxTokenTypeNameLength}}}: {{1}}";
writeLine(string.Format(outputFormat, arg.TokenType, arg.RawValue));
}
}
}
private class ParseContext
{
internal const string IncludeTransformationsArgName = "t";
internal const string IncludeRawCommandLineArgName = "raw";
internal bool IncludeTokenization;
internal bool IncludeRawCommandLine;
internal bool Reported;
internal readonly StringBuilder Transformations = new();
internal static ParseContext Parse(string value)
{
var parts = value.Split(":".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
if (parts.Length <= 1)
{
return new ParseContext();
}
var settings = parts[1].Split(';')
.Select(p => p.Split('='))
.ToDictionary(p => p[0], p => p.Length > 1 ? p[1] : null, StringComparer.OrdinalIgnoreCase);
return new ParseContext
{
IncludeTokenization = settings.ContainsKey(IncludeTransformationsArgName),
IncludeRawCommandLine = settings.ContainsKey(IncludeRawCommandLineArgName)
};
}
}
}
} | 39.893617 | 124 | 0.557333 | [
"MIT"
] | bilal-fazlani/CommandDotNet | CommandDotNet/Diagnostics/ParseDirective.cs | 7,502 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Zl.AutoUpgrade.Core;
namespace Demo.Updater
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
private Thread _updateThread;
private IUpgradeService _upgradeService;
public MainWindow()
{
InitializeComponent();
this.Loaded += MainWindow_Loaded;
}
private void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
if (!AutoUpdater.TryResolveUpgradeService(out _upgradeService))
{
this.Close();
}
_updateThread = new Thread(this.DoUpdate);
_updateThread.Start();
}
private void DoUpdate()
{
if (_upgradeService.DetectNewVersion())
{
_upgradeService.UpgradeStarted += UpgradeService_UpgradeStarted;
_upgradeService.UpgradeProgressChanged += UpgradeService_UpgradeProgressChanged;
_upgradeService.UpgradeEnded += UpgradeService_UpgradeEnded;
_upgradeService.TryUpgradeNow();
_upgradeService.UpgradeStarted -= UpgradeService_UpgradeStarted;
_upgradeService.UpgradeProgressChanged -= UpgradeService_UpgradeProgressChanged;
_upgradeService.UpgradeEnded -= UpgradeService_UpgradeEnded;
}
}
private void UpgradeService_UpgradeStarted(object sender, EventArgs e)
{
this.Dispatcher.BeginInvoke(new Action(() =>
{
this.txtlab.Text = "检测到新版本,正在升级...";
}));
}
private void UpgradeService_UpgradeProgressChanged(object sender, UpgradeProgressArgs e)
{
this.Dispatcher.BeginInvoke(new Action(() =>
{
this.probar.Value = e.ProgressPercent;
this.txtlab.Text = string.Format("正在升级({0:P0})...", e.ProgressPercent);
}));
}
private void UpgradeService_UpgradeEnded(object sender, UpgradeEndedArgs e)
{
this.Dispatcher.BeginInvoke(new Action(() =>
{
if (e.EndedType == UpgradeEndedType.Completed)
{
this.txtlab.Text = "升级成功";
this.DialogResult = true;
}
else if (e.ErrorException is ThreadAbortException)
{
this.txtlab.Text = "已取消升级";
}
else
{
this.txtlab.Text = "升级中遇到错误";
MessageBox.Show(this, e.ErrorMessage, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
this.DialogResult = true;
}
}));
}
private void Button_Click(object sender, RoutedEventArgs e)
{
this.DialogResult = false;
}
protected override void OnClosed(EventArgs e)
{
base.OnClosed(e);
if (this.DialogResult != true)
{
//取消升级
if (_updateThread != null)
_updateThread.Abort();
}
}
}
}
| 31.991071 | 108 | 0.56489 | [
"MIT"
] | zenglo/AutoUpgrade | src/Demo.Updater/MainWindow.xaml.cs | 3,669 | C# |
/********************************************************************************
* The MIT License (MIT)
*
* Copyright 2018+ Cet Electronics.
*
* Based on the original work by Apcera Inc.
* https://github.com/nats-io/csharp-nats
*
* 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.Threading;
using System.Threading.Tasks;
namespace Cet.NATS.Client
{
/// <summary>
/// <see cref="ReactiveSubscription"/> asynchronously delivers messages to listeners
/// </summary>
internal sealed class ReactiveSubscription
: SubscriptionBase, IReactiveSubscription, ISubscription
{
/// <summary>
/// Creates an instance of <see cref="ReactiveSubscription"/>
/// </summary>
/// <param name="owner"></param>
/// <param name="sid"></param>
/// <param name="subject"></param>
/// <param name="queue"></param>
/// <param name="syncHandler"></param>
/// <param name="asyncHandler"></param>
internal ReactiveSubscription(
SubscriptionPool owner,
long sid,
string subject,
string queue,
Action<MsgOut, CancellationToken> syncHandler,
Func<MsgOut, CancellationToken, Task> asyncHandler
)
: base(owner, sid, subject, queue, useCache: true)
{
this._syncHandler = syncHandler;
this._asyncHandler = asyncHandler;
this._cts = new CancellationTokenSource();
}
private readonly Action<MsgOut, CancellationToken> _syncHandler;
private readonly Func<MsgOut, CancellationToken, Task> _asyncHandler;
private readonly CancellationTokenSource _cts;
/// <summary>
/// Indicates whether any pending message is waiting to be delivered
/// </summary>
internal bool AnyPending;
/// <summary>
/// Processe the dispatched message
/// </summary>
/// <param name="message"></param>
protected override void ProcessOutgoingMessage(MsgOut message)
{
this.Owner.ReactiveSubscriptionSignal(this);
}
/// <summary>
/// Dispatches all the pending messages to the listener
/// </summary>
internal void ForwardPendingMessages()
{
if (this._syncHandler != null)
{
//dequeues, and delivers in the sync-fashion
while (
this._cts.IsCancellationRequested == false &&
this.TryDequeueSinglePendingMessage(out MsgOut message)
)
{
try
{
this._syncHandler(message, this._cts.Token);
}
catch (OperationCanceledException)
{
break;
}
catch
{
//do nothing: it's up to the handler to catch exceptions
}
};
}
else if (this._cts.IsCancellationRequested == false)
{
//starts a fire-and-forget task, to dequeue and deliver the pending messages
Task.Factory.StartNew(this.ForwardPendingMessagesAsync)
.GetAwaiter()
.GetResult();
}
}
/// <summary>
/// Dispatches all the pending messages to the listener
/// </summary>
/// <remarks>
/// The sequence of the messages is preserved within a single dequeuing session,
/// that is, each task like the following.
/// However, there's no guarantee to preserve the original publisher sequence,
/// because it may span here across many different parallel tasks.
/// </remarks>
/// <returns></returns>
private async Task ForwardPendingMessagesAsync()
{
//dequeues, and delivers in the async-fashion
while (
this._cts.IsCancellationRequested == false &&
this.TryDequeueSinglePendingMessage(out MsgOut message)
)
{
try
{
await this._asyncHandler(message, this._cts.Token);
}
catch (OperationCanceledException)
{
break;
}
catch
{
//do nothing: it's up to the handler to catch exceptions
}
};
}
/// <summary>
/// Custom disposal of the local resources
/// </summary>
/// <param name="disposing"></param>
protected override void Dispose(bool disposing)
{
if (disposing)
{
this._cts.Cancel();
}
base.Dispose(disposing);
}
}
}
| 35.364162 | 92 | 0.547074 | [
"MIT"
] | highfield/Cet.NATS.Client | Cet.NATS.Client/sub/ReactiveSubscription.cs | 6,120 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
namespace Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801
{
using static Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Extensions;
/// <summary>Resource name availability request content.</summary>
public partial class ResourceNameAvailabilityRequest
{
/// <summary>
/// <c>AfterFromJson</c> will be called after the json deserialization has finished, allowing customization of the object
/// before it is returned. Implement this method in a partial class to enable this behavior
/// </summary>
/// <param name="json">The JsonNode that should be deserialized into this object.</param>
partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonObject json);
/// <summary>
/// <c>AfterToJson</c> will be called after the json serialization has finished, allowing customization of the <see cref="Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonObject"
/// /> before it is returned. Implement this method in a partial class to enable this behavior
/// </summary>
/// <param name="container">The JSON container that the serialization result will be placed in.</param>
partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonObject container);
/// <summary>
/// <c>BeforeFromJson</c> will be called before the json deserialization has commenced, allowing complete customization of
/// the object before it is deserialized.
/// If you wish to disable the default deserialization entirely, return <c>true</c> in the <paramref name= "returnNow" />
/// output parameter.
/// Implement this method in a partial class to enable this behavior.
/// </summary>
/// <param name="json">The JsonNode that should be deserialized into this object.</param>
/// <param name="returnNow">Determines if the rest of the deserialization should be processed, or if the method should return
/// instantly.</param>
partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonObject json, ref bool returnNow);
/// <summary>
/// <c>BeforeToJson</c> will be called before the json serialization has commenced, allowing complete customization of the
/// object before it is serialized.
/// If you wish to disable the default serialization entirely, return <c>true</c> in the <paramref name="returnNow" /> output
/// parameter.
/// Implement this method in a partial class to enable this behavior.
/// </summary>
/// <param name="container">The JSON container that the serialization result will be placed in.</param>
/// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return
/// instantly.</param>
partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonObject container, ref bool returnNow);
/// <summary>
/// Deserializes a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonNode"/> into an instance of Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IResourceNameAvailabilityRequest.
/// </summary>
/// <param name="node">a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonNode" /> to deserialize from.</param>
/// <returns>
/// an instance of Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IResourceNameAvailabilityRequest.
/// </returns>
public static Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IResourceNameAvailabilityRequest FromJson(Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonNode node)
{
return node is Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonObject json ? new ResourceNameAvailabilityRequest(json) : null;
}
/// <summary>
/// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonObject into a new instance of <see cref="ResourceNameAvailabilityRequest" />.
/// </summary>
/// <param name="json">A Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonObject instance to deserialize from.</param>
internal ResourceNameAvailabilityRequest(Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonObject json)
{
bool returnNow = false;
BeforeFromJson(json, ref returnNow);
if (returnNow)
{
return;
}
{_name = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonString>("name"), out var __jsonName) ? (string)__jsonName : (string)Name;}
{_type = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonString>("type"), out var __jsonType) ? (string)__jsonType : (string)Type;}
{_isFqdn = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonBoolean>("isFqdn"), out var __jsonIsFqdn) ? (bool?)__jsonIsFqdn : IsFqdn;}
AfterFromJson(json);
}
/// <summary>
/// Serializes this instance of <see cref="ResourceNameAvailabilityRequest" /> into a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonNode" />.
/// </summary>
/// <param name="container">The <see cref="Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonObject"/> container to serialize this object into. If the caller
/// passes in <c>null</c>, a new instance will be created and returned to the caller.</param>
/// <param name="serializationMode">Allows the caller to choose the depth of the serialization. See <see cref="Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.SerializationMode"/>.</param>
/// <returns>
/// a serialized instance of <see cref="ResourceNameAvailabilityRequest" /> as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonNode" />.
/// </returns>
public Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.SerializationMode serializationMode)
{
container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonObject();
bool returnNow = false;
BeforeToJson(ref container, ref returnNow);
if (returnNow)
{
return container;
}
AddIf( null != (((object)this._name)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonString(this._name.ToString()) : null, "name" ,container.Add );
AddIf( null != (((object)this._type)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonString(this._type.ToString()) : null, "type" ,container.Add );
AddIf( null != this._isFqdn ? (Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonBoolean((bool)this._isFqdn) : null, "isFqdn" ,container.Add );
AfterToJson(ref container);
return container;
}
}
} | 71.705357 | 262 | 0.692815 | [
"MIT"
] | AlanFlorance/azure-powershell | src/Functions/generated/api/Models/Api20190801/ResourceNameAvailabilityRequest.json.cs | 7,920 | C# |
/*******************************************************************************
* Copyright 2012-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use
* this file except in compliance with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file.
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
* *****************************************************************************
*
* AWS Tools for Windows (TM) PowerShell (TM)
*
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
using System.Text;
using Amazon.PowerShell.Common;
using Amazon.Runtime;
using Amazon.CognitoIdentityProvider;
using Amazon.CognitoIdentityProvider.Model;
namespace Amazon.PowerShell.Cmdlets.CGIP
{
/// <summary>
/// Initiates the authentication flow.
/// </summary>
[Cmdlet("Start", "CGIPAuth", SupportsShouldProcess = true, ConfirmImpact = ConfirmImpact.Medium)]
[OutputType("Amazon.CognitoIdentityProvider.Model.InitiateAuthResponse")]
[AWSCmdlet("Calls the Amazon Cognito Identity Provider InitiateAuth API operation.", Operation = new[] {"InitiateAuth"}, SelectReturnType = typeof(Amazon.CognitoIdentityProvider.Model.InitiateAuthResponse))]
[AWSCmdletOutput("Amazon.CognitoIdentityProvider.Model.InitiateAuthResponse",
"This cmdlet returns an Amazon.CognitoIdentityProvider.Model.InitiateAuthResponse object containing multiple properties. The object can also be referenced from properties attached to the cmdlet entry in the $AWSHistory stack."
)]
public partial class StartCGIPAuthCmdlet : AmazonCognitoIdentityProviderClientCmdlet, IExecutor
{
#region Parameter AnalyticsMetadata_AnalyticsEndpointId
/// <summary>
/// <para>
/// <para>The endpoint ID.</para>
/// </para>
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
public System.String AnalyticsMetadata_AnalyticsEndpointId { get; set; }
#endregion
#region Parameter AuthFlow
/// <summary>
/// <para>
/// <para>The authentication flow for this call to execute. The API action will depend on this
/// value. For example: </para><ul><li><para><code>REFRESH_TOKEN_AUTH</code> will take in a valid refresh token and return new
/// tokens.</para></li><li><para><code>USER_SRP_AUTH</code> will take in <code>USERNAME</code> and <code>SRP_A</code>
/// and return the SRP variables to be used for next challenge execution.</para></li><li><para><code>USER_PASSWORD_AUTH</code> will take in <code>USERNAME</code> and <code>PASSWORD</code>
/// and return the next challenge or tokens.</para></li></ul><para>Valid values include:</para><ul><li><para><code>USER_SRP_AUTH</code>: Authentication flow for the Secure Remote Password (SRP)
/// protocol.</para></li><li><para><code>REFRESH_TOKEN_AUTH</code>/<code>REFRESH_TOKEN</code>: Authentication flow for
/// refreshing the access token and ID token by supplying a valid refresh token.</para></li><li><para><code>CUSTOM_AUTH</code>: Custom authentication flow.</para></li><li><para><code>USER_PASSWORD_AUTH</code>: Non-SRP authentication flow; USERNAME and PASSWORD
/// are passed directly. If a user migration Lambda trigger is set, this flow will invoke
/// the user migration Lambda if the USERNAME is not found in the user pool. </para></li><li><para><code>ADMIN_USER_PASSWORD_AUTH</code>: Admin-based user password authentication.
/// This replaces the <code>ADMIN_NO_SRP_AUTH</code> authentication flow. In this flow,
/// Cognito receives the password in the request instead of using the SRP process to verify
/// passwords.</para></li></ul><para><code>ADMIN_NO_SRP_AUTH</code> is not a valid value.</para>
/// </para>
/// </summary>
#if !MODULAR
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
#else
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true, Mandatory = true)]
[System.Management.Automation.AllowNull]
#endif
[Amazon.PowerShell.Common.AWSRequiredParameter]
[AWSConstantClassSource("Amazon.CognitoIdentityProvider.AuthFlowType")]
public Amazon.CognitoIdentityProvider.AuthFlowType AuthFlow { get; set; }
#endregion
#region Parameter AuthParameter
/// <summary>
/// <para>
/// <para>The authentication parameters. These are inputs corresponding to the <code>AuthFlow</code>
/// that you are invoking. The required values depend on the value of <code>AuthFlow</code>:</para><ul><li><para>For <code>USER_SRP_AUTH</code>: <code>USERNAME</code> (required), <code>SRP_A</code>
/// (required), <code>SECRET_HASH</code> (required if the app client is configured with
/// a client secret), <code>DEVICE_KEY</code></para></li><li><para>For <code>REFRESH_TOKEN_AUTH/REFRESH_TOKEN</code>: <code>REFRESH_TOKEN</code> (required),
/// <code>SECRET_HASH</code> (required if the app client is configured with a client secret),
/// <code>DEVICE_KEY</code></para></li><li><para>For <code>CUSTOM_AUTH</code>: <code>USERNAME</code> (required), <code>SECRET_HASH</code>
/// (if app client is configured with client secret), <code>DEVICE_KEY</code></para></li></ul>
/// </para>
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
[Alias("AuthParameters")]
public System.Collections.Hashtable AuthParameter { get; set; }
#endregion
#region Parameter ClientId
/// <summary>
/// <para>
/// <para>The app client ID.</para>
/// </para>
/// </summary>
#if !MODULAR
[System.Management.Automation.Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true)]
#else
[System.Management.Automation.Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true, Mandatory = true)]
[System.Management.Automation.AllowEmptyString]
[System.Management.Automation.AllowNull]
#endif
[Amazon.PowerShell.Common.AWSRequiredParameter]
public System.String ClientId { get; set; }
#endregion
#region Parameter ClientMetadata
/// <summary>
/// <para>
/// <para>A map of custom key-value pairs that you can provide as input for certain custom workflows
/// that this action triggers.</para><para>You create custom workflows by assigning AWS Lambda functions to user pool triggers.
/// When you use the InitiateAuth API action, Amazon Cognito invokes the AWS Lambda functions
/// that are specified for various triggers. The ClientMetadata value is passed as input
/// to the functions for only the following triggers:</para><ul><li><para>Pre signup</para></li><li><para>Pre authentication</para></li><li><para>User migration</para></li></ul><para>When Amazon Cognito invokes the functions for these triggers, it passes a JSON payload,
/// which the function receives as input. This payload contains a <code>validationData</code>
/// attribute, which provides the data that you assigned to the ClientMetadata parameter
/// in your InitiateAuth request. In your function code in AWS Lambda, you can process
/// the <code>validationData</code> value to enhance your workflow for your specific needs.</para><para>When you use the InitiateAuth API action, Amazon Cognito also invokes the functions
/// for the following triggers, but it does not provide the ClientMetadata value as input:</para><ul><li><para>Post authentication</para></li><li><para>Custom message</para></li><li><para>Pre token generation</para></li><li><para>Create auth challenge</para></li><li><para>Define auth challenge</para></li><li><para>Verify auth challenge</para></li></ul><para>For more information, see <a href="https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-identity-pools-working-with-aws-lambda-triggers.html">Customizing
/// User Pool Workflows with Lambda Triggers</a> in the <i>Amazon Cognito Developer Guide</i>.</para><note><para>Take the following limitations into consideration when you use the ClientMetadata
/// parameter:</para><ul><li><para>Amazon Cognito does not store the ClientMetadata value. This data is available only
/// to AWS Lambda triggers that are assigned to a user pool to support custom workflows.
/// If your user pool configuration does not include triggers, the ClientMetadata parameter
/// serves no purpose.</para></li><li><para>Amazon Cognito does not validate the ClientMetadata value.</para></li><li><para>Amazon Cognito does not encrypt the the ClientMetadata value, so don't use it to provide
/// sensitive information.</para></li></ul></note>
/// </para>
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
public System.Collections.Hashtable ClientMetadata { get; set; }
#endregion
#region Parameter UserContextData_EncodedData
/// <summary>
/// <para>
/// <para>Contextual data such as the user's device fingerprint, IP address, or location used
/// for evaluating the risk of an unexpected event by Amazon Cognito advanced security.</para>
/// </para>
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
public System.String UserContextData_EncodedData { get; set; }
#endregion
#region Parameter Select
/// <summary>
/// Use the -Select parameter to control the cmdlet output. The default value is '*'.
/// Specifying -Select '*' will result in the cmdlet returning the whole service response (Amazon.CognitoIdentityProvider.Model.InitiateAuthResponse).
/// Specifying the name of a property of type Amazon.CognitoIdentityProvider.Model.InitiateAuthResponse will result in that property being returned.
/// Specifying -Select '^ParameterName' will result in the cmdlet returning the selected cmdlet parameter value.
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
public string Select { get; set; } = "*";
#endregion
#region Parameter PassThru
/// <summary>
/// Changes the cmdlet behavior to return the value passed to the ClientId parameter.
/// The -PassThru parameter is deprecated, use -Select '^ClientId' instead. This parameter will be removed in a future version.
/// </summary>
[System.Obsolete("The -PassThru parameter is deprecated, use -Select '^ClientId' instead. This parameter will be removed in a future version.")]
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
public SwitchParameter PassThru { get; set; }
#endregion
#region Parameter Force
/// <summary>
/// This parameter overrides confirmation prompts to force
/// the cmdlet to continue its operation. This parameter should always
/// be used with caution.
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
public SwitchParameter Force { get; set; }
#endregion
protected override void ProcessRecord()
{
base.ProcessRecord();
var resourceIdentifiersText = FormatParameterValuesForConfirmationMsg(nameof(this.ClientId), MyInvocation.BoundParameters);
if (!ConfirmShouldProceed(this.Force.IsPresent, resourceIdentifiersText, "Start-CGIPAuth (InitiateAuth)"))
{
return;
}
var context = new CmdletContext();
// allow for manipulation of parameters prior to loading into context
PreExecutionContextLoad(context);
#pragma warning disable CS0618, CS0612 //A class member was marked with the Obsolete attribute
if (ParameterWasBound(nameof(this.Select)))
{
context.Select = CreateSelectDelegate<Amazon.CognitoIdentityProvider.Model.InitiateAuthResponse, StartCGIPAuthCmdlet>(Select) ??
throw new System.ArgumentException("Invalid value for -Select parameter.", nameof(this.Select));
if (this.PassThru.IsPresent)
{
throw new System.ArgumentException("-PassThru cannot be used when -Select is specified.", nameof(this.Select));
}
}
else if (this.PassThru.IsPresent)
{
context.Select = (response, cmdlet) => this.ClientId;
}
#pragma warning restore CS0618, CS0612 //A class member was marked with the Obsolete attribute
context.AnalyticsMetadata_AnalyticsEndpointId = this.AnalyticsMetadata_AnalyticsEndpointId;
context.AuthFlow = this.AuthFlow;
#if MODULAR
if (this.AuthFlow == null && ParameterWasBound(nameof(this.AuthFlow)))
{
WriteWarning("You are passing $null as a value for parameter AuthFlow which is marked as required. In case you believe this parameter was incorrectly marked as required, report this by opening an issue at https://github.com/aws/aws-tools-for-powershell/issues.");
}
#endif
if (this.AuthParameter != null)
{
context.AuthParameter = new Dictionary<System.String, System.String>(StringComparer.Ordinal);
foreach (var hashKey in this.AuthParameter.Keys)
{
context.AuthParameter.Add((String)hashKey, (String)(this.AuthParameter[hashKey]));
}
}
context.ClientId = this.ClientId;
#if MODULAR
if (this.ClientId == null && ParameterWasBound(nameof(this.ClientId)))
{
WriteWarning("You are passing $null as a value for parameter ClientId which is marked as required. In case you believe this parameter was incorrectly marked as required, report this by opening an issue at https://github.com/aws/aws-tools-for-powershell/issues.");
}
#endif
if (this.ClientMetadata != null)
{
context.ClientMetadata = new Dictionary<System.String, System.String>(StringComparer.Ordinal);
foreach (var hashKey in this.ClientMetadata.Keys)
{
context.ClientMetadata.Add((String)hashKey, (String)(this.ClientMetadata[hashKey]));
}
}
context.UserContextData_EncodedData = this.UserContextData_EncodedData;
// allow further manipulation of loaded context prior to processing
PostExecutionContextLoad(context);
var output = Execute(context) as CmdletOutput;
ProcessOutput(output);
}
#region IExecutor Members
public object Execute(ExecutorContext context)
{
var cmdletContext = context as CmdletContext;
// create request
var request = new Amazon.CognitoIdentityProvider.Model.InitiateAuthRequest();
// populate AnalyticsMetadata
var requestAnalyticsMetadataIsNull = true;
request.AnalyticsMetadata = new Amazon.CognitoIdentityProvider.Model.AnalyticsMetadataType();
System.String requestAnalyticsMetadata_analyticsMetadata_AnalyticsEndpointId = null;
if (cmdletContext.AnalyticsMetadata_AnalyticsEndpointId != null)
{
requestAnalyticsMetadata_analyticsMetadata_AnalyticsEndpointId = cmdletContext.AnalyticsMetadata_AnalyticsEndpointId;
}
if (requestAnalyticsMetadata_analyticsMetadata_AnalyticsEndpointId != null)
{
request.AnalyticsMetadata.AnalyticsEndpointId = requestAnalyticsMetadata_analyticsMetadata_AnalyticsEndpointId;
requestAnalyticsMetadataIsNull = false;
}
// determine if request.AnalyticsMetadata should be set to null
if (requestAnalyticsMetadataIsNull)
{
request.AnalyticsMetadata = null;
}
if (cmdletContext.AuthFlow != null)
{
request.AuthFlow = cmdletContext.AuthFlow;
}
if (cmdletContext.AuthParameter != null)
{
request.AuthParameters = cmdletContext.AuthParameter;
}
if (cmdletContext.ClientId != null)
{
request.ClientId = cmdletContext.ClientId;
}
if (cmdletContext.ClientMetadata != null)
{
request.ClientMetadata = cmdletContext.ClientMetadata;
}
// populate UserContextData
var requestUserContextDataIsNull = true;
request.UserContextData = new Amazon.CognitoIdentityProvider.Model.UserContextDataType();
System.String requestUserContextData_userContextData_EncodedData = null;
if (cmdletContext.UserContextData_EncodedData != null)
{
requestUserContextData_userContextData_EncodedData = cmdletContext.UserContextData_EncodedData;
}
if (requestUserContextData_userContextData_EncodedData != null)
{
request.UserContextData.EncodedData = requestUserContextData_userContextData_EncodedData;
requestUserContextDataIsNull = false;
}
// determine if request.UserContextData should be set to null
if (requestUserContextDataIsNull)
{
request.UserContextData = null;
}
CmdletOutput output;
// issue call
var client = Client ?? CreateClient(_CurrentCredentials, _RegionEndpoint);
try
{
var response = CallAWSServiceOperation(client, request);
object pipelineOutput = null;
pipelineOutput = cmdletContext.Select(response, this);
output = new CmdletOutput
{
PipelineOutput = pipelineOutput,
ServiceResponse = response
};
}
catch (Exception e)
{
output = new CmdletOutput { ErrorResponse = e };
}
return output;
}
public ExecutorContext CreateContext()
{
return new CmdletContext();
}
#endregion
#region AWS Service Operation Call
private Amazon.CognitoIdentityProvider.Model.InitiateAuthResponse CallAWSServiceOperation(IAmazonCognitoIdentityProvider client, Amazon.CognitoIdentityProvider.Model.InitiateAuthRequest request)
{
Utils.Common.WriteVerboseEndpointMessage(this, client.Config, "Amazon Cognito Identity Provider", "InitiateAuth");
try
{
#if DESKTOP
return client.InitiateAuth(request);
#elif CORECLR
return client.InitiateAuthAsync(request).GetAwaiter().GetResult();
#else
#error "Unknown build edition"
#endif
}
catch (AmazonServiceException exc)
{
var webException = exc.InnerException as System.Net.WebException;
if (webException != null)
{
throw new Exception(Utils.Common.FormatNameResolutionFailureMessage(client.Config, webException.Message), webException);
}
throw;
}
}
#endregion
internal partial class CmdletContext : ExecutorContext
{
public System.String AnalyticsMetadata_AnalyticsEndpointId { get; set; }
public Amazon.CognitoIdentityProvider.AuthFlowType AuthFlow { get; set; }
public Dictionary<System.String, System.String> AuthParameter { get; set; }
public System.String ClientId { get; set; }
public Dictionary<System.String, System.String> ClientMetadata { get; set; }
public System.String UserContextData_EncodedData { get; set; }
public System.Func<Amazon.CognitoIdentityProvider.Model.InitiateAuthResponse, StartCGIPAuthCmdlet, object> Select { get; set; } =
(response, cmdlet) => response;
}
}
}
| 55.787565 | 539 | 0.642426 | [
"Apache-2.0"
] | 5u5hma/aws-tools-for-powershell | modules/AWSPowerShell/Cmdlets/CognitoIdentityProvider/Basic/Start-CGIPAuth-Cmdlet.cs | 21,534 | C# |
using System;
using System.Web.Http;
using Umbraco.Core;
using Umbraco.Web.Composing;
using Umbraco.Web.Security;
namespace Umbraco.Web.WebApi
{
/// <summary>
/// Ensures authorization is successful for a back office user.
/// </summary>
public sealed class UmbracoAuthorizeAttribute : AuthorizeAttribute
{
private readonly bool _requireApproval;
/// <summary>
/// Can be used by unit tests to enable/disable this filter
/// </summary>
internal static bool Enable = true;
// TODO: inject!
private readonly UmbracoContext _umbracoContext;
private readonly IRuntimeState _runtimeState;
private IRuntimeState RuntimeState => _runtimeState ?? Current.RuntimeState;
private UmbracoContext UmbracoContext => _umbracoContext ?? Current.UmbracoContext;
/// <summary>
/// THIS SHOULD BE ONLY USED FOR UNIT TESTS
/// </summary>
/// <param name="umbracoContext"></param>
/// <param name="runtimeState"></param>
public UmbracoAuthorizeAttribute(UmbracoContext umbracoContext, IRuntimeState runtimeState)
{
if (umbracoContext == null) throw new ArgumentNullException(nameof(umbracoContext));
if (runtimeState == null) throw new ArgumentNullException(nameof(runtimeState));
_umbracoContext = umbracoContext;
_runtimeState = runtimeState;
}
public UmbracoAuthorizeAttribute() : this(true)
{ }
public UmbracoAuthorizeAttribute(bool requireApproval)
{
_requireApproval = requireApproval;
}
protected override bool IsAuthorized(System.Web.Http.Controllers.HttpActionContext actionContext)
{
if (Enable == false)
{
return true;
}
try
{
// if not configured (install or upgrade) then we can continue
// otherwise we need to ensure that a user is logged in
return RuntimeState.Level == RuntimeLevel.Install
|| RuntimeState.Level == RuntimeLevel.Upgrade
|| UmbracoContext.Security.ValidateCurrentUser(false, _requireApproval) == ValidateRequestAttempt.Success;
}
catch (Exception)
{
return false;
}
}
}
}
| 33.082192 | 126 | 0.613665 | [
"MIT"
] | 0Neji/Umbraco-CMS | src/Umbraco.Web/WebApi/UmbracoAuthorizeAttribute.cs | 2,417 | C# |
namespace lab_41_entity_code_first_from_db
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Spatial;
public partial class Category
{
public Category()
{
Oranges = new HashSet<Orange>();
}
public int CategoryId { get; set; }
[StringLength(50)]
public string CategoryName { get; set; }
public virtual ICollection<Orange> Oranges { get; set; }
}
}
| 22.576923 | 64 | 0.630324 | [
"MIT"
] | philanderson888/2019-09-c-sharp-labs | labs/lab_41_entity_code_first_from_db/Category.cs | 587 | C# |
namespace N2.Http
{
public class WellKnownHeaders
{
public const string ETag = "ETag";
public const string ContentRef = "content-ref";
public const string FirstPage = "href-first";
public const string LastPage = "href-last";
public const string NextPage = "href-next";
public const string PrevPage = "href-prev";
}
}
| 27.071429 | 55 | 0.627968 | [
"MIT"
] | gjkaal/http-client | N2.Http/WellKnownHeaders.cs | 381 | C# |
using System.Net;
using BuildingBlocks.Exception;
namespace Flight.Aircrafts.Exceptions;
public class AircraftAlreadyExistException : AppException
{
public AircraftAlreadyExistException() : base("Flight already exist!", HttpStatusCode.Conflict)
{
}
}
| 22.083333 | 99 | 0.781132 | [
"MIT"
] | xpertdev/Airline-Microservices | src/Services/Airline.Flight/src/Flight/Aircrafts/Exceptions/AircraftAlreadyExistException.cs | 265 | C# |
using System;
using System.Linq;
namespace P02._Common_Elements
{
internal class Program
{
static void Main(string[] args)
{
string[] arr1 = Console.ReadLine()
.Split(' ', StringSplitOptions.RemoveEmptyEntries)
.ToArray();
string[] arr2 = Console.ReadLine()
.Split(' ', StringSplitOptions.RemoveEmptyEntries)
.ToArray();
string commonEl = "";
for (int i = 0; i < arr1.Length; i++)
{
for (int j = 0; j < arr2.Length; j++)
{
if (arr1[i] == arr2[j])
{
commonEl += $"{arr2[j]} ";
}
}
}
Console.WriteLine(commonEl);
}
}
}
| 23.971429 | 66 | 0.413588 | [
"MIT"
] | Marti2509/SoftUni | 02.Programming Fundamentals with C# - January 2022/03.2.E - Arrays/P02. Common Elements/Program.cs | 841 | C# |
//
// System.Xml.Serialization.TypeTranslator
//
// Authors:
// Gonzalo Paniagua Javier (gonzalo@ximian.com)
// Erik LeBel (eriklebel@yahoo.ca)
// Lluis Sanchez Gual (lluis@ximian.com)
//
// (C) 2002 Ximian, Inc (http://www.ximian.com)
// (C) 2003 Erik Lebel
//
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections;
using System.Globalization;
using System.Xml.Schema;
namespace System.Xml.Serialization
{
internal class TypeTranslator
{
static Hashtable nameCache;
static Hashtable primitiveTypes;
static Hashtable primitiveArrayTypes;
static Hashtable nullableTypes;
#if TARGET_JVM
static readonly object AppDomain_TypeTranslatorCacheLock = new object ();
const string AppDomain_nameCacheName = "System.Xml.Serialization.TypeTranslator.nameCache";
const string AppDomain_nullableTypesName = "System.Xml.Serialization.TypeTranslator.nullableTypes";
static Hashtable AppDomain_nameCache {
get { return GetAppDomainCache (AppDomain_nameCacheName); }
}
static Hashtable AppDomain_nullableTypes {
get { return GetAppDomainCache (AppDomain_nullableTypesName); }
}
static Hashtable GetAppDomainCache(string name) {
Hashtable res = (Hashtable) AppDomain.CurrentDomain.GetData (name);
if (res == null) {
lock (AppDomain_TypeTranslatorCacheLock) {
res = (Hashtable) AppDomain.CurrentDomain.GetData (name);
if (res == null) {
res = Hashtable.Synchronized (new Hashtable ());
AppDomain.CurrentDomain.SetData (name, res);
}
}
}
return res;
}
#endif
static TypeTranslator ()
{
nameCache = new Hashtable ();
primitiveArrayTypes = Hashtable.Synchronized (new Hashtable ());
#if !TARGET_JVM
nameCache = Hashtable.Synchronized (nameCache);
#endif
// XSD Types with direct map to CLR types
nameCache.Add (typeof (bool), new TypeData (typeof (bool), "boolean", true));
nameCache.Add (typeof (short), new TypeData (typeof (short), "short", true));
nameCache.Add (typeof (ushort), new TypeData (typeof (ushort), "unsignedShort", true));
nameCache.Add (typeof (int), new TypeData (typeof (int), "int", true));
nameCache.Add (typeof (uint), new TypeData (typeof (uint), "unsignedInt", true));
nameCache.Add (typeof (long), new TypeData (typeof (long), "long", true));
nameCache.Add (typeof (ulong), new TypeData (typeof (ulong), "unsignedLong", true));
nameCache.Add (typeof (float), new TypeData (typeof (float), "float", true));
nameCache.Add (typeof (double), new TypeData (typeof (double), "double", true));
nameCache.Add (typeof (DateTime), new TypeData (typeof (DateTime), "dateTime", true)); // TODO: timeInstant, Xml date, xml time
nameCache.Add (typeof (decimal), new TypeData (typeof (decimal), "decimal", true));
nameCache.Add (typeof (XmlQualifiedName), new TypeData (typeof (XmlQualifiedName), "QName", true));
nameCache.Add (typeof (string), new TypeData (typeof (string), "string", true));
#if !MOONLIGHT
XmlSchemaPatternFacet guidFacet = new XmlSchemaPatternFacet();
guidFacet.Value = "[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}";
nameCache.Add (typeof (Guid), new TypeData (typeof (Guid), "guid", true, (TypeData)nameCache[typeof (string)], guidFacet));
#endif
nameCache.Add (typeof (byte), new TypeData (typeof (byte), "unsignedByte", true));
nameCache.Add (typeof (sbyte), new TypeData (typeof (sbyte), "byte", true));
nameCache.Add (typeof (char), new TypeData (typeof (char), "char", true, (TypeData)nameCache[typeof (ushort)], null));
nameCache.Add (typeof (object), new TypeData (typeof (object), "anyType", false));
nameCache.Add (typeof (byte[]), new TypeData (typeof (byte[]), "base64Binary", true));
#if !MOONLIGHT
nameCache.Add (typeof (XmlNode), new TypeData (typeof (XmlNode), "XmlNode", false));
nameCache.Add (typeof (XmlElement), new TypeData (typeof (XmlElement), "XmlElement", false));
#endif
primitiveTypes = new Hashtable();
ICollection types = nameCache.Values;
foreach (TypeData td in types)
primitiveTypes.Add (td.XmlType, td);
// Additional XSD types
primitiveTypes.Add ("date", new TypeData (typeof (DateTime), "date", true)); // TODO: timeInstant
primitiveTypes.Add ("time", new TypeData (typeof (DateTime), "time", true));
primitiveTypes.Add ("timePeriod", new TypeData (typeof (DateTime), "timePeriod", true));
primitiveTypes.Add ("gDay", new TypeData (typeof (string), "gDay", true));
primitiveTypes.Add ("gMonthDay", new TypeData (typeof (string), "gMonthDay", true));
primitiveTypes.Add ("gYear", new TypeData (typeof (string), "gYear", true));
primitiveTypes.Add ("gYearMonth", new TypeData (typeof (string), "gYearMonth", true));
primitiveTypes.Add ("month", new TypeData (typeof (DateTime), "month", true));
primitiveTypes.Add ("NMTOKEN", new TypeData (typeof (string), "NMTOKEN", true));
primitiveTypes.Add ("NMTOKENS", new TypeData (typeof (string), "NMTOKENS", true));
primitiveTypes.Add ("Name", new TypeData (typeof (string), "Name", true));
primitiveTypes.Add ("NCName", new TypeData (typeof (string), "NCName", true));
primitiveTypes.Add ("language", new TypeData (typeof (string), "language", true));
primitiveTypes.Add ("integer", new TypeData (typeof (string), "integer", true));
primitiveTypes.Add ("positiveInteger", new TypeData (typeof (string), "positiveInteger", true));
primitiveTypes.Add ("nonPositiveInteger", new TypeData (typeof (string), "nonPositiveInteger", true));
primitiveTypes.Add ("negativeInteger", new TypeData (typeof (string), "negativeInteger", true));
primitiveTypes.Add ("nonNegativeInteger", new TypeData (typeof (string), "nonNegativeInteger", true));
primitiveTypes.Add ("ENTITIES", new TypeData (typeof (string), "ENTITIES", true));
primitiveTypes.Add ("ENTITY", new TypeData (typeof (string), "ENTITY", true));
primitiveTypes.Add ("hexBinary", new TypeData (typeof (byte[]), "hexBinary", true));
primitiveTypes.Add ("ID", new TypeData (typeof (string), "ID", true));
primitiveTypes.Add ("IDREF", new TypeData (typeof (string), "IDREF", true));
primitiveTypes.Add ("IDREFS", new TypeData (typeof (string), "IDREFS", true));
primitiveTypes.Add ("NOTATION", new TypeData (typeof (string), "NOTATION", true));
primitiveTypes.Add ("token", new TypeData (typeof (string), "token", true));
primitiveTypes.Add ("normalizedString", new TypeData (typeof (string), "normalizedString", true));
primitiveTypes.Add ("anyURI", new TypeData (typeof (string), "anyURI", true));
primitiveTypes.Add ("base64", new TypeData (typeof (byte[]), "base64", true));
primitiveTypes.Add ("duration", new TypeData (typeof (string), "duration", true));
#if NET_2_0
nullableTypes = Hashtable.Synchronized(new Hashtable ());
foreach (DictionaryEntry de in primitiveTypes) {
TypeData td = (TypeData) de.Value;
TypeData ntd = new TypeData (td.Type, td.XmlType, true);
ntd.IsNullable = true;
nullableTypes.Add (de.Key, ntd);
}
#endif
}
public static TypeData GetTypeData (Type type)
{
return GetTypeData (type, null);
}
public static TypeData GetTypeData (Type runtimeType, string xmlDataType, bool underlyingEnumType = false)
{
if (underlyingEnumType && runtimeType.IsEnum)
runtimeType = Enum.GetUnderlyingType (runtimeType);
Type type = runtimeType;
bool nullableOverride = false;
#if NET_2_0
// Nullable<T> is serialized as T
if (type.IsGenericType && type.GetGenericTypeDefinition () == typeof (Nullable<>)) {
nullableOverride = true;
type = type.GetGenericArguments () [0];
}
if ((xmlDataType != null) && (xmlDataType.Length != 0)) {
// If the type is an array, xmlDataType specifies the type for the array elements,
// not for the whole array. The exception is base64Binary, since it is a byte[],
// that's why the following check is needed.
TypeData at = GetPrimitiveTypeData (xmlDataType);
if (type.IsArray && type != at.Type) {
TypeData tt = (TypeData) primitiveArrayTypes [xmlDataType];
if (tt != null)
return tt;
if (at.Type == type.GetElementType ()) {
tt = new TypeData (type, GetArrayName (at.XmlType), false);
primitiveArrayTypes [xmlDataType] = tt;
return tt;
}
else
throw new InvalidOperationException ("Cannot convert values of type '" + type.GetElementType () + "' to '" + xmlDataType + "'");
}
if (nullableOverride){
TypeData tt = (TypeData) nullableTypes [at.XmlType];
if (tt == null){
tt = new TypeData (type, at.XmlType, false);
tt.IsNullable = true;
nullableTypes [at.XmlType] = tt;
}
return tt;
}
return at;
}
if (nullableOverride){
TypeData pt = GetTypeData (type); // beware this recursive call btw ...
if (pt != null) {
TypeData tt = (TypeData) nullableTypes [pt.XmlType];
#if TARGET_JVM
if (tt == null)
tt = (TypeData) AppDomain_nullableTypes [pt.XmlType];
#endif
if (tt == null) {
tt = new TypeData (type, pt.XmlType, false);
tt.IsNullable = true;
#if TARGET_JVM
AppDomain_nullableTypes [pt.XmlType] = tt;
#else
nullableTypes [pt.XmlType] = tt;
#endif
}
return tt;
}
}
#endif
TypeData typeData = nameCache[runtimeType] as TypeData;
if (typeData != null) return typeData;
#if TARGET_JVM
Hashtable dynamicCache = AppDomain_nameCache;
typeData = dynamicCache[runtimeType] as TypeData;
if (typeData != null) return typeData;
#endif
string name;
if (type.IsArray) {
string sufix = GetTypeData (type.GetElementType ()).XmlType;
name = GetArrayName (sufix);
}
#if NET_2_0
else if (type.IsGenericType && !type.IsGenericTypeDefinition) {
name = XmlConvert.EncodeLocalName (type.Name.Substring (0, type.Name.IndexOf ('`'))) + "Of";
foreach (Type garg in type.GetGenericArguments ())
name += garg.IsArray || garg.IsGenericType ?
GetTypeData (garg).XmlType :
CodeIdentifier.MakePascal (XmlConvert.EncodeLocalName (garg.Name));
}
#endif
else
name = XmlConvert.EncodeLocalName (type.Name);
typeData = new TypeData (type, name, false);
if (nullableOverride)
typeData.IsNullable = true;
#if TARGET_JVM
dynamicCache[runtimeType] = typeData;
#else
nameCache[runtimeType] = typeData;
#endif
return typeData;
}
public static bool IsPrimitive (Type type)
{
return GetTypeData (type).SchemaType == SchemaTypes.Primitive;
}
public static TypeData GetPrimitiveTypeData (string typeName)
{
return GetPrimitiveTypeData (typeName, false);
}
public static TypeData GetPrimitiveTypeData (string typeName, bool nullable)
{
TypeData td = (TypeData) primitiveTypes [typeName];
if (td != null && !td.Type.IsValueType)
return td;
// for 1.x profile, 'nullableTypes' is null
Hashtable table = nullable && nullableTypes != null ? nullableTypes : primitiveTypes;
td = (TypeData) table [typeName];
if (td == null) throw new NotSupportedException ("Data type '" + typeName + "' not supported");
return td;
}
public static TypeData FindPrimitiveTypeData (string typeName)
{
return (TypeData) primitiveTypes[typeName];
}
public static TypeData GetDefaultPrimitiveTypeData (TypeData primType)
{
// Returns the TypeData that is mapped by default to the clr type
// that primType represents
if (primType.SchemaType == SchemaTypes.Primitive)
{
TypeData newPrim = GetTypeData (primType.Type, null);
if (newPrim != primType) return newPrim;
}
return primType;
}
public static bool IsDefaultPrimitiveTpeData (TypeData primType)
{
return GetDefaultPrimitiveTypeData (primType) == primType;
}
public static TypeData CreateCustomType (string typeName, string fullTypeName, string xmlType, SchemaTypes schemaType, TypeData listItemTypeData)
{
TypeData td = new TypeData (typeName, fullTypeName, xmlType, schemaType, listItemTypeData);
return td;
}
public static string GetArrayName (string elemName)
{
return "ArrayOf" + Char.ToUpper (elemName [0], CultureInfo.InvariantCulture) + elemName.Substring (1);
}
public static string GetArrayName (string elemName, int dimensions)
{
string aname = GetArrayName (elemName);
for ( ; dimensions > 1; dimensions--)
aname = "ArrayOf" + aname;
return aname;
}
public static void ParseArrayType (string arrayType, out string type, out string ns, out string dimensions)
{
int i = arrayType.LastIndexOf (":");
if (i == -1) ns = "";
else ns = arrayType.Substring (0,i);
int j = arrayType.IndexOf ("[", i+1);
if (j == -1) throw new InvalidOperationException ("Cannot parse WSDL array type: " + arrayType);
type = arrayType.Substring (i+1, j-i-1);
dimensions = arrayType.Substring (j);
}
}
}
| 39.848571 | 147 | 0.693913 | [
"Apache-2.0"
] | Mailaender/mono | mcs/class/System.XML/System.Xml.Serialization/TypeTranslator.cs | 13,947 | 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 marvelReset
{
public partial class App : global::Windows.UI.Xaml.Markup.IXamlMetadataProvider
{
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Windows.UI.Xaml.Build.Tasks"," 10.0.18362.1")]
private global::marvelReset.marvelReset_XamlTypeInfo.XamlMetaDataProvider __appProvider;
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Windows.UI.Xaml.Build.Tasks"," 10.0.18362.1")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
private global::marvelReset.marvelReset_XamlTypeInfo.XamlMetaDataProvider _AppProvider
{
get
{
if (__appProvider == null)
{
__appProvider = new global::marvelReset.marvelReset_XamlTypeInfo.XamlMetaDataProvider();
}
return __appProvider;
}
}
/// <summary>
/// GetXamlType(Type)
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Windows.UI.Xaml.Build.Tasks"," 10.0.18362.1")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public global::Windows.UI.Xaml.Markup.IXamlType GetXamlType(global::System.Type type)
{
return _AppProvider.GetXamlType(type);
}
/// <summary>
/// GetXamlType(String)
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Windows.UI.Xaml.Build.Tasks"," 10.0.18362.1")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public global::Windows.UI.Xaml.Markup.IXamlType GetXamlType(string fullName)
{
return _AppProvider.GetXamlType(fullName);
}
/// <summary>
/// GetXmlnsDefinitions()
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Windows.UI.Xaml.Build.Tasks"," 10.0.18362.1")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public global::Windows.UI.Xaml.Markup.XmlnsDefinition[] GetXmlnsDefinitions()
{
return _AppProvider.GetXmlnsDefinitions();
}
}
}
namespace marvelReset.marvelReset_XamlTypeInfo
{
/// <summary>
/// Main class for providing metadata for the app or library
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Windows.UI.Xaml.Build.Tasks"," 10.0.18362.1")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed class XamlMetaDataProvider : global::Windows.UI.Xaml.Markup.IXamlMetadataProvider
{
private global::marvelReset.marvelReset_XamlTypeInfo.XamlTypeInfoProvider _provider = null;
private global::marvelReset.marvelReset_XamlTypeInfo.XamlTypeInfoProvider Provider
{
get
{
if (_provider == null)
{
_provider = new global::marvelReset.marvelReset_XamlTypeInfo.XamlTypeInfoProvider();
}
return _provider;
}
}
/// <summary>
/// GetXamlType(Type)
/// </summary>
public global::Windows.UI.Xaml.Markup.IXamlType GetXamlType(global::System.Type type)
{
return Provider.GetXamlTypeByType(type);
}
/// <summary>
/// GetXamlType(String)
/// </summary>
public global::Windows.UI.Xaml.Markup.IXamlType GetXamlType(string fullName)
{
return Provider.GetXamlTypeByName(fullName);
}
/// <summary>
/// GetXmlnsDefinitions()
/// </summary>
public global::Windows.UI.Xaml.Markup.XmlnsDefinition[] GetXmlnsDefinitions()
{
return new global::Windows.UI.Xaml.Markup.XmlnsDefinition[0];
}
}
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Windows.UI.Xaml.Build.Tasks"," 10.0.18362.1")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
internal partial class XamlTypeInfoProvider
{
private global::Microsoft.UI.Xaml.Markup.ReflectionXamlMetadataProvider _Provider;
private global::Microsoft.UI.Xaml.Markup.ReflectionXamlMetadataProvider Provider
{
get
{
if (_Provider == null)
{
_Provider = new global::Microsoft.UI.Xaml.Markup.ReflectionXamlMetadataProvider();
}
return _Provider;
}
}
public global::Windows.UI.Xaml.Markup.IXamlType GetXamlTypeByType(global::System.Type type)
{
return Provider.GetXamlType(type);
}
public global::Windows.UI.Xaml.Markup.IXamlType GetXamlTypeByName(string typeName)
{
return Provider.GetXamlType(typeName);
}
}
}
| 37.297872 | 121 | 0.608291 | [
"MIT"
] | shuansanchez/marvelReset | marvelReset/obj/ARM/Debug/XamlTypeInfo.g.cs | 5,261 | C# |
// based on the FNA SpriteBatch implementation by Ethan Lee: https://github.com/FNA-XNA/FNA
using System;
using System.Runtime.InteropServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;
using System.Runtime.CompilerServices;
using Nez.Textures;
namespace Nez
{
public class Batcher : GraphicsResource
{
/// <summary>
/// Matrix to be used when creating the projection matrix
/// </summary>
/// <value>The transform matrix.</value>
public Matrix TransformMatrix => _transformMatrix;
/// <summary>
/// If true, destination positions will be rounded before being drawn.
/// </summary>
public bool ShouldRoundDestinations = true;
#region variables
bool _shouldIgnoreRoundingDestinations;
// Buffer objects used for actual drawing
DynamicVertexBuffer _vertexBuffer;
IndexBuffer _indexBuffer;
// Local data stored before buffering to GPU
VertexPositionColorTexture4[] _vertexInfo;
Texture2D[] _textureInfo;
// Default SpriteEffect
SpriteEffect _spriteEffect;
EffectPass _spriteEffectPass;
// Tracks Begin/End calls
bool _beginCalled;
// Keep render state for non-Immediate modes.
BlendState _blendState;
SamplerState _samplerState;
DepthStencilState _depthStencilState;
RasterizerState _rasterizerState;
bool _disableBatching;
// How many sprites are in the current batch?
int _numSprites;
// Matrix to be used when creating the projection matrix
Matrix _transformMatrix;
// Matrix used internally to calculate the cameras projection
Matrix _projectionMatrix;
// this is the calculated MatrixTransform parameter in sprite shaders
Matrix _matrixTransformMatrix;
// User-provided Effect, if applicable
Effect _customEffect;
#endregion
#region static variables and constants
/// <summary>if true, the older FNA half-pixel offset will be used when creating the ortho matrix</summary>
public static bool UseFnaHalfPixelMatrix = false;
const int MAX_SPRITES = 2048;
const int MAX_VERTICES = MAX_SPRITES * 4;
const int MAX_INDICES = MAX_SPRITES * 6;
// Used to calculate texture coordinates
static readonly float[] _cornerOffsetX = new float[] {0.0f, 1.0f, 0.0f, 1.0f};
static readonly float[] _cornerOffsetY = new float[] {0.0f, 0.0f, 1.0f, 1.0f};
static readonly short[] _indexData = GenerateIndexArray();
#endregion
public Batcher(GraphicsDevice graphicsDevice)
{
Insist.IsTrue(graphicsDevice != null);
GraphicsDevice = graphicsDevice;
_vertexInfo = new VertexPositionColorTexture4[MAX_SPRITES];
_textureInfo = new Texture2D[MAX_SPRITES];
_vertexBuffer = new DynamicVertexBuffer(graphicsDevice, typeof(VertexPositionColorTexture), MAX_VERTICES,
BufferUsage.WriteOnly);
_indexBuffer = new IndexBuffer(graphicsDevice, IndexElementSize.SixteenBits, MAX_INDICES,
BufferUsage.WriteOnly);
_indexBuffer.SetData(_indexData);
_spriteEffect = new SpriteEffect();
_spriteEffectPass = _spriteEffect.CurrentTechnique.Passes[0];
_projectionMatrix = new Matrix(
0f, //(float)( 2.0 / (double)viewport.Width ) is the actual value we will use
0.0f,
0.0f,
0.0f,
0.0f,
0f, //(float)( -2.0 / (double)viewport.Height ) is the actual value we will use
0.0f,
0.0f,
0.0f,
0.0f,
1.0f,
0.0f,
-1.0f,
1.0f,
0.0f,
1.0f
);
}
protected override void Dispose(bool disposing)
{
if (!IsDisposed && disposing)
{
_spriteEffect.Dispose();
_indexBuffer.Dispose();
_vertexBuffer.Dispose();
}
base.Dispose(disposing);
}
/// <summary>
/// sets if position rounding should be ignored. Useful when you are drawing primitives for debugging.
/// </summary>
/// <param name="shouldIgnore">If set to <c>true</c> should ignore.</param>
public void SetIgnoreRoundingDestinations(bool shouldIgnore)
{
_shouldIgnoreRoundingDestinations = shouldIgnore;
}
#region Public begin/end methods
public void Begin()
{
Begin(BlendState.AlphaBlend, Core.DefaultSamplerState, DepthStencilState.None,
RasterizerState.CullCounterClockwise, null, Matrix.Identity, false);
}
public void Begin(Effect effect)
{
Begin(BlendState.AlphaBlend, Core.DefaultSamplerState, DepthStencilState.None,
RasterizerState.CullCounterClockwise, effect, Matrix.Identity, false);
}
public void Begin(Material material)
{
Begin(material.BlendState, material.SamplerState, material.DepthStencilState,
RasterizerState.CullCounterClockwise, material.Effect);
}
public void Begin(Matrix transformationMatrix)
{
Begin(BlendState.AlphaBlend, Core.DefaultSamplerState, DepthStencilState.None,
RasterizerState.CullCounterClockwise, null, transformationMatrix, false);
}
public void Begin(BlendState blendState)
{
Begin(blendState, Core.DefaultSamplerState, DepthStencilState.None, RasterizerState.CullCounterClockwise,
null, Matrix.Identity, false);
}
public void Begin(Material material, Matrix transformationMatrix)
{
Begin(material.BlendState, material.SamplerState, material.DepthStencilState,
RasterizerState.CullCounterClockwise, material.Effect, transformationMatrix, false);
}
public void Begin(BlendState blendState, SamplerState samplerState, DepthStencilState depthStencilState,
RasterizerState rasterizerState)
{
Begin(
blendState,
samplerState,
depthStencilState,
rasterizerState,
null,
Matrix.Identity,
false
);
}
public void Begin(BlendState blendState, SamplerState samplerState, DepthStencilState depthStencilState,
RasterizerState rasterizerState, Effect effect)
{
Begin(
blendState,
samplerState,
depthStencilState,
rasterizerState,
effect,
Matrix.Identity,
false
);
}
public void Begin(BlendState blendState, SamplerState samplerState, DepthStencilState depthStencilState,
RasterizerState rasterizerState,
Effect effect, Matrix transformationMatrix)
{
Begin(
blendState,
samplerState,
depthStencilState,
rasterizerState,
effect,
transformationMatrix,
false
);
}
public void Begin(BlendState blendState, SamplerState samplerState, DepthStencilState depthStencilState,
RasterizerState rasterizerState,
Effect effect, Matrix transformationMatrix, bool disableBatching)
{
Insist.IsFalse(_beginCalled,
"Begin has been called before calling End after the last call to Begin. Begin cannot be called again until End has been successfully called.");
_beginCalled = true;
_blendState = blendState ?? BlendState.AlphaBlend;
_samplerState = samplerState ?? Core.DefaultSamplerState;
_depthStencilState = depthStencilState ?? DepthStencilState.None;
_rasterizerState = rasterizerState ?? RasterizerState.CullCounterClockwise;
_customEffect = effect;
_transformMatrix = transformationMatrix;
_disableBatching = disableBatching;
if (_disableBatching)
PrepRenderState();
}
public void End()
{
Insist.IsTrue(_beginCalled,
"End was called, but Begin has not yet been called. You must call Begin successfully before you can call End.");
_beginCalled = false;
if (!_disableBatching)
FlushBatch();
_customEffect = null;
}
#endregion
#region Public draw methods
public void Draw(Texture2D texture, Vector2 position)
{
CheckBegin();
PushSprite(texture, null, position.X, position.Y, 1.0f, 1.0f,
Color.White, Vector2.Zero, 0.0f, 0.0f, 0, false, 0, 0, 0, 0);
}
public void Draw(Texture2D texture, Vector2 position, Color color)
{
CheckBegin();
PushSprite(texture, null, position.X, position.Y, 1.0f, 1.0f,
color, Vector2.Zero, 0.0f, 0.0f, 0, false, 0, 0, 0, 0);
}
public void Draw(Texture2D texture, Rectangle destinationRectangle)
{
CheckBegin();
PushSprite(texture, null, destinationRectangle.X, destinationRectangle.Y, destinationRectangle.Width,
destinationRectangle.Height,
Color.White, Vector2.Zero, 0.0f, 0.0f, 0, true, 0, 0, 0, 0);
}
public void Draw(Texture2D texture, Rectangle destinationRectangle, Color color)
{
CheckBegin();
PushSprite(texture, null, destinationRectangle.X, destinationRectangle.Y, destinationRectangle.Width,
destinationRectangle.Height,
color, Vector2.Zero, 0.0f, 0.0f, 0, true, 0, 0, 0, 0);
}
public void Draw(Texture2D texture, Rectangle destinationRectangle, Rectangle? sourceRectangle, Color color)
{
CheckBegin();
PushSprite(texture, sourceRectangle, destinationRectangle.X, destinationRectangle.Y,
destinationRectangle.Width, destinationRectangle.Height,
color, Vector2.Zero, 0.0f, 0.0f, 0, true, 0, 0, 0, 0);
}
public void Draw(Texture2D texture, Rectangle destinationRectangle, Rectangle? sourceRectangle, Color color,
SpriteEffects effects)
{
CheckBegin();
PushSprite(texture, sourceRectangle, destinationRectangle.X, destinationRectangle.Y,
destinationRectangle.Width, destinationRectangle.Height,
color, Vector2.Zero, 0.0f, 0.0f, (byte) (effects & (SpriteEffects) 0x03), true, 0, 0, 0, 0);
}
public void Draw(
Texture2D texture,
Rectangle destinationRectangle,
Rectangle? sourceRectangle,
Color color,
float rotation,
SpriteEffects effects,
float layerDepth,
float skewTopX, float skewBottomX, float skewLeftY, float skewRightY
)
{
CheckBegin();
PushSprite(
texture,
sourceRectangle,
destinationRectangle.X,
destinationRectangle.Y,
destinationRectangle.Width,
destinationRectangle.Height,
color,
Vector2.Zero,
rotation,
layerDepth,
(byte) (effects & (SpriteEffects) 0x03),
true,
skewTopX, skewBottomX, skewLeftY, skewRightY
);
}
public void Draw(Texture2D texture, Vector2 position, Rectangle? sourceRectangle, Color color)
{
CheckBegin();
PushSprite(
texture,
sourceRectangle,
position.X,
position.Y,
1.0f,
1.0f,
color,
Vector2.Zero,
0.0f,
0.0f,
0,
false,
0, 0, 0, 0
);
}
public void Draw(
Texture2D texture,
Vector2 position,
Rectangle? sourceRectangle,
Color color,
float rotation,
Vector2 origin,
float scale,
SpriteEffects effects,
float layerDepth
)
{
CheckBegin();
PushSprite(
texture,
sourceRectangle,
position.X,
position.Y,
scale,
scale,
color,
origin,
rotation,
layerDepth,
(byte) (effects & (SpriteEffects) 0x03),
false,
0, 0, 0, 0
);
}
public void Draw(
Sprite sprite,
Vector2 position,
Color color,
float rotation,
Vector2 origin,
float scale,
SpriteEffects effects,
float layerDepth
)
{
CheckBegin();
PushSprite(
sprite,
position.X,
position.Y,
scale,
scale,
color,
origin,
rotation,
layerDepth,
(byte) (effects & (SpriteEffects) 0x03),
0, 0, 0, 0
);
}
public void Draw(
Texture2D texture,
Vector2 position,
Rectangle? sourceRectangle,
Color color,
float rotation,
Vector2 origin,
Vector2 scale,
SpriteEffects effects,
float layerDepth
)
{
CheckBegin();
PushSprite(
texture,
sourceRectangle,
position.X,
position.Y,
scale.X,
scale.Y,
color,
origin,
rotation,
layerDepth,
(byte) (effects & (SpriteEffects) 0x03),
false,
0, 0, 0, 0
);
}
public void Draw(
Sprite sprite,
Vector2 position,
Color color,
float rotation,
Vector2 origin,
Vector2 scale,
SpriteEffects effects,
float layerDepth
)
{
CheckBegin();
PushSprite(
sprite,
position.X,
position.Y,
scale.X,
scale.Y,
color,
origin,
rotation,
layerDepth,
(byte) (effects & (SpriteEffects) 0x03),
0, 0, 0, 0
);
}
public void Draw(
Texture2D texture,
Vector2 position,
Rectangle? sourceRectangle,
Color color,
float rotation,
Vector2 origin,
Vector2 scale,
SpriteEffects effects,
float layerDepth,
float skewTopX, float skewBottomX, float skewLeftY, float skewRightY
)
{
CheckBegin();
PushSprite(
texture,
sourceRectangle,
position.X,
position.Y,
scale.X,
scale.Y,
color,
origin,
rotation,
layerDepth,
(byte) (effects & (SpriteEffects) 0x03),
false,
skewTopX, skewBottomX, skewLeftY, skewRightY
);
}
public void Draw(
Texture2D texture,
Rectangle destinationRectangle,
Rectangle? sourceRectangle,
Color color,
float rotation,
Vector2 origin,
SpriteEffects effects,
float layerDepth
)
{
CheckBegin();
PushSprite(
texture,
sourceRectangle,
destinationRectangle.X,
destinationRectangle.Y,
destinationRectangle.Width,
destinationRectangle.Height,
color,
origin,
rotation,
layerDepth,
(byte) (effects & (SpriteEffects) 0x03),
true,
0, 0, 0, 0
);
}
/// <summary>
/// direct access to setting vert positions, UVs and colors. The order of elements is top-left, top-right, bottom-left, bottom-right
/// </summary>
/// <returns>The raw.</returns>
/// <param name="texture">Texture.</param>
/// <param name="verts">Verts.</param>
/// <param name="textureCoords">Texture coords.</param>
/// <param name="colors">Colors.</param>
public unsafe void DrawRaw(Texture2D texture, Vector3[] verts, Vector2[] textureCoords, Color[] colors)
{
Insist.IsTrue(verts.Length == 4, "there must be only 4 verts");
Insist.IsTrue(textureCoords.Length == 4, "there must be only 4 texture coordinates");
Insist.IsTrue(colors.Length == 4, "there must be only 4 colors");
// we're out of space, flush
if (_numSprites >= MAX_SPRITES)
FlushBatch();
fixed (VertexPositionColorTexture4* vertexInfo = &_vertexInfo[_numSprites])
{
vertexInfo->Position0 = verts[0];
vertexInfo->Position1 = verts[1];
vertexInfo->Position2 = verts[2];
vertexInfo->Position3 = verts[3];
vertexInfo->TextureCoordinate0 = textureCoords[0];
vertexInfo->TextureCoordinate1 = textureCoords[1];
vertexInfo->TextureCoordinate2 = textureCoords[2];
vertexInfo->TextureCoordinate3 = textureCoords[3];
vertexInfo->Color0 = colors[0];
vertexInfo->Color1 = colors[1];
vertexInfo->Color2 = colors[2];
vertexInfo->Color3 = colors[3];
}
if (_disableBatching)
{
_vertexBuffer.SetData(0, _vertexInfo, 0, 1, VertexPositionColorTexture4.RealStride, SetDataOptions.None);
DrawPrimitives(texture, 0, 1);
}
else
{
_textureInfo[_numSprites] = texture;
_numSprites += 1;
}
}
/// <summary>
/// direct access to setting vert positions, UVs and colors. The order of elements is top-left, top-right, bottom-left, bottom-right
/// </summary>
/// <returns>The raw.</returns>
/// <param name="texture">Texture.</param>
/// <param name="verts">Verts.</param>
/// <param name="textureCoords">Texture coords.</param>
/// <param name="color">Color.</param>
public unsafe void DrawRaw(Texture2D texture, Vector3[] verts, Vector2[] textureCoords, Color color)
{
Insist.IsTrue(verts.Length == 4, "there must be only 4 verts");
Insist.IsTrue(textureCoords.Length == 4, "there must be only 4 texture coordinates");
// we're out of space, flush
if (_numSprites >= MAX_SPRITES)
FlushBatch();
fixed (VertexPositionColorTexture4* vertexInfo = &_vertexInfo[_numSprites])
{
vertexInfo->Position0 = verts[0];
vertexInfo->Position1 = verts[1];
vertexInfo->Position2 = verts[2];
vertexInfo->Position3 = verts[3];
vertexInfo->TextureCoordinate0 = textureCoords[0];
vertexInfo->TextureCoordinate1 = textureCoords[1];
vertexInfo->TextureCoordinate2 = textureCoords[2];
vertexInfo->TextureCoordinate3 = textureCoords[3];
vertexInfo->Color0 = color;
vertexInfo->Color1 = color;
vertexInfo->Color2 = color;
vertexInfo->Color3 = color;
}
if (_disableBatching)
{
_vertexBuffer.SetData(0, _vertexInfo, 0, 1, VertexPositionColorTexture4.RealStride,
SetDataOptions.None);
DrawPrimitives(texture, 0, 1);
}
else
{
_textureInfo[_numSprites] = texture;
_numSprites += 1;
}
}
#endregion
[Obsolete("SpriteFont is too locked down to use directly. Wrap it in a NezSpriteFont")]
public void DrawString(SpriteFont spriteFont, string text, Vector2 position, Color color, float rotation,
Vector2 origin, Vector2 scale, SpriteEffects effects, float layerDepth)
{
throw new NotImplementedException("SpriteFont is too locked down to use directly. Wrap it in a NezSpriteFont");
}
static short[] GenerateIndexArray()
{
var result = new short[MAX_INDICES];
for (int i = 0, j = 0; i < MAX_INDICES; i += 6, j += 4)
{
result[i] = (short) (j);
result[i + 1] = (short) (j + 1);
result[i + 2] = (short) (j + 2);
result[i + 3] = (short) (j + 3);
result[i + 4] = (short) (j + 2);
result[i + 5] = (short) (j + 1);
}
return result;
}
#region Methods
/// <summary>
/// the meat of the Batcher. This is where it all goes down
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
unsafe void PushSprite(Texture2D texture, Rectangle? sourceRectangle, float destinationX, float destinationY,
float destinationW, float destinationH, Color color, Vector2 origin,
float rotation, float depth, byte effects, bool destSizeInPixels, float skewTopX,
float skewBottomX, float skewLeftY, float skewRightY)
{
// out of space, flush
if (_numSprites >= MAX_SPRITES)
FlushBatch();
if (!_shouldIgnoreRoundingDestinations && ShouldRoundDestinations)
{
destinationX = Mathf.Round(destinationX);
destinationY = Mathf.Round(destinationY);
}
// Source/Destination/Origin Calculations
float sourceX, sourceY, sourceW, sourceH;
float originX, originY;
if (sourceRectangle.HasValue)
{
var inverseTexW = 1.0f / (float) texture.Width;
var inverseTexH = 1.0f / (float) texture.Height;
sourceX = sourceRectangle.Value.X * inverseTexW;
sourceY = sourceRectangle.Value.Y * inverseTexH;
sourceW = sourceRectangle.Value.Width * inverseTexW;
sourceH = sourceRectangle.Value.Height * inverseTexH;
originX = (origin.X / sourceW) * inverseTexW;
originY = (origin.Y / sourceH) * inverseTexH;
if (!destSizeInPixels)
{
destinationW *= sourceRectangle.Value.Width;
destinationH *= sourceRectangle.Value.Height;
}
}
else
{
sourceX = 0.0f;
sourceY = 0.0f;
sourceW = 1.0f;
sourceH = 1.0f;
originX = origin.X * (1.0f / texture.Width);
originY = origin.Y * (1.0f / texture.Height);
if (!destSizeInPixels)
{
destinationW *= texture.Width;
destinationH *= texture.Height;
}
}
// Rotation Calculations
float rotationMatrix1X;
float rotationMatrix1Y;
float rotationMatrix2X;
float rotationMatrix2Y;
if (!Mathf.WithinEpsilon(rotation))
{
var sin = Mathf.Sin(rotation);
var cos = Mathf.Cos(rotation);
rotationMatrix1X = cos;
rotationMatrix1Y = sin;
rotationMatrix2X = -sin;
rotationMatrix2Y = cos;
}
else
{
rotationMatrix1X = 1.0f;
rotationMatrix1Y = 0.0f;
rotationMatrix2X = 0.0f;
rotationMatrix2Y = 1.0f;
}
// flip our skew values if we have a flipped sprite
if (effects != 0)
{
skewTopX *= -1;
skewBottomX *= -1;
skewLeftY *= -1;
skewRightY *= -1;
}
fixed (VertexPositionColorTexture4* vertexInfo = &_vertexInfo[_numSprites])
{
// calculate vertices
// top-left
var cornerX = (_cornerOffsetX[0] - originX) * destinationW + skewTopX;
var cornerY = (_cornerOffsetY[0] - originY) * destinationH - skewLeftY;
vertexInfo->Position0.X = (
(rotationMatrix2X * cornerY) +
(rotationMatrix1X * cornerX) +
destinationX
);
vertexInfo->Position0.Y = (
(rotationMatrix2Y * cornerY) +
(rotationMatrix1Y * cornerX) +
destinationY
);
// top-right
cornerX = (_cornerOffsetX[1] - originX) * destinationW + skewTopX;
cornerY = (_cornerOffsetY[1] - originY) * destinationH - skewRightY;
vertexInfo->Position1.X = (
(rotationMatrix2X * cornerY) +
(rotationMatrix1X * cornerX) +
destinationX
);
vertexInfo->Position1.Y = (
(rotationMatrix2Y * cornerY) +
(rotationMatrix1Y * cornerX) +
destinationY
);
// bottom-left
cornerX = (_cornerOffsetX[2] - originX) * destinationW + skewBottomX;
cornerY = (_cornerOffsetY[2] - originY) * destinationH - skewLeftY;
vertexInfo->Position2.X = (
(rotationMatrix2X * cornerY) +
(rotationMatrix1X * cornerX) +
destinationX
);
vertexInfo->Position2.Y = (
(rotationMatrix2Y * cornerY) +
(rotationMatrix1Y * cornerX) +
destinationY
);
// bottom-right
cornerX = (_cornerOffsetX[3] - originX) * destinationW + skewBottomX;
cornerY = (_cornerOffsetY[3] - originY) * destinationH - skewRightY;
vertexInfo->Position3.X = (
(rotationMatrix2X * cornerY) +
(rotationMatrix1X * cornerX) +
destinationX
);
vertexInfo->Position3.Y = (
(rotationMatrix2Y * cornerY) +
(rotationMatrix1Y * cornerX) +
destinationY
);
vertexInfo->TextureCoordinate0.X = (_cornerOffsetX[0 ^ effects] * sourceW) + sourceX;
vertexInfo->TextureCoordinate0.Y = (_cornerOffsetY[0 ^ effects] * sourceH) + sourceY;
vertexInfo->TextureCoordinate1.X = (_cornerOffsetX[1 ^ effects] * sourceW) + sourceX;
vertexInfo->TextureCoordinate1.Y = (_cornerOffsetY[1 ^ effects] * sourceH) + sourceY;
vertexInfo->TextureCoordinate2.X = (_cornerOffsetX[2 ^ effects] * sourceW) + sourceX;
vertexInfo->TextureCoordinate2.Y = (_cornerOffsetY[2 ^ effects] * sourceH) + sourceY;
vertexInfo->TextureCoordinate3.X = (_cornerOffsetX[3 ^ effects] * sourceW) + sourceX;
vertexInfo->TextureCoordinate3.Y = (_cornerOffsetY[3 ^ effects] * sourceH) + sourceY;
vertexInfo->Position0.Z = depth;
vertexInfo->Position1.Z = depth;
vertexInfo->Position2.Z = depth;
vertexInfo->Position3.Z = depth;
vertexInfo->Color0 = color;
vertexInfo->Color1 = color;
vertexInfo->Color2 = color;
vertexInfo->Color3 = color;
}
if (_disableBatching)
{
_vertexBuffer.SetData(0, _vertexInfo, 0, 1, VertexPositionColorTexture4.RealStride, SetDataOptions.None);
DrawPrimitives(texture, 0, 1);
}
else
{
_textureInfo[_numSprites] = texture;
_numSprites += 1;
}
}
/// <summary>
/// Sprite alternative to the old SpriteBatch pushSprite
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
unsafe void PushSprite(Sprite sprite, float destinationX, float destinationY, float destinationW,
float destinationH, Color color, Vector2 origin,
float rotation, float depth, byte effects, float skewTopX, float skewBottomX, float skewLeftY,
float skewRightY)
{
// out of space, flush
if (_numSprites >= MAX_SPRITES)
FlushBatch();
// Source/Destination/Origin Calculations. destinationW/H is the scale value so we multiply by the size of the texture region
var originX = (origin.X / sprite.Uvs.Width) / sprite.Texture2D.Width;
var originY = (origin.Y / sprite.Uvs.Height) / sprite.Texture2D.Height;
destinationW *= sprite.SourceRect.Width;
destinationH *= sprite.SourceRect.Height;
// Rotation Calculations
float rotationMatrix1X;
float rotationMatrix1Y;
float rotationMatrix2X;
float rotationMatrix2Y;
if (!Mathf.WithinEpsilon(rotation))
{
var sin = Mathf.Sin(rotation);
var cos = Mathf.Cos(rotation);
rotationMatrix1X = cos;
rotationMatrix1Y = sin;
rotationMatrix2X = -sin;
rotationMatrix2Y = cos;
}
else
{
rotationMatrix1X = 1.0f;
rotationMatrix1Y = 0.0f;
rotationMatrix2X = 0.0f;
rotationMatrix2Y = 1.0f;
}
// flip our skew values if we have a flipped sprite
if (effects != 0)
{
skewTopX *= -1;
skewBottomX *= -1;
skewLeftY *= -1;
skewRightY *= -1;
}
fixed (VertexPositionColorTexture4* vertexInfo = &_vertexInfo[_numSprites])
{
// calculate vertices
// top-left
var cornerX = (_cornerOffsetX[0] - originX) * destinationW + skewTopX;
var cornerY = (_cornerOffsetY[0] - originY) * destinationH - skewLeftY;
vertexInfo->Position0.X = (
(rotationMatrix2X * cornerY) +
(rotationMatrix1X * cornerX) +
destinationX
);
vertexInfo->Position0.Y = (
(rotationMatrix2Y * cornerY) +
(rotationMatrix1Y * cornerX) +
destinationY
);
// top-right
cornerX = (_cornerOffsetX[1] - originX) * destinationW + skewTopX;
cornerY = (_cornerOffsetY[1] - originY) * destinationH - skewRightY;
vertexInfo->Position1.X = (
(rotationMatrix2X * cornerY) +
(rotationMatrix1X * cornerX) +
destinationX
);
vertexInfo->Position1.Y = (
(rotationMatrix2Y * cornerY) +
(rotationMatrix1Y * cornerX) +
destinationY
);
// bottom-left
cornerX = (_cornerOffsetX[2] - originX) * destinationW + skewBottomX;
cornerY = (_cornerOffsetY[2] - originY) * destinationH - skewLeftY;
vertexInfo->Position2.X = (
(rotationMatrix2X * cornerY) +
(rotationMatrix1X * cornerX) +
destinationX
);
vertexInfo->Position2.Y = (
(rotationMatrix2Y * cornerY) +
(rotationMatrix1Y * cornerX) +
destinationY
);
// bottom-right
cornerX = (_cornerOffsetX[3] - originX) * destinationW + skewBottomX;
cornerY = (_cornerOffsetY[3] - originY) * destinationH - skewRightY;
vertexInfo->Position3.X = (
(rotationMatrix2X * cornerY) +
(rotationMatrix1X * cornerX) +
destinationX
);
vertexInfo->Position3.Y = (
(rotationMatrix2Y * cornerY) +
(rotationMatrix1Y * cornerX) +
destinationY
);
vertexInfo->TextureCoordinate0.X =
(_cornerOffsetX[0 ^ effects] * sprite.Uvs.Width) + sprite.Uvs.X;
vertexInfo->TextureCoordinate0.Y =
(_cornerOffsetY[0 ^ effects] * sprite.Uvs.Height) + sprite.Uvs.Y;
vertexInfo->TextureCoordinate1.X =
(_cornerOffsetX[1 ^ effects] * sprite.Uvs.Width) + sprite.Uvs.X;
vertexInfo->TextureCoordinate1.Y =
(_cornerOffsetY[1 ^ effects] * sprite.Uvs.Height) + sprite.Uvs.Y;
vertexInfo->TextureCoordinate2.X =
(_cornerOffsetX[2 ^ effects] * sprite.Uvs.Width) + sprite.Uvs.X;
vertexInfo->TextureCoordinate2.Y =
(_cornerOffsetY[2 ^ effects] * sprite.Uvs.Height) + sprite.Uvs.Y;
vertexInfo->TextureCoordinate3.X =
(_cornerOffsetX[3 ^ effects] * sprite.Uvs.Width) + sprite.Uvs.X;
vertexInfo->TextureCoordinate3.Y =
(_cornerOffsetY[3 ^ effects] * sprite.Uvs.Height) + sprite.Uvs.Y;
vertexInfo->Position0.Z = depth;
vertexInfo->Position1.Z = depth;
vertexInfo->Position2.Z = depth;
vertexInfo->Position3.Z = depth;
vertexInfo->Color0 = color;
vertexInfo->Color1 = color;
vertexInfo->Color2 = color;
vertexInfo->Color3 = color;
}
if (_disableBatching)
{
_vertexBuffer.SetData(0, _vertexInfo, 0, 1, VertexPositionColorTexture4.RealStride, SetDataOptions.None);
DrawPrimitives(sprite, 0, 1);
}
else
{
_textureInfo[_numSprites] = sprite;
_numSprites += 1;
}
}
public unsafe void FlushBatch()
{
if (_numSprites == 0)
return;
var offset = 0;
Texture2D curTexture = null;
PrepRenderState();
#if FNA
fixed (VertexPositionColorTexture4* p = &_vertexInfo[0])
{
_vertexBuffer.SetDataPointerEXT(0, (IntPtr)p, _numSprites * VertexPositionColorTexture4.RealStride, SetDataOptions.Discard);
}
#else
_vertexBuffer.SetData(0, _vertexInfo, 0, _numSprites, VertexPositionColorTexture4.RealStride, SetDataOptions.Discard);
#endif
curTexture = _textureInfo[0];
for (var i = 1; i < _numSprites; i += 1)
{
if (_textureInfo[i] != curTexture)
{
DrawPrimitives(curTexture, offset, i - offset);
curTexture = _textureInfo[i];
offset = i;
}
}
DrawPrimitives(curTexture, offset, _numSprites - offset);
_numSprites = 0;
}
/// <summary>
/// enables/disables scissor testing. If the RasterizerState changes it will cause a batch flush.
/// </summary>
/// <returns>The scissor test.</returns>
/// <param name="shouldEnable">Should enable.</param>
public void EnableScissorTest(bool shouldEnable)
{
var currentValue = _rasterizerState.ScissorTestEnable;
if (currentValue == shouldEnable)
return;
FlushBatch();
_rasterizerState = new RasterizerState
{
CullMode = _rasterizerState.CullMode,
DepthBias = _rasterizerState.DepthBias,
FillMode = _rasterizerState.FillMode,
MultiSampleAntiAlias = _rasterizerState.MultiSampleAntiAlias,
SlopeScaleDepthBias = _rasterizerState.SlopeScaleDepthBias,
ScissorTestEnable = shouldEnable
};
}
void PrepRenderState()
{
GraphicsDevice.BlendState = _blendState;
GraphicsDevice.SamplerStates[0] = _samplerState;
GraphicsDevice.DepthStencilState = _depthStencilState;
GraphicsDevice.RasterizerState = _rasterizerState;
GraphicsDevice.SetVertexBuffer(_vertexBuffer);
GraphicsDevice.Indices = _indexBuffer;
var viewport = GraphicsDevice.Viewport;
// inlined CreateOrthographicOffCenter
// Force UseFnaHalfPixelMatrix
_projectionMatrix.M11 = (float)(2.0 / (double)(viewport.Width / 2 * 2 - 1));
_projectionMatrix.M22 = (float)(-2.0 / (double)(viewport.Height / 2 * 2 - 1));
_projectionMatrix.M41 = -1 - 0.5f * _projectionMatrix.M11;
_projectionMatrix.M42 = 1 - 0.5f * _projectionMatrix.M22;
Matrix.Multiply(ref _transformMatrix, ref _projectionMatrix, out _matrixTransformMatrix);
_spriteEffect.SetMatrixTransform(ref _matrixTransformMatrix);
// we have to Apply here because custom effects often wont have a vertex shader and we need the default SpriteEffect's
_spriteEffectPass.Apply();
}
void DrawPrimitives(Texture texture, int baseSprite, int batchSize)
{
if (_customEffect != null)
{
foreach (var pass in _customEffect.CurrentTechnique.Passes)
{
pass.Apply();
GraphicsDevice.Textures[0] = texture;
GraphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList, baseSprite * 4, 0, batchSize * 2);
}
}
else
{
GraphicsDevice.Textures[0] = texture;
GraphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList, baseSprite * 4, 0, batchSize * 2);
}
}
[System.Diagnostics.Conditional("DEBUG")]
void CheckBegin()
{
if (!_beginCalled)
throw new InvalidOperationException("Begin has not been called. Begin must be called before you can draw");
}
#endregion
#region Sprite Data Container Class
[StructLayout(LayoutKind.Sequential, Pack = 1)]
struct VertexPositionColorTexture4 : IVertexType
{
public const int RealStride = 96;
VertexDeclaration IVertexType.VertexDeclaration => throw new NotImplementedException();
public Vector3 Position0;
public Color Color0;
public Vector2 TextureCoordinate0;
public Vector3 Position1;
public Color Color1;
public Vector2 TextureCoordinate1;
public Vector3 Position2;
public Color Color2;
public Vector2 TextureCoordinate2;
public Vector3 Position3;
public Color Color3;
public Vector2 TextureCoordinate3;
}
#endregion
}
} | 28.094222 | 147 | 0.684459 | [
"Apache-2.0",
"MIT"
] | yatesm4/Nez | Nez.Portable/Graphics/Batcher/Batcher.cs | 31,606 | C# |
//-----------------------------------------------------------------------
// <copyright file="StorageCredentials.cs" company="Microsoft">
// Copyright 2013 Microsoft Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
//-----------------------------------------------------------------------
namespace Microsoft.WindowsAzure.Storage.Auth
{
using Microsoft.WindowsAzure.Storage.Core;
using Microsoft.WindowsAzure.Storage.Core.Util;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
#if WINDOWS_RT
using Windows.Foundation.Metadata;
#endif
/// <summary>
/// Represents a set of credentials used to authenticate access to a Windows Azure storage account.
/// </summary>
public sealed class StorageCredentials
{
private UriQueryBuilder queryBuilder;
/// <summary>
/// Gets the associated shared access signature token for the credentials.
/// </summary>
/// <value>The shared access signature token.</value>
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "SAS", Justification = "Back compatibility.")]
public string SASToken { get; private set; }
/// <summary>
/// Gets the associated account name for the credentials.
/// </summary>
/// <value>The account name.</value>
public string AccountName { get; private set; }
/// <summary>
/// Gets the associated key name for the credentials.
/// </summary>
/// <value>The key name.</value>
public string KeyName
{
get
{
return this.Key.KeyName;
}
}
internal StorageAccountKey Key { get; private set; }
/// <summary>
/// Gets a value indicating whether the credentials are for anonymous access.
/// </summary>
/// <value><c>true</c> if the credentials are for anonymous access; otherwise, <c>false</c>.</value>
public bool IsAnonymous
{
get
{
return (this.SASToken == null) && (this.AccountName == null);
}
}
/// <summary>
/// Gets a value indicating whether the credentials are a shared access signature token.
/// </summary>
/// <value><c>true</c> if the credentials are a shared access signature token; otherwise, <c>false</c>.</value>
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "SAS", Justification = "Back compatibility.")]
public bool IsSAS
{
get
{
return (this.SASToken != null) && (this.AccountName == null);
}
}
/// <summary>
/// Gets a value indicating whether the credentials are a shared key.
/// </summary>
/// <value><c>true</c> if the credentials are a shared key; otherwise, <c>false</c>.</value>
public bool IsSharedKey
{
get
{
return (this.SASToken == null) && (this.AccountName != null);
}
}
/// <summary>
/// Initializes a new instance of the <see cref="StorageCredentials"/> class.
/// </summary>
public StorageCredentials()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="StorageCredentials"/> class with the specified account name and key value.
/// </summary>
/// <param name="accountName">A string that represents the name of the storage account.</param>
/// <param name="keyValue">A string that represents the Base64-encoded account access key.</param>
public StorageCredentials(string accountName, string keyValue)
: this(accountName, keyValue, null)
{
}
#if WINDOWS_DESKTOP
/// <summary>
/// Initializes a new instance of the <see cref="StorageCredentials"/> class with the specified account name and key value.
/// </summary>
/// <param name="accountName">A string that represents the name of the storage account.</param>
/// <param name="keyValue">An array of bytes that represent the account access key.</param>
public StorageCredentials(string accountName, byte[] keyValue)
: this(accountName, keyValue, null)
{
}
#endif
/// <summary>
/// Initializes a new instance of the <see cref="StorageCredentials"/> class with the specified account name, key value, and key name.
/// </summary>
/// <param name="accountName">A string that represents the name of the storage account.</param>
/// <param name="keyValue">A string that represents the Base64-encoded account access key.</param>
/// <param name="keyName">A string that represents the name of the key.</param>
public StorageCredentials(string accountName, string keyValue, string keyName)
{
CommonUtility.AssertNotNullOrEmpty("accountName", accountName);
this.AccountName = accountName;
this.UpdateKey(keyValue, keyName);
}
#if WINDOWS_DESKTOP
/// <summary>
/// Initializes a new instance of the <see cref="StorageCredentials"/> class with the specified account name, key value, and key name.
/// </summary>
/// <param name="accountName">A string that represents the name of the storage account.</param>
/// <param name="keyValue">An array of bytes that represent the account access key.</param>
/// <param name="keyName">A string that represents the name of the key.</param>
public StorageCredentials(string accountName, byte[] keyValue, string keyName)
{
CommonUtility.AssertNotNullOrEmpty("accountName", accountName);
this.AccountName = accountName;
this.UpdateKey(keyValue, keyName);
}
#endif
/// <summary>
/// Initializes a new instance of the <see cref="StorageCredentials"/> class with the specified shared access signature token.
/// </summary>
/// <param name="sasToken">A string representing the shared access signature token.</param>
public StorageCredentials(string sasToken)
{
CommonUtility.AssertNotNullOrEmpty("sasToken", sasToken);
this.SASToken = sasToken;
this.UpdateQueryBuilder();
}
/// <summary>
/// Updates the key value for the credentials.
/// </summary>
/// <param name="keyValue">The key value, as a Base64-encoded string, to update.</param>
public void UpdateKey(string keyValue)
{
this.UpdateKey(keyValue, null);
}
#if WINDOWS_DESKTOP
/// <summary>
/// Updates the key value for the credentials.
/// </summary>
/// <param name="keyValue">The key value, as an array of bytes, to update.</param>
public void UpdateKey(byte[] keyValue)
{
this.UpdateKey(keyValue, null);
}
#endif
/// <summary>
/// Updates the key value and key name for the credentials.
/// </summary>
/// <param name="keyValue">The key value, as a Base64-encoded string, to update.</param>
/// <param name="keyName">The key name to update.</param>
public void UpdateKey(string keyValue, string keyName)
{
if (!this.IsSharedKey)
{
string errorMessage = string.Format(CultureInfo.CurrentCulture, SR.CannotUpdateKeyWithoutAccountKeyCreds);
throw new InvalidOperationException(errorMessage);
}
CommonUtility.AssertNotNull("keyValue", keyValue);
this.Key = new StorageAccountKey(keyName, Convert.FromBase64String(keyValue));
}
#if WINDOWS_DESKTOP
/// <summary>
/// Updates the key value and key name for the credentials.
/// </summary>
/// <param name="keyValue">The key value, as an array of bytes, to update.</param>
/// <param name="keyName">The key name to update.</param>
public void UpdateKey(byte[] keyValue, string keyName)
{
if (!this.IsSharedKey)
{
string errorMessage = string.Format(CultureInfo.CurrentCulture, SR.CannotUpdateKeyWithoutAccountKeyCreds);
throw new InvalidOperationException(errorMessage);
}
CommonUtility.AssertNotNull("keyValue", keyValue);
this.Key = new StorageAccountKey(keyName, keyValue);
}
#endif
/// <summary>
/// Updates the shared access signature (SAS) token value for storage credentials created with a shared access signature.
/// </summary>
/// <param name="sasToken">A string that specifies the SAS token value to update.</param>
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "SAS", Justification = "Back compatibility.")]
public void UpdateSASToken(string sasToken)
{
if (!this.IsSAS)
{
string errorMessage = string.Format(CultureInfo.CurrentCulture, SR.CannotUpdateSasWithoutSasCreds);
throw new InvalidOperationException(errorMessage);
}
CommonUtility.AssertNotNullOrEmpty("sasToken", sasToken);
this.SASToken = sasToken;
this.UpdateQueryBuilder();
}
/// <summary>
/// Returns the account key for the credentials.
/// </summary>
/// <returns>An array of bytes that contains the key.</returns>
public byte[] ExportKey()
{
return (byte[])this.Key.KeyValue.Clone();
}
/// <summary>
/// Transforms a resource URI into a shared access signature URI, by appending a shared access token.
/// </summary>
/// <param name="resourceUri">A <see cref="System.Uri"/> object that represents the resource URI to be transformed.</param>
/// <returns>A <see cref="System.Uri"/> object that represents the signature, including the resource URI and the shared access token.</returns>
#if WINDOWS_RT
[DefaultOverload]
#endif
public Uri TransformUri(Uri resourceUri)
{
if (this.IsSAS)
{
return this.queryBuilder.AddToUri(resourceUri);
}
else
{
return resourceUri;
}
}
/// <summary>
/// Transforms a resource URI into a shared access signature URI, by appending a shared access token.
/// </summary>
/// <param name="resourceUri">A <see cref="StorageUri"/> object that represents the resource URI to be transformed.</param>
/// <returns>A <see cref="StorageUri"/> object that represents the signature, including the resource URI and the shared access token.</returns>
public StorageUri TransformUri(StorageUri resourceUri)
{
CommonUtility.AssertNotNull("resourceUri", resourceUri);
return new StorageUri(
this.TransformUri(resourceUri.PrimaryUri),
this.TransformUri(resourceUri.SecondaryUri));
}
/// <summary>
/// Exports the value of the account access key to a Base64-encoded string.
/// </summary>
/// <returns>The account access key.</returns>
public string ExportBase64EncodedKey()
{
StorageAccountKey localKey = this.Key;
return (localKey.KeyValue == null) ? null : Convert.ToBase64String(localKey.KeyValue);
}
internal string ToString(bool exportSecrets)
{
if (this.IsSharedKey)
{
return string.Format(
CultureInfo.InvariantCulture,
"{0}={1};{2}={3}",
CloudStorageAccount.AccountNameSettingString,
this.AccountName,
CloudStorageAccount.AccountKeySettingString,
exportSecrets ? this.ExportBase64EncodedKey() : "[key hidden]");
}
if (this.IsSAS)
{
return string.Format(CultureInfo.InvariantCulture, "{0}={1}", CloudStorageAccount.SharedAccessSignatureSettingString, exportSecrets ? this.SASToken : "[signature hidden]");
}
return string.Empty;
}
/// <summary>
/// Determines whether an other <see cref="StorageCredentials"/> object is equal to this one by comparing their SAS tokens, account names, key names, and key values.
/// </summary>
/// <param name="other">The <see cref="StorageCredentials"/> object to compare to this one.</param>
/// <returns><c>true</c> if the two <see cref="StorageCredentials"/> objects are equal; otherwise, <c>false</c>.</returns>
public bool Equals(StorageCredentials other)
{
if (other == null)
{
return false;
}
else
{
return string.Equals(this.SASToken, other.SASToken) &&
string.Equals(this.AccountName, other.AccountName) &&
string.Equals(this.KeyName, other.KeyName) &&
string.Equals(this.ExportBase64EncodedKey(), other.ExportBase64EncodedKey());
}
}
private void UpdateQueryBuilder()
{
this.queryBuilder = new UriQueryBuilder();
IDictionary<string, string> parameters = HttpWebUtility.ParseQueryString(this.SASToken);
foreach (KeyValuePair<string, string> parameter in parameters)
{
this.queryBuilder.Add(parameter.Key, parameter.Value);
}
}
}
}
| 40.91831 | 188 | 0.596861 | [
"Apache-2.0"
] | jasonnewyork/azure-storage-net | Lib/Common/Auth/StorageCredentials.cs | 14,528 | C# |
namespace Funkcja_Liniowa
{
partial class Form1
{
/// <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.menuStrip1 = new System.Windows.Forms.MenuStrip();
this.programToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.zamknijToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.infoToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.oProgramieToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.autorToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.label1 = new System.Windows.Forms.Label();
this.textBox1 = new System.Windows.Forms.TextBox();
this.label2 = new System.Windows.Forms.Label();
this.textBox2 = new System.Windows.Forms.TextBox();
this.label3 = new System.Windows.Forms.Label();
this.button1 = new System.Windows.Forms.Button();
this.label4 = new System.Windows.Forms.Label();
this.label5 = new System.Windows.Forms.Label();
this.label6 = new System.Windows.Forms.Label();
this.label7 = new System.Windows.Forms.Label();
this.label8 = new System.Windows.Forms.Label();
this.label9 = new System.Windows.Forms.Label();
this.label10 = new System.Windows.Forms.Label();
this.label11 = new System.Windows.Forms.Label();
this.menuStrip1.SuspendLayout();
this.SuspendLayout();
//
// menuStrip1
//
this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.programToolStripMenuItem,
this.infoToolStripMenuItem});
this.menuStrip1.Location = new System.Drawing.Point(0, 0);
this.menuStrip1.Name = "menuStrip1";
this.menuStrip1.Size = new System.Drawing.Size(1008, 24);
this.menuStrip1.TabIndex = 0;
this.menuStrip1.Text = "menuStrip1";
//
// programToolStripMenuItem
//
this.programToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.zamknijToolStripMenuItem});
this.programToolStripMenuItem.Name = "programToolStripMenuItem";
this.programToolStripMenuItem.Size = new System.Drawing.Size(65, 20);
this.programToolStripMenuItem.Text = "Program";
//
// zamknijToolStripMenuItem
//
this.zamknijToolStripMenuItem.Name = "zamknijToolStripMenuItem";
this.zamknijToolStripMenuItem.Size = new System.Drawing.Size(117, 22);
this.zamknijToolStripMenuItem.Text = "Zamknij";
this.zamknijToolStripMenuItem.Click += new System.EventHandler(this.zamknijToolStripMenuItem_Click);
//
// infoToolStripMenuItem
//
this.infoToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.oProgramieToolStripMenuItem,
this.autorToolStripMenuItem});
this.infoToolStripMenuItem.Name = "infoToolStripMenuItem";
this.infoToolStripMenuItem.Size = new System.Drawing.Size(40, 20);
this.infoToolStripMenuItem.Text = "Info";
//
// oProgramieToolStripMenuItem
//
this.oProgramieToolStripMenuItem.Name = "oProgramieToolStripMenuItem";
this.oProgramieToolStripMenuItem.Size = new System.Drawing.Size(141, 22);
this.oProgramieToolStripMenuItem.Text = "O programie";
this.oProgramieToolStripMenuItem.Click += new System.EventHandler(this.oProgramieToolStripMenuItem_Click);
//
// autorToolStripMenuItem
//
this.autorToolStripMenuItem.Name = "autorToolStripMenuItem";
this.autorToolStripMenuItem.Size = new System.Drawing.Size(141, 22);
this.autorToolStripMenuItem.Text = "Autor";
this.autorToolStripMenuItem.Click += new System.EventHandler(this.autorToolStripMenuItem_Click);
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(163, 684);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(24, 13);
this.label1.TabIndex = 1;
this.label1.Text = "y = ";
//
// textBox1
//
this.textBox1.Location = new System.Drawing.Point(184, 681);
this.textBox1.Name = "textBox1";
this.textBox1.Size = new System.Drawing.Size(41, 20);
this.textBox1.TabIndex = 2;
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(231, 684);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(24, 13);
this.label2.TabIndex = 3;
this.label2.Text = "x + ";
//
// textBox2
//
this.textBox2.Location = new System.Drawing.Point(252, 681);
this.textBox2.Name = "textBox2";
this.textBox2.Size = new System.Drawing.Size(41, 20);
this.textBox2.TabIndex = 4;
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(13, 684);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(133, 13);
this.label3.TabIndex = 5;
this.label3.Text = "Podaj wzór funkcji liniowej:";
//
// button1
//
this.button1.Location = new System.Drawing.Point(323, 679);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(75, 23);
this.button1.TabIndex = 6;
this.button1.Text = "Rysuj!";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// label4
//
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(195, 320);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(0, 13);
this.label4.TabIndex = 7;
//
// label5
//
this.label5.AutoSize = true;
this.label5.Location = new System.Drawing.Point(465, 320);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(0, 13);
this.label5.TabIndex = 8;
//
// label6
//
this.label6.AutoSize = true;
this.label6.Location = new System.Drawing.Point(525, 320);
this.label6.Name = "label6";
this.label6.Size = new System.Drawing.Size(0, 13);
this.label6.TabIndex = 9;
//
// label7
//
this.label7.AutoSize = true;
this.label7.Location = new System.Drawing.Point(795, 320);
this.label7.Name = "label7";
this.label7.Size = new System.Drawing.Size(0, 13);
this.label7.TabIndex = 10;
//
// label8
//
this.label8.AutoSize = true;
this.label8.Location = new System.Drawing.Point(470, 45);
this.label8.Name = "label8";
this.label8.Size = new System.Drawing.Size(0, 13);
this.label8.TabIndex = 11;
//
// label9
//
this.label9.AutoSize = true;
this.label9.Location = new System.Drawing.Point(475, 305);
this.label9.Name = "label9";
this.label9.Size = new System.Drawing.Size(0, 13);
this.label9.TabIndex = 12;
//
// label10
//
this.label10.AutoSize = true;
this.label10.Location = new System.Drawing.Point(475, 370);
this.label10.Name = "label10";
this.label10.Size = new System.Drawing.Size(0, 13);
this.label10.TabIndex = 13;
//
// label11
//
this.label11.AutoSize = true;
this.label11.Location = new System.Drawing.Point(470, 640);
this.label11.Name = "label11";
this.label11.Size = new System.Drawing.Size(10, 13);
this.label11.TabIndex = 14;
this.label11.Text = "-";
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1008, 729);
this.Controls.Add(this.label11);
this.Controls.Add(this.label10);
this.Controls.Add(this.label9);
this.Controls.Add(this.label8);
this.Controls.Add(this.label7);
this.Controls.Add(this.label6);
this.Controls.Add(this.label5);
this.Controls.Add(this.label4);
this.Controls.Add(this.button1);
this.Controls.Add(this.label3);
this.Controls.Add(this.textBox2);
this.Controls.Add(this.label2);
this.Controls.Add(this.textBox1);
this.Controls.Add(this.label1);
this.Controls.Add(this.menuStrip1);
this.MainMenuStrip = this.menuStrip1;
this.MaximumSize = new System.Drawing.Size(1024, 768);
this.MinimumSize = new System.Drawing.Size(1024, 768);
this.Name = "Form1";
this.Text = "Funkcja Liniowa";
this.menuStrip1.ResumeLayout(false);
this.menuStrip1.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.MenuStrip menuStrip1;
private System.Windows.Forms.ToolStripMenuItem programToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem zamknijToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem infoToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem oProgramieToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem autorToolStripMenuItem;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.TextBox textBox1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.TextBox textBox2;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.Label label6;
private System.Windows.Forms.Label label7;
private System.Windows.Forms.Label label8;
private System.Windows.Forms.Label label9;
private System.Windows.Forms.Label label10;
private System.Windows.Forms.Label label11;
}
}
| 45.228261 | 119 | 0.56597 | [
"MIT"
] | grzewas/Program-Graficzny | Funkcja Liniowa/Funkcja Liniowa/Form1.Designer.cs | 12,486 | C# |
namespace Org.BouncyCastle.Bcpg.OpenPgp
{
/// <remarks>Key flag values for the KeyFlags subpacket.</remarks>
public abstract class PgpKeyFlags
{
public const int CanCertify = 0x01; // This key may be used to certify other keys.
public const int CanSign = 0x02; // This key may be used to sign data.
public const int CanEncryptCommunications = 0x04; // This key may be used to encrypt communications.
public const int CanEncryptStorage = 0x08; // This key may be used to encrypt storage.
public const int MaybeSplit = 0x10; // The private component of this key may have been split by a secret-sharing mechanism.
public const int MaybeShared = 0x80; // The private component of this key may be in the possession of more than one person.
}
}
| 58.071429 | 132 | 0.699877 | [
"BSD-3-Clause"
] | GaloisInc/hacrypto | src/C#/BouncyCastle/BouncyCastle-1.7/crypto/src/openpgp/PgpKeyFlags.cs | 813 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class GameOverManager : MonoBehaviour {
public Text resultText;
// Use this for initialization
void Start () {
resultText.text = "Game Over...\nYour score is " + ScoreManager.score + "\nPush Space Key.";
}
// Update is called once per frame
void Update () {
if (Input.GetKeyDown(KeyCode.Space))
{
SceneManager.LoadScene("Main");
}
}
}
| 23.347826 | 100 | 0.674115 | [
"MIT"
] | otiket/Flappy-Bird | Assets/GameOverManager.cs | 539 | C# |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.PowerFx.Core;
using Microsoft.PowerFx.Core.IR;
using Microsoft.PowerFx.Core.Public.Values;
using Microsoft.PowerFx.Core.Tests;
using Microsoft.PowerFx.Core.Utils;
using Xunit;
namespace Microsoft.PowerFx.Interpreter.Tests
{
public class ExpressionEvaluationTests
{
internal static Dictionary<string, Func<(RecalcEngine engine, RecordValue parameters)>> SetupHandlers = new Dictionary<string, Func<(RecalcEngine engine, RecordValue parameters)>>()
{
{ "OptionSetTestSetup", OptionSetTestSetup }
};
private static (RecalcEngine engine, RecordValue parameters) OptionSetTestSetup()
{
var optionSet = new OptionSet("OptionSet", new Dictionary<string, string>()
{
{ "option_1", "Option1" },
{ "option_2", "Option2" }
});
var otherOptionSet = new OptionSet("OtherOptionSet", new Dictionary<string, string>()
{
{ "99", "OptionA" },
{ "112", "OptionB" },
{ "35694", "OptionC" },
{ "123412983", "OptionD" },
});
var config = new PowerFxConfig(null);
config.AddOptionSet(optionSet);
config.AddOptionSet(otherOptionSet);
optionSet.TryGetValue(new DName("option_1"), out var o1Val);
otherOptionSet.TryGetValue(new DName("123412983"), out var o2Val);
var parameters = FormulaValue.RecordFromFields(
new NamedValue("TopOptionSetField", o1Val),
new NamedValue("Nested", FormulaValue.RecordFromFields(
new NamedValue("InnerOtherOptionSet", o2Val))));
return (new RecalcEngine(config), parameters);
}
internal class InterpreterRunner : BaseRunner
{
public override Task<FormulaValue> RunAsync(string expr, string setupHandlerName)
{
FeatureFlags.StringInterpolation = true;
RecalcEngine engine;
RecordValue parameters;
if (setupHandlerName != null)
{
if (!SetupHandlers.TryGetValue(setupHandlerName, out var handler))
{
throw new SetupHandlerNotFoundException();
}
(engine, parameters) = handler();
}
else
{
engine = new RecalcEngine();
parameters = null;
}
var result = engine.Eval(expr, parameters);
return Task.FromResult(result);
}
}
}
}
| 35.421687 | 190 | 0.55034 | [
"MIT"
] | Seanpm2001-Microsoft/Power-Fx | src/tests/Microsoft.PowerFx.Interpreter.Tests/PowerFxEvaluationTests.cs | 2,942 | C# |
using System;
using System.IO;
using System.Threading.Tasks;
namespace Lykke.AlgoStore.MatchingEngineAdapter.Abstractions.Services.Listening
{
internal static class StreamExtensions
{
public static async Task FillBufferAsync(this Stream stream, byte[] buffer)
{
if (stream == null)
throw new ArgumentNullException(nameof(stream));
if (buffer == null)
throw new ArgumentNullException(nameof(buffer));
var bytesReadTotal = 0;
while(bytesReadTotal < buffer.Length)
{
var bytesRead = await stream.ReadAsync(buffer, bytesReadTotal, buffer.Length - bytesReadTotal);
if (bytesRead == 0)
throw new EndOfStreamException();
bytesReadTotal += bytesRead;
}
}
}
}
| 27.935484 | 111 | 0.594688 | [
"MIT"
] | LykkeCity/Lykke.AlgoStore.MatchingEngineAdapter | src/Lykke.AlgoStore.MatchingEngineAdapter.Abstractions/Services/Listening/StreamExtensions.cs | 868 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static void Main(string[] args)
{
var n = int.Parse(Console.ReadLine());
var cars = new List<Car>();
for (int i = 0; i < n; i++)
{
var input = Console.ReadLine().Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries);
var model= input[0];
var eSpeed = int.Parse(input[1]);
var ePower = int.Parse(input[2]);
var cWeight= int.Parse(input[3]);
var cType = input[4];
var tire1 = new Tire();
tire1.TirePressure = double.Parse(input[5]);
tire1.TireAge = int.Parse(input[6]);
var tire2 = new Tire();
tire2.TirePressure = double.Parse(input[7]);
tire2.TireAge = int.Parse(input[8]);
var tire3 = new Tire();
tire3.TirePressure = double.Parse(input[9]);
tire3.TireAge = int.Parse(input[10]);
var tire4 = new Tire();
tire4.TirePressure = double.Parse(input[11]);
tire4.TireAge = int.Parse(input[12]);
var cargo = new Cargo();
cargo.CargoType = cType;
cargo.CargoWeight = cWeight;
var engine = new Engine();
engine.EnginePower = ePower;
engine.EngineSpeed = eSpeed;
var car = new Car();
car.Model = model;
car.Cargo = cargo;
car.Engine = engine;
car.Tires.Add(tire1);
car.Tires.Add(tire2);
car.Tires.Add(tire3);
car.Tires.Add(tire4);
cars.Add(car);
}
var type = Console.ReadLine();
if (type == "fragile")
{
var carsFragile = cars.Where(x => x.Tires.Any(y => y.TirePressure < 1)).ToList();
foreach(var c in carsFragile)
{
Console.WriteLine(c.Model);
}
}
if(type== "flamable")
{
var carsFlamable = cars.Where(x => x.Engine.EnginePower > 250).ToList();
foreach (var c in carsFlamable)
{
Console.WriteLine(c.Model);
}
}
}
}
| 31.236111 | 103 | 0.499333 | [
"MIT"
] | YordanYordanov97/Softuni | OOP Basic/Defining Classes - Exercise/08. Raw Data/Program.cs | 2,251 | C# |
namespace Hexalith.DataIntegrations.Domain.States
{
using System;
using System.Collections.Generic;
using Hexalith.DataIntegrations.Contracts.Events;
public sealed class DataIntegrationState : IDataIntegrationState
{
public dynamic? Data { get; set; }
public string Description { get; set; } = string.Empty;
public string Document { get; set; } = string.Empty;
public string DocumentName { get; set; } = string.Empty;
public string DocumentType { get; set; } = string.Empty;
public string Name { get; set; } = string.Empty;
public void Apply(IEnumerable<object> events)
{
foreach (var @event in events)
{
switch (@event)
{
case DataIntegrationSubmitted submitted:
Apply(submitted);
break;
case DataIntegrationNormalized normalized:
Apply(normalized);
break;
default:
throw new NotSupportedException($"Event type '{@event.GetType().Name} is not supported by '{nameof(DataIntegrationState)}''");
}
}
}
private void Apply(DataIntegrationSubmitted submitted)
{
Name = submitted.Name;
Description = submitted.Description;
DocumentName = submitted.DocumentName;
DocumentType = submitted.DocumentType;
Document = submitted.Document;
}
private void Apply(DataIntegrationNormalized normalized)
{
Data = normalized.Data;
}
}
} | 33.411765 | 150 | 0.556925 | [
"MIT"
] | Hexalith/Hexalith | src/Modules/Shared/Hexalith.DataIntegrations.Common/Domain/States/DataIntegrationState.cs | 1,706 | C# |
#nullable disable
namespace Amazon.Ssm;
public sealed class UpdateDocumentResponse
{
public DocumentDescription DocumentDescription { get; init; }
}
| 18.222222 | 66 | 0.75 | [
"MIT"
] | TheJVaughan/Amazon | src/Amazon.Ssm/Actions/UpdateDocumentResponse.cs | 166 | C# |
#region License
/*
The MIT License
Copyright (c) 2008 Sky Morey
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#endregion
using System.Collections.Generic;
using System.Reflection;
using System.Web.Handlers;
namespace System.Web.UI
{
internal delegate string GetWebResourceUrlDelegate(Type type, string resourceName, bool htmlEncoded);
/// <summary>
/// IClientScriptManager
/// </summary>
public interface IClientScriptManager
{
void EnsureItem(string id, Func<ClientScriptItemBase> item);
void EnsureItem<TShard>(string id, Func<ClientScriptItemBase> item);
void AddRange(ClientScriptItemBase item);
void AddRange(string literal);
void AddRange(params object[] items);
void AddRange<TShard>(ClientScriptItemBase item);
void AddRange<TShard>(string literal);
void AddRange<TShard>(params object[] items);
IClientScriptRepository GetRepository<TShard>();
IClientScriptRepository GetRepository(Type shard);
void SetRepository<TShard>(IClientScriptRepository repository);
void SetRepository(Type type, IClientScriptRepository repository);
}
/// <summary>
/// ClientScriptManagerEx
/// </summary>
public class ClientScriptManagerEx : IClientScriptManager
{
private static readonly GetWebResourceUrlDelegate _getWebResourceUrl = (GetWebResourceUrlDelegate)Delegate.CreateDelegate(typeof(GetWebResourceUrlDelegate), typeof(AssemblyResourceLoader).GetMethod("GetWebResourceUrl", BindingFlags.NonPublic | BindingFlags.Static, null, new[] { typeof(Type), typeof(string), typeof(bool) }, null));
private static readonly Type _type = typeof(IClientScriptManager);
private static readonly Type _htmlHeadType = typeof(System.Web.UI.HtmlControls.HtmlHead);
private IClientScriptRepository _defaultRepository = new ClientScriptRepository();
private IClientScriptRepository _htmlHeadRepository = new ClientScriptRepository();
private Dictionary<Type, IClientScriptRepository> _repositories;
public ClientScriptManagerEx() { }
public void EnsureItem(string id, Func<ClientScriptItemBase> item) { _defaultRepository.EnsureItem(id, item); }
public void EnsureItem<TShard>(string id, Func<ClientScriptItemBase> item) { GetRepository(typeof(TShard)).EnsureItem(id, item); }
public void AddRange(ClientScriptItemBase item) { _defaultRepository.AddRange(item); }
public void AddRange(string literal) { _defaultRepository.AddRange(literal); }
public void AddRange(params object[] items) { _defaultRepository.AddRange(items); }
public void AddRange<TShard>(ClientScriptItemBase item) { GetRepository(typeof(TShard)).AddRange(item); }
public void AddRange<TShard>(string literal) { GetRepository(typeof(TShard)).AddRange(literal); }
public void AddRange<TShard>(params object[] items) { GetRepository(typeof(TShard)).AddRange(items); }
public IClientScriptRepository GetRepository<TShard>() { return GetRepository(typeof(TShard)); }
public IClientScriptRepository GetRepository(Type shard)
{
if (shard == _type)
return _defaultRepository;
if (shard == _htmlHeadType)
return _htmlHeadRepository;
// repositories
if (_repositories == null)
_repositories = new Dictionary<Type, IClientScriptRepository>();
IClientScriptRepository repository;
if (!_repositories.TryGetValue(shard, out repository))
_repositories.Add(shard, (repository = new ClientScriptRepository()));
return repository;
}
public void SetRepository<TShard>(IClientScriptRepository repository) { SetRepository(typeof(TShard), repository); }
public void SetRepository(Type shard, IClientScriptRepository repository)
{
if (shard == _type)
_defaultRepository = repository;
if (shard == _htmlHeadType)
_htmlHeadRepository = repository;
// repositories
if (_repositories == null)
_repositories = new Dictionary<Type, IClientScriptRepository>();
_repositories[shard] = repository;
}
public static string GetWebResourceUrl(Type type, string resourceName) { return GetWebResourceUrl(type, resourceName, false); }
public static string GetWebResourceUrl(Type type, string resourceName, bool htmlEncoded)
{
if (type == null)
throw new ArgumentNullException("type");
if (string.IsNullOrEmpty(resourceName))
throw new ArgumentNullException("resourceName");
return _getWebResourceUrl(type, resourceName, htmlEncoded);
}
}
}
| 52.061404 | 341 | 0.700253 | [
"MIT"
] | Grimace1975/bclcontrib-web | System.WebEx/Web/UI+ClientScript/ClientScriptManagerEx.cs | 5,935 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
namespace GastosAppCoreEF.Models
{
[Table("vCashFlow")]
public class vCashFlow
{
[Key]
public string NombreConcepto { get; set; }
public DateTime Fecha { get; set; }
public decimal Monto { get; set; }
public int? ConceptoId { get; set; }
public virtual Concepto Concepto { get; set; }
public int? CuentaIdTransf { get; set; }
[ForeignKey("CuentaIdTransf")]
public virtual Cuenta CuentaTransf { get; set; }
public int UsuarioId { get; set; }
public virtual Usuario Usuario { get; set; }
}
}
| 28.888889 | 56 | 0.655128 | [
"MIT"
] | pedroren/gastosappvue | GastosAppCoreEF/Models/vCashFlow.cs | 782 | C# |
// ReSharper disable All
namespace OpenTl.Schema
{
using System;
using System.Collections;
using System.Text;
using OpenTl.Schema;
using OpenTl.Schema.Serialization.Attributes;
[Serialize(0xd1d34a26)]
public sealed class TSendMessageUploadPhotoAction : ISendMessageAction
{
[SerializationOrder(0)]
public int Progress {get; set;}
}
}
| 18.15 | 71 | 0.743802 | [
"MIT"
] | zzz8415/OpenTl.Schema | src/OpenTl.Schema/_generated/_Entities/SendMessageAction/TSendMessageUploadPhotoAction.cs | 365 | C# |
// ***********************************************************************
// Assembly : MigrationFactory.O365Groups.ModernPage
// Author : shiv
// Created : 12-21-2018
//
// Last Modified By : shiv
// Last Modified On : 01-04-2019
// ***********************************************************************
namespace MigrationFactory.O365Groups.ModernPage
{
using Microsoft.SharePoint.Client;
//using OfficeDevPnP.Core.Framework.Provisioning.Model;
using System;
using MigrationFactory.O365Groups.Logging;
using MigrationFactory.O365Groups.ModernPage.Utilities;
/// <summary>
/// Class WikiPage.
/// Implements the <see cref="MigrationFactory.O365Groups.ModernPage.ModernPage" />
/// </summary>
/// <seealso cref="MigrationFactory.O365Groups.ModernPage.ModernPage" />
public class WikiPage: ModernPage
{
/// <summary>
/// Initializes a new instance of the <see cref="WikiPage"/> class.
/// </summary>
/// <param name="logger">The logger.</param>
/// <param name="retryCount">The retry count.</param>
/// <param name="delay">The delay.</param>
public WikiPage(IAsyncLogger logger, int retryCount, int delay) : base(logger, retryCount, delay)
{
Logger = logger;
RetryCount = retryCount;
Delay = delay;
}
/// <summary>
/// Creates the page with web parts.
/// </summary>
/// <param name="sourceContext">The source context.</param>
/// <param name="targetContext">The target context.</param>
/// <param name="targetWeb">The target web.</param>
/// <param name="sourceItem">The source item.</param>
/// <param name="pageName">Name of the page.</param>
/// <returns>ListItem.</returns>
public override ListItem CreatePageWithWebParts(ClientContext sourceContext, ClientContext targetContext, Web targetWeb, ListItem sourceItem, string pageName)
{
ListItem targetItem = null;
Logger.Log("Into CreatePageWithWebParts for " + pageName);
if (targetWeb != null)
{
try
{
var wikiPageRelativeUrl = targetWeb.EnsureWikiPage(sourceItem.ParentList.Title, pageName); //.AddWikiPage(Constants.ModernPageLibrary, pageName);
var wikiPage = targetWeb.GetFileByServerRelativeUrl(targetWeb.ServerRelativeUrl + "/" + wikiPageRelativeUrl);
targetItem = wikiPage.ListItemAllFields;
targetContext.Load(wikiPage);
targetContext.Load(targetItem, i => i.DisplayName);
targetContext.ExecuteQueryWithIncrementalRetry(RetryCount, Delay);
var webPartOps = new WebPartOperation(Logger, RetryCount, Delay);
var webpartList = webPartOps.ExportWebPart(sourceContext, sourceItem.File);
webPartOps.ImportWebParts(targetContext, targetWeb, webpartList, wikiPage);
AddContent(targetContext, targetItem, sourceItem, Constants.WikiPageContentControl);
if (targetItem != null && sourceItem.HasUniqueRoleAssignments)
ManagePermissions(sourceContext, targetContext, sourceItem, targetItem);
UpdateSystemFields(targetContext, targetItem, sourceItem);
}
catch (Exception ex)
{
ConsoleOperations.WriteToConsole("Exception in migrating the page: " + pageName + " on " + sourceContext.Web.Url, ConsoleColor.Red);
Logger.LogError("Error in CreatePageWithWebParts for WikiPage " + pageName + Environment.NewLine + ex.Message);
//throw ex;
}
}
return targetItem;
}
}
}
| 46.094118 | 166 | 0.584227 | [
"MIT"
] | sshkkumar/SharePointMigrationTools | MigrationFactory.O365Groups.ModernPage/Entity/WikiPage.cs | 3,920 | C# |
using BizHawk.Common;
using BizHawk.Emulation.Cores.Components.LR35902;
namespace BizHawk.Emulation.Cores.Nintendo.GBHawk
{
// MBC1 with bank switching and RAM
public class MapperMBC1 : MapperBase
{
public int ROM_bank;
public int RAM_bank;
public bool RAM_enable;
public bool sel_mode;
public int ROM_mask;
public int RAM_mask;
public override void Reset()
{
ROM_bank = 1;
RAM_bank = 0;
RAM_enable = false;
sel_mode = false;
ROM_mask = Core._rom.Length / 0x4000 - 1;
// some games have sizes that result in a degenerate ROM, account for it here
if (ROM_mask > 4) { ROM_mask |= 3; }
RAM_mask = 0;
if (Core.cart_RAM != null)
{
RAM_mask = Core.cart_RAM.Length / 0x2000 - 1;
if (Core.cart_RAM.Length == 0x800) { RAM_mask = 0; }
}
}
public override byte ReadMemoryLow(ushort addr)
{
if (addr < 0x4000)
{
// lowest bank is fixed, but is still effected by mode
if (sel_mode)
{
return Core._rom[(ROM_bank & 0x60) * 0x4000 + addr];
}
return Core._rom[addr];
}
return Core._rom[(addr - 0x4000) + ROM_bank * 0x4000];
}
public override byte ReadMemoryHigh(ushort addr)
{
if (Core.cart_RAM != null)
{
if (RAM_enable && (((addr - 0xA000) + RAM_bank * 0x2000) < Core.cart_RAM.Length))
{
return Core.cart_RAM[(addr - 0xA000) + RAM_bank * 0x2000];
}
else
{
return 0xFF;
}
}
else
{
return 0xFF;
}
}
public override void MapCDL(ushort addr, LR35902.eCDLogMemFlags flags)
{
if (addr < 0x4000)
{
// lowest bank is fixed, but is still effected by mode
if (sel_mode)
{
SetCDLROM(flags, (ROM_bank & 0x60) * 0x4000 + addr);
}
else
{
SetCDLROM(flags, addr);
}
}
else if (addr < 0x8000)
{
SetCDLROM(flags, (addr - 0x4000) + ROM_bank * 0x4000);
}
else
{
if (Core.cart_RAM != null)
{
if (RAM_enable && (((addr - 0xA000) + RAM_bank * 0x2000) < Core.cart_RAM.Length))
{
SetCDLRAM(flags, (addr - 0xA000) + RAM_bank * 0x2000);
}
else
{
return;
}
}
else
{
return;
}
}
}
public override byte PeekMemoryLow(ushort addr)
{
return ReadMemoryLow(addr);
}
public override void WriteMemory(ushort addr, byte value)
{
if (addr < 0x8000)
{
if (addr < 0x2000)
{
RAM_enable = (value & 0xF) == 0xA;
}
else if (addr < 0x4000)
{
value &= 0x1F;
// writing zero gets translated to 1
if (value == 0) { value = 1; }
ROM_bank &= 0xE0;
ROM_bank |= value;
ROM_bank &= ROM_mask;
}
else if (addr < 0x6000)
{
if (sel_mode && Core.cart_RAM != null)
{
RAM_bank = value & 3;
RAM_bank &= RAM_mask;
}
else
{
ROM_bank &= 0x1F;
ROM_bank |= ((value & 3) << 5);
ROM_bank &= ROM_mask;
}
}
else
{
sel_mode = (value & 1) > 0;
if (sel_mode && Core.cart_RAM != null)
{
ROM_bank &= 0x1F;
ROM_bank &= ROM_mask;
}
else
{
RAM_bank = 0;
}
}
}
else
{
if (Core.cart_RAM != null)
{
if (RAM_enable && (((addr - 0xA000) + RAM_bank * 0x2000) < Core.cart_RAM.Length))
{
Core.cart_RAM[(addr - 0xA000) + RAM_bank * 0x2000] = value;
}
}
}
}
public override void PokeMemory(ushort addr, byte value)
{
WriteMemory(addr, value);
}
public override void SyncState(Serializer ser)
{
ser.Sync(nameof(ROM_bank), ref ROM_bank);
ser.Sync(nameof(ROM_mask), ref ROM_mask);
ser.Sync(nameof(RAM_bank), ref RAM_bank);
ser.Sync(nameof(RAM_mask), ref RAM_mask);
ser.Sync(nameof(RAM_enable), ref RAM_enable);
ser.Sync(nameof(sel_mode), ref sel_mode);
}
}
}
| 20.806283 | 87 | 0.548566 | [
"MIT"
] | Qapples/BizHawk | src/BizHawk.Emulation.Cores/Consoles/Nintendo/GBHawk/Mappers/Mapper_MBC1.cs | 3,976 | C# |
namespace NeuralNetworkTSU
{
partial class Form1
{
/// <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.button1 = new System.Windows.Forms.Button();
this.pictureBox1 = new System.Windows.Forms.PictureBox();
this.button3 = new System.Windows.Forms.Button();
this.button4 = new System.Windows.Forms.Button();
this.label1 = new System.Windows.Forms.Label();
this.lblDetectedNumber = new System.Windows.Forms.Label();
this.progressBar1 = new System.Windows.Forms.ProgressBar();
this.pictureBox2 = new System.Windows.Forms.PictureBox();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.pictureBox2)).BeginInit();
this.SuspendLayout();
//
// button1
//
this.button1.Location = new System.Drawing.Point(12, 12);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(152, 23);
this.button1.TabIndex = 0;
this.button1.Text = "Load database";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click_1);
//
// pictureBox1
//
this.pictureBox1.BackColor = System.Drawing.Color.White;
this.pictureBox1.Location = new System.Drawing.Point(80, 123);
this.pictureBox1.Name = "pictureBox1";
this.pictureBox1.Size = new System.Drawing.Size(28, 28);
this.pictureBox1.TabIndex = 2;
this.pictureBox1.TabStop = false;
this.pictureBox1.Click += new System.EventHandler(this.pictureBox1_Click);
this.pictureBox1.Paint += new System.Windows.Forms.PaintEventHandler(this.pictureBox1_Paint);
this.pictureBox1.MouseDown += new System.Windows.Forms.MouseEventHandler(this.pictureBox1_MouseDown);
this.pictureBox1.MouseMove += new System.Windows.Forms.MouseEventHandler(this.pictureBox1_MouseMove);
this.pictureBox1.MouseUp += new System.Windows.Forms.MouseEventHandler(this.pictureBox1_MouseUp);
//
// button3
//
this.button3.Location = new System.Drawing.Point(12, 213);
this.button3.Name = "button3";
this.button3.Size = new System.Drawing.Size(96, 23);
this.button3.TabIndex = 3;
this.button3.Text = "Detect number";
this.button3.UseVisualStyleBackColor = true;
this.button3.Click += new System.EventHandler(this.button3_Click);
//
// button4
//
this.button4.Location = new System.Drawing.Point(114, 213);
this.button4.Name = "button4";
this.button4.Size = new System.Drawing.Size(50, 23);
this.button4.TabIndex = 4;
this.button4.Text = "Clear";
this.button4.UseVisualStyleBackColor = true;
this.button4.Click += new System.EventHandler(this.button4_Click);
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(16, 197);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(92, 13);
this.label1.TabIndex = 5;
this.label1.Text = "Detected number:";
//
// lblDetectedNumber
//
this.lblDetectedNumber.AutoSize = true;
this.lblDetectedNumber.Location = new System.Drawing.Point(115, 197);
this.lblDetectedNumber.Name = "lblDetectedNumber";
this.lblDetectedNumber.Size = new System.Drawing.Size(0, 13);
this.lblDetectedNumber.TabIndex = 6;
//
// progressBar1
//
this.progressBar1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.progressBar1.Location = new System.Drawing.Point(12, 311);
this.progressBar1.Name = "progressBar1";
this.progressBar1.Size = new System.Drawing.Size(589, 23);
this.progressBar1.TabIndex = 7;
//
// pictureBox2
//
this.pictureBox2.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.pictureBox2.Location = new System.Drawing.Point(322, 12);
this.pictureBox2.Name = "pictureBox2";
this.pictureBox2.Size = new System.Drawing.Size(280, 280);
this.pictureBox2.TabIndex = 8;
this.pictureBox2.TabStop = false;
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.Color.SeaGreen;
this.ClientSize = new System.Drawing.Size(613, 346);
this.Controls.Add(this.pictureBox2);
this.Controls.Add(this.progressBar1);
this.Controls.Add(this.lblDetectedNumber);
this.Controls.Add(this.label1);
this.Controls.Add(this.button4);
this.Controls.Add(this.button3);
this.Controls.Add(this.pictureBox1);
this.Controls.Add(this.button1);
this.Name = "Form1";
this.Text = "Form1";
this.Load += new System.EventHandler(this.Form1_Load);
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.pictureBox2)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Button button1;
private System.Windows.Forms.PictureBox pictureBox1;
private System.Windows.Forms.Button button3;
private System.Windows.Forms.Button button4;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label lblDetectedNumber;
private System.Windows.Forms.ProgressBar progressBar1;
private System.Windows.Forms.PictureBox pictureBox2;
}
}
| 46.106918 | 161 | 0.5991 | [
"MIT"
] | AleksandreSukh/NeuralNetworkProjectForUniversity | NeuralNetworkTSU/NeuralNetworkTSU/Form1.Designer.cs | 7,333 | C# |
#region Copyright notice and license
// Copyright 2016 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using System;
using System.Reflection;
using Grpc.Core;
using Grpc.Core.Logging;
using NUnit.Common;
using NUnitLite;
namespace Grpc.Core.Tests
{
/// <summary>
/// Provides entry point for NUnitLite
/// </summary>
public class NUnitMain
{
public static int Main(string[] args)
{
// Make logger immune to NUnit capturing stdout and stderr to workaround https://github.com/nunit/nunit/issues/1406.
GrpcEnvironment.SetLogger(new ConsoleLogger());
#if NETCOREAPP1_0
return new AutoRun(typeof(NUnitMain).GetTypeInfo().Assembly).Execute(args, new ExtendedTextWrapper(Console.Out), Console.In);
#else
return new AutoRun().Execute(args);
#endif
}
}
}
| 30.688889 | 137 | 0.706734 | [
"Apache-2.0"
] | 0mok/grpc | src/csharp/Grpc.Core.Tests/NUnitMain.cs | 1,381 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace nba.Entidades
{
public class Jugador
{
int idJugador;
string nombre;
int altura;
double peso;
int dorsal;
int equipo_id;
int posicion_id;
public Jugador()
{
this.idJugador = -1;
this.nombre = string.Empty;
this.altura = -1;
this.peso = 0;
this.dorsal = -1;
this.equipo_id = -1;
this.posicion_id = -1;
}
public Jugador(int idJugador, string nombre, int altura, double peso, int dorsal, int equipo_id, int posicion_id)
{
this.idJugador = idJugador;
this.nombre = nombre;
this.altura = altura;
this.peso = peso;
this.dorsal = dorsal;
this.equipo_id = equipo_id;
this.posicion_id = posicion_id;
}
public int IdJugador
{
get
{
return idJugador;
}
set
{
idJugador = value;
}
}
public string Nombre
{
get
{
return nombre;
}
set
{
nombre = value;
}
}
public int Altura
{
get
{
return altura;
}
set
{
altura = value;
}
}
public double Peso
{
get
{
return peso;
}
set
{
peso = value;
}
}
public int Dorsal
{
get
{
return dorsal;
}
set
{
dorsal = value;
}
}
public int Equipo_id
{
get
{
return equipo_id;
}
set
{
equipo_id = value;
}
}
public int Posicion_id
{
get
{
return posicion_id;
}
set
{
posicion_id = value;
}
}
}
}
| 18.454545 | 121 | 0.362479 | [
"MIT"
] | jaimefrailedb/nbajaime | nba/Entidades/Jugador.cs | 2,438 | C# |
namespace CustomLinkedList
{
public class ListItem<T>
{
T Value { get; set; }
ListItem<T> NextItem { get; set; }
}
}
| 14.7 | 42 | 0.544218 | [
"MIT"
] | vassildinev/Data-Structures-and-Algorithms | 02.LinearDataStructuresHomework/11.CustomLinkedList/ListItem.cs | 149 | C# |
// This file is part of the DSharpPlus project.
//
// Copyright (c) 2015 Mike Santiago
// Copyright (c) 2016-2022 DSharpPlus Contributors
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using DSharpPlus.Entities;
using DSharpPlus.EventArgs;
using DSharpPlus.Net.Abstractions;
using DSharpPlus.Net.Serialization;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Linq;
namespace DSharpPlus
{
public sealed partial class DiscordClient
{
#region Private Fields
private string _sessionId;
private bool _guildDownloadCompleted = false;
#endregion
#region Dispatch Handler
internal async Task HandleDispatchAsync(GatewayPayload payload)
{
if (payload.Data is not JObject dat)
{
this.Logger.LogWarning(LoggerEvents.WebSocketReceive, "Invalid payload body (this message is probably safe to ignore); opcode: {Op} event: {Event}; payload: {Payload}", payload.OpCode, payload.EventName, payload.Data);
return;
}
DiscordChannel chn;
DiscordThreadChannel thread;
ulong gid;
ulong cid;
TransportUser usr = default;
TransportMember mbr = default;
TransportUser refUsr = default;
TransportMember refMbr = default;
JToken rawMbr = default;
var rawRefMsg = dat["referenced_message"];
switch (payload.EventName.ToLowerInvariant())
{
#region Gateway Status
case "ready":
var glds = (JArray)dat["guilds"];
var dmcs = (JArray)dat["private_channels"];
await this.OnReadyEventAsync(dat.ToObject<ReadyPayload>(), glds, dmcs).ConfigureAwait(false);
break;
case "resumed":
await this.OnResumedAsync().ConfigureAwait(false);
break;
#endregion
#region Channel
case "channel_create":
chn = dat.ToObject<DiscordChannel>();
await this.OnChannelCreateEventAsync(chn).ConfigureAwait(false);
break;
case "channel_update":
await this.OnChannelUpdateEventAsync(dat.ToObject<DiscordChannel>()).ConfigureAwait(false);
break;
case "channel_delete":
chn = dat.ToObject<DiscordChannel>();
await this.OnChannelDeleteEventAsync(chn.IsPrivate ? dat.ToObject<DiscordDmChannel>() : chn).ConfigureAwait(false);
break;
case "channel_pins_update":
cid = (ulong)dat["channel_id"];
var ts = (string)dat["last_pin_timestamp"];
await this.OnChannelPinsUpdateAsync((ulong?)dat["guild_id"], cid, ts != null ? DateTimeOffset.Parse(ts, CultureInfo.InvariantCulture) : default(DateTimeOffset?)).ConfigureAwait(false);
break;
#endregion
#region Scheduled Guild Events
case "guild_scheduled_event_create":
var cevt = dat.ToObject<DiscordScheduledGuildEvent>();
await this.OnScheduledGuildEventCreateEventAsync(cevt).ConfigureAwait(false);
break;
case "guild_scheduled_event_delete":
var devt = dat.ToObject<DiscordScheduledGuildEvent>();
await this.OnScheduledGuildEventDeleteEventAsync(devt).ConfigureAwait(false);
break;
case "guild_scheduled_event_update":
var uevt = dat.ToObject<DiscordScheduledGuildEvent>();
await this.OnScheduledGuildEventUpdateEventAsync(uevt).ConfigureAwait(false);
break;
case "guild_scheduled_event_user_add":
gid = (ulong)dat["guild_id"];
var uid = (ulong)dat["user_id"];
var eid = (ulong)dat["event_id"];
await this.OnScheduledGuildEventUserAddEventAsync(gid, eid, uid).ConfigureAwait(false);
break;
case "guild_scheduled_event_user_remove":
gid = (ulong)dat["guild_id"];
uid = (ulong)dat["user_id"];
eid = (ulong)dat["event_id"];
await this.OnScheduledGuildEventUserRemoveEventAsync(gid, eid, uid).ConfigureAwait(false);
break;
#endregion
#region Guild
case "guild_create":
await this.OnGuildCreateEventAsync(dat.ToDiscordObject<DiscordGuild>(), (JArray)dat["members"], dat["presences"].ToDiscordObject<IEnumerable<DiscordPresence>>()).ConfigureAwait(false);
break;
case "guild_update":
await this.OnGuildUpdateEventAsync(dat.ToDiscordObject<DiscordGuild>(), (JArray)dat["members"]).ConfigureAwait(false);
break;
case "guild_delete":
await this.OnGuildDeleteEventAsync(dat.ToDiscordObject<DiscordGuild>(), (JArray)dat["members"]).ConfigureAwait(false);
break;
case "guild_sync":
gid = (ulong)dat["id"];
await this.OnGuildSyncEventAsync(this._guilds[gid], (bool)dat["large"], (JArray)dat["members"], dat["presences"].ToObject<IEnumerable<DiscordPresence>>()).ConfigureAwait(false);
break;
case "guild_emojis_update":
gid = (ulong)dat["guild_id"];
var ems = dat["emojis"].ToObject<IEnumerable<DiscordEmoji>>();
await this.OnGuildEmojisUpdateEventAsync(this._guilds[gid], ems).ConfigureAwait(false);
break;
case "guild_integrations_update":
gid = (ulong)dat["guild_id"];
// discord fires this event inconsistently if the current user leaves a guild.
if (!this._guilds.ContainsKey(gid))
return;
await this.OnGuildIntegrationsUpdateEventAsync(this._guilds[gid]).ConfigureAwait(false);
break;
#endregion
#region Guild Ban
case "guild_ban_add":
usr = dat["user"].ToObject<TransportUser>();
gid = (ulong)dat["guild_id"];
await this.OnGuildBanAddEventAsync(usr, this._guilds[gid]).ConfigureAwait(false);
break;
case "guild_ban_remove":
usr = dat["user"].ToObject<TransportUser>();
gid = (ulong)dat["guild_id"];
await this.OnGuildBanRemoveEventAsync(usr, this._guilds[gid]).ConfigureAwait(false);
break;
#endregion
#region Guild Member
case "guild_member_add":
gid = (ulong)dat["guild_id"];
await this.OnGuildMemberAddEventAsync(dat.ToObject<TransportMember>(), this._guilds[gid]).ConfigureAwait(false);
break;
case "guild_member_remove":
gid = (ulong)dat["guild_id"];
usr = dat["user"].ToObject<TransportUser>();
if (!this._guilds.ContainsKey(gid))
{
// discord fires this event inconsistently if the current user leaves a guild.
if (usr.Id != this.CurrentUser.Id)
this.Logger.LogError(LoggerEvents.WebSocketReceive, "Could not find {Guild} in guild cache", gid);
return;
}
await this.OnGuildMemberRemoveEventAsync(usr, this._guilds[gid]).ConfigureAwait(false);
break;
case "guild_member_update":
gid = (ulong)dat["guild_id"];
await this.OnGuildMemberUpdateEventAsync(dat.ToDiscordObject<TransportMember>(), this._guilds[gid], dat["roles"].ToObject<IEnumerable<ulong>>(), (string)dat["nick"], (bool?)dat["pending"], (DateTimeOffset?)dat["communication_disabled_until"]).ConfigureAwait(false);
break;
case "guild_members_chunk":
await this.OnGuildMembersChunkEventAsync(dat).ConfigureAwait(false);
break;
#endregion
#region Guild Role
case "guild_role_create":
gid = (ulong)dat["guild_id"];
await this.OnGuildRoleCreateEventAsync(dat["role"].ToObject<DiscordRole>(), this._guilds[gid]).ConfigureAwait(false);
break;
case "guild_role_update":
gid = (ulong)dat["guild_id"];
await this.OnGuildRoleUpdateEventAsync(dat["role"].ToObject<DiscordRole>(), this._guilds[gid]).ConfigureAwait(false);
break;
case "guild_role_delete":
gid = (ulong)dat["guild_id"];
await this.OnGuildRoleDeleteEventAsync((ulong)dat["role_id"], this._guilds[gid]).ConfigureAwait(false);
break;
#endregion
#region Invite
case "invite_create":
gid = (ulong)dat["guild_id"];
cid = (ulong)dat["channel_id"];
await this.OnInviteCreateEventAsync(cid, gid, dat.ToObject<DiscordInvite>()).ConfigureAwait(false);
break;
case "invite_delete":
gid = (ulong)dat["guild_id"];
cid = (ulong)dat["channel_id"];
await this.OnInviteDeleteEventAsync(cid, gid, dat).ConfigureAwait(false);
break;
#endregion
#region Message
case "message_ack":
cid = (ulong)dat["channel_id"];
var mid = (ulong)dat["message_id"];
await this.OnMessageAckEventAsync(this.InternalGetCachedChannel(cid), mid).ConfigureAwait(false);
break;
case "message_create":
rawMbr = dat["member"];
if (rawMbr != null)
mbr = rawMbr.ToObject<TransportMember>();
if (rawRefMsg != null && rawRefMsg.HasValues)
{
if (rawRefMsg.SelectToken("author") != null)
{
refUsr = rawRefMsg.SelectToken("author").ToObject<TransportUser>();
}
if (rawRefMsg.SelectToken("member") != null)
{
refMbr = rawRefMsg.SelectToken("member").ToObject<TransportMember>();
}
}
await this.OnMessageCreateEventAsync(dat.ToDiscordObject<DiscordMessage>(), dat["author"].ToObject<TransportUser>(), mbr, refUsr, refMbr).ConfigureAwait(false);
break;
case "message_update":
rawMbr = dat["member"];
if (rawMbr != null)
mbr = rawMbr.ToObject<TransportMember>();
if (rawRefMsg != null && rawRefMsg.HasValues)
{
if (rawRefMsg.SelectToken("author") != null)
{
refUsr = rawRefMsg.SelectToken("author").ToObject<TransportUser>();
}
if (rawRefMsg.SelectToken("member") != null)
{
refMbr = rawRefMsg.SelectToken("member").ToObject<TransportMember>();
}
}
await this.OnMessageUpdateEventAsync(dat.ToDiscordObject<DiscordMessage>(), dat["author"]?.ToObject<TransportUser>(), mbr, refUsr, refMbr).ConfigureAwait(false);
break;
// delete event does *not* include message object
case "message_delete":
await this.OnMessageDeleteEventAsync((ulong)dat["id"], (ulong)dat["channel_id"], (ulong?)dat["guild_id"]).ConfigureAwait(false);
break;
case "message_delete_bulk":
await this.OnMessageBulkDeleteEventAsync(dat["ids"].ToObject<ulong[]>(), (ulong)dat["channel_id"], (ulong?)dat["guild_id"]).ConfigureAwait(false);
break;
#endregion
#region Message Reaction
case "message_reaction_add":
rawMbr = dat["member"];
if (rawMbr != null)
mbr = rawMbr.ToObject<TransportMember>();
await this.OnMessageReactionAddAsync((ulong)dat["user_id"], (ulong)dat["message_id"], (ulong)dat["channel_id"], (ulong?)dat["guild_id"], mbr, dat["emoji"].ToObject<DiscordEmoji>()).ConfigureAwait(false);
break;
case "message_reaction_remove":
await this.OnMessageReactionRemoveAsync((ulong)dat["user_id"], (ulong)dat["message_id"], (ulong)dat["channel_id"], (ulong?)dat["guild_id"], dat["emoji"].ToObject<DiscordEmoji>()).ConfigureAwait(false);
break;
case "message_reaction_remove_all":
await this.OnMessageReactionRemoveAllAsync((ulong)dat["message_id"], (ulong)dat["channel_id"], (ulong?)dat["guild_id"]).ConfigureAwait(false);
break;
case "message_reaction_remove_emoji":
await this.OnMessageReactionRemoveEmojiAsync((ulong)dat["message_id"], (ulong)dat["channel_id"], (ulong)dat["guild_id"], dat["emoji"]).ConfigureAwait(false);
break;
#endregion
#region User/Presence Update
case "presence_update":
await this.OnPresenceUpdateEventAsync(dat, (JObject)dat["user"]).ConfigureAwait(false);
break;
case "user_settings_update":
await this.OnUserSettingsUpdateEventAsync(dat.ToObject<TransportUser>()).ConfigureAwait(false);
break;
case "user_update":
await this.OnUserUpdateEventAsync(dat.ToObject<TransportUser>()).ConfigureAwait(false);
break;
#endregion
#region Voice
case "voice_state_update":
await this.OnVoiceStateUpdateEventAsync(dat).ConfigureAwait(false);
break;
case "voice_server_update":
gid = (ulong)dat["guild_id"];
await this.OnVoiceServerUpdateEventAsync((string)dat["endpoint"], (string)dat["token"], this._guilds[gid]).ConfigureAwait(false);
break;
#endregion
#region Thread
case "thread_create":
thread = dat.ToDiscordObject<DiscordThreadChannel>();
await this.OnThreadCreateEventAsync(thread).ConfigureAwait(false);
break;
case "thread_update":
thread = dat.ToDiscordObject<DiscordThreadChannel>();
await this.OnThreadUpdateEventAsync(thread).ConfigureAwait(false);
break;
case "thread_delete":
thread = dat.ToDiscordObject<DiscordThreadChannel>();
await this.OnThreadDeleteEventAsync(thread).ConfigureAwait(false);
break;
case "thread_list_sync":
gid = (ulong)dat["guild_id"]; //get guild
await this.OnThreadListSyncEventAsync(this._guilds[gid], dat["channel_ids"].ToDiscordObject<IReadOnlyList<ulong>>(), dat["threads"].ToObject<IReadOnlyList<DiscordThreadChannel>>(), dat["members"].ToObject<IReadOnlyList<DiscordThreadChannelMember>>()).ConfigureAwait(false);
break;
case "thread_member_update":
await this.OnThreadMemberUpdateEventAsync(dat.ToDiscordObject<DiscordThreadChannelMember>()).ConfigureAwait(false);
break;
case "thread_members_update":
gid = (ulong)dat["guild_id"];
await this.OnThreadMembersUpdateEventAsync(this._guilds[gid], (ulong)dat["id"], dat["added_members"]?.ToObject<IReadOnlyList<DiscordThreadChannelMember>>(), dat["removed_member_ids"]?.ToObject<IReadOnlyList<ulong?>>(), (int)dat["member_count"]).ConfigureAwait(false);
break;
#endregion
#region Interaction/Integration/Application
case "interaction_create":
rawMbr = dat["member"];
if (rawMbr != null)
{
mbr = dat["member"].ToObject<TransportMember>();
usr = mbr.User;
}
else
{
usr = dat["user"].ToObject<TransportUser>();
}
cid = (ulong)dat["channel_id"];
await this.OnInteractionCreateAsync((ulong?)dat["guild_id"], cid, usr, mbr, dat.ToDiscordObject<DiscordInteraction>()).ConfigureAwait(false);
break;
case "application_command_create":
await this.OnApplicationCommandCreateAsync(dat.ToObject<DiscordApplicationCommand>(), (ulong?)dat["guild_id"]).ConfigureAwait(false);
break;
case "application_command_update":
await this.OnApplicationCommandUpdateAsync(dat.ToObject<DiscordApplicationCommand>(), (ulong?)dat["guild_id"]).ConfigureAwait(false);
break;
case "application_command_delete":
await this.OnApplicationCommandDeleteAsync(dat.ToObject<DiscordApplicationCommand>(), (ulong?)dat["guild_id"]).ConfigureAwait(false);
break;
case "integration_create":
await this.OnIntegrationCreateAsync(dat.ToObject<DiscordIntegration>(), (ulong)dat["guild_id"]).ConfigureAwait(false);
break;
case "integration_update":
await this.OnIntegrationUpdateAsync(dat.ToObject<DiscordIntegration>(), (ulong)dat["guild_id"]).ConfigureAwait(false);
break;
case "integration_delete":
await this.OnIntegrationDeleteAsync((ulong)dat["id"], (ulong)dat["guild_id"], (ulong?)dat["application_id"]).ConfigureAwait(false);
break;
#endregion
#region Stage Instance
case "stage_instance_create":
await this.OnStageInstanceCreateAsync(dat.ToObject<DiscordStageInstance>()).ConfigureAwait(false);
break;
case "stage_instance_update":
await this.OnStageInstanceUpdateAsync(dat.ToObject<DiscordStageInstance>()).ConfigureAwait(false);
break;
case "stage_instance_delete":
await this.OnStageInstanceDeleteAsync(dat.ToObject<DiscordStageInstance>()).ConfigureAwait(false);
break;
#endregion
#region Misc
case "gift_code_update": //Not supposed to be dispatched to bots
break;
case "embedded_activity_update": //Not supposed to be dispatched to bots
break;
case "typing_start":
cid = (ulong)dat["channel_id"];
rawMbr = dat["member"];
if (rawMbr != null)
mbr = rawMbr.ToObject<TransportMember>();
await this.OnTypingStartEventAsync((ulong)dat["user_id"], cid, this.InternalGetCachedChannel(cid), (ulong?)dat["guild_id"], Utilities.GetDateTimeOffset((long)dat["timestamp"]), mbr).ConfigureAwait(false);
break;
case "webhooks_update":
gid = (ulong)dat["guild_id"];
cid = (ulong)dat["channel_id"];
await this.OnWebhooksUpdateAsync(this._guilds[gid].GetChannel(cid), this._guilds[gid]).ConfigureAwait(false);
break;
case "guild_stickers_update":
var strs = dat["stickers"].ToDiscordObject<IEnumerable<DiscordMessageSticker>>();
await this.OnStickersUpdatedAsync(strs, dat).ConfigureAwait(false);
break;
default:
await this.OnUnknownEventAsync(payload).ConfigureAwait(false);
break;
#endregion
}
}
#endregion
#region Events
#region Gateway
internal async Task OnReadyEventAsync(ReadyPayload ready, JArray rawGuilds, JArray rawDmChannels)
{
//ready.CurrentUser.Discord = this;
var rusr = ready.CurrentUser;
this.CurrentUser.Username = rusr.Username;
this.CurrentUser.Discriminator = rusr.Discriminator;
this.CurrentUser.AvatarHash = rusr.AvatarHash;
this.CurrentUser.MfaEnabled = rusr.MfaEnabled;
this.CurrentUser.Verified = rusr.Verified;
this.CurrentUser.IsBot = rusr.IsBot;
this.GatewayVersion = ready.GatewayVersion;
this._sessionId = ready.SessionId;
var raw_guild_index = rawGuilds.ToDictionary(xt => (ulong)xt["id"], xt => (JObject)xt);
this._privateChannels.Clear();
foreach (var rawChannel in rawDmChannels)
{
var channel = rawChannel.ToObject<DiscordDmChannel>();
channel.Discord = this;
//xdc._recipients =
// .Select(xtu => this.InternalGetCachedUser(xtu.Id) ?? new DiscordUser(xtu) { Discord = this })
// .ToList();
var recips_raw = rawChannel["recipients"].ToObject<IEnumerable<TransportUser>>();
var recipients = new List<DiscordUser>();
foreach (var xr in recips_raw)
{
var xu = new DiscordUser(xr) { Discord = this };
xu = this.UpdateUserCache(xu);
recipients.Add(xu);
}
channel.Recipients = recipients;
this._privateChannels[channel.Id] = channel;
}
this._guilds.Clear();
foreach (var guild in ready.Guilds)
{
guild.Discord = this;
if (guild._channels == null)
guild._channels = new ConcurrentDictionary<ulong, DiscordChannel>();
if (guild._threads == null)
guild._threads = new ConcurrentDictionary<ulong, DiscordThreadChannel>();
foreach (var xc in guild.Channels.Values)
{
xc.GuildId = guild.Id;
xc.Discord = this;
foreach (var xo in xc._permissionOverwrites)
{
xo.Discord = this;
xo._channel_id = xc.Id;
}
}
foreach (var xt in guild.Threads.Values)
{
xt.GuildId = guild.Id;
xt.Discord = this;
}
if (guild._roles == null)
guild._roles = new ConcurrentDictionary<ulong, DiscordRole>();
foreach (var xr in guild.Roles.Values)
{
xr.Discord = this;
xr._guild_id = guild.Id;
}
var raw_guild = raw_guild_index[guild.Id];
var raw_members = (JArray)raw_guild["members"];
if (guild._members != null)
guild._members.Clear();
else
guild._members = new ConcurrentDictionary<ulong, DiscordMember>();
if (raw_members != null)
{
foreach (var xj in raw_members)
{
var xtm = xj.ToObject<TransportMember>();
var xu = new DiscordUser(xtm.User) { Discord = this };
xu = this.UpdateUserCache(xu);
guild._members[xtm.User.Id] = new DiscordMember(xtm) { Discord = this, _guild_id = guild.Id };
}
}
if (guild._emojis == null)
guild._emojis = new ConcurrentDictionary<ulong, DiscordEmoji>();
foreach (var xe in guild.Emojis.Values)
xe.Discord = this;
if (guild._voiceStates == null)
guild._voiceStates = new ConcurrentDictionary<ulong, DiscordVoiceState>();
foreach (var xvs in guild.VoiceStates.Values)
xvs.Discord = this;
this._guilds[guild.Id] = guild;
}
await this._ready.InvokeAsync(this, new ReadyEventArgs()).ConfigureAwait(false);
}
internal Task OnResumedAsync()
{
this.Logger.LogInformation(LoggerEvents.SessionUpdate, "Session resumed");
return this._resumed.InvokeAsync(this, new ReadyEventArgs());
}
#endregion
#region Channel
internal async Task OnChannelCreateEventAsync(DiscordChannel channel)
{
channel.Discord = this;
foreach (var xo in channel._permissionOverwrites)
{
xo.Discord = this;
xo._channel_id = channel.Id;
}
this._guilds[channel.GuildId.Value]._channels[channel.Id] = channel;
await this._channelCreated.InvokeAsync(this, new ChannelCreateEventArgs { Channel = channel, Guild = channel.Guild }).ConfigureAwait(false);
}
internal async Task OnChannelUpdateEventAsync(DiscordChannel channel)
{
if (channel == null)
return;
channel.Discord = this;
var gld = channel.Guild;
var channel_new = this.InternalGetCachedChannel(channel.Id);
DiscordChannel channel_old = null;
if (channel_new != null)
{
channel_old = new DiscordChannel
{
Bitrate = channel_new.Bitrate,
Discord = this,
GuildId = channel_new.GuildId,
Id = channel_new.Id,
//IsPrivate = channel_new.IsPrivate,
LastMessageId = channel_new.LastMessageId,
Name = channel_new.Name,
_permissionOverwrites = new List<DiscordOverwrite>(channel_new._permissionOverwrites),
Position = channel_new.Position,
Topic = channel_new.Topic,
Type = channel_new.Type,
UserLimit = channel_new.UserLimit,
ParentId = channel_new.ParentId,
IsNSFW = channel_new.IsNSFW,
PerUserRateLimit = channel_new.PerUserRateLimit,
RtcRegionId = channel_new.RtcRegionId,
QualityMode = channel_new.QualityMode
};
channel_new.Bitrate = channel.Bitrate;
channel_new.Name = channel.Name;
channel_new.Position = channel.Position;
channel_new.Topic = channel.Topic;
channel_new.UserLimit = channel.UserLimit;
channel_new.ParentId = channel.ParentId;
channel_new.IsNSFW = channel.IsNSFW;
channel_new.PerUserRateLimit = channel.PerUserRateLimit;
channel_new.Type = channel.Type;
channel_new.RtcRegionId = channel.RtcRegionId;
channel_new.QualityMode = channel.QualityMode;
channel_new._permissionOverwrites.Clear();
foreach (var po in channel._permissionOverwrites)
{
po.Discord = this;
po._channel_id = channel.Id;
}
channel_new._permissionOverwrites.AddRange(channel._permissionOverwrites);
}
else if (gld != null)
{
gld._channels[channel.Id] = channel;
}
await this._channelUpdated.InvokeAsync(this, new ChannelUpdateEventArgs { ChannelAfter = channel_new, Guild = gld, ChannelBefore = channel_old }).ConfigureAwait(false);
}
internal async Task OnChannelDeleteEventAsync(DiscordChannel channel)
{
if (channel == null)
return;
channel.Discord = this;
//if (channel.IsPrivate)
if (channel.Type == ChannelType.Group || channel.Type == ChannelType.Private)
{
var dmChannel = channel as DiscordDmChannel;
_ = this._privateChannels.TryRemove(dmChannel.Id, out _);
await this._dmChannelDeleted.InvokeAsync(this, new DmChannelDeleteEventArgs { Channel = dmChannel }).ConfigureAwait(false);
}
else
{
var gld = channel.Guild;
if (gld._channels.TryRemove(channel.Id, out var cachedChannel)) channel = cachedChannel;
await this._channelDeleted.InvokeAsync(this, new ChannelDeleteEventArgs { Channel = channel, Guild = gld }).ConfigureAwait(false);
}
}
internal async Task OnChannelPinsUpdateAsync(ulong? guildId, ulong channelId, DateTimeOffset? lastPinTimestamp)
{
var guild = this.InternalGetCachedGuild(guildId);
var channel = this.InternalGetCachedChannel(channelId) ?? this.InternalGetCachedThread(channelId);
if (channel == null)
{
channel = new DiscordDmChannel
{
Id = channelId,
Discord = this,
Type = ChannelType.Private,
Recipients = Array.Empty<DiscordUser>()
};
this._privateChannels.AddOrUpdate(channelId, (DiscordDmChannel)channel, (oldChannel, channel) => channel);
}
var ea = new ChannelPinsUpdateEventArgs
{
Guild = guild,
Channel = channel,
LastPinTimestamp = lastPinTimestamp
};
await this._channelPinsUpdated.InvokeAsync(this, ea).ConfigureAwait(false);
}
#endregion
#region Scheduled Guild Events
private async Task OnScheduledGuildEventCreateEventAsync(DiscordScheduledGuildEvent evt)
{
evt.Discord = this;
if (evt.Creator != null)
{
evt.Creator.Discord = this;
this.UpdateUserCache(evt.Creator);
}
evt.Guild._scheduledEvents.AddOrUpdate(evt.Id, evt, (old, newEvt) => newEvt);
await this._scheduledGuildEventCreated.InvokeAsync(this, new ScheduledGuildEventCreateEventArgs { Event = evt }).ConfigureAwait(false);
}
private async Task OnScheduledGuildEventDeleteEventAsync(DiscordScheduledGuildEvent evt)
{
var guild = this.InternalGetCachedGuild(evt.GuildId);
if (guild == null) // ??? //
return;
guild._scheduledEvents.TryRemove(evt.Id, out var _);
evt.Discord = this;
if (evt.Creator != null)
{
evt.Creator.Discord = this;
this.UpdateUserCache(evt.Creator);
}
await this._scheduledGuildEventDeleted.InvokeAsync(this, new ScheduledGuildEventDeleteEventArgs { Event = evt }).ConfigureAwait(false);
}
private async Task OnScheduledGuildEventUpdateEventAsync(DiscordScheduledGuildEvent evt)
{
evt.Discord = this;
if (evt.Creator != null)
{
evt.Creator.Discord = this;
this.UpdateUserCache(evt.Creator);
}
var guild = this.InternalGetCachedGuild(evt.GuildId);
guild._scheduledEvents.TryGetValue(evt.GuildId, out var oldEvt);
evt.Guild._scheduledEvents.AddOrUpdate(evt.Id, evt, (old, newEvt) => newEvt);
if (evt.Status is ScheduledGuildEventStatus.Completed)
await this._scheduledGuildEventCompleted.InvokeAsync(this, new ScheduledGuildEventCompletedEventArgs() { Event = evt }).ConfigureAwait(false);
else
await this._scheduledGuildEventUpdated.InvokeAsync(this, new ScheduledGuildEventUpdateEventArgs() { EventBefore = oldEvt, EventAfter = evt }).ConfigureAwait(false);
}
private async Task OnScheduledGuildEventUserAddEventAsync(ulong guildId, ulong eventId, ulong userId)
{
var guild = this.InternalGetCachedGuild(guildId);
var evt = guild._scheduledEvents.GetOrAdd(eventId, new DiscordScheduledGuildEvent()
{
Id = eventId,
GuildId = guildId,
Discord = this,
UserCount = 0
});
evt.UserCount++;
var user =
guild.Members.TryGetValue(userId, out var mbr) ? mbr :
this.GetCachedOrEmptyUserInternal(userId) ?? new DiscordUser() {Id = userId , Discord = this};
await this._scheduledGuildEventUserAdded.InvokeAsync(this, new ScheduledGuildEventUserAddEventArgs() { Event = evt, User = user }).ConfigureAwait(false);
}
private async Task OnScheduledGuildEventUserRemoveEventAsync(ulong guildId, ulong eventId, ulong userId)
{
var guild = this.InternalGetCachedGuild(guildId);
var evt = guild._scheduledEvents.GetOrAdd(eventId, new DiscordScheduledGuildEvent()
{
Id = eventId,
GuildId = guildId,
Discord = this,
UserCount = 0
});
evt.UserCount = evt.UserCount is 0 ? 0 : evt.UserCount - 1;
var user =
guild.Members.TryGetValue(userId, out var mbr) ? mbr :
this.GetCachedOrEmptyUserInternal(userId) ?? new DiscordUser() {Id = userId , Discord = this};
await this._scheduledGuildEventUserRemoved.InvokeAsync(this, new ScheduledGuildEventUserRemoveEventArgs() { Event = evt, User = user }).ConfigureAwait(false);
}
#endregion
#region Guild
internal async Task OnGuildCreateEventAsync(DiscordGuild guild, JArray rawMembers, IEnumerable<DiscordPresence> presences)
{
if (presences != null)
{
foreach (var xp in presences)
{
xp.Discord = this;
xp.GuildId = guild.Id;
xp.Activity = new DiscordActivity(xp.RawActivity);
if (xp.RawActivities != null)
{
xp._internalActivities = new DiscordActivity[xp.RawActivities.Length];
for (var i = 0; i < xp.RawActivities.Length; i++)
xp._internalActivities[i] = new DiscordActivity(xp.RawActivities[i]);
}
this._presences[xp.InternalUser.Id] = xp;
}
}
var exists = this._guilds.TryGetValue(guild.Id, out var foundGuild);
guild.Discord = this;
guild.IsUnavailable = false;
var eventGuild = guild;
if (exists)
guild = foundGuild;
if (guild._channels == null)
guild._channels = new ConcurrentDictionary<ulong, DiscordChannel>();
if (guild._threads == null)
guild._threads = new ConcurrentDictionary<ulong, DiscordThreadChannel>();
if (guild._roles == null)
guild._roles = new ConcurrentDictionary<ulong, DiscordRole>();
if (guild._emojis == null)
guild._emojis = new ConcurrentDictionary<ulong, DiscordEmoji>();
if (guild._stickers == null)
guild._stickers = new ConcurrentDictionary<ulong, DiscordMessageSticker>();
if (guild._voiceStates == null)
guild._voiceStates = new ConcurrentDictionary<ulong, DiscordVoiceState>();
if (guild._members == null)
guild._members = new ConcurrentDictionary<ulong, DiscordMember>();
if (guild._stageInstances == null)
guild._stageInstances = new ConcurrentDictionary<ulong, DiscordStageInstance>();
if (guild._scheduledEvents == null)
guild._scheduledEvents = new ConcurrentDictionary<ulong, DiscordScheduledGuildEvent>();
this.UpdateCachedGuild(eventGuild, rawMembers);
guild.JoinedAt = eventGuild.JoinedAt;
guild.IsLarge = eventGuild.IsLarge;
guild.MemberCount = Math.Max(eventGuild.MemberCount, guild._members.Count);
guild.IsUnavailable = eventGuild.IsUnavailable;
guild.PremiumSubscriptionCount = eventGuild.PremiumSubscriptionCount;
guild.PremiumTier = eventGuild.PremiumTier;
guild.Banner = eventGuild.Banner;
guild.VanityUrlCode = eventGuild.VanityUrlCode;
guild.Description = eventGuild.Description;
guild.IsNSFW = eventGuild.IsNSFW;
foreach (var kvp in eventGuild._voiceStates) guild._voiceStates[kvp.Key] = kvp.Value;
foreach (var xe in guild._scheduledEvents.Values)
{
xe.Discord = this;
if (xe.Creator != null)
xe.Creator.Discord = this;
}
foreach (var xc in guild._channels.Values)
{
xc.GuildId = guild.Id;
xc.Discord = this;
foreach (var xo in xc._permissionOverwrites)
{
xo.Discord = this;
xo._channel_id = xc.Id;
}
}
foreach (var xt in guild._threads.Values)
{
xt.GuildId = guild.Id;
xt.Discord = this;
}
foreach (var xe in guild._emojis.Values)
xe.Discord = this;
foreach (var xs in guild._stickers.Values)
xs.Discord = this;
foreach (var xvs in guild._voiceStates.Values)
xvs.Discord = this;
foreach (var xr in guild._roles.Values)
{
xr.Discord = this;
xr._guild_id = guild.Id;
}
foreach (var instance in guild._stageInstances.Values)
instance.Discord = this;
var old = Volatile.Read(ref this._guildDownloadCompleted);
var dcompl = this._guilds.Values.All(xg => !xg.IsUnavailable);
Volatile.Write(ref this._guildDownloadCompleted, dcompl);
if (exists)
await this._guildAvailable.InvokeAsync(this, new GuildCreateEventArgs { Guild = guild }).ConfigureAwait(false);
else
await this._guildCreated.InvokeAsync(this, new GuildCreateEventArgs { Guild = guild }).ConfigureAwait(false);
if (dcompl && !old)
await this._guildDownloadCompletedEv.InvokeAsync(this, new GuildDownloadCompletedEventArgs(this.Guilds)).ConfigureAwait(false);
}
internal async Task OnGuildUpdateEventAsync(DiscordGuild guild, JArray rawMembers)
{
DiscordGuild oldGuild;
if (!this._guilds.ContainsKey(guild.Id))
{
this._guilds[guild.Id] = guild;
oldGuild = null;
}
else
{
var gld = this._guilds[guild.Id];
oldGuild = new DiscordGuild
{
Discord = gld.Discord,
Name = gld.Name,
AfkChannelId = gld.AfkChannelId,
AfkTimeout = gld.AfkTimeout,
DefaultMessageNotifications = gld.DefaultMessageNotifications,
ExplicitContentFilter = gld.ExplicitContentFilter,
Features = gld.Features,
IconHash = gld.IconHash,
Id = gld.Id,
IsLarge = gld.IsLarge,
IsSynced = gld.IsSynced,
IsUnavailable = gld.IsUnavailable,
JoinedAt = gld.JoinedAt,
MemberCount = gld.MemberCount,
MaxMembers = gld.MaxMembers,
MaxPresences = gld.MaxPresences,
ApproximateMemberCount = gld.ApproximateMemberCount,
ApproximatePresenceCount = gld.ApproximatePresenceCount,
MaxVideoChannelUsers = gld.MaxVideoChannelUsers,
DiscoverySplashHash = gld.DiscoverySplashHash,
PreferredLocale = gld.PreferredLocale,
MfaLevel = gld.MfaLevel,
OwnerId = gld.OwnerId,
SplashHash = gld.SplashHash,
SystemChannelId = gld.SystemChannelId,
SystemChannelFlags = gld.SystemChannelFlags,
WidgetEnabled = gld.WidgetEnabled,
WidgetChannelId = gld.WidgetChannelId,
VerificationLevel = gld.VerificationLevel,
RulesChannelId = gld.RulesChannelId,
PublicUpdatesChannelId = gld.PublicUpdatesChannelId,
VoiceRegionId = gld.VoiceRegionId,
PremiumProgressBarEnabled = gld.PremiumProgressBarEnabled,
IsNSFW = gld.IsNSFW,
_channels = new ConcurrentDictionary<ulong, DiscordChannel>(),
_threads = new ConcurrentDictionary<ulong, DiscordThreadChannel>(),
_emojis = new ConcurrentDictionary<ulong, DiscordEmoji>(),
_members = new ConcurrentDictionary<ulong, DiscordMember>(),
_roles = new ConcurrentDictionary<ulong, DiscordRole>(),
_voiceStates = new ConcurrentDictionary<ulong, DiscordVoiceState>()
};
foreach (var kvp in gld._channels) oldGuild._channels[kvp.Key] = kvp.Value;
foreach (var kvp in gld._threads) oldGuild._threads[kvp.Key] = kvp.Value;
foreach (var kvp in gld._emojis) oldGuild._emojis[kvp.Key] = kvp.Value;
foreach (var kvp in gld._roles) oldGuild._roles[kvp.Key] = kvp.Value;
foreach (var kvp in gld._voiceStates) oldGuild._voiceStates[kvp.Key] = kvp.Value;
foreach (var kvp in gld._members) oldGuild._members[kvp.Key] = kvp.Value;
}
guild.Discord = this;
guild.IsUnavailable = false;
var eventGuild = guild;
guild = this._guilds[eventGuild.Id];
if (guild._channels == null)
guild._channels = new ConcurrentDictionary<ulong, DiscordChannel>();
if (guild._threads == null)
guild._threads = new ConcurrentDictionary<ulong, DiscordThreadChannel>();
if (guild._roles == null)
guild._roles = new ConcurrentDictionary<ulong, DiscordRole>();
if (guild._emojis == null)
guild._emojis = new ConcurrentDictionary<ulong, DiscordEmoji>();
if (guild._voiceStates == null)
guild._voiceStates = new ConcurrentDictionary<ulong, DiscordVoiceState>();
if (guild._members == null)
guild._members = new ConcurrentDictionary<ulong, DiscordMember>();
this.UpdateCachedGuild(eventGuild, rawMembers);
foreach (var xc in guild._channels.Values)
{
xc.GuildId = guild.Id;
xc.Discord = this;
foreach (var xo in xc._permissionOverwrites)
{
xo.Discord = this;
xo._channel_id = xc.Id;
}
}
foreach (var xc in guild._threads.Values)
{
xc.GuildId = guild.Id;
xc.Discord = this;
}
foreach (var xe in guild._emojis.Values)
xe.Discord = this;
foreach (var xvs in guild._voiceStates.Values)
xvs.Discord = this;
foreach (var xr in guild._roles.Values)
{
xr.Discord = this;
xr._guild_id = guild.Id;
}
await this._guildUpdated.InvokeAsync(this, new GuildUpdateEventArgs { GuildBefore = oldGuild, GuildAfter = guild }).ConfigureAwait(false);
}
internal async Task OnGuildDeleteEventAsync(DiscordGuild guild, JArray rawMembers)
{
if (guild.IsUnavailable)
{
if (!this._guilds.TryGetValue(guild.Id, out var gld))
return;
gld.IsUnavailable = true;
await this._guildUnavailable.InvokeAsync(this, new GuildDeleteEventArgs { Guild = guild, Unavailable = true }).ConfigureAwait(false);
}
else
{
if (!this._guilds.TryRemove(guild.Id, out var gld))
return;
await this._guildDeleted.InvokeAsync(this, new GuildDeleteEventArgs { Guild = gld }).ConfigureAwait(false);
}
}
internal async Task OnGuildSyncEventAsync(DiscordGuild guild, bool isLarge, JArray rawMembers, IEnumerable<DiscordPresence> presences)
{
presences = presences.Select(xp => { xp.Discord = this; xp.Activity = new DiscordActivity(xp.RawActivity); return xp; });
foreach (var xp in presences)
this._presences[xp.InternalUser.Id] = xp;
guild.IsSynced = true;
guild.IsLarge = isLarge;
this.UpdateCachedGuild(guild, rawMembers);
await this._guildAvailable.InvokeAsync(this, new GuildCreateEventArgs { Guild = guild }).ConfigureAwait(false);
}
internal async Task OnGuildEmojisUpdateEventAsync(DiscordGuild guild, IEnumerable<DiscordEmoji> newEmojis)
{
var oldEmojis = new ConcurrentDictionary<ulong, DiscordEmoji>(guild._emojis);
guild._emojis.Clear();
foreach (var emoji in newEmojis)
{
emoji.Discord = this;
guild._emojis[emoji.Id] = emoji;
}
var ea = new GuildEmojisUpdateEventArgs
{
Guild = guild,
EmojisAfter = guild.Emojis,
EmojisBefore = oldEmojis
};
await this._guildEmojisUpdated.InvokeAsync(this, ea).ConfigureAwait(false);
}
internal async Task OnGuildIntegrationsUpdateEventAsync(DiscordGuild guild)
{
var ea = new GuildIntegrationsUpdateEventArgs
{
Guild = guild
};
await this._guildIntegrationsUpdated.InvokeAsync(this, ea).ConfigureAwait(false);
}
#endregion
#region Guild Ban
internal async Task OnGuildBanAddEventAsync(TransportUser user, DiscordGuild guild)
{
var usr = new DiscordUser(user) { Discord = this };
usr = this.UpdateUserCache(usr);
if (!guild.Members.TryGetValue(user.Id, out var mbr))
mbr = new DiscordMember(usr) { Discord = this, _guild_id = guild.Id };
var ea = new GuildBanAddEventArgs
{
Guild = guild,
Member = mbr
};
await this._guildBanAdded.InvokeAsync(this, ea).ConfigureAwait(false);
}
internal async Task OnGuildBanRemoveEventAsync(TransportUser user, DiscordGuild guild)
{
var usr = new DiscordUser(user) { Discord = this };
usr = this.UpdateUserCache(usr);
if (!guild.Members.TryGetValue(user.Id, out var mbr))
mbr = new DiscordMember(usr) { Discord = this, _guild_id = guild.Id };
var ea = new GuildBanRemoveEventArgs
{
Guild = guild,
Member = mbr
};
await this._guildBanRemoved.InvokeAsync(this, ea).ConfigureAwait(false);
}
#endregion
#region Guild Member
internal async Task OnGuildMemberAddEventAsync(TransportMember member, DiscordGuild guild)
{
var usr = new DiscordUser(member.User) { Discord = this };
usr = this.UpdateUserCache(usr);
var mbr = new DiscordMember(member)
{
Discord = this,
_guild_id = guild.Id
};
guild._members[mbr.Id] = mbr;
guild.MemberCount++;
var ea = new GuildMemberAddEventArgs
{
Guild = guild,
Member = mbr
};
await this._guildMemberAdded.InvokeAsync(this, ea).ConfigureAwait(false);
}
internal async Task OnGuildMemberRemoveEventAsync(TransportUser user, DiscordGuild guild)
{
var usr = new DiscordUser(user);
if (!guild._members.TryRemove(user.Id, out var mbr))
mbr = new DiscordMember(usr) { Discord = this, _guild_id = guild.Id };
guild.MemberCount--;
this.UpdateUserCache(usr);
var ea = new GuildMemberRemoveEventArgs
{
Guild = guild,
Member = mbr
};
await this._guildMemberRemoved.InvokeAsync(this, ea).ConfigureAwait(false);
}
internal async Task OnGuildMemberUpdateEventAsync(TransportMember member, DiscordGuild guild, IEnumerable<ulong> roles, string nick, bool? pending, DateTimeOffset? comunication_disabled_until)
{
var usr = new DiscordUser(member.User) { Discord = this };
usr = this.UpdateUserCache(usr);
if (!guild.Members.TryGetValue(member.User.Id, out var mbr))
mbr = new DiscordMember(usr) { Discord = this, _guild_id = guild.Id };
var nick_old = mbr.Nickname;
var pending_old = mbr.IsPending;
var roles_old = new ReadOnlyCollection<DiscordRole>(new List<DiscordRole>(mbr.Roles));
var avatar_old = mbr.GuildAvatarHash;
var commm_old = mbr.CommunicationDisabledUntil;
mbr._avatarHash = member.AvatarHash;
mbr.Nickname = nick;
mbr.IsPending = pending;
mbr._role_ids.Clear();
mbr._role_ids.AddRange(roles);
mbr.CommunicationDisabledUntil = comunication_disabled_until;
var ea = new GuildMemberUpdateEventArgs
{
Guild = guild,
Member = mbr,
NicknameAfter = mbr.Nickname,
RolesAfter = new ReadOnlyCollection<DiscordRole>(new List<DiscordRole>(mbr.Roles)),
AvatarHashAfter = mbr.AvatarHash,
PendingAfter = mbr.IsPending,
CommunicationDisabledUntilAfter = mbr.CommunicationDisabledUntil,
NicknameBefore = nick_old,
RolesBefore = roles_old,
AvatarHashBefore = avatar_old,
PendingBefore = pending_old,
CommunicationDisabledUntilBefore = commm_old
};
await this._guildMemberUpdated.InvokeAsync(this, ea).ConfigureAwait(false);
}
internal async Task OnGuildMembersChunkEventAsync(JObject dat)
{
var guild = this.Guilds[(ulong)dat["guild_id"]];
var chunkIndex = (int)dat["chunk_index"];
var chunkCount = (int)dat["chunk_count"];
var nonce = (string)dat["nonce"];
var mbrs = new HashSet<DiscordMember>();
var pres = new HashSet<DiscordPresence>();
var members = dat["members"].ToObject<TransportMember[]>();
var memCount = members.Count();
for (var i = 0; i < memCount; i++)
{
var mbr = new DiscordMember(members[i]) { Discord = this, _guild_id = guild.Id };
if (!this.UserCache.ContainsKey(mbr.Id))
this.UserCache[mbr.Id] = new DiscordUser(members[i].User) { Discord = this };
guild._members[mbr.Id] = mbr;
mbrs.Add(mbr);
}
guild.MemberCount = guild._members.Count;
var ea = new GuildMembersChunkEventArgs
{
Guild = guild,
Members = new ReadOnlySet<DiscordMember>(mbrs),
ChunkIndex = chunkIndex,
ChunkCount = chunkCount,
Nonce = nonce,
};
if (dat["presences"] != null)
{
var presences = dat["presences"].ToObject<DiscordPresence[]>();
var presCount = presences.Count();
for (var i = 0; i < presCount; i++)
{
var xp = presences[i];
xp.Discord = this;
xp.Activity = new DiscordActivity(xp.RawActivity);
if (xp.RawActivities != null)
{
xp._internalActivities = new DiscordActivity[xp.RawActivities.Length];
for (var j = 0; j < xp.RawActivities.Length; j++)
xp._internalActivities[j] = new DiscordActivity(xp.RawActivities[j]);
}
pres.Add(xp);
}
ea.Presences = new ReadOnlySet<DiscordPresence>(pres);
}
if (dat["not_found"] != null)
{
var nf = dat["not_found"].ToObject<ISet<ulong>>();
ea.NotFound = new ReadOnlySet<ulong>(nf);
}
await this._guildMembersChunked.InvokeAsync(this, ea).ConfigureAwait(false);
}
#endregion
#region Guild Role
internal async Task OnGuildRoleCreateEventAsync(DiscordRole role, DiscordGuild guild)
{
role.Discord = this;
role._guild_id = guild.Id;
guild._roles[role.Id] = role;
var ea = new GuildRoleCreateEventArgs
{
Guild = guild,
Role = role
};
await this._guildRoleCreated.InvokeAsync(this, ea).ConfigureAwait(false);
}
internal async Task OnGuildRoleUpdateEventAsync(DiscordRole role, DiscordGuild guild)
{
var newRole = guild.GetRole(role.Id);
var oldRole = new DiscordRole
{
_guild_id = guild.Id,
_color = newRole._color,
Discord = this,
IsHoisted = newRole.IsHoisted,
Id = newRole.Id,
IsManaged = newRole.IsManaged,
IsMentionable = newRole.IsMentionable,
Name = newRole.Name,
Permissions = newRole.Permissions,
Position = newRole.Position,
IconHash = newRole.IconHash,
_emoji = newRole._emoji
};
newRole._guild_id = guild.Id;
newRole._color = role._color;
newRole.IsHoisted = role.IsHoisted;
newRole.IsManaged = role.IsManaged;
newRole.IsMentionable = role.IsMentionable;
newRole.Name = role.Name;
newRole.Permissions = role.Permissions;
newRole.Position = role.Position;
newRole._emoji = role._emoji;
newRole.IconHash = role.IconHash;
var ea = new GuildRoleUpdateEventArgs
{
Guild = guild,
RoleAfter = newRole,
RoleBefore = oldRole
};
await this._guildRoleUpdated.InvokeAsync(this, ea).ConfigureAwait(false);
}
internal async Task OnGuildRoleDeleteEventAsync(ulong roleId, DiscordGuild guild)
{
if (!guild._roles.TryRemove(roleId, out var role))
this.Logger.LogWarning($"Attempted to delete a nonexistent role ({roleId}) from guild ({guild}).");
var ea = new GuildRoleDeleteEventArgs
{
Guild = guild,
Role = role
};
await this._guildRoleDeleted.InvokeAsync(this, ea).ConfigureAwait(false);
}
#endregion
#region Invite
internal async Task OnInviteCreateEventAsync(ulong channelId, ulong guildId, DiscordInvite invite)
{
var guild = this.InternalGetCachedGuild(guildId);
var channel = this.InternalGetCachedChannel(channelId);
invite.Discord = this;
guild._invites[invite.Code] = invite;
var ea = new InviteCreateEventArgs
{
Channel = channel,
Guild = guild,
Invite = invite
};
await this._inviteCreated.InvokeAsync(this, ea).ConfigureAwait(false);
}
internal async Task OnInviteDeleteEventAsync(ulong channelId, ulong guildId, JToken dat)
{
var guild = this.InternalGetCachedGuild(guildId);
var channel = this.InternalGetCachedChannel(channelId);
if (!guild._invites.TryRemove(dat["code"].ToString(), out var invite))
{
invite = dat.ToObject<DiscordInvite>();
invite.Discord = this;
}
invite.IsRevoked = true;
var ea = new InviteDeleteEventArgs
{
Channel = channel,
Guild = guild,
Invite = invite
};
await this._inviteDeleted.InvokeAsync(this, ea).ConfigureAwait(false);
}
#endregion
#region Message
internal async Task OnMessageAckEventAsync(DiscordChannel chn, ulong messageId)
{
if (this.MessageCache == null || !this.MessageCache.TryGet(xm => xm.Id == messageId && xm.ChannelId == chn.Id, out var msg))
{
msg = new DiscordMessage
{
Id = messageId,
ChannelId = chn.Id,
Discord = this,
};
}
await this._messageAcknowledged.InvokeAsync(this, new MessageAcknowledgeEventArgs { Message = msg }).ConfigureAwait(false);
}
internal async Task OnMessageCreateEventAsync(DiscordMessage message, TransportUser author, TransportMember member, TransportUser referenceAuthor, TransportMember referenceMember)
{
message.Discord = this;
this.PopulateMessageReactionsAndCache(message, author, member);
message.PopulateMentions();
if (message.Channel == null && message.ChannelId == default)
this.Logger.LogWarning(LoggerEvents.WebSocketReceive, "Channel which the last message belongs to is not in cache - cache state might be invalid!");
if (message.ReferencedMessage != null)
{
message.ReferencedMessage.Discord = this;
this.PopulateMessageReactionsAndCache(message.ReferencedMessage, referenceAuthor, referenceMember);
message.ReferencedMessage.PopulateMentions();
}
foreach (var sticker in message.Stickers)
sticker.Discord = this;
var ea = new MessageCreateEventArgs
{
Message = message,
MentionedUsers = new ReadOnlyCollection<DiscordUser>(message._mentionedUsers),
MentionedRoles = message._mentionedRoles != null ? new ReadOnlyCollection<DiscordRole>(message._mentionedRoles) : null,
MentionedChannels = message._mentionedChannels != null ? new ReadOnlyCollection<DiscordChannel>(message._mentionedChannels) : null
};
await this._messageCreated.InvokeAsync(this, ea).ConfigureAwait(false);
}
internal async Task OnMessageUpdateEventAsync(DiscordMessage message, TransportUser author, TransportMember member, TransportUser referenceAuthor, TransportMember referenceMember)
{
DiscordGuild guild;
message.Discord = this;
var event_message = message;
DiscordMessage oldmsg = null;
if (this.Configuration.MessageCacheSize == 0
|| this.MessageCache == null
|| !this.MessageCache.TryGet(xm => xm.Id == event_message.Id && xm.ChannelId == event_message.ChannelId, out message))
{
message = event_message;
this.PopulateMessageReactionsAndCache(message, author, member);
guild = message.Channel?.Guild;
if (message.ReferencedMessage != null)
{
message.ReferencedMessage.Discord = this;
this.PopulateMessageReactionsAndCache(message.ReferencedMessage, referenceAuthor, referenceMember);
message.ReferencedMessage.PopulateMentions();
}
}
else
{
oldmsg = new DiscordMessage(message);
guild = message.Channel?.Guild;
message.EditedTimestampRaw = event_message.EditedTimestampRaw;
if (event_message.Content != null)
message.Content = event_message.Content;
message._embeds.Clear();
message._embeds.AddRange(event_message._embeds);
message._attachments.Clear();
message._attachments.AddRange(event_message._attachments);
message.Pinned = event_message.Pinned;
message.IsTTS = event_message.IsTTS;
}
message.PopulateMentions();
var ea = new MessageUpdateEventArgs
{
Message = message,
MessageBefore = oldmsg,
MentionedUsers = new ReadOnlyCollection<DiscordUser>(message._mentionedUsers),
MentionedRoles = message._mentionedRoles != null ? new ReadOnlyCollection<DiscordRole>(message._mentionedRoles) : null,
MentionedChannels = message._mentionedChannels != null ? new ReadOnlyCollection<DiscordChannel>(message._mentionedChannels) : null
};
await this._messageUpdated.InvokeAsync(this, ea).ConfigureAwait(false);
}
internal async Task OnMessageDeleteEventAsync(ulong messageId, ulong channelId, ulong? guildId)
{
var guild = this.InternalGetCachedGuild(guildId);
var channel = this.InternalGetCachedChannel(channelId) ?? this.InternalGetCachedThread(channelId);
if (channel == null)
{
channel = new DiscordDmChannel
{
Id = channelId,
Discord = this,
Type = ChannelType.Private,
Recipients = Array.Empty<DiscordUser>()
};
this._privateChannels.AddOrUpdate(channelId, (DiscordDmChannel)channel, (oldChannel, channel) => channel);
}
if (channel == null
|| this.Configuration.MessageCacheSize == 0
|| this.MessageCache == null
|| !this.MessageCache.TryGet(xm => xm.Id == messageId && xm.ChannelId == channelId, out var msg))
{
msg = new DiscordMessage
{
Id = messageId,
ChannelId = channelId,
Discord = this,
};
}
if (this.Configuration.MessageCacheSize > 0)
this.MessageCache?.Remove(xm => xm.Id == msg.Id && xm.ChannelId == channelId);
var ea = new MessageDeleteEventArgs
{
Message = msg,
Channel = channel,
Guild = guild,
};
await this._messageDeleted.InvokeAsync(this, ea).ConfigureAwait(false);
}
internal async Task OnMessageBulkDeleteEventAsync(ulong[] messageIds, ulong channelId, ulong? guildId)
{
var channel = this.InternalGetCachedChannel(channelId) ?? this.InternalGetCachedThread(channelId);
var msgs = new List<DiscordMessage>(messageIds.Length);
foreach (var messageId in messageIds)
{
if (channel == null
|| this.Configuration.MessageCacheSize == 0
|| this.MessageCache == null
|| !this.MessageCache.TryGet(xm => xm.Id == messageId && xm.ChannelId == channelId, out var msg))
{
msg = new DiscordMessage
{
Id = messageId,
ChannelId = channelId,
Discord = this,
};
}
if (this.Configuration.MessageCacheSize > 0)
this.MessageCache?.Remove(xm => xm.Id == msg.Id && xm.ChannelId == channelId);
msgs.Add(msg);
}
var guild = this.InternalGetCachedGuild(guildId);
var ea = new MessageBulkDeleteEventArgs
{
Channel = channel,
Messages = new ReadOnlyCollection<DiscordMessage>(msgs),
Guild = guild
};
await this._messagesBulkDeleted.InvokeAsync(this, ea).ConfigureAwait(false);
}
#endregion
#region Message Reaction
internal async Task OnMessageReactionAddAsync(ulong userId, ulong messageId, ulong channelId, ulong? guildId, TransportMember mbr, DiscordEmoji emoji)
{
var channel = this.InternalGetCachedChannel(channelId) ?? this.InternalGetCachedThread(channelId);
var guild = this.InternalGetCachedGuild(guildId);
emoji.Discord = this;
var usr = this.UpdateUser(new DiscordUser { Id = userId, Discord = this }, guildId, guild, mbr);
if (channel == null)
{
channel = new DiscordDmChannel
{
Id = channelId,
Discord = this,
Type = ChannelType.Private,
Recipients = new DiscordUser[] { usr }
};
this._privateChannels.AddOrUpdate(channelId, (DiscordDmChannel)channel, (oldChannel, channel) => channel);
}
if (channel == null
|| this.Configuration.MessageCacheSize == 0
|| this.MessageCache == null
|| !this.MessageCache.TryGet(xm => xm.Id == messageId && xm.ChannelId == channelId, out var msg))
{
msg = new DiscordMessage
{
Id = messageId,
ChannelId = channelId,
Discord = this,
_reactions = new List<DiscordReaction>()
};
}
var react = msg._reactions.FirstOrDefault(xr => xr.Emoji == emoji);
if (react == null)
{
msg._reactions.Add(react = new DiscordReaction
{
Count = 1,
Emoji = emoji,
IsMe = this.CurrentUser.Id == userId
});
}
else
{
react.Count++;
react.IsMe |= this.CurrentUser.Id == userId;
}
var ea = new MessageReactionAddEventArgs
{
Message = msg,
User = usr,
Guild = guild,
Emoji = emoji
};
await this._messageReactionAdded.InvokeAsync(this, ea).ConfigureAwait(false);
}
internal async Task OnMessageReactionRemoveAsync(ulong userId, ulong messageId, ulong channelId, ulong? guildId, DiscordEmoji emoji)
{
var channel = this.InternalGetCachedChannel(channelId) ?? this.InternalGetCachedThread(channelId);
emoji.Discord = this;
if (!this.UserCache.TryGetValue(userId, out var usr))
usr = new DiscordUser { Id = userId, Discord = this };
if (channel == null)
{
channel = new DiscordDmChannel
{
Id = channelId,
Discord = this,
Type = ChannelType.Private,
Recipients = new DiscordUser[] { usr }
};
this._privateChannels.AddOrUpdate(channelId, (DiscordDmChannel)channel, (oldChannel, channel) => channel);
}
if (channel?.Guild != null)
usr = channel.Guild.Members.TryGetValue(userId, out var member)
? member
: new DiscordMember(usr) { Discord = this, _guild_id = channel.GuildId.Value };
if (channel == null
|| this.Configuration.MessageCacheSize == 0
|| this.MessageCache == null
|| !this.MessageCache.TryGet(xm => xm.Id == messageId && xm.ChannelId == channelId, out var msg))
{
msg = new DiscordMessage
{
Id = messageId,
ChannelId = channelId,
Discord = this
};
}
var react = msg._reactions?.FirstOrDefault(xr => xr.Emoji == emoji);
if (react != null)
{
react.Count--;
react.IsMe &= this.CurrentUser.Id != userId;
if (msg._reactions != null && react.Count <= 0) // shit happens
for (var i = 0; i < msg._reactions.Count; i++)
if (msg._reactions[i].Emoji == emoji)
{
msg._reactions.RemoveAt(i);
break;
}
}
var guild = this.InternalGetCachedGuild(guildId);
var ea = new MessageReactionRemoveEventArgs
{
Message = msg,
User = usr,
Guild = guild,
Emoji = emoji
};
await this._messageReactionRemoved.InvokeAsync(this, ea).ConfigureAwait(false);
}
internal async Task OnMessageReactionRemoveAllAsync(ulong messageId, ulong channelId, ulong? guildId)
{
var channel = this.InternalGetCachedChannel(channelId) ?? this.InternalGetCachedThread(channelId);
if (channel == null
|| this.Configuration.MessageCacheSize == 0
|| this.MessageCache == null
|| !this.MessageCache.TryGet(xm => xm.Id == messageId && xm.ChannelId == channelId, out var msg))
{
msg = new DiscordMessage
{
Id = messageId,
ChannelId = channelId,
Discord = this
};
}
msg._reactions?.Clear();
var guild = this.InternalGetCachedGuild(guildId);
var ea = new MessageReactionsClearEventArgs
{
Message = msg,
};
await this._messageReactionsCleared.InvokeAsync(this, ea).ConfigureAwait(false);
}
internal async Task OnMessageReactionRemoveEmojiAsync(ulong messageId, ulong channelId, ulong guildId, JToken dat)
{
var guild = this.InternalGetCachedGuild(guildId);
var channel = this.InternalGetCachedChannel(channelId) ?? this.InternalGetCachedThread(channelId);
if (channel == null)
{
channel = new DiscordDmChannel
{
Id = channelId,
Discord = this,
Type = ChannelType.Private,
Recipients = Array.Empty<DiscordUser>()
};
this._privateChannels.AddOrUpdate(channelId, (DiscordDmChannel)channel, (oldChannel, channel) => channel);
}
if (channel == null
|| this.Configuration.MessageCacheSize == 0
|| this.MessageCache == null
|| !this.MessageCache.TryGet(xm => xm.Id == messageId && xm.ChannelId == channelId, out var msg))
{
msg = new DiscordMessage
{
Id = messageId,
ChannelId = channelId,
Discord = this
};
}
var partialEmoji = dat.ToObject<DiscordEmoji>();
if (!guild._emojis.TryGetValue(partialEmoji.Id, out var emoji))
{
emoji = partialEmoji;
emoji.Discord = this;
}
msg._reactions?.RemoveAll(r => r.Emoji.Equals(emoji));
var ea = new MessageReactionRemoveEmojiEventArgs
{
Message = msg,
Channel = channel,
Guild = guild,
Emoji = emoji
};
await this._messageReactionRemovedEmoji.InvokeAsync(this, ea).ConfigureAwait(false);
}
#endregion
#region User/Presence Update
internal async Task OnPresenceUpdateEventAsync(JObject rawPresence, JObject rawUser)
{
var uid = (ulong)rawUser["id"];
DiscordPresence old = null;
if (this._presences.TryGetValue(uid, out var presence))
{
old = new DiscordPresence(presence);
DiscordJson.PopulateObject(rawPresence, presence);
}
else
{
presence = rawPresence.ToObject<DiscordPresence>();
presence.Discord = this;
presence.Activity = new DiscordActivity(presence.RawActivity);
this._presences[presence.InternalUser.Id] = presence;
}
// reuse arrays / avoid linq (this is a hot zone)
if (presence.Activities == null || rawPresence["activities"] == null)
{
presence._internalActivities = Array.Empty<DiscordActivity>();
}
else
{
if (presence._internalActivities.Length != presence.RawActivities.Length)
presence._internalActivities = new DiscordActivity[presence.RawActivities.Length];
for (var i = 0; i < presence._internalActivities.Length; i++)
presence._internalActivities[i] = new DiscordActivity(presence.RawActivities[i]);
if (presence._internalActivities.Length > 0)
{
presence.RawActivity = presence.RawActivities[0];
if (presence.Activity != null)
presence.Activity.UpdateWith(presence.RawActivity);
else
presence.Activity = new DiscordActivity(presence.RawActivity);
}
}
if (this.UserCache.TryGetValue(uid, out var usr))
{
if (old != null)
{
old.InternalUser.Username = usr.Username;
old.InternalUser.Discriminator = usr.Discriminator;
old.InternalUser.AvatarHash = usr.AvatarHash;
}
if (rawUser["username"] is object)
usr.Username = (string)rawUser["username"];
if (rawUser["discriminator"] is object)
usr.Discriminator = (string)rawUser["discriminator"];
if (rawUser["avatar"] is object)
usr.AvatarHash = (string)rawUser["avatar"];
presence.InternalUser.Username = usr.Username;
presence.InternalUser.Discriminator = usr.Discriminator;
presence.InternalUser.AvatarHash = usr.AvatarHash;
}
var usrafter = usr ?? new DiscordUser(presence.InternalUser);
var ea = new PresenceUpdateEventArgs
{
Status = presence.Status,
Activity = presence.Activity,
User = usr,
PresenceBefore = old,
PresenceAfter = presence,
UserBefore = old != null ? new DiscordUser(old.InternalUser) : usrafter,
UserAfter = usrafter
};
await this._presenceUpdated.InvokeAsync(this, ea).ConfigureAwait(false);
}
internal async Task OnUserSettingsUpdateEventAsync(TransportUser user)
{
var usr = new DiscordUser(user) { Discord = this };
var ea = new UserSettingsUpdateEventArgs
{
User = usr
};
await this._userSettingsUpdated.InvokeAsync(this, ea).ConfigureAwait(false);
}
internal async Task OnUserUpdateEventAsync(TransportUser user)
{
var usr_old = new DiscordUser
{
AvatarHash = this.CurrentUser.AvatarHash,
Discord = this,
Discriminator = this.CurrentUser.Discriminator,
Email = this.CurrentUser.Email,
Id = this.CurrentUser.Id,
IsBot = this.CurrentUser.IsBot,
MfaEnabled = this.CurrentUser.MfaEnabled,
Username = this.CurrentUser.Username,
Verified = this.CurrentUser.Verified
};
this.CurrentUser.AvatarHash = user.AvatarHash;
this.CurrentUser.Discriminator = user.Discriminator;
this.CurrentUser.Email = user.Email;
this.CurrentUser.Id = user.Id;
this.CurrentUser.IsBot = user.IsBot;
this.CurrentUser.MfaEnabled = user.MfaEnabled;
this.CurrentUser.Username = user.Username;
this.CurrentUser.Verified = user.Verified;
var ea = new UserUpdateEventArgs
{
UserAfter = this.CurrentUser,
UserBefore = usr_old
};
await this._userUpdated.InvokeAsync(this, ea).ConfigureAwait(false);
}
#endregion
#region Voice
internal async Task OnVoiceStateUpdateEventAsync(JObject raw)
{
var gid = (ulong)raw["guild_id"];
var uid = (ulong)raw["user_id"];
var gld = this._guilds[gid];
var vstateNew = raw.ToObject<DiscordVoiceState>();
vstateNew.Discord = this;
gld._voiceStates.TryRemove(uid, out var vstateOld);
if (vstateNew.Channel != null)
{
gld._voiceStates[vstateNew.UserId] = vstateNew;
}
if (gld._members.TryGetValue(uid, out var mbr))
{
mbr.IsMuted = vstateNew.IsServerMuted;
mbr.IsDeafened = vstateNew.IsServerDeafened;
}
else
{
var transportMbr = vstateNew.TransportMember;
this.UpdateUser(new DiscordUser(transportMbr.User) { Discord = this }, gid, gld, transportMbr);
}
var ea = new VoiceStateUpdateEventArgs
{
Guild = vstateNew.Guild,
Channel = vstateNew.Channel,
User = vstateNew.User,
SessionId = vstateNew.SessionId,
Before = vstateOld,
After = vstateNew
};
await this._voiceStateUpdated.InvokeAsync(this, ea).ConfigureAwait(false);
}
internal async Task OnVoiceServerUpdateEventAsync(string endpoint, string token, DiscordGuild guild)
{
var ea = new VoiceServerUpdateEventArgs
{
Endpoint = endpoint,
VoiceToken = token,
Guild = guild
};
await this._voiceServerUpdated.InvokeAsync(this, ea).ConfigureAwait(false);
}
#endregion
#region Thread
internal async Task OnThreadCreateEventAsync(DiscordThreadChannel thread)
{
thread.Discord = this;
this.InternalGetCachedGuild(thread.GuildId)._threads.AddOrUpdate(thread.Id, thread, (oldThread, newThread) => newThread);
await this._threadCreated.InvokeAsync(this, new ThreadCreateEventArgs { Thread = thread, Guild = thread.Guild, Parent = thread.Parent }).ConfigureAwait(false);
}
internal async Task OnThreadUpdateEventAsync(DiscordThreadChannel thread)
{
if (thread == null)
return;
DiscordThreadChannel threadOld;
ThreadUpdateEventArgs updateEvent;
thread.Discord = this;
var guild = thread.Guild;
guild.Discord = this;
var cthread = this.InternalGetCachedThread(thread.Id);
if (cthread != null) //thread is cached
{
threadOld = new DiscordThreadChannel
{
Discord = this,
GuildId = cthread.GuildId,
CreatorId = cthread.CreatorId,
ParentId = cthread.ParentId,
Id = cthread.Id,
Name = cthread.Name,
Type = cthread.Type,
LastMessageId = cthread.LastMessageId,
MessageCount = cthread.MessageCount,
MemberCount = cthread.MemberCount,
ThreadMetadata = cthread.ThreadMetadata,
CurrentMember = cthread.CurrentMember,
};
updateEvent = new ThreadUpdateEventArgs
{
ThreadAfter = thread,
ThreadBefore = threadOld,
Guild = thread.Guild,
Parent = thread.Parent
};
}
else
{
updateEvent = new ThreadUpdateEventArgs
{
ThreadAfter = thread,
Guild = thread.Guild,
Parent = thread.Parent
};
guild._threads[thread.Id] = thread;
}
await this._threadUpdated.InvokeAsync(this, updateEvent).ConfigureAwait(false);
}
internal async Task OnThreadDeleteEventAsync(DiscordThreadChannel thread)
{
if (thread == null)
return;
thread.Discord = this;
var gld = thread.Guild;
if (gld._threads.TryRemove(thread.Id, out var cachedThread))
thread = cachedThread;
await this._threadDeleted.InvokeAsync(this, new ThreadDeleteEventArgs { Thread = thread, Guild = thread.Guild, Parent = thread.Parent }).ConfigureAwait(false);
}
internal async Task OnThreadListSyncEventAsync(DiscordGuild guild, IReadOnlyList<ulong> channel_ids, IReadOnlyList<DiscordThreadChannel> threads, IReadOnlyList<DiscordThreadChannelMember> members)
{
guild.Discord = this;
var channels = channel_ids.Select(x => guild.GetChannel(x) ?? new DiscordChannel{ Id = x, GuildId = guild.Id}); //getting channel objects
foreach (var channel in channels)
{
channel.Discord = this;
}
foreach (var thread in threads)
{
thread.Discord = this;
guild._threads[thread.Id] = thread;
}
foreach (var member in members)
{
member.Discord = this;
member._guild_id = guild.Id;
var thread = threads.SingleOrDefault(x => x.Id == member.ThreadId);
if (thread != null)
thread.CurrentMember = member;
}
await this._threadListSynced.InvokeAsync(this, new ThreadListSyncEventArgs { Guild = guild, Channels = channels.ToList().AsReadOnly(), Threads = threads, CurrentMembers = members.ToList().AsReadOnly() }).ConfigureAwait(false);
}
internal async Task OnThreadMemberUpdateEventAsync(DiscordThreadChannelMember member)
{
member.Discord = this;
var thread = this.InternalGetCachedThread(member.ThreadId);
member._guild_id = thread.Guild.Id;
thread.CurrentMember = member;
thread.Guild._threads.AddOrUpdate(member.ThreadId, thread, (oldThread, newThread) => newThread);
await this._threadMemberUpdated.InvokeAsync(this, new ThreadMemberUpdateEventArgs { ThreadMember = member, Thread = thread }).ConfigureAwait(false);
}
internal async Task OnThreadMembersUpdateEventAsync(DiscordGuild guild, ulong thread_id, IReadOnlyList<DiscordThreadChannelMember> addedMembers, IReadOnlyList<ulong?> removed_member_ids, int member_count)
{
var thread = this.InternalGetCachedThread(thread_id);
thread.Discord = this;
guild.Discord = this;
var removedMembers = new List<DiscordMember>();
if (removed_member_ids != null)
{
foreach (var removedId in removed_member_ids)
{
removedMembers.Add(guild._members.TryGetValue(removedId.Value, out var member) ? member : new DiscordMember { Id = removedId.Value, _guild_id = guild.Id, Discord = this });
}
}
else
removed_member_ids = Array.Empty<ulong?>();
if (addedMembers != null)
{
foreach (var threadMember in addedMembers)
{
threadMember.Discord = this;
threadMember._guild_id = guild.Id;
if (threadMember.Id == this.CurrentUser.Id)
thread.CurrentMember = threadMember;
}
}
else
addedMembers = Array.Empty<DiscordThreadChannelMember>();
if (removed_member_ids.Contains(this.CurrentUser.Id)) //indicates the bot was removed from the thread
thread.CurrentMember = null;
thread.MemberCount = member_count;
var threadMembersUpdateArg = new ThreadMembersUpdateEventArgs
{
Guild = guild,
Thread = thread,
AddedMembers = addedMembers,
RemovedMembers = removedMembers,
MemberCount = member_count
};
await this._threadMembersUpdated.InvokeAsync(this, threadMembersUpdateArg).ConfigureAwait(false);
}
#endregion
#region Commands
internal async Task OnApplicationCommandCreateAsync(DiscordApplicationCommand cmd, ulong? guild_id)
{
cmd.Discord = this;
var guild = this.InternalGetCachedGuild(guild_id);
if (guild == null && guild_id.HasValue)
{
guild = new DiscordGuild
{
Id = guild_id.Value,
Discord = this
};
}
var ea = new ApplicationCommandEventArgs
{
Guild = guild,
Command = cmd
};
await this._applicationCommandCreated.InvokeAsync(this, ea).ConfigureAwait(false);
}
internal async Task OnApplicationCommandUpdateAsync(DiscordApplicationCommand cmd, ulong? guild_id)
{
cmd.Discord = this;
var guild = this.InternalGetCachedGuild(guild_id);
if (guild == null && guild_id.HasValue)
{
guild = new DiscordGuild
{
Id = guild_id.Value,
Discord = this
};
}
var ea = new ApplicationCommandEventArgs
{
Guild = guild,
Command = cmd
};
await this._applicationCommandUpdated.InvokeAsync(this, ea).ConfigureAwait(false);
}
internal async Task OnApplicationCommandDeleteAsync(DiscordApplicationCommand cmd, ulong? guild_id)
{
cmd.Discord = this;
var guild = this.InternalGetCachedGuild(guild_id);
if (guild == null && guild_id.HasValue)
{
guild = new DiscordGuild
{
Id = guild_id.Value,
Discord = this
};
}
var ea = new ApplicationCommandEventArgs
{
Guild = guild,
Command = cmd
};
await this._applicationCommandDeleted.InvokeAsync(this, ea).ConfigureAwait(false);
}
#endregion
#region Integration
internal async Task OnIntegrationCreateAsync(DiscordIntegration integration, ulong guild_id)
{
var guild = this.InternalGetCachedGuild(guild_id);
if (guild == null)
{
guild = new DiscordGuild
{
Id = guild_id,
Discord = this
};
}
var ea = new IntegrationCreateEventArgs
{
Guild = guild,
Integration = integration
};
await this._integrationCreated.InvokeAsync(this, ea).ConfigureAwait(false);
}
internal async Task OnIntegrationUpdateAsync(DiscordIntegration integration, ulong guild_id)
{
var guild = this.InternalGetCachedGuild(guild_id);
if (guild == null)
{
guild = new DiscordGuild
{
Id = guild_id,
Discord = this
};
}
var ea = new IntegrationUpdateEventArgs
{
Guild = guild,
Integration = integration
};
await this._integrationUpdated.InvokeAsync(this, ea).ConfigureAwait(false);
}
internal async Task OnIntegrationDeleteAsync(ulong integration_id, ulong guild_id, ulong? application_id)
{
var guild = this.InternalGetCachedGuild(guild_id);
if (guild == null)
{
guild = new DiscordGuild
{
Id = guild_id,
Discord = this
};
}
var ea = new IntegrationDeleteEventArgs
{
Guild = guild,
Applicationid = application_id,
IntegrationId = integration_id
};
await this._integrationDeleted.InvokeAsync(this, ea).ConfigureAwait(false);
}
#endregion
#region Stage Instance
internal async Task OnStageInstanceCreateAsync(DiscordStageInstance instance)
{
instance.Discord = this;
var guild = this.InternalGetCachedGuild(instance.GuildId);
guild._stageInstances[instance.Id] = instance;
var eventArgs = new StageInstanceCreateEventArgs
{
StageInstance = instance
};
await this._stageInstanceCreated.InvokeAsync(this, eventArgs).ConfigureAwait(false);
}
internal async Task OnStageInstanceUpdateAsync(DiscordStageInstance instance)
{
instance.Discord = this;
var guild = this.InternalGetCachedGuild(instance.GuildId);
if (!guild._stageInstances.TryRemove(instance.Id, out var oldInstance))
oldInstance = new DiscordStageInstance { Id = instance.Id, GuildId = instance.GuildId, ChannelId = instance.ChannelId };
guild._stageInstances[instance.Id] = instance;
var eventArgs = new StageInstanceUpdateEventArgs
{
StageInstanceBefore = oldInstance,
StageInstanceAfter = instance
};
await this._stageInstanceUpdated.InvokeAsync(this, eventArgs).ConfigureAwait(false);
}
internal async Task OnStageInstanceDeleteAsync(DiscordStageInstance instance)
{
instance.Discord = this;
var guild = this.InternalGetCachedGuild(instance.GuildId);
guild._stageInstances.TryRemove(instance.Id, out _);
var eventArgs = new StageInstanceDeleteEventArgs
{
StageInstance = instance
};
await this._stageInstanceDeleted.InvokeAsync(this, eventArgs).ConfigureAwait(false);
}
#endregion
#region Misc
internal async Task OnInteractionCreateAsync(ulong? guildId, ulong channelId, TransportUser user, TransportMember member, DiscordInteraction interaction)
{
var usr = new DiscordUser(user) { Discord = this };
interaction.ChannelId = channelId;
interaction.GuildId = guildId;
interaction.Discord = this;
interaction.Data.Discord = this;
if (member != null)
{
usr = new DiscordMember(member) { _guild_id = guildId.Value, Discord = this };
this.UpdateUser(usr, guildId, interaction.Guild, member);
}
else
this.UpdateUserCache(usr);
interaction.User = usr;
var resolved = interaction.Data.Resolved;
if (resolved != null)
{
if (resolved.Users != null)
{
foreach (var c in resolved.Users)
{
c.Value.Discord = this;
this.UpdateUserCache(c.Value);
}
}
if (resolved.Members != null)
{
foreach (var c in resolved.Members)
{
c.Value.Discord = this;
c.Value.Id = c.Key;
c.Value._guild_id = guildId.Value;
c.Value.User.Discord = this;
this.UpdateUserCache(c.Value.User);
}
}
if (resolved.Channels != null)
{
foreach (var c in resolved.Channels)
{
c.Value.Discord = this;
if (guildId.HasValue)
c.Value.GuildId = guildId.Value;
}
}
if (resolved.Roles != null)
{
foreach (var c in resolved.Roles)
{
c.Value.Discord = this;
if (guildId.HasValue)
c.Value._guild_id = guildId.Value;
}
}
if (resolved.Messages != null)
{
foreach (var m in resolved.Messages)
{
m.Value.Discord = this;
if (guildId.HasValue)
m.Value.GuildId = guildId.Value;
}
}
}
if (interaction.Type is InteractionType.Component)
{
interaction.Message.Discord = this;
interaction.Message.ChannelId = interaction.ChannelId;
var cea = new ComponentInteractionCreateEventArgs
{
Message = interaction.Message,
Interaction = interaction
};
await this._componentInteractionCreated.InvokeAsync(this, cea).ConfigureAwait(false);
}
else
{
if (interaction.Data.Target.HasValue) // Context-Menu. //
{
var targetId = interaction.Data.Target.Value;
DiscordUser targetUser = null;
DiscordMember targetMember = null;
DiscordMessage targetMessage = null;
interaction.Data.Resolved.Messages?.TryGetValue(targetId, out targetMessage);
interaction.Data.Resolved.Members?.TryGetValue(targetId, out targetMember);
interaction.Data.Resolved.Users?.TryGetValue(targetId, out targetUser);
var ctea = new ContextMenuInteractionCreateEventArgs
{
Interaction = interaction,
TargetUser = targetMember ?? targetUser,
TargetMessage = targetMessage,
Type = interaction.Data.Type,
};
await this._contextMenuInteractionCreated.InvokeAsync(this, ctea).ConfigureAwait(false);
}
else
{
var ea = new InteractionCreateEventArgs
{
Interaction = interaction
};
await this._interactionCreated.InvokeAsync(this, ea).ConfigureAwait(false);
}
}
}
internal async Task OnTypingStartEventAsync(ulong userId, ulong channelId, DiscordChannel channel, ulong? guildId, DateTimeOffset started, TransportMember mbr)
{
if (channel == null)
{
channel = new DiscordChannel
{
Discord = this,
Id = channelId,
GuildId = guildId ?? default,
};
}
var guild = this.InternalGetCachedGuild(guildId);
var usr = this.UpdateUser(new DiscordUser { Id = userId, Discord = this }, guildId, guild, mbr);
var ea = new TypingStartEventArgs
{
Channel = channel,
User = usr,
Guild = guild,
StartedAt = started
};
await this._typingStarted.InvokeAsync(this, ea).ConfigureAwait(false);
}
internal async Task OnWebhooksUpdateAsync(DiscordChannel channel, DiscordGuild guild)
{
var ea = new WebhooksUpdateEventArgs
{
Channel = channel,
Guild = guild
};
await this._webhooksUpdated.InvokeAsync(this, ea).ConfigureAwait(false);
}
internal async Task OnStickersUpdatedAsync(IEnumerable<DiscordMessageSticker> newStickers, JObject raw)
{
var guild = this.InternalGetCachedGuild((ulong)raw["guild_id"]);
var oldStickers = new ConcurrentDictionary<ulong, DiscordMessageSticker>(guild._stickers);
guild._stickers.Clear();
foreach (var nst in newStickers)
{
if (nst.User != null)
nst.User.Discord = this;
nst.Discord = this;
guild._stickers[nst.Id] = nst;
}
var sea = new GuildStickersUpdateEventArgs
{
Guild = guild,
StickersBefore = oldStickers,
StickersAfter = guild.Stickers
};
await this._guildStickersUpdated.InvokeAsync(this, sea).ConfigureAwait(false);
}
internal async Task OnUnknownEventAsync(GatewayPayload payload)
{
var ea = new UnknownEventArgs { EventName = payload.EventName, Json = (payload.Data as JObject)?.ToString() };
await this._unknownEvent.InvokeAsync(this, ea).ConfigureAwait(false);
}
#endregion
#endregion
}
}
| 39.234686 | 293 | 0.54212 | [
"MIT"
] | FlawCra/DSharpPlus | DSharpPlus/Clients/DiscordClient.Dispatch.cs | 102,481 | C# |
using System;
using System.Threading.Tasks;
using MediatR;
using Microsoft.AspNetCore.Mvc;
using SFA.DAS.Campaign.Web.Helpers;
namespace SFA.DAS.Campaign.Web.Controllers.EmployerInform
{
[Route("employers/funding-an-apprenticeship")]
public class FundingAnApprenticeshipController : Controller
{
private readonly ISessionService _sessionService;
private readonly IMediator _mediator;
public FundingAnApprenticeshipController(ISessionService sessionService, IMediator mediator)
{
_sessionService = sessionService;
_mediator = mediator;
}
[HttpGet]
public async Task<IActionResult> Index()
{
var vm =
_sessionService.Get<LevyOptionViewModel>(_sessionService.LevyOptionViewModelKey)
?? new LevyOptionViewModel();
var page = await _mediator.GetModelForStaticContent();
vm.Menu = page.Menu;
vm.BannerModels = page.BannerModels;
return View("~/Views/EmployerInform/FundingAnApprenticeship.cshtml", vm);
}
[HttpPost]
public async Task<IActionResult> Index(LevyOptionViewModel vm)
{
if (!ModelState.IsValid)
{
var menu = await _mediator.GetMenuForStaticContent();
vm.Menu = menu.Menu;
return View("~/Views/EmployerInform/FundingAnApprenticeship.cshtml", vm);
}
_sessionService.Set(_sessionService.LevyOptionViewModelKey, vm);
return Redirect(vm.LevyStatus == LevyStatus.Levy ? "/employers/funding-an-apprenticeship-levy-payers" : "/employers/funding-an-apprenticeship-non-levy");
}
}
}
| 34.294118 | 165 | 0.641509 | [
"MIT"
] | SkillsFundingAgency/das-campaign | src/SFA.DAS.Campaign.Web/Controllers/EmployerInform/FundingAnApprenticeshipController.cs | 1,751 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace lab_40_entity_code_first.Models
{
class User
{
public int UserId { get; set; }
public string Username { get; set; }
public DateTime DateOfBirth { get; set; }
public int? CategoryId { get; set; }
public Category Category { get; set; }
}
}
| 20.777778 | 49 | 0.625668 | [
"MIT"
] | BrynMorley/2020-06-c-sharp-labs | labs/lab_40_entity_code_first/Models/User.cs | 376 | C# |
// <copyright file="AdminCommandEventArgs.cs" company="StevoTVR">
// Copyright (c) StevoTVR. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
// </copyright>
namespace SevenMod.Console
{
using System;
using System.Collections.Generic;
using SevenMod.Core;
/// <summary>
/// Contains arguments for the <see cref="AdminCommand.Executed"/> event.
/// </summary>
public class AdminCommandEventArgs : EventArgs
{
/// <summary>
/// Initializes a new instance of the <see cref="AdminCommandEventArgs"/> class.
/// </summary>
/// <param name="command">The <see cref="AdminCommand"/> object that raised the event.</param>
/// <param name="arguments">The list of arguments supplied to the admin command.</param>
/// <param name="client">The <see cref="ClientInfo"/> object representing the client that executed the admin command.</param>
internal AdminCommandEventArgs(AdminCommand command, List<string> arguments, ClientInfo client)
{
this.Command = command;
this.Arguments = arguments;
this.Client = (client == null) ? SMClient.Console : new SMClient(client);
}
/// <summary>
/// Gets the <see cref="AdminCommand"/> object representing the admin command that was executed.
/// </summary>
public AdminCommand Command { get; }
/// <summary>
/// Gets the list of arguments supplied to the admin command.
/// </summary>
public List<string> Arguments { get; }
/// <summary>
/// Gets the <see cref="SMClient"/> object representing the client that executed the admin command.
/// </summary>
public SMClient Client { get; }
}
}
| 39.913043 | 133 | 0.634532 | [
"MIT"
] | SevenMod/SevenMod | SevenMod/Console/AdminCommandEventArgs.cs | 1,838 | C# |
/*
* Copyright (c) 2017 Samsung Electronics Co., Ltd. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using TextReader.Tizen.Wearable.Views;
using TextReader.Views;
using Xamarin.Forms;
[assembly:Xamarin.Forms.Dependency(typeof(WearableViewResolver))]
namespace TextReader.Tizen.Wearable.Views
{
/// <summary>
/// Tizen mobile view resolver class.
/// Allows to obtain views for mobile device.
/// </summary>
public class WearableViewResolver : IViewResolver
{
#region fields
/// <summary>
/// Root page instance.
/// </summary>
private NavigationPage _rootPage;
#endregion
#region methods
/// <summary>
/// Returns root page for Tizen mobile application.
/// </summary>
/// <returns>Root page of the application.</returns>
public Page GetRootPage()
{
if (_rootPage != null)
{
return _rootPage;
}
MainPage main = new MainPage();
_rootPage = new NavigationPage(main)
{
BarBackgroundColor = (Color)main.Resources?["MainColor"]
};
return _rootPage;
}
#endregion
}
}
| 27.4 | 75 | 0.624368 | [
"Apache-2.0"
] | Inhong/Tizen-CSharp-Samples | Wearable/Xamarin.Forms/TextReader/TextReader/Views/WearableViewResolver.cs | 1,781 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis;
namespace RazorLight.Compilation
{
public class TemplateCompilationException : RazorLightException
{
private readonly List<TemplateCompilationDiagnostic> compilationDiagnostics = new List<TemplateCompilationDiagnostic>();
public IReadOnlyList<string> CompilationErrors => compilationDiagnostics?.Select(x => x.FormattedMessage).ToList() ?? new List<string>();
public IReadOnlyList<TemplateCompilationDiagnostic> CompilationDiagnostics => compilationDiagnostics;
[Obsolete("Use constructor that takes enumerable of TemplateCompilationDiagnostic as input parameters")]
public TemplateCompilationException(string message, IEnumerable<string> errors) : base(message)
{
if (errors != null)
{
compilationDiagnostics.AddRange(errors.Select(x => new TemplateCompilationDiagnostic(x, x, null)));
}
}
public TemplateCompilationException(string message, IEnumerable<TemplateCompilationDiagnostic> diagnostics) : base(message)
{
if (diagnostics != null)
{
compilationDiagnostics.AddRange(diagnostics);
}
}
}
}
| 33.911765 | 139 | 0.784042 | [
"Apache-2.0"
] | Fenetre/RazorLight | src/RazorLight/Compilation/TemplateCompilationException.cs | 1,155 | C# |
using System;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using WireMock.Logging;
using WireMock.Net.StandAlone;
using WireMock.Server;
namespace WireMock.Net
{
public class Program
{
private static readonly int SleepTime = 30000;
private static readonly ILogger xLogger = LoggerFactory.Create(o =>
{
o.SetMinimumLevel(LogLevel.Debug);
o.AddSimpleConsole(options =>
{
options.IncludeScopes = true;
options.SingleLine = false;
options.TimestampFormat = "yyyy-MM-ddTHH:mm:ss ";
});
}).CreateLogger("WireMock.Net");
private static readonly IWireMockLogger Logger = new WireMockLogger(xLogger);
private static WireMockServer Server;
static async Task Main(string[] args)
{
if (!StandAloneApp.TryStart(args, out Server, Logger))
{
return;
}
Logger.Info("Press Ctrl+C to shut down");
Console.CancelKeyPress += (s, e) =>
{
Stop("CancelKeyPress");
};
System.Runtime.Loader.AssemblyLoadContext.Default.Unloading += ctx =>
{
Stop("AssemblyLoadContext.Default.Unloading");
};
while (true)
{
Logger.Info("Server running : {IsStarted}", Server.IsStarted);
await Task.Delay(SleepTime).ConfigureAwait(false);
}
}
private static void Stop(string why)
{
Logger.Info("Server stopping because '{why}'", why);
Server.Stop();
Logger.Info("Server stopped");
}
}
} | 30.1 | 86 | 0.533223 | [
"Apache-2.0"
] | BearerPipelineTest/WireMock.Net | src/dotnet-WireMock.Net/Program.cs | 1,806 | C# |
using System.Collections.Generic;
using System.Threading.Tasks;
using Destiny2;
using Destiny2.Definitions;
namespace Destiny2WeaponMods.Services
{
public interface IWeaponMods
{
Task<IEnumerable<DestinyInventoryItemDefinition>> GetModsFromManifest();
Task<IEnumerable<DestinyInventoryItemDefinition>> GetModsFromInventory(BungieMembershipType type,
long accountId);
}
} | 29.5 | 106 | 0.769976 | [
"MIT"
] | andyschott/Destiny2WeaponMods | Destiny2WeaponMods/Services/IWeaponMods.cs | 413 | C# |
// This source code is dual-licensed under the Apache License, version
// 2.0, and the Mozilla Public License, version 2.0.
//
// The APL v2.0:
//
//---------------------------------------------------------------------------
// Copyright (c) 2007-2020 VMware, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 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.
//---------------------------------------------------------------------------
//
// The MPL v2.0:
//
//---------------------------------------------------------------------------
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
//
// Copyright (c) 2007-2020 VMware, Inc. All rights reserved.
//---------------------------------------------------------------------------
using System;
using System.Threading;
using RabbitMQ.Util;
using Xunit;
namespace RabbitMQ.Client.Unit
{
public class TestBlockingCell : TimingFixture
{
internal class DelayedSetter<T>
{
public BlockingCell<T> m_k;
public TimeSpan m_delay;
public T m_v;
public void Run()
{
Thread.Sleep(m_delay);
m_k.ContinueWithValue(m_v);
}
}
internal static void SetAfter<T>(TimeSpan delay, BlockingCell<T> k, T v)
{
var ds = new DelayedSetter<T>
{
m_k = k,
m_delay = delay,
m_v = v
};
new Thread(new ThreadStart(ds.Run)).Start();
}
public DateTime m_startTime;
private void ResetTimer()
{
m_startTime = DateTime.Now;
}
public TimeSpan ElapsedMs()
{
return DateTime.Now - m_startTime;
}
[Fact]
public void TestSetBeforeGet()
{
var k = new BlockingCell<int>();
k.ContinueWithValue(123);
Assert.Equal(123, k.WaitForValue());
}
[Fact]
public void TestGetValueWhichDoesNotTimeOut()
{
var k = new BlockingCell<int>();
k.ContinueWithValue(123);
ResetTimer();
int v = k.WaitForValue(TimingInterval);
Assert.True(SafetyMargin > ElapsedMs());
Assert.Equal(123, v);
}
[Fact]
public void TestGetValueWhichDoesTimeOut()
{
var k = new BlockingCell<int>();
ResetTimer();
Assert.Throws<TimeoutException>(() => k.WaitForValue(TimingInterval));
}
[Fact]
public void TestGetValueWhichDoesTimeOutWithTimeSpan()
{
var k = new BlockingCell<int>();
ResetTimer();
Assert.Throws<TimeoutException>(() => k.WaitForValue(TimingInterval));
}
[Fact]
public void TestGetValueWithTimeoutInfinite()
{
var k = new BlockingCell<int>();
SetAfter(TimingInterval, k, 123);
ResetTimer();
int v = k.WaitForValue(Timeout.InfiniteTimeSpan);
Assert.True(TimingInterval - SafetyMargin < ElapsedMs());
Assert.Equal(123, v);
}
[Fact]
public void TestBackgroundUpdateSucceeds()
{
var k = new BlockingCell<int>();
SetAfter(TimingInterval, k, 123);
ResetTimer();
int v = k.WaitForValue(TimingInterval_2X);
Assert.True(TimingInterval - SafetyMargin < ElapsedMs());
Assert.Equal(123, v);
}
[Fact]
public void TestBackgroundUpdateSucceedsWithTimeSpan()
{
var k = new BlockingCell<int>();
SetAfter(TimingInterval, k, 123);
ResetTimer();
int v = k.WaitForValue(TimingInterval_2X);
Assert.True(TimingInterval - SafetyMargin < ElapsedMs());
Assert.Equal(123, v);
}
[Fact]
public void TestBackgroundUpdateSucceedsWithInfiniteTimeoutTimeSpan()
{
var k = new BlockingCell<int>();
SetAfter(TimingInterval, k, 123);
ResetTimer();
TimeSpan infiniteTimeSpan = Timeout.InfiniteTimeSpan;
int v = k.WaitForValue(infiniteTimeSpan);
Assert.True(TimingInterval - SafetyMargin < ElapsedMs());
Assert.Equal(123, v);
}
[Fact]
public void TestBackgroundUpdateFails()
{
var k = new BlockingCell<int>();
SetAfter(TimingInterval_2X, k, 123);
ResetTimer();
Assert.Throws<TimeoutException>(() => k.WaitForValue(TimingInterval));
}
}
}
| 30.425287 | 82 | 0.533434 | [
"MPL-2.0-no-copyleft-exception",
"MPL-2.0",
"Apache-2.0"
] | 554393109/rabbitmq-dotnet-client | projects/Unit/TestBlockingCell.cs | 5,294 | C# |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="CefGlueWebsocketHandler.cs" company="Chromely Projects">
// Copyright (c) 2017-2019 Chromely Projects
// </copyright>
// <license>
// See the LICENSE.md file in the project root for more information.
// </license>
// ----------------------------------------------------------------------------------------------------------------------
using System;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using Chromely.CefGlue.RestfulService;
using Chromely.Core;
using Chromely.Core.Infrastructure;
using Chromely.Core.RestfulService;
using LitJson;
namespace Chromely.CefGlue.Browser.ServerHandlers
{
/// <summary>
/// The CefGlue websocket handler.
/// </summary>
public class CefGlueWebsocketHandler : IChromelyWebsocketHandler
{
/// <summary>
/// The on message.
/// </summary>
/// <param name="connectionId">
/// The connection id.
/// </param>
/// <param name="data">
/// The data.
/// </param>
/// <param name="dataSize">
/// The data size.
/// </param>
public void OnMessage(int connectionId, IntPtr data, long dataSize)
{
Task.Run(() =>
{
IntPtr tempPtr = IntPtr.Zero;
try
{
var managedArray = new byte[dataSize];
Marshal.Copy(data, managedArray, 0, (int)dataSize);
tempPtr = Marshal.AllocHGlobal(managedArray.Length);
Marshal.Copy(managedArray, 0, tempPtr, managedArray.Length);
var requestString = Encoding.UTF8.GetString(managedArray);
var requestInfo = new RequestInfo(requestString);
switch (requestInfo.Type)
{
case MessageType.Echo:
WebsocketMessageSender.Send(connectionId, requestInfo.Data);
break;
case MessageType.TargetRecepient:
WebsocketMessageSender.Send(requestInfo.TargetConnectionId, requestInfo.Data);
break;
case MessageType.Broadcast:
WebsocketMessageSender.Broadcast(connectionId, requestInfo.Data);
break;
case MessageType.ControllerAction:
var jsonData = JsonMapper.ToObject<JsonData>(requestString);
var request = new ChromelyRequest(jsonData);
var response = RequestTaskRunner.Run(request);
WebsocketMessageSender.Send(connectionId, response);
break;
default:
WebsocketMessageSender.Send(connectionId, requestInfo.Data);
break;
}
}
catch (Exception exception)
{
Log.Error(exception);
}
finally
{
// Free the unmanaged memory.
Marshal.FreeHGlobal(tempPtr);
}
});
}
/// <summary>
/// The send.
/// </summary>
/// <param name="connectionId">
/// The connection id.
/// </param>
/// <param name="data">
/// The data.
/// </param>
/// <param name="dataSize">
/// The data size.
/// </param>
public void Send(int connectionId, IntPtr data, long dataSize)
{
WebsocketMessageSender.Send(connectionId, data, dataSize);
}
/// <summary>
/// The send.
/// </summary>
/// <param name="connectionId">
/// The connection id.
/// </param>
/// <param name="data">
/// The data.
/// </param>
public void Send(int connectionId, string data)
{
WebsocketMessageSender.Send(connectionId, data);
}
/// <summary>
/// The send.
/// </summary>
/// <param name="connectionId">
/// The connection id.
/// </param>
/// <param name="response">
/// The response.
/// </param>
public void Send(int connectionId, ChromelyResponse response)
{
WebsocketMessageSender.Send(connectionId, response);
}
/// <summary>
/// The broadcast.
/// </summary>
/// <param name="connectionId">
/// The connection id.
/// </param>
/// <param name="data">
/// The data.
/// </param>
/// <param name="dataSize">
/// The data size.
/// </param>
public void Broadcast(int connectionId, IntPtr data, long dataSize)
{
WebsocketMessageSender.Broadcast(connectionId, data, dataSize);
}
/// <summary>
/// The broadcast.
/// </summary>
/// <param name="connectionId">
/// The connection id.
/// </param>
/// <param name="data">
/// The data.
/// </param>
public void Broadcast(int connectionId, string data)
{
WebsocketMessageSender.Broadcast(connectionId, data);
}
/// <summary>
/// The broadcast.
/// </summary>
/// <param name="connectionId">
/// The connection id.
/// </param>
/// <param name="response">
/// The response.
/// </param>
public void Broadcast(int connectionId, ChromelyResponse response)
{
WebsocketMessageSender.Broadcast(connectionId, response);
}
}
}
| 34.272222 | 121 | 0.46296 | [
"MIT",
"BSD-3-Clause"
] | NovusTheory/Chromely | src/Chromely.CefGlue/Browser/ServerHandlers/CefGlueWebsocketHandler.cs | 6,171 | C# |
/*
* Copyright 2010-2014 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.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.EC2.Model
{
/// <summary>
/// Container for the parameters to the DescribeRegions operation.
/// Describes the regions that are currently available to you.
///
///
/// <para>
/// For a list of the regions supported by Amazon EC2, see <a href="https://docs.aws.amazon.com/general/latest/gr/rande.html#ec2_region">Regions
/// and Endpoints</a>.
/// </para>
/// </summary>
public partial class DescribeRegionsRequest : AmazonEC2Request
{
private List<Filter> _filters = new List<Filter>();
private List<string> _regionNames = new List<string>();
/// <summary>
/// Gets and sets the property Filters.
/// <para>
/// The filters.
/// </para>
/// <ul> <li>
/// <para>
/// <code>endpoint</code> - The endpoint of the region (for example, <code>ec2.us-east-1.amazonaws.com</code>).
/// </para>
/// </li> <li>
/// <para>
/// <code>region-name</code> - The name of the region (for example, <code>us-east-1</code>).
/// </para>
/// </li> </ul>
/// </summary>
public List<Filter> Filters
{
get { return this._filters; }
set { this._filters = value; }
}
// Check to see if Filters property is set
internal bool IsSetFilters()
{
return this._filters != null && this._filters.Count > 0;
}
/// <summary>
/// Gets and sets the property RegionNames.
/// <para>
/// The names of the regions.
/// </para>
/// </summary>
public List<string> RegionNames
{
get { return this._regionNames; }
set { this._regionNames = value; }
}
// Check to see if RegionNames property is set
internal bool IsSetRegionNames()
{
return this._regionNames != null && this._regionNames.Count > 0;
}
}
} | 31.67033 | 148 | 0.591256 | [
"Apache-2.0"
] | FoxBearBear/aws-sdk-net | sdk/src/Services/EC2/Generated/Model/DescribeRegionsRequest.cs | 2,882 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNative.ContainerService.V20210801.Outputs
{
/// <summary>
/// Settings for upgrading an agentpool
/// </summary>
[OutputType]
public sealed class AgentPoolUpgradeSettingsResponse
{
/// <summary>
/// This can either be set to an integer (e.g. '5') or a percentage (e.g. '50%'). If a percentage is specified, it is the percentage of the total agent pool size at the time of the upgrade. For percentages, fractional nodes are rounded up. If not specified, the default is 1. For more information, including best practices, see: https://docs.microsoft.com/azure/aks/upgrade-cluster#customize-node-surge-upgrade
/// </summary>
public readonly string? MaxSurge;
[OutputConstructor]
private AgentPoolUpgradeSettingsResponse(string? maxSurge)
{
MaxSurge = maxSurge;
}
}
}
| 38.387097 | 418 | 0.695798 | [
"Apache-2.0"
] | polivbr/pulumi-azure-native | sdk/dotnet/ContainerService/V20210801/Outputs/AgentPoolUpgradeSettingsResponse.cs | 1,190 | C# |
using GroupDocs.Viewer.Interfaces;
using System.IO;
namespace GroupDocs.Viewer.Forms.UI
{
internal class MemoryPageStreamFactory : IPageStreamFactory
{
public Stream Stream { get; }
public MemoryPageStreamFactory() : this(new MemoryStream()) { }
public MemoryPageStreamFactory(Stream stream) => Stream = stream;
public Stream CreatePageStream(int pageNumber)
{
Stream.Position = 0;
Stream.SetLength(0);
return Stream;
}
public void ReleasePageStream(int pageNumber, Stream pageStream)
{
//NOTE: the pageStream will be disposed by the consumer of this class
}
}
}
| 25.071429 | 81 | 0.633903 | [
"MIT"
] | groupdocs-viewer/GroupDocs.Viewer-for-.NET | Demos/WinForms/src/GroupDocs.Viewer.WinForms/Utils/MemoryPageStreamFactory.cs | 704 | C# |
using Etimo.Benchmarks.Interfaces.Operations;
namespace Etimo.Benchmarks.Implementations.Operations
{
public class OperationGroup<TOperation1> : OperationGroupBase, IOperationGroup<TOperation1> where TOperation1 : IOperationBase
{
public TOperation1 Operation1 { get; set; }
}
public class OperationGroup<TOperation1, TOperation2> : OperationGroupBase, IOperationGroup<TOperation1, TOperation2>
where TOperation1 : IOperationBase
where TOperation2 : IOperationBase
{
public TOperation1 Operation1 { get; set; }
public TOperation2 Operation2 { get; set; }
}
public class OperationGroup<TOperation1, TOperation2, TOperation3> : OperationGroupBase, IOperationGroup<TOperation1, TOperation2, TOperation3>
where TOperation1 : IOperationBase
where TOperation2 : IOperationBase
where TOperation3 : IOperationBase
{
public TOperation1 Operation1 { get; set; }
public TOperation2 Operation2 { get; set; }
public TOperation3 Operation3 { get; set; }
}
public class OperationGroup<TOperation1, TOperation2, TOperation3, TOperation4> : OperationGroupBase, IOperationGroup<TOperation1, TOperation2, TOperation3, TOperation4>
where TOperation1 : IOperationBase
where TOperation2 : IOperationBase
where TOperation3 : IOperationBase
where TOperation4 : IOperationBase
{
public TOperation1 Operation1 { get; set; }
public TOperation2 Operation2 { get; set; }
public TOperation3 Operation3 { get; set; }
public TOperation4 Operation4 { get; set; }
}
public class OperationGroup<TOperation1, TOperation2, TOperation3, TOperation4, TOperation5> : OperationGroupBase, IOperationGroup<TOperation1, TOperation2, TOperation3, TOperation4, TOperation5>
where TOperation1 : IOperationBase
where TOperation2 : IOperationBase
where TOperation3 : IOperationBase
where TOperation4 : IOperationBase
where TOperation5 : IOperationBase
{
public TOperation1 Operation1 { get; set; }
public TOperation2 Operation2 { get; set; }
public TOperation3 Operation3 { get; set; }
public TOperation4 Operation4 { get; set; }
public TOperation5 Operation5 { get; set; }
}
} | 43.886792 | 199 | 0.711092 | [
"Unlicense"
] | Etimo/Etimo.Benchmarks | Src/Etimo.Benchmarks/Implementations/Operations/OperationGroup.cs | 2,328 | C# |
namespace Fasetto.Word.Core
{
/// <summary>
/// The types of icons to use within the application
/// </summary>
public enum IconType
{
/// <summary>
/// No icon
/// </summary>
None = 0,
/// <summary>
/// A picture frame
/// </summary>
Picture = 1,
/// <summary>
/// A file icon
/// </summary>
File = 2,
}
}
| 17.916667 | 56 | 0.427907 | [
"MIT"
] | Drumahota/fasetto-word | Source/Fasetto.Word.Core/DataModels/IconType.cs | 432 | C# |
using Lucene.Net.Index;
using Lucene.Net.Util;
using System.Diagnostics;
namespace Lucene.Net.Codecs.Pulsing
{
/*
* 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.
*/
/// <summary>
/// This postings format "inlines" the postings for terms that have
/// low docFreq. It wraps another postings format, which is used for
/// writing the non-inlined terms.
/// <para/>
/// @lucene.experimental
/// </summary>
public abstract class PulsingPostingsFormat : PostingsFormat
{
private readonly int _freqCutoff;
private readonly int _minBlockSize;
private readonly int _maxBlockSize;
private readonly PostingsBaseFormat _wrappedPostingsBaseFormat;
public PulsingPostingsFormat(PostingsBaseFormat wrappedPostingsBaseFormat, int freqCutoff)
: this(wrappedPostingsBaseFormat, freqCutoff, BlockTreeTermsWriter.DEFAULT_MIN_BLOCK_SIZE,
BlockTreeTermsWriter.DEFAULT_MAX_BLOCK_SIZE)
{
}
/// <summary>Terms with freq less than or equal <paramref name="freqCutoff"/> are inlined into terms dict.</summary>
public PulsingPostingsFormat(PostingsBaseFormat wrappedPostingsBaseFormat, int freqCutoff,
int minBlockSize, int maxBlockSize)
: base()
{
Debug.Assert(minBlockSize > 1);
_freqCutoff = freqCutoff;
_minBlockSize = minBlockSize;
_maxBlockSize = maxBlockSize;
_wrappedPostingsBaseFormat = wrappedPostingsBaseFormat;
}
public override string ToString()
{
return string.Format("{0} (freqCutoff={1}, minBlockSize={2}, maxBlockSize={3})", Name, _freqCutoff, _minBlockSize, _maxBlockSize);
}
public override FieldsConsumer FieldsConsumer(SegmentWriteState state)
{
PostingsWriterBase docsWriter = null;
// Terms that have <= freqCutoff number of docs are
// "pulsed" (inlined):
PostingsWriterBase pulsingWriter = null;
// Terms dict
bool success = false;
try
{
docsWriter = _wrappedPostingsBaseFormat.PostingsWriterBase(state);
// Terms that have <= freqCutoff number of docs are
// "pulsed" (inlined):
pulsingWriter = new PulsingPostingsWriter(state, _freqCutoff, docsWriter);
FieldsConsumer ret = new BlockTreeTermsWriter(state, pulsingWriter, _minBlockSize, _maxBlockSize);
success = true;
return ret;
}
finally
{
if (!success)
{
IOUtils.DisposeWhileHandlingException(docsWriter, pulsingWriter);
}
}
}
public override FieldsProducer FieldsProducer(SegmentReadState state)
{
PostingsReaderBase docsReader = null;
PostingsReaderBase pulsingReader = null;
bool success = false;
try
{
docsReader = _wrappedPostingsBaseFormat.PostingsReaderBase(state);
pulsingReader = new PulsingPostingsReader(state, docsReader);
FieldsProducer ret = new BlockTreeTermsReader(
state.Directory, state.FieldInfos, state.SegmentInfo,
pulsingReader,
state.Context,
state.SegmentSuffix,
state.TermsIndexDivisor);
success = true;
return ret;
}
finally
{
if (!success)
{
IOUtils.DisposeWhileHandlingException(docsReader, pulsingReader);
}
}
}
public virtual int FreqCutoff
{
get { return _freqCutoff; }
}
}
} | 37.792 | 142 | 0.605419 | [
"Apache-2.0"
] | DiogenesPolanco/lucenenet | src/Lucene.Net.Codecs/Pulsing/PulsingPostingsFormat.cs | 4,724 | C# |
// <copyright file="InternetExplorerDriver.cs" company="WebDriver Committers">
// Copyright 2007-2011 WebDriver committers
// Copyright 2007-2011 Google Inc.
// Portions copyright 2011 Software Freedom Conservancy
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Net;
using System.Net.Sockets;
using System.Text;
using OpenQA.Selenium.Internal;
using OpenQA.Selenium.Remote;
namespace OpenQA.Selenium.IE
{
/// <summary>
/// Provides a way to access Internet Explorer to run your tests by creating a InternetExplorerDriver instance
/// </summary>
/// <remarks>
/// When the WebDriver object has been instantiated the browser will load. The test can then navigate to the URL under test and
/// start your test.
/// </remarks>
/// <example>
/// <code>
/// [TestFixture]
/// public class Testing
/// {
/// private IWebDriver driver;
/// <para></para>
/// [SetUp]
/// public void SetUp()
/// {
/// driver = new InternetExplorerDriver();
/// }
/// <para></para>
/// [Test]
/// public void TestGoogle()
/// {
/// driver.Navigate().GoToUrl("http://www.google.co.uk");
/// /*
/// * Rest of the test
/// */
/// }
/// <para></para>
/// [TearDown]
/// public void TearDown()
/// {
/// driver.Quit();
/// driver.Dispose();
/// }
/// }
/// </code>
/// </example>
public class InternetExplorerDriver : RemoteWebDriver, ITakesScreenshot
{
/// <summary>
/// Initializes a new instance of the InternetExplorerDriver class.
/// </summary>
public InternetExplorerDriver()
: this(new InternetExplorerOptions())
{
}
/// <summary>
/// Initializes a new instance of the <see cref="InternetExplorerDriver"/> class with the desired
/// options.
/// </summary>
/// <param name="options">The <see cref="InternetExplorerOptions"/> used to initialize the driver.</param>
public InternetExplorerDriver(InternetExplorerOptions options)
: this(InternetExplorerDriverService.CreateDefaultService(), options)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="InternetExplorerDriver"/> class using the specified path
/// to the directory containing IEDriverServer.exe.
/// </summary>
/// <param name="internetExplorerDriverServerDirectory">The full path to the directory containing IEDriverServer.exe.</param>
public InternetExplorerDriver(string internetExplorerDriverServerDirectory)
: this(internetExplorerDriverServerDirectory, new InternetExplorerOptions())
{
}
/// <summary>
/// Initializes a new instance of the <see cref="InternetExplorerDriver"/> class using the specified path
/// to the directory containing IEDriverServer.exe and options.
/// </summary>
/// <param name="internetExplorerDriverServerDirectory">The full path to the directory containing IEDriverServer.exe.</param>
/// <param name="options">The <see cref="InternetExplorerOptions"/> used to initialize the driver.</param>
public InternetExplorerDriver(string internetExplorerDriverServerDirectory, InternetExplorerOptions options)
: this(InternetExplorerDriverService.CreateDefaultService(internetExplorerDriverServerDirectory), options)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="InternetExplorerDriver"/> class using the specified path
/// to the directory containing IEDriverServer.exe, options, and command timeout.
/// </summary>
/// <param name="internetExplorerDriverServerDirectory">The full path to the directory containing IEDriverServer.exe.</param>
/// <param name="options">The <see cref="InternetExplorerOptions"/> used to initialize the driver.</param>
/// <param name="commandTimeout">The maximum amount of time to wait for each command.</param>
public InternetExplorerDriver(string internetExplorerDriverServerDirectory, InternetExplorerOptions options, TimeSpan commandTimeout)
: this(InternetExplorerDriverService.CreateDefaultService(internetExplorerDriverServerDirectory), options, commandTimeout)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="InternetExplorerDriver"/> class using the specified
/// <see cref="InternetExplorerDriverService"/> and options.
/// </summary>
/// <param name="service">The <see cref="DriverService"/> to use.</param>
/// <param name="options">The <see cref="InternetExplorerOptions"/> used to initialize the driver.</param>
public InternetExplorerDriver(InternetExplorerDriverService service, InternetExplorerOptions options)
: this(service, options, RemoteWebDriver.DefaultCommandTimeout)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="InternetExplorerDriver"/> class using the specified
/// <see cref="DriverService"/>, <see cref="InternetExplorerOptions"/>, and command timeout.
/// </summary>
/// <param name="service">The <see cref="InternetExplorerDriverService"/> to use.</param>
/// <param name="options">The <see cref="InternetExplorerOptions"/> used to initialize the driver.</param>
/// <param name="commandTimeout">The maximum amount of time to wait for each command.</param>
public InternetExplorerDriver(InternetExplorerDriverService service, InternetExplorerOptions options, TimeSpan commandTimeout)
: base(new DriverServiceCommandExecutor(service, commandTimeout), options.ToCapabilities())
{
}
#region ITakesScreenshot Members
/// <summary>
/// Gets a <see cref="Screenshot"/> object representing the image of the page on the screen.
/// </summary>
/// <returns>A <see cref="Screenshot"/> object containing the image.</returns>
public Screenshot GetScreenshot()
{
// Get the screenshot as base64.
Response screenshotResponse = Execute(DriverCommand.Screenshot, null);
string base64 = screenshotResponse.Value.ToString();
// ... and convert it.
return new Screenshot(base64);
}
#endregion
}
}
| 45.670807 | 142 | 0.637155 | [
"Apache-2.0"
] | yumingjuan/selenium | dotnet/src/WebDriver/IE/InternetExplorerDriver.cs | 7,353 | C# |
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Linq;
using Xamarin.Forms;
namespace XLabs.Forms
{
//From the Xamarin forums
//http://forums.xamarin.com/discussion/comment/68739#Comment_68739
public class OnPlatformList<T> : ObservableCollection<T>
{
private ObservableCollection<T> _realData;
public OnPlatformList()
{
iOS = new ObservableCollection<T>();
Android = new ObservableCollection<T>();
WinPhone = new ObservableCollection<T>();
// Unfortunately, there's no way to see the complete initialization of the tag in XAML,
// in this case, the ctor fires before we've seen the collection data
// so hook the collections and wait for each one to change -
// when we find the right one, we'll pull it's data and ignore the others.
iOS.CollectionChanged += OnInitialize;
Android.CollectionChanged += OnInitialize;
WinPhone.CollectionChanged += OnInitialize;
}
// ReSharper disable once InconsistentNaming
public ObservableCollection<T> iOS { get; private set; }
public ObservableCollection<T> Android { get; private set; }
public ObservableCollection<T> WinPhone { get; private set; }
void OnInitialize(object sender, NotifyCollectionChangedEventArgs e)
{
bool foundCollection = false;
if (Device.OS == TargetPlatform.iOS && sender == iOS)
{
Setup(iOS);
foundCollection = true;
}
else if (Device.OS == TargetPlatform.Android && sender == Android)
{
Setup(Android);
foundCollection = true;
}
else if (Device.OS == TargetPlatform.WinPhone && sender == WinPhone)
{
Setup(WinPhone);
foundCollection = true;
}
if (foundCollection)
{
iOS.CollectionChanged -= OnInitialize;
Android.CollectionChanged -= OnInitialize;
WinPhone.CollectionChanged -= OnInitialize;
}
}
void Setup(ObservableCollection<T> data)
{
_realData = data;
foreach (var item in data) Add(item);
data.CollectionChanged += (sender, e) =>
{
switch (e.Action)
{
case NotifyCollectionChangedAction.Add:
foreach (var item in e.NewItems.Cast<T>()) Add(item);
break;
case NotifyCollectionChangedAction.Remove:
foreach (var item in e.OldItems.Cast<T>()) Remove(item);
break;
// TODO: add other operations.
default:
Clear();
foreach (var item in _realData) Add(item);
break;
}
};
}
}
}
| 35.25 | 99 | 0.537073 | [
"Apache-2.0"
] | alemarko/Xamarin-Forms-Labs | src/Forms/XLabs.Forms/Extensions/OnPlatformList.cs | 3,104 | C# |
//
// Unit tests for NSMutableSAttributedString
//
// Authors:
// Sebastien Pouliot <sebastien@xamarin.com>
//
// Copyright 2013-2014 Xamarin Inc. All rights reserved.
//
using System;
using Foundation;
using NUnit.Framework;
namespace MonoTouchFixtures.Foundation {
[TestFixture]
public class MutableSAttributedStringTest {
[Test]
public void InitWith ()
{
using (var s1 = new NSMutableAttributedString ("string")) {
// initWithString: does not respond (see dontlink.app) but it works
Assert.That (s1.Handle, Is.Not.EqualTo (IntPtr.Zero), "Handle-1");
using (var d = new NSDictionary ())
using (var s2 = new NSMutableAttributedString ("string", d)) {
// initWithString:attributes: does not respond (see dontlink.app) but it works
Assert.That (s2.Handle, Is.Not.EqualTo (IntPtr.Zero), "Handle-2");
}
using (var s3 = new NSMutableAttributedString (s1)) {
// initWithAttributedString: does not respond (see dontlink.app) but it works
Assert.That (s3.Handle, Is.Not.EqualTo (IntPtr.Zero), "Handle-3");
}
}
}
[Test]
public void NullDictionary ()
{
using (var s = new NSMutableAttributedString ("string", (NSDictionary) null)) {
Assert.That (s.Handle, Is.Not.EqualTo (IntPtr.Zero));
}
}
#if !__WATCHOS__ && !MONOMAC // No foregroundColor parameter for mac
[Test]
public void IndirectNullDictionary ()
{
// that will call NSAttributedString.ToDictionary which may return null (if empty)
using (var s = new NSMutableAttributedString ("string", foregroundColor: null)) {
Assert.That (s.Handle, Is.Not.EqualTo (IntPtr.Zero));
}
}
#endif // !__WATCHOS__
}
}
| 28.135593 | 85 | 0.689759 | [
"BSD-3-Clause"
] | dottam/xamarin-macios | tests/monotouch-test/Foundation/MutableAttributedStringTest.cs | 1,660 | C# |
using System.IO;
// https://stackoverflow.com/a/452945/148962
namespace Cyotek.DownDetector.Client
{
internal static class StreamUtil
{
#region Public Methods
public static void ReadExactly(Stream input, byte[] buffer, int bytesToRead)
{
int index = 0;
while (index < bytesToRead)
{
int read = input.Read(buffer, index, bytesToRead - index);
if (read == 0)
{
throw new EndOfStreamException
(string.Format("End of stream reached with {0} byte{1} left to read.",
bytesToRead - index,
bytesToRead - index == 1 ? "s" : ""));
}
index += read;
}
}
#endregion Public Methods
}
} | 24.933333 | 84 | 0.552139 | [
"MIT"
] | cyotek/CyotekDownDetector | gui/StreamUtil.cs | 750 | C# |
using System;
namespace Basic
{
public class ReportColorScheme
{
public static ReportColorScheme LightAndBlue = new ReportColorScheme
{
BackgroundColor = ConsoleColor.Gray,
ForegroundColor = ConsoleColor.Black,
ForegorundColor_Keyword = ConsoleColor.Blue,
ForegroundColor_ErrorUnderline = ConsoleColor.Red
};
public static ReportColorScheme LightAndRed = new ReportColorScheme
{
BackgroundColor = ConsoleColor.Gray,
ForegroundColor = ConsoleColor.Black,
ForegorundColor_Keyword = ConsoleColor.Red,
ForegroundColor_ErrorUnderline = ConsoleColor.DarkRed
};
public static ReportColorScheme Default = new ReportColorScheme
{
BackgroundColor = ConsoleColor.Black,
ForegroundColor = ConsoleColor.Gray,
ForegorundColor_Keyword = ConsoleColor.Blue,
ForegroundColor_ErrorUnderline = ConsoleColor.Red
};
public ConsoleColor BackgroundColor;
public ConsoleColor ForegorundColor_Keyword;
public ConsoleColor ForegroundColor;
public ConsoleColor ForegroundColor_ErrorUnderline;
protected ReportColorScheme()
{
}
}
} | 54.35 | 115 | 0.393284 | [
"Apache-2.0"
] | robertsundstrom/vb-lite-compiler | basc/ReportColorScheme.cs | 2,176 | C# |
using System;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("AWSSDK.IoTThingsGraph")]
#if BCL35
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - AWS IoT Things Graph. Initial Release.")]
#elif BCL45
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (4.5) - AWS IoT Things Graph. Initial Release.")]
#elif PCL
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (PCL) - AWS IoT Things Graph. Initial Release.")]
#elif UNITY
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (Unity) - AWS IoT Things Graph. Initial Release.")]
#elif NETSTANDARD13
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (NetStandard 1.3)- AWS IoT Things Graph. Initial Release.")]
#elif NETSTANDARD20
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (NetStandard 2.0)- AWS IoT Things Graph. Initial Release.")]
#else
#error Unknown platform constant - unable to set correct AssemblyDescription
#endif
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyProduct("Amazon Web Services SDK for .NET")]
[assembly: AssemblyCompany("Amazon.com, Inc")]
[assembly: AssemblyCopyright("Copyright 2009-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("3.3")]
[assembly: AssemblyFileVersion("3.3.100.82")]
#if WINDOWS_PHONE || UNITY
[assembly: System.CLSCompliant(false)]
# else
[assembly: System.CLSCompliant(true)]
#endif
#if BCL
[assembly: System.Security.AllowPartiallyTrustedCallers]
#endif | 41.322034 | 129 | 0.758409 | [
"Apache-2.0"
] | damianh/aws-sdk-net | sdk/src/Services/IoTThingsGraph/Properties/AssemblyInfo.cs | 2,438 | C# |
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using MK.Core;
using Quartz;
namespace MK.Modules.BlackDesert.BossTimer
{
public class BossTimerJob : IJob
{
public virtual Task Execute(IJobExecutionContext context)
{
Dictionary<string, BossTimerModule.Settings> bossTimes = (Dictionary <string, BossTimerModule.Settings>)context.MergedJobDataMap.Get("bossTimes");
DateTime dateNow = DateTime.Now;
bool eraseMessages = false;
foreach (var boss in bossTimes)
{
foreach (var time in boss.Value.schedule)
{
DateTime dateBoss = new DateTime(dateNow.Year, dateNow.Month, dateNow.ClosestWeekDay(time.weekDay).Day, time.hour, time.minute, 0);
int minutesLeft = (int)Math.Round((dateBoss - dateNow).TotalMinutes);
if (minutesLeft >= 0 && minutesLeft <= 20)
{
//We delete the messages only one time to avoid situations where there are 2 or more bosses spawning at the same time.
if(!eraseMessages)
{
eraseMessages = true;
MKManager.GetInstance().GetModule<BossTimerModule>().EraseMessages();
}
MKManager.GetInstance().GetModule<BossTimerModule>().SendMessage(boss.Key, minutesLeft, dateBoss, boss.Value.color);
}
}
}
return Task.CompletedTask;
}
}
} | 39.926829 | 158 | 0.55956 | [
"Apache-2.0"
] | Kirbyrawr/mk-discord-bot | mk-discord-bot/src/MK.Modules/BlackDesert/BossTimer/BossTimerJob.cs | 1,639 | C# |
#pragma checksum "..\..\..\Moving.xaml" "{8829d00f-11b8-4213-878b-770e8597ac16}" "5E8F2458CC9F4390AACF38269F78C2F2C6AB0646E3267B2430E1F2E557CC34AE"
//------------------------------------------------------------------------------
// <auto-generated>
// 此代码由工具生成。
// 运行时版本:4.0.30319.42000
//
// 对此文件的更改可能会导致不正确的行为,并且如果
// 重新生成代码,这些更改将会丢失。
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Diagnostics;
using System.Windows;
using System.Windows.Automation;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Effects;
using System.Windows.Media.Imaging;
using System.Windows.Media.Media3D;
using System.Windows.Media.TextFormatting;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Shell;
using cs2_chs;
namespace cs2_chs {
/// <summary>
/// Moving
/// </summary>
public partial class Moving : System.Windows.Window, System.Windows.Markup.IComponentConnector {
private bool _contentLoaded;
/// <summary>
/// InitializeComponent
/// </summary>
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")]
public void InitializeComponent() {
if (_contentLoaded) {
return;
}
_contentLoaded = true;
System.Uri resourceLocater = new System.Uri("/cs2_chs;component/moving.xaml", System.UriKind.Relative);
#line 1 "..\..\..\Moving.xaml"
System.Windows.Application.LoadComponent(this, resourceLocater);
#line default
#line hidden
}
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")]
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes")]
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily")]
void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) {
this._contentLoaded = true;
}
}
}
| 37.618421 | 148 | 0.662469 | [
"MIT"
] | rootacite/cs2_united | cs2_chs/obj/x86/Release/Moving.g.i.cs | 2,967 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using HotChocolate.Execution;
using HotChocolate.Resolvers;
using HotChocolate.Types.Descriptors;
using HotChocolate.Types.Relay;
using Moq;
#if NETCOREAPP2_1
using Snapshooter;
#endif
using Snapshooter.Xunit;
using Xunit;
namespace HotChocolate.Types
{
public class ObjectTypeTests
: TypeTestBase
{
[Fact]
public void ObjectType_DynamicName()
{
// act
var schema = Schema.Create(c =>
{
c.RegisterType(new ObjectType(d => d
.Name(dep => dep.Name + "Foo")
.DependsOn<StringType>()
.Field("bar")
.Type<StringType>()
.Resolver("foo")));
c.Options.StrictValidation = false;
});
// assert
ObjectType type = schema.GetType<ObjectType>("StringFoo");
Assert.NotNull(type);
}
[Fact]
public void ObjectType_DynamicName_NonGeneric()
{
// act
var schema = Schema.Create(c =>
{
c.RegisterType(new ObjectType(d => d
.Name(dep => dep.Name + "Foo")
.DependsOn(typeof(StringType))
.Field("bar")
.Type<StringType>()
.Resolver("foo")));
c.Options.StrictValidation = false;
});
// assert
ObjectType type = schema.GetType<ObjectType>("StringFoo");
Assert.NotNull(type);
}
[Fact]
public void GenericObjectType_DynamicName()
{
// act
var schema = Schema.Create(c =>
{
c.RegisterType(new ObjectType<Foo>(d => d
.Name(dep => dep.Name + "Foo")
.DependsOn<StringType>()));
c.Options.StrictValidation = false;
});
// assert
ObjectType type = schema.GetType<ObjectType>("StringFoo");
Assert.NotNull(type);
}
[Fact]
public void GenericObjectType_DynamicName_NonGeneric()
{
// act
var schema = Schema.Create(c =>
{
c.RegisterType(new ObjectType<Foo>(d => d
.Name(dep => dep.Name + "Foo")
.DependsOn(typeof(StringType))));
c.Options.StrictValidation = false;
});
// assert
ObjectType type = schema.GetType<ObjectType>("StringFoo");
Assert.NotNull(type);
}
[Fact]
public void IntializeExplicitFieldWithImplicitResolver()
{
// arrange
// act
ObjectType<Foo> fooType = CreateType(new ObjectType<Foo>(d => d
.Field(f => f.Description)
.Name("a")));
// assert
Assert.NotNull(fooType.Fields["a"].Resolver);
}
[Fact]
public void IntArgumentIsInferredAsNonNullType()
{
// arrange
// act
ObjectType<QueryWithIntArg> fooType =
CreateType(new ObjectType<QueryWithIntArg>());
// assert
IType argumentType = fooType.Fields["bar"]
.Arguments.First().Type;
Assert.NotNull(argumentType);
Assert.True(argumentType.IsNonNullType());
Assert.Equal("Int", argumentType.NamedType().Name.Value);
}
[Fact]
public async Task FieldMiddlewareIsIntegrated()
{
// arrange
var resolverContext = new Mock<IMiddlewareContext>();
resolverContext.SetupAllProperties();
// act
ObjectType fooType = CreateType(new ObjectType(c => c
.Name("Foo")
.Field("bar")
.Resolver(() => "baz")),
b => b.Use(next => async context =>
{
await next(context);
if (context.Result is string s)
{
context.Result = s.ToUpperInvariant();
}
}));
// assert
await fooType.Fields["bar"].Middleware(resolverContext.Object);
Assert.Equal("BAZ", resolverContext.Object.Result);
}
[Obsolete]
[Fact]
public void DeprecationReasion_Obsolete()
{
// arrange
var resolverContext = new Mock<IMiddlewareContext>();
resolverContext.SetupAllProperties();
// act
ObjectType fooType = CreateType(new ObjectType(c => c
.Name("Foo")
.Field("bar")
.DeprecationReason("fooBar")
.Resolver(() => "baz")));
// assert
Assert.Equal("fooBar", fooType.Fields["bar"].DeprecationReason);
Assert.True(fooType.Fields["bar"].IsDeprecated);
}
[Fact]
public void Deprecated_Field_With_Reason()
{
// arrange
var resolverContext = new Mock<IMiddlewareContext>();
resolverContext.SetupAllProperties();
// act
ObjectType fooType = CreateType(new ObjectType(c => c
.Name("Foo")
.Field("bar")
.Deprecated("fooBar")
.Resolver(() => "baz")));
// assert
Assert.Equal("fooBar", fooType.Fields["bar"].DeprecationReason);
Assert.True(fooType.Fields["bar"].IsDeprecated);
}
[Fact]
public void Deprecated_Field_With_Reason_Is_Serialized()
{
// arrange
var resolverContext = new Mock<IMiddlewareContext>();
resolverContext.SetupAllProperties();
// act
ISchema schema = CreateSchema(new ObjectType(c => c
.Name("Foo")
.Field("bar")
.Deprecated("fooBar")
.Resolver(() => "baz")));
// assert
schema.ToString().MatchSnapshot();
}
[Fact]
public void Deprecated_Field_Without_Reason()
{
// arrange
var resolverContext = new Mock<IMiddlewareContext>();
resolverContext.SetupAllProperties();
// act
ObjectType fooType = CreateType(new ObjectType(c => c
.Name("Foo")
.Field("bar")
.Deprecated()
.Resolver(() => "baz")));
// assert
Assert.Equal(
WellKnownDirectives.DeprecationDefaultReason,
fooType.Fields["bar"].DeprecationReason);
Assert.True(fooType.Fields["bar"].IsDeprecated);
}
[Fact]
public void Deprecated_Field_Without_Reason_Is_Serialized()
{
// arrange
var resolverContext = new Mock<IMiddlewareContext>();
resolverContext.SetupAllProperties();
// act
ISchema schema = CreateSchema(new ObjectType(c => c
.Name("Foo")
.Field("bar")
.Deprecated()
.Resolver(() => "baz")));
// assert
schema.ToString().MatchSnapshot();
}
[Fact]
public void IntializeImpicitFieldWithImplicitResolver()
{
// arrange
// act
ObjectType<Foo> fooType = CreateType(new ObjectType<Foo>());
// assert
Assert.NotNull(fooType.Fields.First().Resolver);
}
[Fact]
public void EnsureObjectTypeKindIsCorret()
{
// arrange
// act
ObjectType<Foo> someObject = CreateType(new ObjectType<Foo>());
// assert
Assert.Equal(TypeKind.Object, someObject.Kind);
}
/// <summary>
/// For the type detection the order of the resolver or type descriptor function should not matter.
///
/// descriptor.Field("test")
/// .Resolver<List<string>>(() => new List<string>())
/// .Type<ListType<StringType>>();
///
/// descriptor.Field("test")
/// .Type<ListType<StringType>>();
/// .Resolver<List<string>>(() => new List<string>())
/// </summary>
[Fact]
public void ObjectTypeWithDynamicField_TypeDeclaOrderShouldNotMatter()
{
// act
FooType fooType = CreateType(new FooType());
// assert
Assert.True(fooType.Fields.TryGetField("test", out ObjectField field));
Assert.IsType<ListType>(field.Type);
Assert.IsType<StringType>(((ListType)field.Type).ElementType);
}
[Fact]
public void GenericObjectTypes()
{
// arrange
// act
ObjectType<GenericFoo<string>> genericType =
CreateType(new ObjectType<GenericFoo<string>>());
// assert
Assert.Equal("GenericFooOfString", genericType.Name);
}
[Fact]
public void NestedGenericObjectTypes()
{
// arrange
// act
ObjectType<GenericFoo<GenericFoo<string>>> genericType =
CreateType(new ObjectType<GenericFoo<GenericFoo<string>>>());
// assert
Assert.Equal("GenericFooOfGenericFooOfString", genericType.Name);
}
[Fact]
public void BindFieldToResolverTypeField()
{
// arrange
// act
ObjectType<Foo> fooType = CreateType(new ObjectType<Foo>(d => d
.Field<FooResolver>(t => t.GetBar(default))));
// assert
Assert.Equal("foo", fooType.Fields["bar"].Arguments.First().Name);
Assert.NotNull(fooType.Fields["bar"].Resolver);
Assert.IsType<StringType>(fooType.Fields["bar"].Type);
}
[Fact]
public void TwoInterfacesProvideFieldAWithDifferentOutputType()
{
// arrange
string source = @"
interface A {
a: String
}
interface B {
a: Int
}
type C implements A & B {
a: String
}";
// act
try
{
Schema.Create(source, c =>
{
c.BindResolver(() => "foo").To("C", "a");
});
}
catch (SchemaException ex)
{
ex.Message.MatchSnapshot();
return;
}
Assert.True(false, "Schema exception was not thrown.");
}
[Fact]
public void TwoInterfacesProvideFieldAWithDifferentArguments1()
{
// arrange
string source = @"
interface A {
a(a: String): String
}
interface B {
a(b: String): String
}
type C implements A & B {
a(a: String): String
}";
// act
try
{
Schema.Create(source, c =>
{
c.BindResolver(() => "foo").To("C", "a");
});
}
catch (SchemaException ex)
{
ex.Message.MatchSnapshot();
return;
}
Assert.True(false, "Schema exception was not thrown.");
}
[Fact]
public void TwoInterfacesProvideFieldAWithDifferentArguments2()
{
// arrange
var source = @"
interface A {
a(a: String): String
}
interface B {
a(a: Int): String
}
type C implements A & B {
a(a: String): String
}";
// act
try
{
Schema.Create(source, c =>
{
c.BindResolver(() => "foo").To("C", "a");
});
}
catch (SchemaException ex)
{
ex.Message.MatchSnapshot();
return;
}
Assert.True(false, "Schema exception was not thrown.");
}
[Fact]
public void TwoInterfacesProvideFieldAWithDifferentArguments3()
{
// arrange
string source = @"
interface A {
a(a: String): String
}
interface B {
a(a: String, b: String): String
}
type C implements A & B {
a(a: String): String
}";
// act
try
{
Schema.Create(source, c =>
{
c.BindResolver(() => "foo").To("C", "a");
});
}
catch (SchemaException ex)
{
ex.Message.MatchSnapshot();
return;
}
Assert.True(false, "Schema exception was not thrown.");
}
[Fact]
public void SpecifyQueryTypeNameInSchemaFirst()
{
// arrange
string source = @"
type A { field: String }
type B { field: String }
type C { field: String }
schema {
query: A
mutation: B
subscription: C
}
";
// act
var schema = Schema.Create(source,
c => c.Use(next => context => default(ValueTask)));
Assert.Equal("A", schema.QueryType.Name.Value);
Assert.Equal("B", schema.MutationType.Name.Value);
Assert.Equal("C", schema.SubscriptionType.Name.Value);
}
[Fact]
public void SpecifyQueryTypeNameInSchemaFirstWithOptions()
{
// arrange
string source = @"
type A { field: String }
type B { field: String }
type C { field: String }
";
// act
var schema = Schema.Create(source,
c =>
{
c.Use(next => context => default(ValueTask));
c.Options.QueryTypeName = "A";
c.Options.MutationTypeName = "B";
c.Options.SubscriptionTypeName = "C";
});
Assert.Equal("A", schema.QueryType.Name.Value);
Assert.Equal("B", schema.MutationType.Name.Value);
Assert.Equal("C", schema.SubscriptionType.Name.Value);
}
[Fact]
public void NoQueryType()
{
// arrange
string source = @"
type A { field: String }
";
// act
Action action = () => Schema.Create(source,
c => c.Use(next => context => default(ValueTask)));
Assert.Throws<SchemaException>(action).Errors.MatchSnapshot();
}
[Fact]
public void ObjectFieldDoesNotMatchInterfaceDefinitionArgTypeInvalid()
{
// arrange
string source = @"
interface A {
a(a: String): String
}
interface B {
a(a: String): String
}
type C implements A & B {
a(a: [String]): String
}";
// act
try
{
Schema.Create(source, c =>
{
c.BindResolver(() => "foo").To("C", "a");
});
}
catch (SchemaException ex)
{
ex.Message.MatchSnapshot();
return;
}
Assert.True(false, "Schema exception was not thrown.");
}
[Fact]
public void ObjectFieldDoesNotMatchInterfaceDefinitionReturnTypeInvalid()
{
// arrange
string source = @"
interface A {
a(a: String): String
}
interface B {
a(a: String): String
}
type C implements A & B {
a(a: String): Int
}";
// act
try
{
Schema.Create(source, c =>
{
c.BindResolver(() => "foo").To("C", "a");
});
}
catch (SchemaException ex)
{
ex.Message.MatchSnapshot();
return;
}
Assert.True(false, "Schema exception was not thrown.");
}
[Fact]
public void ObjectTypeImplementsAllFields()
{
// arrange
string source = @"
interface A {
a(a: String): String
}
interface B {
a(a: String): String
}
type C implements A & B {
a(a: String): String
}
schema {
query: C
}
";
// act
var schema = Schema.Create(source, c =>
{
c.BindResolver(() => "foo").To("C", "a");
});
// assert
ObjectType type = schema.GetType<ObjectType>("C");
Assert.Equal(2, type.Interfaces.Count);
}
[Fact]
public void ObjectTypeImplementsAllFieldsWithWrappedTypes()
{
// arrange
string source = @"
interface A {
a(a: String!): String!
}
interface B {
a(a: String!): String!
}
type C implements A & B {
a(a: String!): String!
}
schema {
query: C
}
";
// act
var schema = Schema.Create(source, c =>
{
c.BindResolver(() => "foo").To("C", "a");
});
// assert
ObjectType type = schema.GetType<ObjectType>("C");
Assert.Equal(2, type.Interfaces.Count);
}
[Fact]
public void Include_TypeWithOneField_ContainsThisField()
{
// arrange
// act
ObjectType<object> fooType =
CreateType(new ObjectType<object>(d => d
.Include<Foo>()));
// assert
Assert.True(fooType.Fields.ContainsField("description"));
}
[Fact]
public void Include_TypeWithOneField_And_Update_FieldDefinition()
{
// arrange
// act
ObjectType<object> fooType =
CreateType(new ObjectType<object>(d => d
.Include<Foo>()
.Field<Foo>(t => t.Description).Name("desc")));
// assert
Assert.True(fooType.Fields.ContainsField("desc"));
}
[Fact]
public void NonNullAttribute_StringIsRewritten_NonNullStringType()
{
// arrange
// act
ObjectType<Bar> fooType = CreateType(new ObjectType<Bar>());
// assert
Assert.True(fooType.Fields["baz"].Type.IsNonNullType());
Assert.Equal("String", fooType.Fields["baz"].Type.NamedType().Name);
}
[Fact]
public void ObjectType_FieldDefaultValue_SerializesCorrectly()
{
// arrange
var objectType = new ObjectType(t => t
.Name("Bar")
.Field("_123")
.Type<StringType>()
.Resolver(() => "")
.Argument("_456",
a => a.Type<InputObjectType<Foo>>()
.DefaultValue(new Foo())));
// act
var schema = Schema.Create(t => t.RegisterQueryType(objectType));
// assert
schema.ToString().MatchSnapshot();
}
[Fact]
public void ObjectType_ResolverOverrides_FieldMember()
{
// arrange
var objectType = new ObjectType<Foo>(t => t
.Field(f => f.Description)
.Resolver("World"));
// act
IRequestExecutor executor =
SchemaBuilder.New()
.AddQueryType(objectType)
.Create()
.MakeExecutable();
// assert
executor.Execute("{ description }").ToJson().MatchSnapshot();
}
[Fact]
public void ObjectType_FuncString_Resolver()
{
// arrange
var objectType = new ObjectType(t => t
.Name("Bar")
.Field("_123")
.Type<StringType>()
.Resolver(() => "fooBar"));
// act
IRequestExecutor executor =
SchemaBuilder.New()
.AddQueryType(objectType)
.Create()
.MakeExecutable();
// assert
executor.Execute("{ _123 }").ToJson().MatchSnapshot();
}
[Fact]
public void ObjectType_FuncString_ResolverInferType()
{
// arrange
var objectType = new ObjectType(t => t
.Name("Bar")
.Field("_123")
.Resolver(() => "fooBar"));
// act
IRequestExecutor executor =
SchemaBuilder.New()
.AddQueryType(objectType)
.Create()
.MakeExecutable();
// assert
executor.Execute("{ _123 }").ToJson().MatchSnapshot();
}
[Fact]
public void ObjectType_ConstantString_Resolver()
{
// arrange
var objectType = new ObjectType(t => t
.Name("Bar")
.Field("_123")
.Type<StringType>()
.Resolver("fooBar"));
// act
IRequestExecutor executor =
SchemaBuilder.New()
.AddQueryType(objectType)
.Create()
.MakeExecutable();
// assert
executor.Execute("{ _123 }").ToJson().MatchSnapshot();
}
[Fact]
public void ObjectType_ConstantString_ResolverInferType()
{
// arrange
var objectType = new ObjectType(t => t
.Name("Bar")
.Field("_123")
.Resolver("fooBar"));
// act
IRequestExecutor executor =
SchemaBuilder.New()
.AddQueryType(objectType)
.Create()
.MakeExecutable();
// assert
executor.Execute("{ _123 }").ToJson().MatchSnapshot();
}
[Fact]
public void ObjectType_FuncCtxString_Resolver()
{
// arrange
var objectType = new ObjectType(t => t
.Name("Bar")
.Field("_123")
.Type<StringType>()
.Resolver(ctx => ctx.Field.Name.Value));
// act
IRequestExecutor executor =
SchemaBuilder.New()
.AddQueryType(objectType)
.Create()
.MakeExecutable();
// assert
executor.Execute("{ _123 }").ToJson().MatchSnapshot();
}
[Fact]
public void ObjectType_FuncCtxString_ResolverInferType()
{
// arrange
var objectType = new ObjectType(t => t
.Name("Bar")
.Field("_123")
.Resolver(ctx => ctx.Field.Name.Value));
// act
IRequestExecutor executor =
SchemaBuilder.New()
.AddQueryType(objectType)
.Create()
.MakeExecutable();
// assert
executor.Execute("{ _123 }").ToJson().MatchSnapshot();
}
[Fact]
public void ObjectType_FuncCtxCtString_Resolver()
{
// arrange
var objectType = new ObjectType(t => t
.Name("Bar")
.Field("_123")
.Type<StringType>()
.Resolver((ctx, ct) => ctx.Field.Name.Value));
// act
IRequestExecutor executor =
SchemaBuilder.New()
.AddQueryType(objectType)
.Create()
.MakeExecutable();
// assert
executor.Execute("{ _123 }").ToJson().MatchSnapshot();
}
[Fact]
public void ObjectType_FuncCtxCtString_ResolverInferType()
{
// arrange
var objectType = new ObjectType(t => t
.Name("Bar")
.Field("_123")
.Resolver((ctx, ct) => ctx.Field.Name.Value));
// act
IRequestExecutor executor =
SchemaBuilder.New()
.AddQueryType(objectType)
.Create()
.MakeExecutable();
// assert
executor.Execute("{ _123 }").ToJson().MatchSnapshot();
}
[Fact]
public void ObjectType_FuncObject_Resolver()
{
// arrange
var objectType = new ObjectType(t => t
.Name("Bar")
.Field("_123")
.Type<StringType>()
.Resolver(() => (object)"fooBar"));
// act
IRequestExecutor executor =
SchemaBuilder.New()
.AddQueryType(objectType)
.Create()
.MakeExecutable();
// assert
executor.Execute("{ _123 }").ToJson().MatchSnapshot();
}
[Fact]
public void ObjectType_ConstantObject_Resolver()
{
// arrange
var objectType = new ObjectType(t => t
.Name("Bar")
.Field("_123")
.Type<StringType>()
.Resolver((object)"fooBar"));
// act
IRequestExecutor executor =
SchemaBuilder.New()
.AddQueryType(objectType)
.Create()
.MakeExecutable();
// assert
executor.Execute("{ _123 }").ToJson().MatchSnapshot();
}
[Fact]
public void ObjectType_FuncCtxObject_Resolver()
{
// arrange
var objectType = new ObjectType(t => t
.Name("Bar")
.Field("_123")
.Type<StringType>()
.Resolver(ctx => (object)ctx.Field.Name.Value));
// act
IRequestExecutor executor =
SchemaBuilder.New()
.AddQueryType(objectType)
.Create()
.MakeExecutable();
// assert
executor.Execute("{ _123 }").ToJson().MatchSnapshot();
}
[Fact]
public void ObjectType_FuncCtxCtObject_Resolver()
{
// arrange
var objectType = new ObjectType(t => t
.Name("Bar")
.Field("_123")
.Type<StringType>()
.Resolver((ctx, ct) => (object)ctx.Field.Name.Value));
// act
IRequestExecutor executor =
SchemaBuilder.New()
.AddQueryType(objectType)
.Create()
.MakeExecutable();
// assert
executor.Execute("{ _123 }").ToJson().MatchSnapshot();
}
[Fact]
public void ObjectTypeOfFoo_FuncString_Resolver()
{
// arrange
var objectType = new ObjectType<Foo>(t => t
.Field(f => f.Description)
.Type<StringType>()
.Resolver(() => "fooBar"));
// act
IRequestExecutor executor =
SchemaBuilder.New()
.AddQueryType(objectType)
.Create()
.MakeExecutable();
// assert
executor.Execute("{ description }").ToJson().MatchSnapshot();
}
[Fact]
public void ObjectTypeOfFoo_ConstantString_Resolver()
{
// arrange
var objectType = new ObjectType<Foo>(t => t
.Field(f => f.Description)
.Type<StringType>()
.Resolver("fooBar"));
// act
IRequestExecutor executor =
SchemaBuilder.New()
.AddQueryType(objectType)
.Create()
.MakeExecutable();
// assert
executor.Execute("{ description }").ToJson().MatchSnapshot();
}
[Fact]
public void ObjectTypeOfFoo_FuncCtxString_Resolver()
{
// arrange
var objectType = new ObjectType<Foo>(t => t
.Field(f => f.Description)
.Type<StringType>()
.Resolver(ctx => ctx.Field.Name.Value));
// act
IRequestExecutor executor =
SchemaBuilder.New()
.AddQueryType(objectType)
.Create()
.MakeExecutable();
// assert
executor.Execute("{ description }").ToJson().MatchSnapshot();
}
[Fact]
public void ObjectTypeOfFoo_FuncCtxCtString_Resolver()
{
// arrange
var objectType = new ObjectType<Foo>(t => t
.Field(f => f.Description)
.Type<StringType>()
.Resolver((ctx, ct) => ctx.Field.Name.Value));
// act
IRequestExecutor executor =
SchemaBuilder.New()
.AddQueryType(objectType)
.Create()
.MakeExecutable();
// assert
executor.Execute("{ description }").ToJson().MatchSnapshot();
}
[Fact]
public void ObjectTypeOfFoo_FuncObject_Resolver()
{
// arrange
var objectType = new ObjectType<Foo>(t => t
.Field(f => f.Description)
.Type<StringType>()
.Resolver(() => (object)"fooBar"));
// act
IRequestExecutor executor =
SchemaBuilder.New()
.AddQueryType(objectType)
.Create()
.MakeExecutable();
// assert
executor.Execute("{ description }").ToJson().MatchSnapshot();
}
[Fact]
public void ObjectTypeOfFoo_ConstantObject_Resolver()
{
// arrange
var objectType = new ObjectType<Foo>(t => t
.Field(f => f.Description)
.Type<StringType>()
.Resolver((object)"fooBar"));
// act
IRequestExecutor executor =
SchemaBuilder.New()
.AddQueryType(objectType)
.Create()
.MakeExecutable();
// assert
executor.Execute("{ description }").ToJson().MatchSnapshot();
}
[Fact]
public void ObjectTypeOfFoo_FuncCtxObject_Resolver()
{
// arrange
var objectType = new ObjectType<Foo>(t => t
.Field(f => f.Description)
.Type<StringType>()
.Resolver(ctx => (object)ctx.Field.Name.Value));
// act
IRequestExecutor executor =
SchemaBuilder.New()
.AddQueryType(objectType)
.Create()
.MakeExecutable();
// assert
executor.Execute("{ description }").ToJson().MatchSnapshot();
}
[Fact]
public void ObjectTypeOfFoo_FuncCtxCtObject_Resolver()
{
// arrange
var objectType = new ObjectType<Foo>(t => t
.Field(f => f.Description)
.Type<StringType>()
.Resolver((ctx, ct) => (object)ctx.Field.Name.Value));
// act
IRequestExecutor executor =
SchemaBuilder.New()
.AddQueryType(objectType)
.Create()
.MakeExecutable();
// assert
executor.Execute("{ description }").ToJson().MatchSnapshot();
}
[Fact]
public async Task ObjectType_SourceTypeObject_BindsResolverCorrectly()
{
// arrange
var objectType = new ObjectType(t => t.Name("Bar")
.Field<FooResolver>(f => f.GetDescription(default))
.Name("desc")
.Type<StringType>());
var schema = Schema.Create(t => t.RegisterQueryType(objectType));
IRequestExecutor executor = schema.MakeExecutable();
// act
IExecutionResult result = await executor.ExecuteAsync(
QueryRequestBuilder.New()
.SetQuery("{ desc }")
.SetInitialValue(new Foo())
.Create());
// assert
result.ToJson().MatchSnapshot();
}
[Fact]
public void InferInterfaceImplementation()
{
// arrange
// act
ObjectType<Foo> fooType = CreateType(new ObjectType<Foo>(),
b => b.AddType(new InterfaceType<IFoo>()));
// assert
Assert.IsType<InterfaceType<IFoo>>(
fooType.Interfaces[0]);
}
[Fact]
public void IgnoreFieldWithShortcut()
{
// arrange
// act
ObjectType<Foo> fooType = CreateType(new ObjectType<Foo>(d =>
{
d.Ignore(t => t.Description);
d.Field("foo").Type<StringType>().Resolver("abc");
}));
// assert
Assert.Collection(
fooType.Fields.Where(t => !t.IsIntrospectionField),
t => Assert.Equal("foo", t.Name));
}
[Fact]
public void UnignoreFieldWithShortcut()
{
// arrange
// act
ObjectType<Foo> fooType = CreateType(new ObjectType<Foo>(d =>
{
d.Ignore(t => t.Description);
d.Field("foo").Type<StringType>().Resolver("abc");
d.Field(t => t.Description).Ignore(false);
}));
// assert
Assert.Collection(
fooType.Fields.Where(t => !t.IsIntrospectionField),
t => Assert.Equal("description", t.Name),
t => Assert.Equal("foo", t.Name));
}
[Fact]
public void IgnoreField_DescriptorIsNull_ArgumentNullException()
{
// arrange
// act
Action a = () => ObjectTypeDescriptorExtensions
.Ignore<Foo>(null, t => t.Description);
// assert
Assert.Throws<ArgumentNullException>(a);
}
[Fact]
public void IgnoreField_ExpressionIsNull_ArgumentNullException()
{
// arrange
var descriptor = new Mock<IObjectTypeDescriptor<Foo>>();
// act
Action a = () => ObjectTypeDescriptorExtensions
.Ignore(descriptor.Object, null);
// assert
Assert.Throws<ArgumentNullException>(a);
}
[Fact]
public void DoNotAllow_InputTypes_OnFields()
{
// arrange
// act
Action a = () => SchemaBuilder.New()
.AddType(new ObjectType(t => t
.Name("Foo")
.Field("bar")
.Type<NonNullType<InputObjectType<Foo>>>()))
.Create();
// assert
Assert.Throws<SchemaException>(a)
.Errors.First().Message.MatchSnapshot();
}
[Fact]
public void DoNotAllow_DynamicInputTypes_OnFields()
{
// arrange
// act
Action a = () => SchemaBuilder.New()
.AddType(new ObjectType(t => t
.Name("Foo")
.Field("bar")
.Type(new NonNullType(new InputObjectType<Foo>()))))
.Create();
// assert
Assert.Throws<SchemaException>(a)
.Errors.First().Message.MatchSnapshot();
}
[Fact]
public void Support_Argument_Attributes()
{
// arrange
// act
ISchema schema = SchemaBuilder.New()
.AddQueryType<Baz>()
.Create();
// assert
schema.ToString().MatchSnapshot();
}
[Fact]
public void Argument_Type_IsInferred_From_Parameter()
{
// arrange
// act
ISchema schema = SchemaBuilder.New()
.AddQueryType<QueryWithIntArg>(t => t
.Field(f => f.GetBar(1))
.Argument("foo", a => a.DefaultValue(default)))
.Create();
// assert
schema.ToString().MatchSnapshot();
}
[Fact]
public void Argument_Type_Cannot_Be_Inferred()
{
// arrange
// act
Action action = () => SchemaBuilder.New()
.AddQueryType<QueryWithIntArg>(t => t
.Field(f => f.GetBar(1))
.Argument("bar", a => a.DefaultValue(default)))
.Create();
// assert
Assert.Throws<SchemaException>(action)
.Errors.First().Message.MatchSnapshot();
}
[Fact]
public void CreateObjectTypeWithXmlDocumentation()
{
// arrange
// act
ISchema schema = SchemaBuilder.New()
.AddQueryType<QueryWithDocumentation>()
.Create();
// assert
schema.ToString().MatchSnapshot();
}
[Fact]
public void CreateObjectTypeWithXmlDocumentation_IgnoreXmlDocs()
{
// arrange
// act
ISchema schema = SchemaBuilder.New()
.AddQueryType<QueryWithDocumentation>()
.ModifyOptions(options => options.UseXmlDocumentation = false)
.Create();
// assert
schema.ToString().MatchSnapshot();
}
[Fact]
public void CreateObjectTypeWithXmlDocumentation_IgnoreXmlDocs_SchemaCreate()
{
// arrange
// act
ISchema schema = Schema.Create(c =>
{
c.RegisterQueryType<QueryWithDocumentation>();
c.Options.UseXmlDocumentation = false;
});
// assert
schema.ToString().MatchSnapshot();
}
[Fact]
public void Field_Is_Missing_Type_Throws_SchemaException()
{
// arrange
// act
Action action = () => SchemaBuilder.New()
.AddObjectType(t => t
.Name("abc")
.Field("def")
.Resolve((object)"ghi"))
.Create();
// assert
Assert.Throws<SchemaException>(action)
.Errors.Select(t => new { t.Message, t.Code })
.MatchSnapshot();
}
[Fact]
public void Deprecate_Obsolete_Fields()
{
// arrange
// act
ISchema schema = SchemaBuilder.New()
.AddQueryType(c => c
.Name("Query")
.Field("foo")
.Type<StringType>()
.Resolver("bar"))
.AddType(new ObjectType<FooObsolete>())
.Create();
// assert
schema.ToString().MatchSnapshot();
}
[Fact]
public void Deprecate_Fields_With_Deprecated_Attribute()
{
// arrange
// act
ISchema schema = SchemaBuilder.New()
.AddQueryType(c => c
.Name("Query")
.Field("foo")
.Type<StringType>()
.Resolver("bar"))
.AddType(new ObjectType<FooDeprecated>())
.Create();
// assert
schema.ToString().MatchSnapshot();
}
[Fact]
public void ObjectType_From_Struct()
{
// arrange
// act
ISchema schema = SchemaBuilder.New()
.AddQueryType(new ObjectType<FooStruct>())
.Create();
// assert
schema.ToString().MatchSnapshot();
}
[Fact]
public async Task Execute_With_Query_As_Struct()
{
// arrange
IRequestExecutor executor = SchemaBuilder.New()
.AddQueryType(new ObjectType<FooStruct>())
.Create()
.MakeExecutable();
// act
IExecutionResult result = await executor.ExecuteAsync(
QueryRequestBuilder.New()
.SetQuery("{ bar baz }")
.SetInitialValue(new FooStruct
{
Qux = "Qux_Value",
Baz = "Baz_Value"
})
.Create());
// assert
result.ToJson().MatchSnapshot();
}
[Fact]
public void ObjectType_From_Dictionary()
{
// arrange
// act
ISchema schema = SchemaBuilder.New()
.AddQueryType<FooWithDict>()
.Create();
// assert
#if NETCOREAPP2_1
schema.ToString().MatchSnapshot(new SnapshotNameExtension("NETCOREAPP2_1"));
#else
schema.ToString().MatchSnapshot();
#endif
}
[Fact]
public void Infer_List_From_Queryable()
{
// arrange
// act
ISchema schema = SchemaBuilder.New()
.AddQueryType<MyListQuery>()
.Create();
// assert
#if NETCOREAPP2_1
schema.ToString().MatchSnapshot(new SnapshotNameExtension("NETCOREAPP2_1"));
#else
schema.ToString().MatchSnapshot();
#endif
}
[Fact]
public void NonNull_Attribute_With_Explicit_Nullability_Definition()
{
// arrange
// act
ISchema schema = SchemaBuilder.New()
.AddQueryType<AnnotatedNestedList>()
.Create();
// assert
schema.ToString().MatchSnapshot();
}
[Fact]
public void Infer_Non_Null_Filed()
{
// arrange
// act
ISchema schema = SchemaBuilder.New()
.AddQueryType<Bar>()
.Create();
// assert
#if NETCOREAPP2_1
schema.ToString().MatchSnapshot(new SnapshotNameExtension("NETCOREAPP2_1"));
#else
schema.ToString().MatchSnapshot();
#endif
}
[Fact]
public void Ignore_Fields_With_GraphQLIgnoreAttribute()
{
// arrange
// act
ISchema schema = SchemaBuilder.New()
.AddQueryType<FooIgnore>()
.Create();
// assert
schema.ToString().MatchSnapshot();
}
[Fact]
public void Declare_Resolver_With_Result_Type_String()
{
// arrange
// act
ISchema schema = SchemaBuilder.New()
.AddQueryType(t => t
.Name("Query")
.Field("test")
.Resolver(
ctx => new ValueTask<object>("abc"),
typeof(string)))
.Create();
// assert
schema.ToString().MatchSnapshot();
}
[Fact]
public void Declare_Resolver_With_Result_Type_NativeTypeListOfInt()
{
// arrange
// act
ISchema schema = SchemaBuilder.New()
.AddQueryType(t => t
.Name("Query")
.Field("test")
.Resolver(
ctx => new ValueTask<object>("abc"),
typeof(NativeType<List<int>>)))
.Create();
// assert
schema.ToString().MatchSnapshot();
}
[Fact]
public void Declare_Resolver_With_Result_Type_ListTypeOfIntType()
{
// arrange
// act
ISchema schema = SchemaBuilder.New()
.AddQueryType(t => t
.Name("Query")
.Field("test")
.Resolver(
ctx => new ValueTask<object>("abc"),
typeof(ListType<IntType>)))
.Create();
// assert
schema.ToString().MatchSnapshot();
}
[Fact]
public void Declare_Resolver_With_Result_Type_Override_ListTypeOfIntType()
{
// arrange
// act
ISchema schema = SchemaBuilder.New()
.AddQueryType(t => t
.Name("Query")
.Field("test")
.Type<StringType>()
.Resolver(
ctx => new ValueTask<object>("abc"),
typeof(ListType<IntType>)))
.Create();
// assert
schema.ToString().MatchSnapshot();
}
[Fact]
public void Declare_Resolver_With_Result_Type_Weak_Override_ListTypeOfIntType()
{
// arrange
// act
ISchema schema = SchemaBuilder.New()
.AddQueryType(t => t
.Name("Query")
.Field("test")
.Type<StringType>()
.Resolver(
ctx => new ValueTask<object>("abc"),
typeof(int)))
.Create();
// assert
schema.ToString().MatchSnapshot();
}
[Fact]
public void Declare_Resolver_With_Result_Type_Is_Null()
{
// arrange
// act
ISchema schema = SchemaBuilder.New()
.AddQueryType(t => t
.Name("Query")
.Field("test")
.Type<StringType>()
.Resolver(
ctx => new ValueTask<object>("abc"),
null))
.Create();
// assert
schema.ToString().MatchSnapshot();
}
[Fact]
public void Infer_Argument_Default_Values()
{
// arrange
// act
ISchema schema = SchemaBuilder.New()
.AddQueryType<QueryWithArgumentDefaults>()
.Create();
// assert
schema.ToString().MatchSnapshot();
}
[Fact]
public void Inferred_Interfaces_From_Type_Extensions_Are_Merged()
{
SchemaBuilder.New()
.AddDocumentFromString("type Query { some: Some } type Some { foo: String }")
.AddType<SomeTypeExtensionWithInterface>()
.Use(next => context => default(ValueTask))
.EnableRelaySupport()
.Create()
.ToString()
.MatchSnapshot();
}
[Fact]
public void Interfaces_From_Type_Extensions_Are_Merged()
{
SchemaBuilder.New()
.AddDocumentFromString("type Query { some: Some } type Some { foo: String }")
.AddDocumentFromString("extend type Some implements Node { id: ID! }")
.Use(next => context => default(ValueTask))
.EnableRelaySupport()
.Create()
.ToString()
.MatchSnapshot();
}
[Fact]
public void Nested_Lists_With_Sdl_First()
{
SchemaBuilder.New()
.AddDocumentFromString("type Query { some: [[Some]] } type Some { foo: String }")
.Use(next => context => default(ValueTask))
.Create()
.ToString()
.MatchSnapshot();
}
[Fact]
public void Nested_Lists_With_Code_First()
{
SchemaBuilder.New()
.AddQueryType<QueryWithNestedList>()
.Create()
.ToString()
.MatchSnapshot();
}
[Fact]
public void Execute_Nested_Lists_With_Code_First()
{
SchemaBuilder.New()
.AddQueryType<QueryWithNestedList>()
.Create()
.MakeExecutable()
.Execute("{ fooMatrix { baz } }")
.MatchSnapshot();
}
[Fact]
public void ResolveWith()
{
SchemaBuilder.New()
.AddQueryType<ResolveWithQueryType>()
.Create()
.MakeExecutable()
.Execute("{ foo baz }")
.MatchSnapshot();
}
public class GenericFoo<T>
{
public T Value { get; }
}
public class Foo
: IFoo
{
public Foo() { }
public Foo(string description)
{
Description = description;
}
public string Description { get; } = "hello";
}
public interface IFoo
{
string Description { get; }
}
public class FooResolver
{
public string GetBar(string foo) => "hello foo";
public string GetDescription([Parent] Foo foo) => foo.Description;
}
public class QueryWithIntArg
{
public string GetBar(int foo) => "hello foo";
}
#nullable enable
public class Bar
{
[GraphQLNonNullType]
public string Baz { get; set; }
}
#nullable disable
public class Baz
{
public string Qux(
[GraphQLName("arg2")]
[GraphQLDescription("argdesc")]
[GraphQLNonNullType]
string arg) => arg;
public string Quux(
[GraphQLType(typeof(ListType<StringType>))]
string arg) => arg;
}
public class FooType
: ObjectType<Foo>
{
protected override void Configure(IObjectTypeDescriptor<Foo> descriptor)
{
descriptor.Field(t => t.Description);
descriptor.Field("test")
.Resolver(() => new List<string>())
.Type<ListType<StringType>>();
}
}
public class FooObsolete
{
[Obsolete("Baz")]
public string Bar() => "foo";
}
public class FooIgnore
{
[GraphQLIgnore]
public string Bar() => "foo";
public string Baz() => "foo";
}
public class FooDeprecated
{
[GraphQLDeprecated("Use Bar2.")]
public string Bar() => "foo";
public string Bar2() => "Foo 2: Electric foo-galoo";
}
public struct FooStruct
{
// should be ignored by the automatic field
// inference.
public string Qux;
// should be included by the automatic field
// inference.
public string Baz { get; set; }
// should be ignored by the automatic field
// inference since we cannot determine what object means
// in the graphql context.
// This field has to be included explicitly.
public object Quux { get; set; }
// should be included by the automatic field
// inference.
public string GetBar() => Qux + "_Bar_Value";
}
public class FooWithDict
{
public Dictionary<string, Bar> Map { get; set; }
}
public class MyList
: MyListBase
{
}
public class MyListBase
: IQueryable<Bar>
{
public Type ElementType => throw new NotImplementedException();
public Expression Expression => throw new NotImplementedException();
public IQueryProvider Provider => throw new NotImplementedException();
public IEnumerator<Bar> GetEnumerator()
{
throw new NotImplementedException();
}
IEnumerator IEnumerable.GetEnumerator()
{
throw new NotImplementedException();
}
}
public class MyListQuery
{
public MyList List { get; set; }
}
public class FooWithNullable
{
public bool? Bar { get; set; }
public List<bool?> Bars { get; set; }
}
public class QueryWithArgumentDefaults
{
public string Field1(
string a = null,
string b = "abc") => null;
public string Field2(
[DefaultValue(null)] string a,
[DefaultValue("abc")] string b) => null;
}
[ExtendObjectType(Name = "Some")]
public class SomeTypeExtensionWithInterface
: INode
{
[GraphQLType(typeof(NonNullType<IdType>))]
public string Id { get; }
}
public class QueryWithNestedList
{
public List<List<FooIgnore>> FooMatrix =>
new List<List<FooIgnore>>
{
new List<FooIgnore>
{
new FooIgnore()
}
};
}
public class ResolveWithQuery
{
public int Foo { get; set; } = 123;
}
public class ResolveWithQueryResolver
{
public string Bar { get; set; } = "Bar";
}
public class ResolveWithQueryType : ObjectType<ResolveWithQuery>
{
protected override void Configure(IObjectTypeDescriptor<ResolveWithQuery> descriptor)
{
descriptor.Field(t => t.Foo).ResolveWith<ResolveWithQueryResolver>(t => t.Bar);
descriptor.Field("baz").ResolveWith<ResolveWithQueryResolver>(t => t.Bar);
}
}
public class AnnotatedNestedList
{
[GraphQLNonNullType(true, false, false)]
public List<List<string>> NestedList { get; set; }
}
}
}
| 28.919959 | 107 | 0.453295 | [
"MIT"
] | damikun/hotchocolate | src/HotChocolate/Core/test/Types.Tests/Types/ObjectTypeTests.cs | 56,365 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Obecné informace o sestavení se řídí přes následující
// sadu atributů. Změnou hodnot těchto atributů se upraví informace
// přidružené k sestavení.
[assembly: AssemblyTitle("Pexeso")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Pexeso")]
[assembly: AssemblyCopyright("Copyright © 2022")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Nastavení ComVisible na false způsobí neviditelnost typů v tomto sestavení
// pro komponenty modelu COM. Pokud potřebujete přístup k typu v tomto sestavení
// modelu COM, nastavte atribut ComVisible daného typu na hodnotu True.
[assembly: ComVisible(false)]
// Následující GUID se používá pro ID knihovny typů, pokud je tento projekt vystavený pro COM.
[assembly: Guid("a8f14d3f-a212-421b-afb1-4b337159e96f")]
// Informace o verzi sestavení se skládá z těchto čtyř hodnot:
//
// Hlavní verze
// Podverze
// Číslo sestavení
// Revize
//
// Můžete zadat všechny hodnoty nebo nastavit výchozí číslo buildu a revize
// pomocí zástupného znaku * takto:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 36.486486 | 94 | 0.754074 | [
"MIT"
] | oskarbukovsky/repos | Pexeso/Pexeso/Properties/AssemblyInfo.cs | 1,409 | C# |
using MasterDevs.ChromeDevTools;
using Newtonsoft.Json;
using System.Collections.Generic;
namespace MasterDevs.ChromeDevTools.Protocol.Chrome.Overlay
{
/// <summary>
/// Fired when the node should be highlighted. This happens after call to `setInspectMode`.
/// </summary>
[Event(ProtocolName.Overlay.NodeHighlightRequested)]
[SupportedBy("Chrome")]
public class NodeHighlightRequestedEvent
{
/// <summary>
/// Gets or sets NodeId
/// </summary>
public long NodeId { get; set; }
}
}
| 24.95 | 92 | 0.739479 | [
"MIT"
] | rollrat/custom-crawler | ChromeDevTools/Protocol/Chrome/Overlay/NodeHighlightRequestedEvent.cs | 499 | C# |
/****
* Exrecodel - "Extensible Regulation/Convention Descriptor Language"
* 「拡張可能な規則/規約記述言語」
* Copyright (C) 2020-2021 Yigty.ORG; all rights reserved.
* Copyright (C) 2020-2021 Takym.
*
* distributed under the MIT License.
****/
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using Exrecodel.ContactInfo;
using TakymLib;
namespace Exrecodel.InternalImplementations.ContactInfo
{
internal sealed class XrcdlEmailInfoImplementation : XrcdlEmailInfo
{
private readonly XmlElement _email_elem;
public override string Address
{
get => _email_elem.InnerText ?? string.Empty;
set => _email_elem.InnerText = value;
}
public override string? Subject
{
get => _email_elem.GetAttribute(Constants.Subject);
set => _email_elem.SetAttribute(Constants.Subject, value);
}
public override string? Body
{
get => _email_elem.GetAttribute(Constants.Body);
set => _email_elem.SetAttribute(Constants.Body, value);
}
public XrcdlEmailInfoImplementation(XrcdlMetadataImplementation metadata, XmlElement emailElement) : base(metadata)
{
_email_elem = emailElement;
}
public override string GetContactType()
{
return Constants.EmailInfo;
}
public override IXrcdlConverter GetConverter()
{
return new XrcdlConverter(this);
}
private readonly struct XrcdlConverter : IXrcdlAsyncConverter
{
private readonly XrcdlEmailInfoImplementation _info;
internal XrcdlConverter(XrcdlEmailInfoImplementation info)
{
_info = info;
}
public void ConvertToHtml(StringBuilder sb)
{
sb.EnsureNotNull(nameof(sb));
sb.AppendStartContactInfo(_info);
sb.Append($"<p><a href=\"{_info.AsUri()}\">{_info.Address}</a></p>");
sb.AppendEndContactInfo();
}
public Task ConvertToHtmlAsync(StringBuilder sb)
{
this.ConvertToHtml(sb);
return Task.CompletedTask;
}
public void Dispose()
{
// do nothing
}
public ValueTask DisposeAsync()
{
// do nothing
return default;
}
}
}
}
| 23.230769 | 118 | 0.684011 | [
"MIT"
] | Takym/TakymLib | Deprecated/Exrecodel/InternalImplementations/ContactInfo/XrcdlEmailInfoImplementation.cs | 2,056 | C# |
using AES.Core.Controllers;
using AES.Order.API.Application.DTO;
using AES.Order.API.Application.Queries;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Net;
using System.Threading.Tasks;
namespace AES.Order.API.Controllers
{
[Authorize]
public class VoucherController : MainController
{
private readonly IVoucherQueries _voucherQueries;
public VoucherController(IVoucherQueries voucherQueries)
{
_voucherQueries = voucherQueries;
}
[HttpGet("voucher/{code}")]
[ProducesResponseType(typeof(VoucherDTO), (int)HttpStatusCode.OK)]
[ProducesResponseType((int)HttpStatusCode.NotFound)]
public async Task<IActionResult> GetByCode(string code)
{
if (string.IsNullOrEmpty(code)) return NotFound();
var voucher = await _voucherQueries.GetVoucherByCode(code);
return voucher == null ? NotFound() : CustomResponse();
}
}
} | 30.333333 | 74 | 0.69031 | [
"MIT"
] | thiagocruzrj/Advanced-EShop | src/Services/Order/AES.Order.API/Controllers/VoucherController.cs | 1,003 | C# |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Diagnostics.ContractsLight;
using BuildXL.FrontEnd.Script.Values;
using BuildXL.Utilities;
using static BuildXL.Utilities.FormattableStringEx;
using LineInfo = TypeScript.Net.Utilities.LineInfo;
namespace BuildXL.FrontEnd.Script.Literals
{
/// <summary>
/// Marker interface that represent a constant expression.
/// </summary>
public interface IConstantExpression
{
/// <summary>
/// Returns boxed value of a constant expression.
/// </summary>
object Value { get; }
/// <summary>
/// Location of the constant expression
/// </summary>
LineInfo Location { get; }
}
/// <summary>
/// Kind of a constant expression.
/// </summary>
public enum ConstExpressionKind : byte
{
/// <nodoc />
Node,
/// <nodoc />
Number,
/// <nodoc />
Boolean,
/// <nodoc />
EnumValue,
/// <nodoc />
String,
/// <nodoc />
File,
/// <nodoc />
Path,
/// <nodoc />
RelativePath,
/// <nodoc />
UndefinedLiteral,
/// <nodoc />
UndefinedValue,
}
/// <summary>
/// Helper responsible for serializing/deserializing const expressions.
/// </summary>
public static class ConstExpressionSerializer
{
/// <nodoc />
public static object Read(DeserializationContext context)
{
var reader = context.Reader;
bool isNode = reader.ReadBoolean();
if (isNode)
{
return (IConstantExpression)Node.Read(context);
}
return ReadConstValue(reader);
}
/// <nodoc />
public static object ReadConstValue(BuildXLReader reader)
{
var kind = (ConstExpressionKind)reader.ReadByte();
switch (kind)
{
case ConstExpressionKind.Number:
return reader.ReadInt32Compact();
case ConstExpressionKind.Boolean:
return reader.ReadBoolean();
case ConstExpressionKind.EnumValue:
return new EnumValue(reader.ReadSymbolAtom(), reader.ReadInt32Compact());
case ConstExpressionKind.String:
return reader.ReadString();
case ConstExpressionKind.File:
return reader.ReadFileArtifact();
case ConstExpressionKind.Path:
return reader.ReadAbsolutePath();
case ConstExpressionKind.RelativePath:
return reader.ReadRelativePath();
case ConstExpressionKind.UndefinedLiteral:
return UndefinedLiteral.Instance;
case ConstExpressionKind.UndefinedValue:
return UndefinedValue.Instance;
}
throw new InvalidOperationException(I($"Unknown const expression kind '{kind}'."));
}
/// <summary>
/// Reads the value as <see cref="EvaluationResult"/>.
/// </summary>
public static EvaluationResult ReadConstValueAsEvaluationResult(BuildXLReader reader)
{
var kind = (ConstExpressionKind)reader.ReadByte();
switch (kind)
{
case ConstExpressionKind.Number:
return EvaluationResult.Create(reader.ReadInt32Compact());
case ConstExpressionKind.Boolean:
return EvaluationResult.Create(reader.ReadBoolean());
case ConstExpressionKind.EnumValue:
return EvaluationResult.Create(new EnumValue(reader.ReadSymbolAtom(), reader.ReadInt32Compact()));
case ConstExpressionKind.String:
return EvaluationResult.Create(reader.ReadString());
case ConstExpressionKind.File:
return EvaluationResult.Create(reader.ReadFileArtifact());
case ConstExpressionKind.Path:
return EvaluationResult.Create(reader.ReadAbsolutePath());
case ConstExpressionKind.RelativePath:
return EvaluationResult.Create(reader.ReadRelativePath());
case ConstExpressionKind.UndefinedLiteral:
case ConstExpressionKind.UndefinedValue:
return EvaluationResult.Undefined;
}
throw new InvalidOperationException(I($"Unknown const expression kind '{kind}'."));
}
/// <nodoc />
public static void Write(BuildXLWriter writer, IConstantExpression constExpression)
{
if (constExpression is Node node)
{
writer.Write(true);
node.Serialize(writer);
}
else
{
writer.Write(false);
WriteConstValue(writer, constExpression.Value);
}
}
/// <nodoc />
public static void WriteConstValue(BuildXLWriter writer, object value)
{
switch (value)
{
case int intValue:
writer.Write((byte)ConstExpressionKind.Number);
writer.WriteCompact(intValue);
return;
case bool boolValue:
writer.Write((byte)ConstExpressionKind.Boolean);
writer.Write(boolValue);
return;
case AbsolutePath absolutePath:
writer.Write((byte)ConstExpressionKind.Path);
writer.Write(absolutePath);
return;
case RelativePath relativePath:
writer.Write((byte)ConstExpressionKind.RelativePath);
writer.Write(relativePath);
return;
case FileArtifact fileValue:
writer.Write((byte)ConstExpressionKind.File);
writer.Write(fileValue);
return;
case EnumValue enumValue:
writer.Write((byte)ConstExpressionKind.EnumValue);
writer.Write(enumValue.Name);
writer.WriteCompact(enumValue.Value);
return;
case string stringValue:
writer.Write((byte)ConstExpressionKind.String);
writer.Write(stringValue);
return;
case object o when
value == UndefinedLiteral.Instance ||
value == UndefinedValue.Instance:
writer.Write((byte)ConstExpressionKind.UndefinedLiteral);
return;
default:
throw Contract.AssertFailure(I($"Can't serialize an object literal with member value of type '{value.GetType()}'."));
}
}
}
}
| 36.024752 | 138 | 0.528102 | [
"MIT"
] | BearerPipelineTest/BuildXL | Public/Src/FrontEnd/Script/Ast/Literals/IConstantExpression.cs | 7,277 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _03_Forum_Topics
{
class Program
{
static void Main(string[] args)
{
var solution = new Dictionary<string, HashSet<string>>();
string inputTopicsAndTags = Console.ReadLine();
while (inputTopicsAndTags != "filter")
{
string[] topicsAndTags = inputTopicsAndTags.Split(new char[] { ' ', ',', '-', '>' },
StringSplitOptions.RemoveEmptyEntries)
.ToArray();
string initialTopic = topicsAndTags[0];
if (!solution.ContainsKey(initialTopic))
{
solution[initialTopic] = new HashSet<string>();
}
for (int cycle = 1; cycle < topicsAndTags.Length; cycle++)
{
solution[initialTopic].Add(topicsAndTags[cycle]);
}
inputTopicsAndTags = Console.ReadLine();
}
string[] filterByWords = Console.ReadLine().Split(new char[] { ' ', ',' },
StringSplitOptions.RemoveEmptyEntries)
.ToArray();
bool trulyContains = false;
int count = 0;
foreach (var kvp in solution)
{
count = 0;
for (int cycle2 = 0; cycle2 < filterByWords.Length; cycle2++)
{
for (int cycle3 = 0; cycle3 < kvp.Value.Count; cycle3++)
{
if (kvp.Value.Contains(filterByWords[cycle2]))
{
trulyContains = true;
count++;
break;
}
else
{
trulyContains = false;
break;
}
}
if (!trulyContains)
{
break;
}
}
if (trulyContains && count == filterByWords.Length)
{
Console.WriteLine($"{kvp.Key} | #{string.Join(", #", kvp.Value)}");
}
}
//2nd method to print out the answer:
//foreach (var kvp in solution)
//{
// bool contains = true;
// foreach (var filter in filterByWords)
// {
// if (kvp.Value.Contains(filter))
// {
// contains = false;
// }
// }
// if (contains)
// {
// Console.WriteLine($"{kvp.Key} | #{string.Join(", #", kvp.Value)}");
// }
//}
}
}
} | 32.271739 | 100 | 0.397777 | [
"MIT"
] | Bullsized/Assignments-Fundamentals | 11 Advanced Collections/2017-05-04/03 Forum Topics/03 Forum Topics.cs | 2,971 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Evereal.VRVideoPlayer;
public class RotateBar : BarBase, IRunnable
{
private IAppInfo appInfo;
public GameObject target;
// Start is called before the first frame update
void Start()
{
appInfo = transform.parent.parent.parent.GetComponentInParent<IAppInfo>();
//Debug.Log(appInfo);
}
// Update is called once per frame
void Update()
{
}
public void Run(Vector3 currentPoint)
{
float currentWidth = Vector3.Distance(startPoint.position, currentPoint);
float progress = Mathf.Clamp(currentWidth / progressBarWidth, 0f, 1f);
float ydegree = 360.0f * progress;
Debug.Log(ydegree);
target.transform.localEulerAngles = new Vector3(target.transform.localEulerAngles.x, ydegree, target.transform.localEulerAngles.z);
SetProgress(progress);
}
}
| 25.131579 | 139 | 0.682723 | [
"Apache-2.0"
] | tcdanielh/TutoriVR | Assets/TutoriVR/Scripts/RotateBar.cs | 957 | C# |
using System;
using System.Linq;
using System.Text.RegularExpressions;
using Telegram.Bot.Framework.Abstractions;
using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums;
namespace Telegram.Bot.Framework
{
public static class BotExtensions
{
public static bool CanHandleCommand(this IBot bot, string commandName, Message message)
{
if (string.IsNullOrWhiteSpace(commandName))
throw new ArgumentException("Invalid command name", nameof(commandName));
if (message == null)
throw new ArgumentNullException(nameof(message));
if (commandName.StartsWith("/"))
throw new ArgumentException("Command name must not start with '/'.", nameof(commandName));
{
bool isTextMessage = message.Text != null;
if (!isTextMessage)
return false;
}
{
bool isCommand = message.Entities?.FirstOrDefault()?.Type == MessageEntityType.BotCommand;
if (!isCommand)
return false;
}
return Regex.IsMatch(
message.EntityValues.First(),
$@"^/{commandName}(?:@{bot.Username})?$",
RegexOptions.IgnoreCase
);
}
}
} | 33.175 | 106 | 0.571967 | [
"MIT"
] | RomanOdynets/telbot | src/Telegram.Bot.Framework/Extensions/BotExtensions.cs | 1,329 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.LanguageServices;
namespace Microsoft.CodeAnalysis.NewLines.ConsecutiveStatementPlacement
{
internal abstract class AbstractConsecutiveStatementPlacementDiagnosticAnalyzer<TExecutableStatementSyntax>
: AbstractBuiltInCodeStyleDiagnosticAnalyzer
where TExecutableStatementSyntax : SyntaxNode
{
private readonly ISyntaxFacts _syntaxFacts;
protected AbstractConsecutiveStatementPlacementDiagnosticAnalyzer(ISyntaxFacts syntaxFacts)
: base(IDEDiagnosticIds.ConsecutiveStatementPlacementDiagnosticId,
EnforceOnBuildValues.ConsecutiveStatementPlacement,
CodeStyleOptions2.AllowStatementImmediatelyAfterBlock,
LanguageNames.CSharp,
new LocalizableResourceString(
nameof(AnalyzersResources.Blank_line_required_between_block_and_subsequent_statement), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)))
{
_syntaxFacts = syntaxFacts;
}
protected abstract bool IsBlockLikeStatement(SyntaxNode node);
protected abstract Location GetDiagnosticLocation(SyntaxNode block);
public sealed override DiagnosticAnalyzerCategory GetAnalyzerCategory()
=> DiagnosticAnalyzerCategory.SyntaxTreeWithoutSemanticsAnalysis;
protected sealed override void InitializeWorker(AnalysisContext context)
=> context.RegisterSyntaxTreeAction(AnalyzeSyntaxTree);
private void AnalyzeSyntaxTree(SyntaxTreeAnalysisContext context)
{
var cancellationToken = context.CancellationToken;
var tree = context.Tree;
var option = context.GetOption(CodeStyleOptions2.AllowStatementImmediatelyAfterBlock, tree.Options.Language);
if (option.Value)
return;
Recurse(context, option.Notification.Severity, tree.GetRoot(cancellationToken), cancellationToken);
}
private void Recurse(SyntaxTreeAnalysisContext context, ReportDiagnostic severity, SyntaxNode node, CancellationToken cancellationToken)
{
if (node.ContainsDiagnostics && node.GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error))
return;
if (IsBlockLikeStatement(node))
ProcessBlockLikeStatement(context, severity, node);
foreach (var child in node.ChildNodesAndTokens())
{
if (child.IsNode)
Recurse(context, severity, child.AsNode()!, cancellationToken);
}
}
private void ProcessBlockLikeStatement(SyntaxTreeAnalysisContext context, ReportDiagnostic severity, SyntaxNode block)
{
// Don't examine broken blocks.
var endToken = block.GetLastToken();
if (endToken.IsMissing)
return;
// If the close brace itself doesn't have a newline, then ignore this. This is a case of series of
// statements on the same line.
if (!endToken.TrailingTrivia.Any())
return;
if (!_syntaxFacts.IsEndOfLineTrivia(endToken.TrailingTrivia.Last()))
return;
// Grab whatever comes after the close brace. If it's not the start of a statement, ignore it.
var nextToken = endToken.GetNextToken();
var nextTokenContainingStatement = nextToken.Parent!.FirstAncestorOrSelf<TExecutableStatementSyntax>();
if (nextTokenContainingStatement == null)
return;
if (nextToken != nextTokenContainingStatement.GetFirstToken())
return;
// There has to be at least a blank line between the end of the block and the start of the next statement.
foreach (var trivia in nextToken.LeadingTrivia)
{
// If there's a blank line between the brace and the next token, we're all set.
if (_syntaxFacts.IsEndOfLineTrivia(trivia))
return;
if (_syntaxFacts.IsWhitespaceTrivia(trivia))
continue;
// got something that wasn't whitespace. Bail out as we don't want to place any restrictions on this code.
return;
}
context.ReportDiagnostic(DiagnosticHelper.Create(
this.Descriptor,
GetDiagnosticLocation(block),
severity,
additionalLocations: ImmutableArray.Create(nextToken.GetLocation()),
properties: null));
}
}
}
| 43.938596 | 174 | 0.665003 | [
"MIT"
] | Acidburn0zzz/roslyn | src/Analyzers/Core/Analyzers/NewLines/ConsecutiveStatementPlacement/AbstractConsecutiveStatementPlacementDiagnosticAnalyzer.cs | 5,011 | C# |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
#if HAVE_ASYNC
using System.Diagnostics;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
namespace Newtonsoft.Json.Utilities
{
internal static class AsyncUtils
{
// Pre-allocate to avoid wasted allocations.
public static readonly Task<bool> False = Task.FromResult(false);
public static readonly Task<bool> True = Task.FromResult(true);
internal static Task<bool> ToAsync(this bool value) => value ? True : False;
public static Task CancelIfRequestedAsync(this CancellationToken cancellationToken)
{
return cancellationToken.IsCancellationRequested ? FromCanceled(cancellationToken) : null;
}
public static Task<T> CancelIfRequestedAsync<T>(this CancellationToken cancellationToken)
{
return cancellationToken.IsCancellationRequested ? FromCanceled<T>(cancellationToken) : null;
}
// From 4.6 on we could use Task.FromCanceled(), but we need an equivalent for
// previous frameworks.
public static Task FromCanceled(this CancellationToken cancellationToken)
{
Debug.Assert(cancellationToken.IsCancellationRequested);
return new Task(() => {}, cancellationToken);
}
public static Task<T> FromCanceled<T>(this CancellationToken cancellationToken)
{
Debug.Assert(cancellationToken.IsCancellationRequested);
return new Task<T>(() => default, cancellationToken);
}
// Task.Delay(0) is optimised as a cached task within the framework, and indeed
// the same cached task that Task.CompletedTask returns as of 4.6, but we'll add
// our own cached field for previous frameworks.
internal static readonly Task CompletedTask = Task.Delay(0);
public static Task WriteAsync(this TextWriter writer, char value, CancellationToken cancellationToken)
{
Debug.Assert(writer != null);
return cancellationToken.IsCancellationRequested ? FromCanceled(cancellationToken) : writer.WriteAsync(value);
}
public static Task WriteAsync(this TextWriter writer, string value, CancellationToken cancellationToken)
{
Debug.Assert(writer != null);
return cancellationToken.IsCancellationRequested ? FromCanceled(cancellationToken) : writer.WriteAsync(value);
}
public static Task WriteAsync(this TextWriter writer, char[] value, int start, int count, CancellationToken cancellationToken)
{
Debug.Assert(writer != null);
return cancellationToken.IsCancellationRequested ? FromCanceled(cancellationToken) : writer.WriteAsync(value, start, count);
}
public static Task<int> ReadAsync(this TextReader reader, char[] buffer, int index, int count, CancellationToken cancellationToken)
{
Debug.Assert(reader != null);
return cancellationToken.IsCancellationRequested ? FromCanceled<int>(cancellationToken) : reader.ReadAsync(buffer, index, count);
}
public static bool IsCompletedSucessfully(this Task task)
{
// IsCompletedSucessfully is the faster method, but only currently exposed on .NET Core 2.0
#if NETCOREAPP2_0
return task.IsCompletedSucessfully;
#else
return task.Status == TaskStatus.RanToCompletion;
#endif
}
}
}
#endif
| 42.155963 | 141 | 0.703808 | [
"MIT"
] | AartBluestoke/Newtonsoft.Json | Src/Newtonsoft.Json/Utilities/AsyncUtils.cs | 4,597 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
namespace Microsoft.Azure.Common.Authentication
{
public enum ShowDialog
{
Auto,
Always,
Never
}
} | 24.416667 | 95 | 0.686007 | [
"MIT"
] | DiogenesPolanco/azure-sdk-for-net | src/Authentication/Common.Authentication/Authentication/ShowDialog.cs | 295 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace rentAcar
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Data.mdf;Integrated Security=True;Connect Timeout=30");
private void buttonLogin_Click(object sender, EventArgs e)
{
con.Open();
SqlDataAdapter sda = new SqlDataAdapter("Select Count(*) From useri where username='" + textBoxUserName.Text + "' and password = '" + textBoxPassword.Text + "'", con);
DataTable dt = new DataTable();
sda.Fill(dt);
if (dt.Rows[0][0].ToString() == "1")
{
this.Hide();
Home form = new Home();
form.Show();
}
else
{
MessageBox.Show("Datele de conectare nu sunt corecte");
}
con.Close();
}
private void buttonRegister_Click(object sender, EventArgs e)
{
if (textBoxUserName.Text == "" || textBoxPassword.Text == "")
{
MessageBox.Show("Introdu date!");
}
else
{
SqlDataAdapter sda = new SqlDataAdapter("Select Count(*) From useri where username='" + textBoxUserName.Text + "'", con);
DataTable dt = new DataTable();
sda.Fill(dt);
if (dt.Rows[0][0].ToString() == "1")
{
MessageBox.Show("Exista deja un cont cu acest nume");
}
else
{
SqlCommand cmd;
cmd = new SqlCommand("insert into useri(username,password) values(@us,@pw)", con);
con.Open();
cmd.Parameters.AddWithValue("@us", textBoxUserName.Text);
cmd.Parameters.AddWithValue("@pw", textBoxPassword.Text);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Cont creat!");
}
}
}
}
}
| 32.133333 | 179 | 0.519087 | [
"MIT"
] | ALINCOP/Car-rental-dashboard | rent-a-car/Form1.cs | 2,412 | C# |
namespace _3rd_party.Particle_Dissolve_Shader_by_Moonflower_Carnivore.Shaders.unity5.Editor
{
public class Shader_softrim_dissolve : CustomMaterialEditor
{
protected override void CreateToggleList()
{
Toggles.Add(new FeatureToggle("Soft Dissolve Enabled","soft_dissolve","SOFTDISSOLVE_ON","SOFTDISSOLVE_OFF"));
Toggles.Add(new FeatureToggle("Opacity Slider Enabled","opacity","OPACITYSLIDER_ON","OPACITYSLIDER_OFF"));
Toggles.Add(new FeatureToggle("Soft Rim Enabled","rim","SOFTRIM_ON","SOFTRIM_OFF"));
Toggles.Add(new FeatureToggle("For_Stretch_Billboard Enabled","stretch","STRETCH_ON","STRETCH_OFF"));
Toggles.Add(new FeatureToggle("Edge Enabled","edge","EDGE_ON","EDGE_OFF"));
}
}
} | 44.5625 | 112 | 0.776999 | [
"MIT"
] | dubu-0/Argon-Assault | Assets/3rd party/Particle Dissolve Shader by Moonflower Carnivore/Shaders/unity5/Editor/Shader_softrim_dissolve.cs | 715 | C# |
namespace Manga.WebApi.UseCases.V1.GetAccountDetails
{
using System.Collections.Generic;
using Manga.Application.Boundaries.GetAccountDetails;
using Manga.WebApi.ViewModels;
using Microsoft.AspNetCore.Mvc;
public sealed class GetAccountDetailsPresenter : IOutputPort
{
public IActionResult ViewModel { get; private set; }
public void Standard(GetAccountDetailsOutput getAccountDetailsOutput)
{
List<TransactionModel> transactions = new List<TransactionModel>();
foreach (var item in getAccountDetailsOutput.Transactions)
{
var transaction = new TransactionModel(
item.Amount,
item.Description,
item.TransactionDate);
transactions.Add(transaction);
}
var getAccountDetailsResponse = new GetAccountDetailsResponse(
getAccountDetailsOutput.AccountId,
getAccountDetailsOutput.CurrentBalance,
transactions);
ViewModel = new OkObjectResult(getAccountDetailsResponse);
}
public void NotFound(string message)
{
ViewModel = new NotFoundObjectResult(message);
}
}
}
| 31.775 | 79 | 0.631786 | [
"Apache-2.0"
] | markchan1209/clean-architecture-manga | source/Manga.WebApi/UseCases/V1/GetAccountDetails/GetAccountDetailsPresenter.cs | 1,271 | C# |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.ServiceModel.Description
{
using System.Runtime;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Dispatcher;
class CallbackTimeoutsBehavior : IEndpointBehavior
{
TimeSpan transactionTimeout = TimeSpan.Zero;
public TimeSpan TransactionTimeout
{
get { return this.transactionTimeout; }
set
{
if (value < TimeSpan.Zero)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value,
SR.GetString(SR.SFxTimeoutOutOfRange0)));
}
if (TimeoutHelper.IsTooLarge(value))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value,
SR.GetString(SR.SFxTimeoutOutOfRangeTooBig)));
}
this.transactionTimeout = value;
}
}
public CallbackTimeoutsBehavior()
{
}
void IEndpointBehavior.Validate(ServiceEndpoint serviceEndpoint)
{
}
void IEndpointBehavior.AddBindingParameters(ServiceEndpoint serviceEndpoint, BindingParameterCollection bindingParameters)
{
}
void IEndpointBehavior.ApplyDispatchBehavior(ServiceEndpoint serviceEndpoint, EndpointDispatcher endpointDispatcher)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(
SR.GetString(SR.SFXEndpointBehaviorUsedOnWrongSide, typeof(CallbackTimeoutsBehavior).Name)));
}
void IEndpointBehavior.ApplyClientBehavior(ServiceEndpoint serviceEndpoint, ClientRuntime behavior)
{
if (this.transactionTimeout != TimeSpan.Zero)
{
ChannelDispatcher channelDispatcher = behavior.CallbackDispatchRuntime.ChannelDispatcher;
if ((channelDispatcher != null) &&
(channelDispatcher.TransactionTimeout == TimeSpan.Zero) ||
(channelDispatcher.TransactionTimeout > this.transactionTimeout))
{
channelDispatcher.TransactionTimeout = this.transactionTimeout;
}
}
}
}
}
| 39.121212 | 130 | 0.597986 | [
"Apache-2.0"
] | 295007712/295007712.github.io | sourceCode/dotNet4.6/ndp/cdf/src/WCF/ServiceModel/System/ServiceModel/Description/CallbackTimeoutsBehavior.cs | 2,582 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.