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 (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
[assembly: Azure.Core.AzureResourceProviderNamespace("Microsoft.DigitalTwins")]
| 35.6 | 79 | 0.792135 | [
"MIT"
] | AWESOME-S-MINDSET/azure-sdk-for-net | sdk/digitaltwins/Azure.ResourceManager.DigitalTwins/tests/Properties/AssemblyInfo.cs | 180 | C# |
// Copyright (c) 2014 SIL International
// This software is licensed under the MIT License (http://opensource.org/licenses/MIT)
using System;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Windows.Forms;
using SIL.IO;
using SIL.Reporting;
using SIL.Windows.Forms.HtmlBrowser;
namespace SIL.Windows.Forms.GeckoBrowserAdapter
{
/// <summary>
/// This class is an adapter for GeckoFx' GeckoWebBrowser class. It is used by
/// Palaso.UI.WindowsForms.HtmlBrowser.XWebBrowser.
///
/// Clients should NOT use this class directly. Instead they should use the XWebBrowser
/// class (or Gecko.GeckoWebBrowser if they need GeckoFx functionality).
/// </summary>
/// <remarks> The assembly containing this class gets loaded dynamically so
/// that we don't have a dependency on GeckoFx unless we want to use it.</remarks>
class GeckoFxWebBrowserAdapter: IWebBrowser
{
private const string GeckoBrowserType = "Gecko.GeckoWebBrowser";
private const string XpcomType = "Gecko.Xpcom";
private readonly Control _webBrowser;
internal static Assembly GeckoCoreAssembly;
internal static Assembly GeckoWinAssembly;
public GeckoFxWebBrowserAdapter(Control parent)
{
LoadGeckoAssemblies();
SetUpXulRunner();
_webBrowser = InstantiateGeckoWebBrowser();
parent.Controls.Add(_webBrowser);
var callbacks = parent as IWebBrowserCallbacks;
AddEventHandler(_webBrowser, "CanGoBackChanged", (sender, e) => callbacks.OnCanGoBackChanged(e));
AddEventHandler(_webBrowser, "CanGoForwardChanged", (sender, e) => callbacks.OnCanGoForwardChanged(e));
AddEventHandler(_webBrowser, "DocumentTitleChanged", (sender, e) => callbacks.OnDocumentTitleChanged(e));
AddEventHandler(_webBrowser, "StatusTextChanged", (sender, e) => callbacks.OnStatusTextChanged(e));
AddGeckoDefinedEventHandler(_webBrowser, "DocumentCompleted", "DocumentCompletedHandler");
AddGeckoDefinedEventHandler(_webBrowser, "Navigated", "NavigatedHandler");
AddGeckoDefinedEventHandler(_webBrowser, "Navigating", "NavigatingHandler");
AddGeckoDefinedEventHandler(_webBrowser, "CreateWindow2", "CreateWindow2Handler");
AddGeckoDefinedEventHandler(_webBrowser, "ProgressChanged", "WebProgressHandler");
AddGeckoDefinedEventHandler(_webBrowser, "DomClick", "DomClickHandler");
}
private static int XulRunnerVersion
{
get
{
var geckofx = GeckoCoreAssembly;
if (geckofx == null)
return 0;
var versionAttribute = geckofx.GetCustomAttributes(typeof(AssemblyFileVersionAttribute), true)
.FirstOrDefault() as AssemblyFileVersionAttribute;
return versionAttribute == null ? 0 : new Version(versionAttribute.Version).Major;
}
}
private static void SetUpXulRunner()
{
if (IsXpcomInitialized())
return;
string xulRunnerPath = Environment.GetEnvironmentVariable("XULRUNNER");
if (!Directory.Exists(xulRunnerPath))
{
xulRunnerPath = Path.Combine(FileLocator.DirectoryOfApplicationOrSolution, "xulrunner");
if (!Directory.Exists(xulRunnerPath))
{
// Gecko 45
xulRunnerPath = Path.Combine(FileLocator.DirectoryOfApplicationOrSolution,
Path.Combine("Firefox"));
if (!Directory.Exists(xulRunnerPath))
{
//if this is a programmer, go look in the lib directory
xulRunnerPath = Path.Combine(FileLocator.DirectoryOfApplicationOrSolution,
Path.Combine("lib", "xulrunner"));
}
//on my build machine, I really like to have the dir labelled with the version.
//but it's a hassle to update all the other parts (installer, build machine) with this number,
//so we only use it if we don't find the unnumbered alternative.
if (!Directory.Exists(xulRunnerPath))
{
xulRunnerPath = Path.Combine(FileLocator.DirectoryOfApplicationOrSolution,
Path.Combine("lib", "xulrunner" + XulRunnerVersion));
}
if (!Directory.Exists(xulRunnerPath))
{
throw new ConfigurationException(
"Can't find the directory where xulrunner (version {0}) is installed",
XulRunnerVersion);
}
}
}
InitializeXpcom(xulRunnerPath);
Application.ApplicationExit += OnApplicationExit;
}
#region Reflective methods for handling Gecko in a version agnostic way
private Uri GetGeckoNavigatedEventArgsUri(object eventArg)
{
var eventType = GeckoWinAssembly.GetType("Gecko.GeckoNavigatedEventArgs");
return GetUriValue(eventArg, eventType);
}
private Uri GetGeckoNavigatingEventArgsUri(object eventArg)
{
var eventType = GeckoCoreAssembly.GetType("Gecko.Events.GeckoNavigatingEventArgs") ??
GeckoWinAssembly.GetType("Gecko.GeckoNavigatingEventArgs"); //Try new ns then old ns
return GetUriValue(eventArg, eventType);
}
private static Uri GetUriValue(object eventArg, Type eventType)
{
var uriField = eventType.GetField("Uri");
return uriField.GetValue(eventArg) as Uri;
}
private void SetCancelEventArgsCancel(EventArgs eventArg, bool cancelValue)
{
var cancelArgs = eventArg as CancelEventArgs;
if(cancelArgs != null)
{
cancelArgs.Cancel = cancelValue;
}
}
private Uri GetBrowserUrl(object webBrowser)
{
return GetBrowserProperty<Uri>(webBrowser, "Url");
}
/// <summary>
/// This method will reflectively add a locally defined handler to an event of the
/// GeckoWebBrowser. If the type of the EventHandler or EventArg is defined in gecko
/// then the <code>AddGeckoDefinedEventhandler</code> must be used.
/// </summary>
private void AddEventHandler(Control webBrowser, string eventName, EventHandler action)
{
var webBrowserType = GeckoWinAssembly.GetType(GeckoBrowserType);
var browserEvent = webBrowserType.GetEvent(eventName);
browserEvent.AddEventHandler(webBrowser, action);
}
/// <summary>
/// This method will reflectively add a locally defined handler to an event defined in the GeckoWebBrowser.
/// This method will look up all the event types reflectively and can be used even when the EventArgs or
/// EventHandler types are defined in the gecko assembly.
/// </summary>
private void AddGeckoDefinedEventHandler(Control webBrowser, string eventName, string handlerName)
{
var webBrowserType = GeckoWinAssembly.GetType(GeckoBrowserType);
var browserEvent = webBrowserType.GetEvent(eventName);
var eventArgsType = browserEvent.EventHandlerType;
var methodInfo = GetType().GetMethod(handlerName, BindingFlags.NonPublic | BindingFlags.Instance);
var docCompletedDelegate = Delegate.CreateDelegate(eventArgsType, this, methodInfo);
var addEventMethod = browserEvent.GetAddMethod();
addEventMethod.Invoke(webBrowser, new object[] { docCompletedDelegate });
}
// ReSharper disable UnusedMember.Local
// these Handlers are all used by reflection
private void WebProgressHandler(object sender, EventArgs e)
{
var geckoProgressArgsType = GeckoWinAssembly.GetType("Gecko.GeckoProgressEventArgs");
var currentProgressProp = geckoProgressArgsType.GetField("CurrentProgress");
var currentProgressVal = currentProgressProp.GetValue(e);
var maxProgressProp = geckoProgressArgsType.GetField("MaximumProgress");
var maxProgressVal = maxProgressProp.GetValue(e);
var callbacks = _webBrowser.Parent as IWebBrowserCallbacks;
callbacks.OnProgressChanged(new WebBrowserProgressChangedEventArgs((long)currentProgressVal, (long)maxProgressVal));
}
private void NavigatedHandler(object sender, EventArgs args)
{
var callbacks = _webBrowser.Parent as IWebBrowserCallbacks;
callbacks.OnNavigated(new WebBrowserNavigatedEventArgs(GetGeckoNavigatedEventArgsUri(args)));
}
private void DocumentCompletedHandler(object sender, EventArgs args)
{
var callbacks = _webBrowser.Parent as IWebBrowserCallbacks;
callbacks.OnDocumentCompleted(new WebBrowserDocumentCompletedEventArgs(GetBrowserUrl(_webBrowser)));
}
private void NavigatingHandler(object sender, EventArgs args)
{
var callbacks = _webBrowser.Parent as IWebBrowserCallbacks;
var ev = new WebBrowserNavigatingEventArgs(GetGeckoNavigatingEventArgsUri(args), string.Empty);
callbacks.OnNavigating(ev);
SetCancelEventArgsCancel(args, ev.Cancel);
}
private void CreateWindow2Handler(object sender, EventArgs args)
{
var callbacks = _webBrowser.Parent as IWebBrowserCallbacks;
var ev = new CancelEventArgs();
callbacks.OnNewWindow(ev);
SetCancelEventArgsCancel(args, ev.Cancel);
}
// ReSharper restore UnusedMember.Local
/// <summary>
/// Reflectively construct a GeckoWebBrowser and set the Dock property.
/// </summary>
/// <returns>a reflectively created GeckoWebBrowser as a Control</returns>
private Control InstantiateGeckoWebBrowser()
{
var browserType = GeckoWinAssembly.GetType(GeckoBrowserType);
var constructor = browserType.GetConstructor(new Type[] { });
var dockProp = browserType.GetProperty("Dock");
var geckoWebBrowser = constructor.Invoke(new object[] { });
dockProp.SetValue(geckoWebBrowser, DockStyle.Fill, BindingFlags.Default, null, null, null);
return geckoWebBrowser as Control;
}
/// <summary>
/// Attempt to load GeckoAssemblies from the programs running environment. Try and load modern gecko dlls which have
/// no version number in the filenames then fallback to trying to load geckofx 14.
/// </summary>
private static void LoadGeckoAssemblies()
{
if (GeckoCoreAssembly != null && GeckoWinAssembly != null)
return;
try
{
try
{
GeckoCoreAssembly = Assembly.Load("Geckofx-Core");
}
catch(FileNotFoundException)
{
//Fallback to geckofx version 14 name
GeckoCoreAssembly = Assembly.LoadFrom("geckofx-core-14.dll");
}
try
{
GeckoWinAssembly = Assembly.Load("Geckofx-Winforms");
}
catch(FileNotFoundException)
{
//Fallback to geckofx version 14 name
GeckoWinAssembly = Assembly.LoadFrom("Geckofx-Winforms-14.dll");
}
}
catch(Exception e)
{
MessageBox.Show("Unable to load geckofx dependancy. Files may not have been included in the build.",
"Failed to load geckofx", MessageBoxButtons.OK, MessageBoxIcon.Error);
throw new ApplicationException("Unable to load geckofx dependancy", e);
}
}
private T GetBrowserProperty<T>(object webBrowser, string propertyName)
{
var webBrowserType = GeckoWinAssembly.GetType(GeckoBrowserType);
var property = webBrowserType.GetProperty(propertyName, typeof(T));
return (T)property.GetValue(webBrowser, BindingFlags.Default, null, null, null);
}
private void SetBrowserProperty<T>(object webBrowser, string propertyName, T propertyValue)
{
var webBrowserType = GeckoWinAssembly.GetType(GeckoBrowserType);
var property = webBrowserType.GetProperty(propertyName, typeof(T));
property.SetValue(webBrowser, propertyValue, BindingFlags.Default, null, null, null);
}
/// <summary>
/// Call a browser method which returns a specific type.
/// Looks up the method name by reflection and calls that method
/// on the given webbrowser instance and return the value.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="webBrowser"></param>
/// <param name="methodName"></param>
/// <returns></returns>
private T CallBrowserMethod<T>(object webBrowser, string methodName)
{
var webBrowserType = GeckoWinAssembly.GetType(GeckoBrowserType);
var method = webBrowserType.GetMethod(methodName);
return (T)method.Invoke(webBrowser, BindingFlags.Default, null, null, null);
}
private static bool IsXpcomInitialized()
{
var xpcomType = GeckoCoreAssembly.GetType(XpcomType);
var initProp = xpcomType.GetProperty("IsInitialized");
var initialized = initProp.GetValue(null, BindingFlags.Static, null, null, null);
return (bool)initialized;
}
private static void InitializeXpcom(string xulRunnerPath)
{
var xpcomType = GeckoCoreAssembly.GetType(XpcomType);
var initMethod = xpcomType.GetMethod("Initialize", new [] { typeof(string) });
initMethod.Invoke(null, new object[] {xulRunnerPath});
}
private static void ShutdownXpcom()
{
var xpcomType = GeckoCoreAssembly.GetType(XpcomType);
var initMethod = xpcomType.GetMethod("Shutdown");
initMethod.Invoke(null, null);
}
/// <summary>
/// Look up a method name from the browser that matches the method name and
/// the type of the parameters given and then call that on the given webbrowser
/// instance.
/// </summary>
/// <param name="webBrowser"></param>
/// <param name="methodName"></param>
/// <param name="parameters"></param>
private bool CallBrowserMethod(object webBrowser, string methodName, object[] parameters)
{
var webBrowserType = GeckoWinAssembly.GetType(GeckoBrowserType);
var types = new Type[parameters.Length];
for(var i = 0; i < parameters.Length; ++i)
{
types[i] = parameters[i].GetType();
}
var method = webBrowserType.GetMethod(methodName, types);
if(method == null)
{
return false;
}
method.Invoke(webBrowser, parameters);
return true;
}
#endregion
private static void OnApplicationExit(object sender, EventArgs e)
{
// We come here iff we initialized Xpcom. In that case we want to call shutdown,
// otherwise the app might not exit properly.
if (IsXpcomInitialized())
ShutdownXpcom();
Application.ApplicationExit -= OnApplicationExit;
}
private void DomClickHandler(object sender, EventArgs e)
{
var callbacks = _webBrowser.Parent as IWebBrowserCallbacks;
callbacks.OnDomClick(e);
}
internal void SetClass(object target, string val)
{
if (target == null)
return;
// target.SetAttribute("class", "selected")
var elementType = GeckoCoreAssembly.GetType("Gecko.GeckoHtmlElement");
var setAttrMethod = elementType.GetMethod("SetAttribute");
setAttrMethod.Invoke(target, new object[] {"class", val});
}
#region IWebBrowser Members
/// <summary>
/// Rather then adding more reflective methods just handle this property here at the adapter level.
/// </summary>
public bool AllowNavigation { get; set; }
/// <summary>
/// TODO: If this is necessary for the GeckoBrowser we need to figure out an implementation
/// </summary>
public bool AllowWebBrowserDrop { get; set; }
public bool CanGoBack
{
get { return AllowNavigation && GetBrowserProperty<bool>(_webBrowser, "CanGoBack"); }
}
public bool CanGoForward
{
get { return AllowNavigation && GetBrowserProperty<bool>(_webBrowser, "CanGoForward"); }
}
public string DocumentText
{
set
{
// we used to use LoadContent and fall back to LoadHtml if that method didn't
// work. However, I (EB) couldn't get LoadContent to work, so we now always use
// LoadHtml which should work in most cases unless it is a complex HTML page.
CallBrowserMethod(_webBrowser, "LoadHtml", new object[] { value });
}
}
public string DocumentTitle
{
get { return GetBrowserProperty<string>(_webBrowser, "DocumentTitle"); }
}
public bool Focused
{
get { return _webBrowser.Focused; }
}
public bool IsBusy
{
get { return GetBrowserProperty<bool>(_webBrowser, "IsBusy"); }
}
public bool IsWebBrowserContextMenuEnabled
{
get { return !GetBrowserProperty<bool>(_webBrowser, "NoDefaultContextMenu"); }
set { SetBrowserProperty(_webBrowser, "NoDefaultContextMenu", !value); }
}
public string StatusText
{
get { return GetBrowserProperty<string>(_webBrowser, "StatusText"); }
}
public Uri Url
{
get { return GetBrowserUrl(_webBrowser); }
set { CallBrowserMethod(_webBrowser, "Navigate", new object[] { value.OriginalString }); }
}
public bool GoBack()
{
if(AllowNavigation)
return CallBrowserMethod<bool>(_webBrowser, "GoBack");
return false;
}
public bool GoForward()
{
if(AllowNavigation)
return CallBrowserMethod<bool>(_webBrowser, "GoForward");
return false;
}
public void Navigate(string urlString)
{
CallBrowserMethod(_webBrowser, "Navigate", new object[] { urlString });
}
public void Navigate(Uri url)
{
Navigate(url.AbsoluteUri);
}
public void Refresh()
{
_webBrowser.Refresh();
}
public void Refresh(WebBrowserRefreshOption opt)
{
_webBrowser.Refresh();
}
public void Stop()
{
CallBrowserMethod(_webBrowser, "Stop", new object[] {});
}
public void ScrollLastElementIntoView()
{
var geckoDocumentType = GeckoCoreAssembly.GetType("Gecko.GeckoDocument");
var geckoHtmlElementType = GeckoCoreAssembly.GetType("Gecko.GeckoHtmlElement");
var geckoNodeListType = GeckoCoreAssembly.GetType("Gecko.GeckoNodeCollection");
var webBrowserType = GeckoWinAssembly.GetType(GeckoBrowserType);
var documentProperty = webBrowserType.GetProperty("Document", geckoDocumentType);
var document = documentProperty.GetValue(_webBrowser, BindingFlags.Default, null, null, null);
if(document != null)
{
var bodyProperty = geckoDocumentType.GetProperty("Body", geckoHtmlElementType);
var body = bodyProperty.GetValue(document, BindingFlags.Default, null, null, null);
if(body != null)
{
var childrenProperty = geckoHtmlElementType.GetProperty("ChildNodes", geckoNodeListType);
var children = childrenProperty.GetValue(body, BindingFlags.Default, null, null, null);
var countLengthProp = geckoNodeListType.GetProperty("Length", typeof(int));
var countLength = (int)countLengthProp.GetValue(children, BindingFlags.Default, null, null, null);
if(countLength > 0)
{
var lastChildProp = geckoNodeListType.GetProperty("Item"); //Magic
var lastchild = lastChildProp.GetValue(children, new object[] { countLength - 1 });
var scrollIntoView = geckoHtmlElementType.GetMethod("ScrollIntoView");
scrollIntoView.Invoke(lastchild, BindingFlags.Default, null, null, null);
}
}
}
}
public object NativeBrowser
{
get { return _webBrowser; }
}
/// <summary>
/// TODO: If Gecko browsers have keyboard shortcuts, write some code to enable/disable them here.
/// </summary>
public bool WebBrowserShortcutsEnabled { get; set; }
#endregion
}
}
| 35.316505 | 119 | 0.733066 | [
"MIT"
] | andrew-polk/libpalaso | SIL.Windows.Forms.GeckoBrowserAdapter/GeckoFxWebBrowserAdapter.cs | 18,190 | C# |
using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Storage;
using Microsoft.Xna.Framework.Content;
using IRTaktiks.Components.Playable;
using IRTaktiks.Components.Scenario;
using IRTaktiks.Components.Action;
using System.Collections.Generic;
using IRTaktiks.Components.Logic;
namespace IRTaktiks.Components.Manager
{
/// <summary>
/// Manager of items.
/// </summary>
public class ItemManager
{
#region Singleton
/// <summary>
/// The instance of the class.
/// </summary>
private static ItemManager InstanceField;
/// <summary>
/// The instance of the class.
/// </summary>
public static ItemManager Instance
{
get { if (InstanceField == null) InstanceField = new ItemManager(); return InstanceField; }
}
/// <summary>
/// Private constructor.
/// </summary>
private ItemManager()
{
this.Random = new Random();
}
#endregion
#region Properties
/// <summary>
/// Random number generator.
/// </summary>
private Random Random;
#endregion
#region Construct
/// <summary>
/// Construct the list of the items based on attributes.
/// </summary>
/// <param name="unit">The unit that the items will be constructed.</param>
/// <returns>The list of items.</returns>
public List<Item> Construct(Unit unit)
{
List<Item> items = new List<Item>();
#region Same items in all Jobs
/*
switch (unit.Attributes.Job)
{
case Job.Assasin:
{
return attacks;
}
case Job.Knight:
{
return attacks;
}
case Job.Monk:
{
return attacks;
}
case Job.Paladin:
{
return attacks;
}
case Job.Priest:
{
return attacks;
}
case Job.Wizard:
{
return attacks;
}
default:
{
return attacks;
}
}
*/
#endregion
items.Add(new Item(unit, "Potion", 10, Item.ItemType.Target, Potion));
items.Add(new Item(unit, "Ether", 5, Item.ItemType.Target, Ether));
items.Add(new Item(unit, "Elixir", 1, Item.ItemType.Self, Elixir));
return items;
}
#endregion
#region Item
/// <summary>
/// Restores 500 life points.
/// </summary>
/// <param name="command">Item used.</param>
/// <param name="caster">The caster of the item.</param>
/// <param name="target">The target of the item.</param>
/// <param name="position">The position of the target.</param>
private void Potion(Command command, Unit caster, Unit target, Vector2 position)
{
// Obtain the game instance.
IRTGame game = caster.Game as IRTGame;
// Show the animation.
Vector2 animationPosition = target == null ? position : new Vector2(target.Position.X + target.Texture.Width / 2, target.Position.Y + target.Texture.Height / 8);
AnimationManager.Instance.QueueAnimation(AnimationManager.AnimationType.Item, animationPosition);
// Effects on caster.
caster.Time = 0;
// Effects on target.
if (target != null)
{
target.Life += 500;
// Show the damage.
game.DamageManager.Queue(new Damage(500, null, target.Position, Damage.DamageType.Benefit));
}
}
/// <summary>
/// Restore 350 mana points.
/// </summary>
/// <param name="command">Item used.</param>
/// <param name="caster">The caster of the item.</param>
/// <param name="target">The target of the item.</param>
/// <param name="position">The position of the target.</param>
private void Ether(Command command, Unit caster, Unit target, Vector2 position)
{
// Obtain the game instance.
IRTGame game = caster.Game as IRTGame;
// Show the animation.
Vector2 animationPosition = target == null ? position : new Vector2(target.Position.X + target.Texture.Width / 2, target.Position.Y + target.Texture.Height / 8);
AnimationManager.Instance.QueueAnimation(AnimationManager.AnimationType.Item, animationPosition);
// Effects on caster.
caster.Time = 0;
// Effects on target.
if (target != null)
{
target.Mana += 350;
// Show the damage.
game.DamageManager.Queue(new Damage(350, "MP", target.Position, Damage.DamageType.Benefit));
}
}
/// <summary>
/// Restore all life points and mana poins.
/// </summary>
/// <param name="command">Item used.</param>
/// <param name="caster">The caster of the item.</param>
/// <param name="target">The target of the item.</param>
/// <param name="position">The position of the target.</param>
private void Elixir(Command command, Unit caster, Unit target, Vector2 position)
{
// Obtain the game instance.
IRTGame game = caster.Game as IRTGame;
// Show the animation.
Vector2 animationPosition = target == null ? position : new Vector2(target.Position.X + target.Texture.Width / 2, target.Position.Y + target.Texture.Height / 8);
AnimationManager.Instance.QueueAnimation(AnimationManager.AnimationType.Elixir, animationPosition);
// Effects on caster.
caster.Time = 0;
// Effects on target.
if (target != null)
{
target.Life = target.Attributes.MaximumLife;
target.Mana = target.Attributes.MaximumMana;
// Show the damage.
game.DamageManager.Queue(new Damage("WOHOO", target.Position, Damage.DamageType.Benefit));
}
}
#endregion
}
} | 33.247619 | 174 | 0.513893 | [
"MIT"
] | schalleneider/irtaktiks | src/IRTaktiks/IRTaktiks/Components/Manager/ItemManager.cs | 6,982 | C# |
#pragma warning disable 108 // new keyword hiding
#pragma warning disable 114 // new keyword hiding
namespace Windows.Devices.Bluetooth
{
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
[global::Uno.NotImplemented]
#endif
public enum BluetoothMinorClass
{
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
Uncategorized,
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
ComputerDesktop,
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
ComputerServer,
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
ComputerLaptop,
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
ComputerHandheld,
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
ComputerPalmSize,
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
ComputerWearable,
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
ComputerTablet,
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
PhoneCellular,
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
PhoneCordless,
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
PhoneSmartPhone,
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
PhoneWired,
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
PhoneIsdn,
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
NetworkFullyAvailable,
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
NetworkUsed01To17Percent,
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
NetworkUsed17To33Percent,
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
NetworkUsed33To50Percent,
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
NetworkUsed50To67Percent,
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
NetworkUsed67To83Percent,
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
NetworkUsed83To99Percent,
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
NetworkNoServiceAvailable,
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
AudioVideoWearableHeadset,
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
AudioVideoHandsFree,
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
AudioVideoMicrophone,
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
AudioVideoLoudspeaker,
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
AudioVideoHeadphones,
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
AudioVideoPortableAudio,
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
AudioVideoCarAudio,
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
AudioVideoSetTopBox,
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
AudioVideoHifiAudioDevice,
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
AudioVideoVcr,
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
AudioVideoVideoCamera,
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
AudioVideoCamcorder,
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
AudioVideoVideoMonitor,
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
AudioVideoVideoDisplayAndLoudspeaker,
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
AudioVideoVideoConferencing,
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
AudioVideoGamingOrToy,
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
PeripheralJoystick,
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
PeripheralGamepad,
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
PeripheralRemoteControl,
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
PeripheralSensing,
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
PeripheralDigitizerTablet,
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
PeripheralCardReader,
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
PeripheralDigitalPen,
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
PeripheralHandheldScanner,
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
PeripheralHandheldGesture,
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
WearableWristwatch,
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
WearablePager,
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
WearableJacket,
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
WearableHelmet,
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
WearableGlasses,
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
ToyRobot,
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
ToyVehicle,
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
ToyDoll,
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
ToyController,
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
ToyGame,
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
HealthBloodPressureMonitor,
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
HealthThermometer,
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
HealthWeighingScale,
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
HealthGlucoseMeter,
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
HealthPulseOximeter,
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
HealthHeartRateMonitor,
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
HealthHealthDataDisplay,
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
HealthStepCounter,
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
HealthBodyCompositionAnalyzer,
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
HealthPeakFlowMonitor,
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
HealthMedicationMonitor,
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
HealthKneeProsthesis,
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
HealthAnkleProsthesis,
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
HealthGenericHealthManager,
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
HealthPersonalMobilityDevice,
#endif
}
#endif
}
| 31.290749 | 62 | 0.696607 | [
"Apache-2.0"
] | AlexTrepanier/Uno | src/Uno.UWP/Generated/3.0.0.0/Windows.Devices.Bluetooth/BluetoothMinorClass.cs | 7,103 | C# |
using Cvl.ApplicationServer.Core.Model.Processes;
using Cvl.ApplicationServer.Core.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Cvl.ApplicationServer.Core.Services
{
public class ProcessActivityService : BaseService<ProcessActivity, ProcessActivityRepository>
{
public ProcessActivityService(ProcessActivityRepository repository)
: base(repository)
{ }
public IQueryable<ProcessActivity> GetProcessActivities(long procesId)
{
return Repository.GetAll().Where(x => x.ProcessInstanceId == procesId);
}
}
}
| 29.478261 | 97 | 0.734513 | [
"MIT"
] | cv-lang/application-server | Cvl.ApplicationServer/Cvl.ApplicationServer/Core/Services/ProcessActivityService.cs | 680 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System.Collections.Generic;
using System.Text.Json;
using Azure.Core;
namespace Azure.ResourceManager.Resources.Models
{
public partial class DeploymentScriptPropertiesBase : IUtf8JsonSerializable
{
void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
{
writer.WriteStartObject();
if (ContainerSettings != null)
{
writer.WritePropertyName("containerSettings");
writer.WriteObjectValue(ContainerSettings);
}
if (StorageAccountSettings != null)
{
writer.WritePropertyName("storageAccountSettings");
writer.WriteObjectValue(StorageAccountSettings);
}
if (CleanupPreference != null)
{
writer.WritePropertyName("cleanupPreference");
writer.WriteStringValue(CleanupPreference.Value.ToString());
}
if (ProvisioningState != null)
{
writer.WritePropertyName("provisioningState");
writer.WriteStringValue(ProvisioningState.Value.ToString());
}
if (Status != null)
{
writer.WritePropertyName("status");
writer.WriteObjectValue(Status);
}
if (Outputs != null)
{
writer.WritePropertyName("outputs");
writer.WriteStartObject();
foreach (var item in Outputs)
{
writer.WritePropertyName(item.Key);
writer.WriteObjectValue(item.Value);
}
writer.WriteEndObject();
}
writer.WriteEndObject();
}
internal static DeploymentScriptPropertiesBase DeserializeDeploymentScriptPropertiesBase(JsonElement element)
{
ContainerConfiguration containerSettings = default;
StorageAccountConfiguration storageAccountSettings = default;
CleanupOptions? cleanupPreference = default;
ScriptProvisioningState? provisioningState = default;
ScriptStatus status = default;
IDictionary<string, object> outputs = default;
foreach (var property in element.EnumerateObject())
{
if (property.NameEquals("containerSettings"))
{
if (property.Value.ValueKind == JsonValueKind.Null)
{
continue;
}
containerSettings = ContainerConfiguration.DeserializeContainerConfiguration(property.Value);
continue;
}
if (property.NameEquals("storageAccountSettings"))
{
if (property.Value.ValueKind == JsonValueKind.Null)
{
continue;
}
storageAccountSettings = StorageAccountConfiguration.DeserializeStorageAccountConfiguration(property.Value);
continue;
}
if (property.NameEquals("cleanupPreference"))
{
if (property.Value.ValueKind == JsonValueKind.Null)
{
continue;
}
cleanupPreference = new CleanupOptions(property.Value.GetString());
continue;
}
if (property.NameEquals("provisioningState"))
{
if (property.Value.ValueKind == JsonValueKind.Null)
{
continue;
}
provisioningState = new ScriptProvisioningState(property.Value.GetString());
continue;
}
if (property.NameEquals("status"))
{
if (property.Value.ValueKind == JsonValueKind.Null)
{
continue;
}
status = ScriptStatus.DeserializeScriptStatus(property.Value);
continue;
}
if (property.NameEquals("outputs"))
{
if (property.Value.ValueKind == JsonValueKind.Null)
{
continue;
}
Dictionary<string, object> dictionary = new Dictionary<string, object>();
foreach (var property0 in property.Value.EnumerateObject())
{
if (property0.Value.ValueKind == JsonValueKind.Null)
{
dictionary.Add(property0.Name, null);
}
else
{
dictionary.Add(property0.Name, property0.Value.GetObject());
}
}
outputs = dictionary;
continue;
}
}
return new DeploymentScriptPropertiesBase(containerSettings, storageAccountSettings, cleanupPreference, provisioningState, status, outputs);
}
}
}
| 39.093525 | 152 | 0.502392 | [
"MIT"
] | AzureDataBox/azure-sdk-for-net | sdk/resources/Azure.ResourceManager.Resources/src/Generated/Models/DeploymentScriptPropertiesBase.Serialization.cs | 5,434 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using Xunit;
#nullable disable
namespace Microsoft.VisualStudio.ProjectSystem.Logging
{
public class ProjectLoggingExtensionsTests
{
[Fact]
public void BeginBatch_NullAsLogger_ThrowsArgumentNull()
{
Assert.Throws<ArgumentNullException>("logger", () =>
{
ProjectLoggerExtensions.BeginBatch((IProjectLogger)null);
});
}
[Theory]
[InlineData(int.MinValue)]
[InlineData(-2)]
[InlineData(-1)]
public void BeginBatch_SetIndentLevelToLessThanZero_ThrowsArgumentOutOfRange(int indentLevel)
{
var logger = new ProjectLogger();
var batch = ProjectLoggerExtensions.BeginBatch(logger);
Assert.Throws<ArgumentOutOfRangeException>("value", () =>
{
batch.IndentLevel = indentLevel;
});
}
[Theory]
[InlineData(0, "")]
[InlineData(1, " ")]
[InlineData(2, " ")]
[InlineData(4, " ")]
public void BeginBatch_IndentLevel_AppendsIndentToWriteLine(int indentLevel, string expected)
{
var logger = new ProjectLogger();
using (var batch = ProjectLoggerExtensions.BeginBatch(logger))
{
batch.IndentLevel = indentLevel;
batch.WriteLine(string.Empty);
}
Assert.Equal(expected, logger.Text);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void BeginBatch_IsEnabled_ReturnsLoggerIsEnabled(bool isEnabled)
{
var logger = new ProjectLogger() { IsEnabled = isEnabled };
var batch = ProjectLoggerExtensions.BeginBatch(logger);
Assert.Equal(batch.IsEnabled, logger.IsEnabled);
}
[Fact]
public void BeginBatch_WhenUnderlyingLoggerIsNotEnabled_DoesNotLog()
{
var logger = new ProjectLogger() { IsEnabled = false };
using (var batch = ProjectLoggerExtensions.BeginBatch(logger))
{
batch.WriteLine("Hello World!");
}
Assert.Null(logger.Text);
}
[Fact]
public void BeginBatch_WhenUnderlyingLoggerIsEnabled_Logs()
{
var logger = new ProjectLogger() { IsEnabled = true };
using (var batch = ProjectLoggerExtensions.BeginBatch(logger))
{
batch.WriteLine("Hello World!");
}
Assert.Equal("Hello World!", logger.Text);
}
[Fact]
public void BeginBatch_CanLogMultipleWriteLines()
{
var logger = new ProjectLogger() { IsEnabled = true };
using (var batch = ProjectLoggerExtensions.BeginBatch(logger))
{
batch.WriteLine("Line1");
batch.IndentLevel = 1;
batch.WriteLine("Line2");
batch.IndentLevel = 0;
batch.WriteLine("Line3");
}
// NOTE: No trailing new line, as the logger itself should be adding it
Assert.Equal("Line1\r\n Line2\r\nLine3", logger.Text, ignoreLineEndingDifferences: true);
}
private class ProjectLogger : IProjectLogger
{
public ProjectLogger()
{
IsEnabled = true;
}
public bool IsEnabled
{
get;
set;
}
public string Text
{
get;
set;
}
public void WriteLine(in StringFormat format)
{
Text = format.Text;
}
}
}
}
| 28.446043 | 161 | 0.539454 | [
"Apache-2.0"
] | JeremyKuhne/project-system | src/Microsoft.VisualStudio.ProjectSystem.Managed.UnitTests/ProjectSystem/Logging/ProjectLoggingExtensionsTests.cs | 3,956 | C# |
using HarmonyLib;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection.Emit;
using System.Text;
using System.Threading.Tasks;
using Vintagestory.API;
using Vintagestory.API.Client;
using Vintagestory.API.Common;
using Vintagestory.API.Common.Entities;
using Vintagestory.API.Datastructures;
using Vintagestory.API.MathTools;
using Vintagestory.Client.NoObf;
using Vintagestory.Common;
using Vintagestory.GameContent;
using Vintagestory.GameContent.Mechanics;
using Vintagestory.ServerMods;
namespace VSHUD
{
[HarmonyPatch(typeof(CollectibleObject), "OnHeldIdle")]
public class SetPlacementPreviewItem
{
public static void Postfix(CollectibleObject __instance, ItemSlot slot, EntityAgent byEntity)
{
if (__instance.ItemClass == EnumItemClass.Item)
{
if (__instance is ItemStone)
{
var loc0 = __instance.CodeWithPath("loosestones-" + __instance.LastCodePart() + "-free");
var loc1 = __instance.CodeWithPath("loosestones-" + __instance.LastCodePart(1) + "-" + __instance.LastCodePart(0) + "-free");
var block = byEntity.World.GetBlock(loc0);
block = block ?? byEntity.World.GetBlock(loc1);
if (block != null) block.OnHeldIdle(new DummySlot(new ItemStack(block)), byEntity);
}
else SetBlockRedirect.blockId = 0;
}
}
}
[HarmonyPatch(typeof(Block), "OnHeldIdle")]
public class SetPlacementPreviewBlock
{
static HashSet<Type> KnownBroken = new HashSet<Type>();
public static void Postfix(Block __instance, ItemSlot slot, EntityAgent byEntity)
{
if (byEntity.World.Side.IsClient())
{
if (!(slot is DummySlot) && slot is ItemSlotOffhand) return;
if ((byEntity.World as ClientMain).ElapsedMilliseconds % 4 == 0)
{
var player = (byEntity as EntityPlayer).Player;
if (!KnownBroken.Contains(__instance.GetType()) && player?.CurrentBlockSelection != null && slot?.Itemstack != null)
{
SetBlockRedirect.setBlock = false;
var blockSel = player.CurrentBlockSelection;
Block onBlock = byEntity.World.BlockAccessor.GetBlock(blockSel.Position);
BlockPos buildPos = blockSel.Position;
if (onBlock == null || !onBlock.IsReplacableBy(__instance))
{
buildPos = buildPos.Offset(blockSel.Face);
blockSel.DidOffset = true;
}
string fail = "";
bool works = false;
try
{
works = __instance.TryPlaceBlock(byEntity.World, player, slot.Itemstack, blockSel, ref fail);
}
catch (Exception)
{
KnownBroken.Add(__instance.GetType());
}
if (blockSel.DidOffset)
{
buildPos.Offset(blockSel.Face.Opposite);
blockSel.DidOffset = false;
}
if (!works) SetBlockRedirect.blockId = 0;
SetBlockRedirect.setBlock = true;
}
else SetBlockRedirect.blockId = 0;
}
}
}
}
[HarmonyPatch(typeof(BlockAccessorBase), "SpawnBlockEntity")]
public class SpawnBlockEntityHalt
{
public static bool Prefix() => SetBlockRedirect.ShouldNotSkipOriginal;
}
[HarmonyPatch(typeof(BlockAccessorRelaxed), "ExchangeBlock")]
public class ExchangeBlockHalt
{
public static bool Prefix() => SetBlockRedirect.ShouldNotSkipOriginal;
}
[HarmonyPatch(typeof(BlockAccessorRelaxed), "SetBlock")]
public class SetBlockRedirect
{
public static bool ShouldNotSkipOriginal { get => setBlock || CheckAppSideAnywhere.Side == EnumAppSide.Server; }
public static bool setBlock = true;
public static int blockId;
public static int[] xyz = new int[3];
public static bool Prefix() => ShouldNotSkipOriginal;
public static void Postfix(ref int blockId, BlockPos pos)
{
if (ShouldNotSkipOriginal) return;
SetBlockRedirect.blockId = blockId;
xyz[0] = pos.X;
xyz[1] = pos.Y;
xyz[2] = pos.Z;
}
}
}
| 34.717391 | 145 | 0.558547 | [
"Unlicense"
] | Novocain1/MiscMods | VSHUD/Systems/Patches/ForPlacementPreview.cs | 4,793 | C# |
//*******************************************************
//
// Delphi DataSnap Framework
//
// Copyright(c) 1995-2011 Embarcadero Technologies, Inc.
//
//*******************************************************
namespace Embarcadero.Datasnap.WindowsPhone7
{
/**
*
* Wraps the Date type and allows it to be null
*
*/
public class TDBXDateValue : DBXValue {
protected bool ValueNull = false;
private int DBXDateValue;
/**
* Class constructor, initialized this {@link DBXDataTypes} like a DateType
*/
public TDBXDateValue() : base(){
setDBXType(DBXDataTypes.DateType);
}
/**
* Returns true if this object is null false otherwise.
*/
public override bool isNull()
{
return ValueNull;
}
/**
* Sets this object to null
*/
public override void setNull()
{
ValueNull = true;
DBXDateValue = 0;
}
/**
* Sets the internal value with the value passed
*/
public override void SetAsTDBXDate(int Value)
{
DBXDateValue = Value;
ValueNull = false;
}
/**
* Returns the internal value
*/
public override int GetAsTDBXDate()
{
return DBXDateValue;
}
}
}
| 20.9375 | 81 | 0.499254 | [
"Apache-2.0"
] | CarlosHe/fortesreport-ce | Demos/Datasnap/Server/proxy/csharp_silverlight/TDBXDateValue.cs | 1,340 | C# |
using Bogus;
using CursoOnline.Domain.Entidades;
using CursoOnline.Domain.Enums;
using CursoOnline.Tests.Builders;
using CursoOnline.Tests.Extensoes;
using ExpectedObjects;
using System;
using Xunit;
namespace CursoOnline.Tests.Cursos
{
public class CursoTests : IDisposable
{
private readonly string _nome;
private readonly string _descricao;
private readonly double _cargaHoraria;
private readonly EPublicoAlvo _publicoAlvo;
private readonly decimal _valor;
public CursoTests()//O construtor no xUnit difere do ctor de uma classe normal, pois o mesmo é executado novamente antes de cada metodo da classe de testes.
{//Esta parte é chamada de setup da classe de teste
var faker = new Faker();
_nome = faker.Random.Word();
_descricao = faker.Lorem.Paragraph();
_cargaHoraria = faker.Random.Double(50, 100);
_publicoAlvo = EPublicoAlvo.Estudante;
_valor = faker.Random.Decimal(100, 1000);
}
public void Dispose()// é executado novamente depois de cada metodo da classe de testes.
{//Esta parte é chamada de clean up da classe de teste
}
[Fact(DisplayName = "Deve_Criar_Curso")]
public void Deve_Criar_Curso()
{
var cursoEsperado = new
{
Nome = _nome,
Descricao = _descricao,
CargaHoraria = _cargaHoraria,
PublicoAlvo = _publicoAlvo,
Valor = _valor
};
var curso = new Curso(cursoEsperado.Nome, cursoEsperado.Descricao, cursoEsperado.CargaHoraria, cursoEsperado.PublicoAlvo, cursoEsperado.Valor);
cursoEsperado.ToExpectedObject().ShouldMatch(curso);// Substitui o assert e torna mais simples verificar se curso esperado corresponde a curso.
}
[Theory(DisplayName = "Nome_Do_Curso_Nao_Deve_Ser_Vazio")]//Testa as teorias enviado inlinedata como argumento
[InlineData("")]
[InlineData(null)]
public void Nome_Do_Curso_Nao_Deve_Ser_Vazio_Ou_Nulo(string nomeInvalido)
{
Assert.Throws<ArgumentException>(() =>
CursoBuilder.CriarNovoCurso().DefinirNome(nomeInvalido).Build())
.ValidarMensagem("Nome inválido."); ;
}
[Theory(DisplayName = "Curso_Nao_Deve_Ter_Carga_Horaria_Menor_Que_1_Hora")]
[InlineData(0)]
[InlineData(-1)]
public void Curso_Nao_Deve_Ter_Carga_Horaria_Menor_Que_1_Hora(double cargaHorariaInvalida)
{
Assert.Throws<ArgumentException>(() =>
CursoBuilder.CriarNovoCurso().DefinirCargaHoraria(cargaHorariaInvalida).Build())
.ValidarMensagem("Carga horaria inválida.");
}
[Theory(DisplayName = "Curso_Nao_Deve_Ter_Valor_Menor_Que_1")]
[InlineData(0)]
[InlineData(-1)]
public void Curso_Nao_Deve_Ter_Valor_Menor_Que_1(decimal valorInvalido)
{
Assert.Throws<ArgumentException>(() =>
CursoBuilder.CriarNovoCurso().DefinirValor(valorInvalido).Build())
.ValidarMensagem("Valor inválido.");
}
}
}
| 38.571429 | 164 | 0.644444 | [
"MIT"
] | Felipe13devmaster/Estudo-TDD-X-Unit | CursoOnline/CursoOnline.Tests/Cursos/CursoTests.cs | 3,249 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Nucleo.Presentation;
using Nucleo.Views;
using Nucleo.Web.Views;
namespace Nucleo.Tests.PresenterLoading
{
public interface IAttributeMatchFirstLookView : IView
{
string Message { get; set; }
}
public class AttributeMatchFirstLookPresenter : BasePresenter<IAttributeMatchFirstLookView>
{
public AttributeMatchFirstLookPresenter(IAttributeMatchFirstLookView view)
: base(view)
{
view.Starting += View_Starting;
}
void View_Starting(object sender, EventArgs e)
{
this.View.Message = "Loaded by PresenterBindingAttribute declarationon the view.";
}
}
[PresenterBinding(typeof(AttributeMatchFirstLookPresenter))]
public partial class AttributeMatchFirstLook : BaseViewPage, IAttributeMatchFirstLookView
{
public string Message
{
get { return this.lblMessage.Text; }
set { this.lblMessage.Text = value; }
}
}
} | 23.325581 | 92 | 0.771685 | [
"MIT"
] | brianmains/Nucleo.NET | src/Backup/Nucleo.OnlineMVPTests/Tests/PresenterLoading/AttributeMatchFirstLook.aspx.cs | 1,005 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Simplification;
namespace Microsoft.CodeAnalysis.IntroduceVariable
{
internal partial class AbstractIntroduceVariableService<TService, TExpressionSyntax, TTypeSyntax, TTypeDeclarationSyntax, TQueryExpressionSyntax>
{
internal abstract class AbstractIntroduceVariableCodeAction : CodeAction
{
private readonly bool _allOccurrences;
private readonly bool _isConstant;
private readonly bool _isLocal;
private readonly bool _isQueryLocal;
private readonly TExpressionSyntax _expression;
private readonly SemanticDocument _document;
private readonly TService _service;
internal AbstractIntroduceVariableCodeAction(
TService service,
SemanticDocument document,
TExpressionSyntax expression,
bool allOccurrences,
bool isConstant,
bool isLocal,
bool isQueryLocal)
{
_service = service;
_document = document;
_expression = expression;
_allOccurrences = allOccurrences;
_isConstant = isConstant;
_isLocal = isLocal;
_isQueryLocal = isQueryLocal;
Title = CreateDisplayText(expression);
}
public override string Title { get; }
protected override async Task<Document> GetChangedDocumentAsync(CancellationToken cancellationToken)
{
var changedDocument = await GetChangedDocumentCoreAsync(cancellationToken).ConfigureAwait(false);
return await Simplifier.ReduceAsync(changedDocument, cancellationToken: cancellationToken).ConfigureAwait(false);
}
private async Task<Document> GetChangedDocumentCoreAsync(CancellationToken cancellationToken)
{
if (_isQueryLocal)
{
return await _service.IntroduceQueryLocalAsync(_document, _expression, _allOccurrences, cancellationToken).ConfigureAwait(false);
}
else if (_isLocal)
{
return await _service.IntroduceLocalAsync(_document, _expression, _allOccurrences, _isConstant, cancellationToken).ConfigureAwait(false);
}
else
{
return await IntroduceFieldAsync(cancellationToken).ConfigureAwait(false);
}
}
private async Task<Document> IntroduceFieldAsync(CancellationToken cancellationToken)
{
var result = await _service.IntroduceFieldAsync(_document, _expression, _allOccurrences, _isConstant, cancellationToken).ConfigureAwait(false);
return result.Item1;
}
private string CreateDisplayText(TExpressionSyntax expression)
{
var singleLineExpression = _document.Project.LanguageServices.GetService<ISyntaxFactsService>().ConvertToSingleLine(expression);
var nodeString = singleLineExpression.ToString();
// prevent the display string from being too long
const int MaxLength = 40;
if (nodeString.Length > MaxLength)
{
nodeString = nodeString.Substring(0, MaxLength) + "...";
}
return CreateDisplayText(nodeString);
}
private string CreateDisplayText(string nodeString)
{
// Indexed by: allOccurrences, isConstant, isLocal
var formatStrings = new string[2, 2, 2]
{
{
{ FeaturesResources.Introduce_field_for_0, FeaturesResources.Introduce_local_for_0 },
{ FeaturesResources.Introduce_constant_for_0, FeaturesResources.Introduce_local_constant_for_0 }
},
{
{ FeaturesResources.Introduce_field_for_all_occurrences_of_0, FeaturesResources.Introduce_local_for_all_occurrences_of_0 },
{ FeaturesResources.Introduce_constant_for_all_occurrences_of_0, FeaturesResources.Introduce_local_constant_for_all_occurrences_of_0 }
}
};
var formatString = _isQueryLocal
? _allOccurrences
? FeaturesResources.Introduce_query_variable_for_all_occurrences_of_0
: FeaturesResources.Introduce_query_variable_for_0
: formatStrings[_allOccurrences ? 1 : 0, _isConstant ? 1 : 0, _isLocal ? 1 : 0];
return string.Format(formatString, nodeString);
}
protected ITypeSymbol GetExpressionType(
CancellationToken cancellationToken)
{
var semanticModel = _document.SemanticModel;
var typeInfo = semanticModel.GetTypeInfo(_expression, cancellationToken);
return typeInfo.Type ?? typeInfo.ConvertedType ?? semanticModel.Compilation.GetSpecialType(SpecialType.System_Object);
}
}
}
}
| 45.860656 | 160 | 0.624486 | [
"Apache-2.0"
] | AArnott/roslyn | src/Features/Core/Portable/IntroduceVariable/AbstractIntroduceVariableService.AbstractIntroduceVariableCodeAction.cs | 5,595 | C# |
using System;
using System.Collections.Generic;
using VRage;
using VRageMath;
using RichStringMembers = VRage.MyTuple<System.Text.StringBuilder, VRage.MyTuple<byte, float, VRageMath.Vector2I, VRageMath.Color>>;
namespace RichHudFramework
{
namespace UI
{
using ToolTipMembers = MyTuple<
List<RichStringMembers>, // Text
Color? // BgColor
>;
/// <summary>
/// Class used to define tooltips attached to the RHF cursor. Tooltips must be
/// registered in HandleInput() every input tick. The first tooltip registered
/// takes precedence.
/// </summary>
public class ToolTip
{
public static readonly GlyphFormat DefaultText = GlyphFormat.Blueish.WithSize(.75f);
public static readonly Color DefaultBG = new Color(73, 86, 95),
orangeWarningBG = new Color(180, 110, 0),
redWarningBG = new Color(126, 39, 44);
/// <summary>
/// Text to be assigned to the tooltip. Multiline tooltips are allowed, but
/// are not wrapped.
/// </summary>
public RichText text;
/// <summary>
/// Color of the text background
/// </summary>
public Color? bgColor;
/// <summary>
/// Callback delegate used by the API to retrieve tooltip information
/// </summary>
public readonly Func<ToolTipMembers> GetToolTipFunc;
public ToolTip()
{
bgColor = DefaultBG;
GetToolTipFunc = () => new ToolTipMembers()
{
Item1 = text?.apiData,
Item2 = bgColor,
};
}
public ToolTip(Func<ToolTipMembers> GetToolTipFunc)
{
bgColor = DefaultBG;
this.GetToolTipFunc = GetToolTipFunc;
}
}
}
}
| 31.507937 | 132 | 0.541058 | [
"MIT"
] | ZachHembree/RichHudFramework.Client | Shared/UI/HUD/ToolTip.cs | 1,987 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web;
using System.Web.UI.HtmlControls;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Threading;
using Microsoft.Win32;
using Newtonsoft.Json.Linq;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
namespace AIDungeon_Extension
{
class WebBrowserTranslator
{
private const string inputElementXPath = "//*[@id=\"yDmH0d\"]/c-wiz/div/div[2]/c-wiz/div[2]/c-wiz/div[1]/div[2]/div[2]/c-wiz[1]/span/span/div/textarea";
private const string translatedElementXPath = "//*[@id=\"yDmH0d\"]/c-wiz/div/div[2]/c-wiz/div[2]/c-wiz/div[1]/div[2]/div[2]/c-wiz[2]/div[5]/div/div[3]";
private Grid grid = null;
public WebBrowserTranslator(Grid grid)
{
this.grid = grid;
}
public class TranlateWorker
{
private Grid grid = null;
private string text = null;
private Action<string> onTranslated = null;
private WebBrowser webBrowser = null;
public TranlateWorker(Grid grid, string text, Action<string> onTranslated)
{
if (string.IsNullOrEmpty(text))
{
onTranslated?.Invoke(null);
return;
}
this.grid = grid;
this.text = text;
this.onTranslated = onTranslated;
}
public void Start()
{
this.webBrowser = new WebBrowser();
this.webBrowser.LoadCompleted += loadCompleted;
this.grid.Children.Add(webBrowser);
string sUrl = "https://translate.google.co.kr/?hl=ko&tab=TT#en/ko/";
sUrl = sUrl + HttpUtility.UrlPathEncode(text);
webBrowser.Navigate(sUrl);
}
private void loadCompleted(object sender, System.Windows.Navigation.NavigationEventArgs e)
{
Console.WriteLine("loadCompleted");
Task.Run(() =>
{
while (true)
{
string html = string.Empty;
this.grid.Dispatcher.Invoke(() =>
{
var document = this.webBrowser.Document as mshtml.HTMLDocument;
html = document.documentElement.outerHTML;
});
while (string.IsNullOrEmpty(html))
{
}
var doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(html);
try
{
var nodeCollection = doc.DocumentNode.SelectNodes(translatedElementXPath);
if (nodeCollection == null) continue;
var node = nodeCollection.LastOrDefault();
if (node == null) continue;
var attributes = node.Attributes["data-text"];
if (attributes == null) continue;
var translated = attributes.Value;
this.grid.Dispatcher.Invoke(() =>
{
onTranslated?.Invoke(translated);
});
break;
}
catch (Exception exception) { }
}
});
}
public void Dispose()
{
this.webBrowser.LoadCompleted -= loadCompleted;
this.grid.Children.Remove(webBrowser);
}
}
public void Translate(string text, System.Action<string> onSuccess, System.Action onFailed)
{
var worker = new TranlateWorker(this.grid, text, onSuccess);
worker.Start();
}
public void Dispose()
{
}
}
} | 32.984252 | 160 | 0.489854 | [
"MIT"
] | hisacat/AIDungeon-Extension | AIDungeon-Extension/WebBrowserTranslator.cs | 4,191 | C# |
#pragma checksum "D:\SENAC\UC4\LógicaDeProgramação\AplicaçãoWebComBancoDeDados\Parte3_Cadastro_Listar_Sessão\Cadastros\Views\Usuario\Login.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "b7064bc44a09a7a339ceb2d8a8a6ab75cfea1e14"
// <auto-generated/>
#pragma warning disable 1591
[assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCore.Views_Usuario_Login), @"mvc.1.0.view", @"/Views/Usuario/Login.cshtml")]
namespace AspNetCore
{
#line hidden
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
#nullable restore
#line 1 "D:\SENAC\UC4\LógicaDeProgramação\AplicaçãoWebComBancoDeDados\Parte3_Cadastro_Listar_Sessão\Cadastros\Views\_ViewImports.cshtml"
using Cadastros;
#line default
#line hidden
#nullable disable
#nullable restore
#line 2 "D:\SENAC\UC4\LógicaDeProgramação\AplicaçãoWebComBancoDeDados\Parte3_Cadastro_Listar_Sessão\Cadastros\Views\_ViewImports.cshtml"
using Cadastros.Models;
#line default
#line hidden
#nullable disable
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"b7064bc44a09a7a339ceb2d8a8a6ab75cfea1e14", @"/Views/Usuario/Login.cshtml")]
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"6bdb0dc22cfe52403a06683669d4e27c1c452006", @"/Views/_ViewImports.cshtml")]
public class Views_Usuario_Login : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<Usuario>
{
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_0 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("type", "password", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_1 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-action", "Login", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_2 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("method", "POST", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
#line hidden
#pragma warning disable 0649
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext __tagHelperExecutionContext;
#pragma warning restore 0649
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner __tagHelperRunner = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner();
#pragma warning disable 0169
private string __tagHelperStringValueBuffer;
#pragma warning restore 0169
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __backed__tagHelperScopeManager = null;
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __tagHelperScopeManager
{
get
{
if (__backed__tagHelperScopeManager == null)
{
__backed__tagHelperScopeManager = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager(StartTagHelperWritingScope, EndTagHelperWritingScope);
}
return __backed__tagHelperScopeManager;
}
}
private global::Microsoft.AspNetCore.Mvc.TagHelpers.FormTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper;
private global::Microsoft.AspNetCore.Mvc.TagHelpers.RenderAtEndOfFormTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper;
private global::Microsoft.AspNetCore.Mvc.TagHelpers.LabelTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper;
private global::Microsoft.AspNetCore.Mvc.TagHelpers.InputTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper;
#pragma warning disable 1998
public async override global::System.Threading.Tasks.Task ExecuteAsync()
{
#nullable restore
#line 2 "D:\SENAC\UC4\LógicaDeProgramação\AplicaçãoWebComBancoDeDados\Parte3_Cadastro_Listar_Sessão\Cadastros\Views\Usuario\Login.cshtml"
ViewData["Title"] = "Login";
#line default
#line hidden
#nullable disable
WriteLiteral("<h2>Login</h2>\r\n<p id=\"pMensagem\">");
#nullable restore
#line 6 "D:\SENAC\UC4\LógicaDeProgramação\AplicaçãoWebComBancoDeDados\Parte3_Cadastro_Listar_Sessão\Cadastros\Views\Usuario\Login.cshtml"
Write(ViewBag.Mensagem);
#line default
#line hidden
#nullable disable
WriteLiteral("</p>\r\n");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("form", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "b7064bc44a09a7a339ceb2d8a8a6ab75cfea1e145083", async() => {
WriteLiteral("\r\n <p>\r\n ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("label", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "b7064bc44a09a7a339ceb2d8a8a6ab75cfea1e145360", async() => {
WriteLiteral("Login: ");
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.LabelTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper);
#nullable restore
#line 9 "D:\SENAC\UC4\LógicaDeProgramação\AplicaçãoWebComBancoDeDados\Parte3_Cadastro_Listar_Sessão\Cadastros\Views\Usuario\Login.cshtml"
__Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.Login);
#line default
#line hidden
#nullable disable
__tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\r\n ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "b7064bc44a09a7a339ceb2d8a8a6ab75cfea1e146951", async() => {
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.InputTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper);
#nullable restore
#line 10 "D:\SENAC\UC4\LógicaDeProgramação\AplicaçãoWebComBancoDeDados\Parte3_Cadastro_Listar_Sessão\Cadastros\Views\Usuario\Login.cshtml"
__Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.Login);
#line default
#line hidden
#nullable disable
__tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\r\n </p>\r\n <p>\r\n ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("label", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "b7064bc44a09a7a339ceb2d8a8a6ab75cfea1e148514", async() => {
WriteLiteral("Senha: ");
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.LabelTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper);
#nullable restore
#line 13 "D:\SENAC\UC4\LógicaDeProgramação\AplicaçãoWebComBancoDeDados\Parte3_Cadastro_Listar_Sessão\Cadastros\Views\Usuario\Login.cshtml"
__Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.Senha);
#line default
#line hidden
#nullable disable
__tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\r\n ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "b7064bc44a09a7a339ceb2d8a8a6ab75cfea1e1410106", async() => {
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.InputTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper);
#nullable restore
#line 14 "D:\SENAC\UC4\LógicaDeProgramação\AplicaçãoWebComBancoDeDados\Parte3_Cadastro_Listar_Sessão\Cadastros\Views\Usuario\Login.cshtml"
__Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.Senha);
#line default
#line hidden
#nullable disable
__tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
__Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.InputTypeName = (string)__tagHelperAttribute_0.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_0);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\r\n </p>\r\n <p>\r\n <input type=\"submit\" value=\"Entrar\" />\r\n </p>\r\n");
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.FormTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper);
__Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.RenderAtEndOfFormTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper);
__Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper.Action = (string)__tagHelperAttribute_1.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_1);
__Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper.Method = (string)__tagHelperAttribute_2.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_2);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
}
#pragma warning restore 1998
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<Usuario> Html { get; private set; }
}
}
#pragma warning restore 1591
| 69.425743 | 298 | 0.752282 | [
"MIT"
] | kellykawase/senac-estudante | MóduloA/UC4/LógicadeProgramação/AplicaçãoWebComBancoDeDados/Parte3_Cadastro_Listar_Login/Cadastros/obj/Debug/net5.0/Razor/Views/Usuario/Login.cshtml.g.cs | 14,078 | C# |
using System;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Fpl.Client.Abstractions;
using Fpl.Search.Models;
using Fpl.Search.Searching;
using FplBot.Core.Abstractions;
using FplBot.Core.Extensions;
using FplBot.Core.Helpers;
using FplBot.Data.Abstractions;
using FplBot.Data.Models;
using Microsoft.Extensions.Logging;
using Slackbot.Net.Endpoints.Abstractions;
using Slackbot.Net.Endpoints.Models.Events;
namespace FplBot.Core.Handlers
{
public class FplSearchHandler : HandleAppMentionBase
{
private readonly ISearchService _searchService;
private readonly IGlobalSettingsClient _globalSettingsClient;
private readonly ISlackWorkSpacePublisher _workSpacePublisher;
private readonly ISlackTeamRepository _slackTeamRepo;
private readonly ILeagueClient _leagueClient;
private readonly IEntryClient _entryClient;
private readonly ILogger<FplSearchHandler> _logger;
public FplSearchHandler(
ISearchService searchService,
IGlobalSettingsClient globalSettingsClient,
ISlackWorkSpacePublisher workSpacePublisher,
ISlackTeamRepository slackTeamRepo,
ILeagueClient leagueClient,
IEntryClient entryClient,
ILogger<FplSearchHandler> logger)
{
_searchService = searchService;
_globalSettingsClient = globalSettingsClient;
_workSpacePublisher = workSpacePublisher;
_slackTeamRepo = slackTeamRepo;
_leagueClient = leagueClient;
_entryClient = entryClient;
_logger = logger;
}
public override string[] Commands => new[] { "search" };
public override async Task<EventHandledResponse> Handle(EventMetaData eventMetadata, AppMentionEvent message)
{
var term = ParseArguments(message);
SlackTeam slackTeam = null;
try
{
slackTeam = await _slackTeamRepo.GetTeam(eventMetadata.Team_Id);
}
catch (Exception e)
{
_logger.LogError(e, "Unable to get team {teamId} during search.", eventMetadata.Team_Id);
}
string countryToBoost = await GetCountryToBoost(slackTeam);
var searchMetaData = GetSearchMetaData(slackTeam, message);
var entriesTask = _searchService.SearchForEntry(term, 0, 10, searchMetaData);
var leaguesTask = _searchService.SearchForLeague(term, 0, 10, searchMetaData, countryToBoost);
var entries = await entriesTask;
var leagues = await leaguesTask;
var sb = new StringBuilder();
sb.Append("Matching teams:\n");
int? currentGameweek = null;
if (entries.Any() || leagues.Any())
{
try
{
var globalSettings = await _globalSettingsClient.GetGlobalSettings();
var gameweeks = globalSettings.Gameweeks;
currentGameweek = gameweeks.GetCurrentGameweek().Id;
}
catch (Exception e)
{
_logger.LogError(e, "Unable to obtain current gameweek when creating search result links");
}
}
if (entries.Any())
{
sb.Append(Formatter.BulletPoints(entries.ExposedHits.Select(e => Formatter.FormatEntryItem(e, currentGameweek))));
if (entries.HitCountExceedingExposedOnes > 0)
{
sb.Append($"\n...and {entries.HitCountExceedingExposedOnes} more");
}
}
else
{
sb.Append("Found no matching teams :shrug:");
}
sb.Append("\n\nMatching leagues:\n");
if (leagues.Any())
{
sb.Append(Formatter.BulletPoints(leagues.ExposedHits.Select(e => Formatter.FormatLeagueItem(e, currentGameweek))));
if (leagues.HitCountExceedingExposedOnes > 0)
{
sb.Append($"\n...and {leagues.HitCountExceedingExposedOnes} more");
}
}
else
{
sb.Append("Found no matching leagues :shrug:");
}
await _workSpacePublisher.PublishToWorkspace(eventMetadata.Team_Id, message.Channel, sb.ToString());
return new EventHandledResponse(sb.ToString());
}
private static SearchMetaData GetSearchMetaData(SlackTeam slackTeam, AppMentionEvent message)
{
var metaData = new SearchMetaData
{
Team = slackTeam?.TeamId, FollowingFplLeagueId = slackTeam?.FplbotLeagueId.ToString(), Actor = message.User,
Client = QueryClient.Slack
};
return metaData;
}
private async Task<string> GetCountryToBoost(SlackTeam slackTeam)
{
string countryToBoost = null;
if (slackTeam?.FplbotLeagueId != null)
{
var league = await _leagueClient.GetClassicLeague((int)slackTeam.FplbotLeagueId);
var adminEntry = league?.Properties?.AdminEntry;
if (adminEntry != null)
{
var admin = await _entryClient.Get(adminEntry.Value);
if (admin != null)
{
countryToBoost = admin.PlayerRegionShortIso;
}
}
}
return countryToBoost;
}
public override (string, string) GetHelpDescription() => ($"{CommandsFormatted} {{name}}", $"(:wrench: Beta) Search for teams or leagues. E.g. \"{CommandsFormatted} magnus carlsen\".");
}
}
| 36.60625 | 193 | 0.592453 | [
"MIT"
] | ehamberg/fplbot | src/FplBot.Core/Handlers/SlackEvents/FplSearchHandler.cs | 5,859 | C# |
using System;
using System.Threading.Tasks;
using NFig.Converters;
using NFig.Infrastructure;
using NFig.Metadata;
namespace NFig
{
/// <summary>
/// Contains all methods for administering the settings for an application, such as setting or clearing overrides.
/// </summary>
public class NFigAdminClient<TTier, TDataCenter>
where TTier : struct
where TDataCenter : struct
{
readonly AppInternalInfo<TTier, TDataCenter> _appInfo;
/// <summary>
/// The backing store for NFig overrides and metadata.
/// </summary>
public NFigStore<TTier, TDataCenter> Store { get; }
/// <summary>
/// The name of the application to administer.
/// </summary>
public string AppName => _appInfo.AppName;
/// <summary>
/// The deployment tier of the application.
/// </summary>
public TTier Tier { get; }
/// <summary>
/// Metadata about the application, not including default values.
/// </summary>
public AppMetadata AppMetadata => _appInfo.AppMetadata;
/// <summary>
/// True if this admin client is capable of encrypting settings for the application.
/// </summary>
public bool CanEncrypt => _appInfo.CanEncrypt;
/// <summary>
/// True if this admin client is capable of decrypting the application's encrypted settings.
/// </summary>
public bool CanDecrypt => _appInfo.CanDecrypt;
/// <summary>
/// Gets the current overrides-snapshot for the app.
/// </summary>
public OverridesSnapshot<TTier, TDataCenter> Snapshot => _appInfo.Snapshot;
/// <summary>
/// Returns the current snapshot commit for the app.
/// </summary>
public string Commit => Snapshot.Commit;
internal NFigAdminClient(NFigStore<TTier, TDataCenter> store, AppInternalInfo<TTier, TDataCenter> appInfo)
{
_appInfo = appInfo;
Store = store;
Tier = store.Tier;
}
/// <summary>
/// Gets the default values for a sub-app, or the root app if <paramref name="subAppId"/> is null.
/// </summary>
/// <param name="subAppId">The ID of the sub-app, or null for the root app.</param>
public Defaults<TTier, TDataCenter> GetDefaults(int? subAppId)
{
if (subAppId == null)
{
var rootDefaults = _appInfo.RootDefaults;
if (rootDefaults == null)
throw new NFigException("Could not find defaults for root application.");
return rootDefaults;
}
if (_appInfo.SubAppDefaults.TryGetValue(subAppId.Value, out var subAppDefaults))
return subAppDefaults;
throw new NFigException($"Could not find defaults for sub-app {subAppId}. It may not be in use.");
}
/// <summary>
/// Checks the backing store for changes to the app's metadata, including sub-apps, and updates as necessary.
/// </summary>
/// <param name="forceReload">If true, the metadata will be reloaded, even if no change was detected.</param>
public void RefreshMetadata(bool forceReload) => Store.RefreshAppMetadataInternal(AppName, forceReload);
/// <summary>
/// Checks the backing store for changes to the app's metadata, including sub-apps, and updates as necessary.
/// </summary>
/// <param name="forceReload">If true, the metadata will be reloaded, even if no change was detected.</param>
public Task RefreshMetadataAsync(bool forceReload) => Store.RefreshAppMetadataAsyncInternal(AppName, forceReload);
/// <summary>
/// Checks the backing store for changes to the app's overrides, including sub-apps, and updates the snapshot as necessary.
/// </summary>
/// <param name="forceReload">If true, the snapshot will be reloaded, even if no change was detected.</param>
public void RefreshSnapshot(bool forceReload) => Store.RefreshSnapshotInternal(AppName, forceReload);
/// <summary>
/// Checks the backing store for changes to the app's overrides, including sub-apps, and updates the snapshot as necessary.
/// </summary>
/// <param name="forceReload">If true, the snapshot will be reloaded, even if no change was detected.</param>
public Task RefreshSnapshotAsync(bool forceReload) => Store.RefreshSnapshotAsyncInternal(AppName, forceReload);
/// <summary>
/// Sets an override for the specified setting name and data center combination. If an existing override shares that exact combination, it will be
/// replaced.
/// </summary>
/// <param name="settingName">Name of the setting.</param>
/// <param name="dataCenter">Data center which the override should be applicable to.</param>
/// <param name="value">The string-value of the setting. If the setting is an encrypted setting, this value must be pre-encrypted.</param>
/// <param name="user">The user who is setting the override (used for logging purposes). This can be null if you don't care about logging.</param>
/// <param name="subAppId">(optional) The sub-app which the override should apply to.</param>
/// <param name="commit">(optional) If non-null, the override will only be applied if this is the current commit ID.</param>
/// <param name="expirationTime">(optional) The time when the override should be automatically cleared.</param>
/// <returns>
/// A snapshot of the state immediately after the override is applied. If the override is not applied because the current commit didn't match the
/// commit parameter, the return value will be null.
/// </returns>
public OverridesSnapshot<TTier, TDataCenter> SetOverride(
string settingName,
TDataCenter dataCenter,
string value,
string user,
int? subAppId = null,
string commit = null,
DateTimeOffset? expirationTime = null)
{
// todo: validate, if possible
var ov = new OverrideValue<TTier, TDataCenter>(settingName, value, subAppId, dataCenter, expirationTime);
return Store.SetOverrideInternal(AppName, ov, user, commit);
}
/// <summary>
/// Sets an override for the specified setting name and data center combination. If an existing override shares that exact combination, it will be
/// replaced.
/// </summary>
/// <param name="settingName">Name of the setting.</param>
/// <param name="dataCenter">Data center which the override should be applicable to.</param>
/// <param name="value">The string-value of the setting. If the setting is an encrypted setting, this value must be pre-encrypted.</param>
/// <param name="user">The user who is setting the override (used for logging purposes). This can be null if you don't care about logging.</param>
/// <param name="subAppId">(optional) The sub-app which the override should apply to.</param>
/// <param name="commit">(optional) If non-null, the override will only be applied if this is the current commit ID.</param>
/// <param name="expirationTime">(optional) The time when the override should be automatically cleared.</param>
/// <returns>
/// A snapshot of the state immediately after the override is applied. If the override is not applied because the current commit didn't match the
/// commit parameter, the return value will be null.
/// </returns>
public Task<OverridesSnapshot<TTier, TDataCenter>> SetOverrideAsync(
string settingName,
TDataCenter dataCenter,
string value,
string user,
int? subAppId = null,
string commit = null,
DateTimeOffset? expirationTime = null)
{
// todo: validate, if possible
var ov = new OverrideValue<TTier, TDataCenter>(settingName, value, subAppId, dataCenter, expirationTime);
return Store.SetOverrideAsyncInternal(AppName, ov, user, commit);
}
/// <summary>
/// Clears an override with the specified setting name and data center combination. Even if the override does not exist, this operation may result in a
/// change of the current commit, depending on the store's implementation.
/// </summary>
/// <param name="settingName">Name of the setting.</param>
/// <param name="dataCenter">Data center which the override is applied to.</param>
/// <param name="user">The user who is clearing the override (used for logging purposes). This can be null if you don't care about logging.</param>
/// <param name="subAppId">The sub-app which the override is applied to.</param>
/// <param name="commit">(optional) If non-null, the override will only be cleared if this is the current commit ID.</param>
/// <returns>
/// A snapshot of the state immediately after the override is cleared. If the override is not applied, either because it didn't exist, or because the
/// current commit didn't match the commit parameter, the return value will be null.
/// </returns>
public OverridesSnapshot<TTier, TDataCenter> ClearOverride(
string settingName,
TDataCenter dataCenter,
string user,
int? subAppId = null,
string commit = null)
{
// todo: validate setting name
return Store.ClearOverrideInternal(AppName, settingName, dataCenter, user, subAppId, commit);
}
/// <summary>
/// Clears an override with the specified setting name and data center combination. Even if the override does not exist, this operation may result in a
/// change of the current commit, depending on the store's implementation.
/// </summary>
/// <param name="settingName">Name of the setting.</param>
/// <param name="dataCenter">Data center which the override is applied to.</param>
/// <param name="user">The user who is clearing the override (used for logging purposes). This can be null if you don't care about logging.</param>
/// <param name="subAppId">The sub-app which the override is applied to.</param>
/// <param name="commit">(optional) If non-null, the override will only be cleared if this is the current commit ID.</param>
/// <returns>
/// A snapshot of the state immediately after the override is cleared. If the override is not applied, either because it didn't exist, or because the
/// current commit didn't match the commit parameter, the return value will be null.
/// </returns>
public Task<OverridesSnapshot<TTier, TDataCenter>> ClearOverrideAsync(
string settingName,
TDataCenter dataCenter,
string user,
int? subAppId = null,
string commit = null)
{
// todo: validate setting name
return Store.ClearOverrideAsyncInternal(AppName, settingName, dataCenter, user, subAppId, commit);
}
/// <summary>
/// Returns an encrypted version of <paramref name="plainText"/>. If this admin client was not provided with an encryptor for the application, then
/// <see cref="CanEncrypt"/> will be false, and this method will always throw an exception. Null values are not encrypted, and are simply returned as
/// null.
/// </summary>
public string Encrypt(string plainText) => _appInfo.Encrypt(plainText);
/// <summary>
/// Returns a plain-text (decrypted) version of <paramref name="encrypted"/>. If this admin client is not able to decrypt settings for the application,
/// then <see cref="CanDecrypt"/> will be false, and this method will always throw an exception. Null are considered to be unencrypted to begin with,
/// and will result in a null return value.
/// </summary>
public string Decrypt(string encrypted) => _appInfo.Decrypt(encrypted);
/// <summary>
/// Restores all overrides to a previous state.
/// </summary>
/// <param name="snapshot">The snapshot to restore.</param>
/// <param name="user">The user performing the restore (for logging purposes).</param>
/// <returns>A snapshot of the new current state (after restoring).</returns>
public OverridesSnapshot<TTier, TDataCenter> RestoreSnapshot(OverridesSnapshot<TTier, TDataCenter> snapshot, string user)
{
return Store.RestoreSnapshotInternal(AppName, snapshot, user);
}
/// <summary>
/// Restores all overrides to a previous state.
/// </summary>
/// <param name="snapshot">The snapshot to restore.</param>
/// <param name="user">The user performing the restore (for logging purposes).</param>
/// <returns>A snapshot of the new current state (after restoring).</returns>
public Task<OverridesSnapshot<TTier, TDataCenter>> RestoreSnapshotAsync(OverridesSnapshot<TTier, TDataCenter> snapshot, string user)
{
return Store.RestoreSnapshotAsyncInternal(AppName, snapshot, user);
}
/// <summary>
/// Returns true if this admin client is capable of validating values for the setting. This may be false if the setting uses a custom
/// <see cref="ISettingConverter{TValue}"/>, and no <see cref="NFigAppClient{TSettings,TTier,TDataCenter}"/> has been instantiated for the application.
/// </summary>
public bool CanValidate(string settingName)
{
throw new NotImplementedException();
}
/// <summary>
/// Returns true if <paramref name="value"/> can be converted into a valid value for the setting. If the setting is encrypted, then
/// <paramref name="value"/> must be encrypted. If <see cref="CanValidate"/> returns false for this setting name, then this method will always throw an
/// exception.
/// </summary>
public bool IsValidForSetting(string settingName, string value)
{
throw new NotImplementedException();
}
/// <summary>
/// Returns true if the setting exists. Setting names are case-sensitive.
/// </summary>
public bool SettingExists(string settingName)
{
return _appInfo.AppMetadata.SettingsMetadata.ContainsKey(settingName);
}
}
} | 53.147482 | 160 | 0.641489 | [
"MIT"
] | NFig/NFig | NFig/NFigAdminClient.cs | 14,777 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Windows.Foundation.Metadata
{
public partial class ApiInformation
{
public static bool IsApiContractPresent(string contractName, ushort majorVersion)
=> IsApiContractPresent(contractName, majorVersion, 0);
public static bool IsApiContractPresent(string contractName, ushort majorVersion, ushort minorVersion)
{
switch (contractName)
{
case "Windows.Foundation.UniversalApiContract":
// See https://docs.microsoft.com/en-us/uwp/extension-sdks/windows-universal-sdk
return majorVersion <= 6; // SDK 10.0.17134.1
case "Uno.WinUI":
#if HAS_UNO_WINUI
return true;
#else
return false;
#endif
default:
return false;
}
}
}
}
| 23.735294 | 104 | 0.738538 | [
"Apache-2.0"
] | AnshSSonkhia/uno | src/Uno.Foundation/Metadata/ApiInformation.shared.cs | 809 | C# |
// <auto-generated>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Azure.Management.Sql.Models
{
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using System.Linq;
/// <summary>
/// A recoverable managed database resource.
/// </summary>
[Rest.Serialization.JsonTransformation]
public partial class RecoverableManagedDatabase : ProxyResource
{
/// <summary>
/// Initializes a new instance of the RecoverableManagedDatabase class.
/// </summary>
public RecoverableManagedDatabase()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the RecoverableManagedDatabase class.
/// </summary>
/// <param name="id">Resource ID.</param>
/// <param name="name">Resource name.</param>
/// <param name="type">Resource type.</param>
/// <param name="lastAvailableBackupDate">The last available backup
/// date.</param>
public RecoverableManagedDatabase(string id = default(string), string name = default(string), string type = default(string), string lastAvailableBackupDate = default(string))
: base(id, name, type)
{
LastAvailableBackupDate = lastAvailableBackupDate;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets the last available backup date.
/// </summary>
[JsonProperty(PropertyName = "properties.lastAvailableBackupDate")]
public string LastAvailableBackupDate { get; private set; }
}
}
| 34.533333 | 182 | 0.641409 | [
"MIT"
] | 0rland0Wats0n/azure-sdk-for-net | sdk/sqlmanagement/Microsoft.Azure.Management.SqlManagement/src/Generated/Models/RecoverableManagedDatabase.cs | 2,072 | C# |
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
using System;
namespace CollectSFData
{
public class KustoAdditionalProperties
{
public string authorizationContext;
public bool compressed;
public string csvMapping;
public string jsonMapping;
}
public class KustoErrorMessage
{
public string Database;
public string Details;
public string ErrorCode;
public DateTime FailedOn;
public string FailureStatus;
public string IngestionSourceId;
public string IngestionSourcePath;
public string OperationId;
public bool OriginatesFromUpdatePolicy;
public string RootActivityId;
public bool ShouldRetry;
public string Table;
}
public class KustoIngestionMessage
{
public KustoAdditionalProperties AdditionalProperties;
public string BlobPath;
public string DatabaseName;
public bool FlushImmediately;
public string Format;
public string Id;
public int RawDataSize;
public int ReportLevel;
public int ReportMethod;
public bool RetainBlobOnSuccess;
public string TableName;
}
public class KustoSuccessMessage
{
public string Database;
public string FailureStatus;
public string IngestionSourceId;
public string IngestionSourcePath;
public string OperationId;
public string RootActivityId;
public DateTime SucceededOn;
public string Table;
}
} | 30.083333 | 98 | 0.625485 | [
"MIT"
] | Bhaskers-Blu-Org2/CollectServiceFabricData | CollectSFData/Kusto/KustoMessages.cs | 1,807 | C# |
using System.Reflection;
[assembly: AssemblyTitle("SFA.DAS.EmployerPortal.Web.UnitTests")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 29.166667 | 65 | 0.754286 | [
"MIT"
] | SkillsFundingAgency/das-employerportal | src/SFA.DAS.EmployerPortal.Web.UnitTests/Properties/AssemblyInfo.cs | 177 | C# |
using System;
using Project.Infrastructure;
using Project.Framework.ViewMain;
using Project.Framework.ViewStart;
using Project.Framework.ViewPage1;
using Project.Framework.ViewPage2;
using Project.Framework.ViewPage3;
namespace Project.Framework
{
public class FactoryGUI_GTK : IFactoryGUI
{
public IGLApplication GetIGLApplication()
{
return new ApplicationGTK();
}
public IViewStart GetViewStart()
{
return new WindowStart();
}
public IViewMain GetViewMain()
{
return new WindowMain();
}
public INavigationNode_Page1 GetViewPage1()
{
return new WidgetPage1();
}
public INavigationNode_Page2 GetViewPage2 ()
{
return new WidgetPage2();
}
public INavigationNode_Page3 GetViewPage3 ()
{
return new WidgetPage3();
}
}
}
| 19.097561 | 46 | 0.736909 | [
"MIT"
] | govorukhin/ApplicationController_crossplatform | cross/cross/Project/NativeCode/GTK/FactoryGUI_GTK.cs | 785 | C# |
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using DVSA.MOT.SDK.Interfaces;
using DVSA.MOT.SDK.Models;
using Microsoft.Extensions.Logging;
namespace DVSA.MOT.SDK.Services
{
public class AllVehiclesService : IAllVehiclesService
{
private readonly ILogger<SingleVehicleService> _logger;
private readonly IProcessApiResponse _processApiResponse;
public AllVehiclesService(ILogger<SingleVehicleService> logger, IProcessApiResponse processApiResponse)
{
_logger = logger;
_processApiResponse = processApiResponse;
}
/// <summary>
/// Get paginated full extract of the database
/// </summary>
/// <param name="page">[0-58002]</param>
/// <returns>A full extract of the database.The last page normally increments by 10 each day.</returns>
public async Task<ApiResponse> GetAllMotTests(int page)
{
try
{
var parameters = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>(Constants.Parameters.Page, page.ToString())
};
return await _processApiResponse.GetData(parameters);
}
catch (Exception ex)
{
_logger.Log(LogLevel.Error, ex, ex.Message);
return null;
}
}
/// <summary>
/// Get paginated extract of the database by date
/// </summary>
/// <param name="date">YYYYMMDD</param>
/// <param name="page">[1-1440]</param>
/// <returns>A extract of the database filtered by day</returns>
public async Task<ApiResponse> GetAllMotTestsByDate(DateTime date, int page)
{
try
{
var parameters = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>(Constants.Parameters.Date, date.ToString("yyyyMMdd")),
new KeyValuePair<string, string>(Constants.Parameters.Page, page.ToString())
};
return await _processApiResponse.GetData(parameters);
}
catch (Exception ex)
{
_logger.Log(LogLevel.Error, ex, ex.Message);
return null;
}
}
}
}
| 35.485294 | 111 | 0.571488 | [
"MIT"
] | AaronSadlerUK/DVSA.MOT.SDK | DVSA.MOT.SDK/Services/AllVehiclesService.cs | 2,415 | C# |
namespace Essensoft.Paylink.Alipay.Response
{
/// <summary>
/// AlipayMerchantStoreMiniappBindResponse.
/// </summary>
public class AlipayMerchantStoreMiniappBindResponse : AlipayResponse
{
}
}
| 21.9 | 72 | 0.703196 | [
"MIT"
] | Frunck8206/payment | src/Essensoft.Paylink.Alipay/Response/AlipayMerchantStoreMiniappBindResponse.cs | 221 | C# |
using System.Collections.Generic;
namespace EveOnlineApi;
/// <summary>
/// 200 ok object
/// </summary>
[System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "13.15.5.0 (NJsonSchema v10.6.6.0 (Newtonsoft.Json v9.0.0.0))")]
public record Get_universe_systems_system_id_ok
{
[System.Text.Json.Serialization.JsonConstructor]
public Get_universe_systems_system_id_ok(int @constellation_id, string @name, IList<Planets>? @planets, Position8 @position, string? @security_class, float @security_status, int? @star_id, IList<int>? @stargates, IList<int>? @stations, int @system_id)
{
this.Constellation_id = @constellation_id;
this.Name = @name;
this.Planets = @planets;
this.Position = @position;
this.Security_class = @security_class;
this.Security_status = @security_status;
this.Star_id = @star_id;
this.Stargates = @stargates;
this.Stations = @stations;
this.System_id = @system_id;
} /// <summary>
/// The constellation this solar system is in
/// </summary>
[System.Text.Json.Serialization.JsonPropertyName("constellation_id")]
public int Constellation_id { get; init; }
/// <summary>
/// name string
/// </summary>
[System.Text.Json.Serialization.JsonPropertyName("name")]
public string Name { get; init; }
/// <summary>
/// planets array
/// </summary>
[System.Text.Json.Serialization.JsonPropertyName("planets")]
public IList<Planets>? Planets { get; init; }
/// <summary>
/// position object
/// </summary>
[System.Text.Json.Serialization.JsonPropertyName("position")]
public Position8 Position { get; init; }
/// <summary>
/// security_class string
/// </summary>
[System.Text.Json.Serialization.JsonPropertyName("security_class")]
public string? Security_class { get; init; }
/// <summary>
/// security_status number
/// </summary>
[System.Text.Json.Serialization.JsonPropertyName("security_status")]
public float Security_status { get; init; }
/// <summary>
/// star_id integer
/// </summary>
[System.Text.Json.Serialization.JsonPropertyName("star_id")]
public int? Star_id { get; init; }
/// <summary>
/// stargates array
/// </summary>
[System.Text.Json.Serialization.JsonPropertyName("stargates")]
public IList<int>? Stargates { get; init; }
/// <summary>
/// stations array
/// </summary>
[System.Text.Json.Serialization.JsonPropertyName("stations")]
public IList<int>? Stations { get; init; }
/// <summary>
/// system_id integer
/// </summary>
[System.Text.Json.Serialization.JsonPropertyName("system_id")]
public int System_id { get; init; }
}
| 28.398148 | 259 | 0.589501 | [
"MIT"
] | frankhaugen/Frank.Extensions | src/Frank.Libraries.Gaming/Engine/EveOnlineApi/Get_universe_systems_system_id_ok.cs | 3,067 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;
namespace WpfUtils.ValueConverters
{
/// <summary>
/// Provides an interface to chain two separate value converters together
/// </summary>
public class DualConverter : BaseConverter
{
public IValueConverter Stage1 { get; set; }
public IValueConverter Stage2 { get; set; }
public override object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return Stage2.Convert(
Stage1.Convert(
value, targetType, parameter, culture),
targetType, parameter, culture);
}
public override object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return Stage1.ConvertBack(
Stage2.ConvertBack(
value, targetType, parameter, culture),
targetType, parameter, culture);
}
}
}
| 32.285714 | 133 | 0.640708 | [
"MIT"
] | kmclarnon/FactorioModBuilder | WpfUtils/ValueConverters/DualConverter.cs | 1,132 | C# |
using System;
using Conference.DataStore.Abstractions;
using Xamarin.Forms;
using System.Threading.Tasks;
using Conference.DataObjects;
using System.Windows.Input;
using FormsToolkit;
using Xamarin.Essentials;
using Conference.Utils.Helpers;
namespace Conference.Clients.Portable
{
public class SessionDetailsViewModel : ViewModelBase
{
Session session;
public Session Session
{
get => session;
set => SetProperty(ref session, value);
}
public SessionDetailsViewModel(INavigation navigation, Session session) : base(navigation)
{
Session = session;
if (Session.StartTime.HasValue)
ShowReminder = !Session.StartTime.Value.IsTBA();
else
ShowReminder = false;
}
public bool LoginEnabled => FeatureFlags.LoginEnabled;
public bool ShowReminder { get; set; }
bool isReminderSet;
public bool IsReminderSet
{
get => isReminderSet;
set => SetProperty(ref isReminderSet, value);
}
Speaker selectedSpeaker;
public Speaker SelectedSpeaker
{
get => selectedSpeaker;
set
{
selectedSpeaker = value;
OnPropertyChanged();
if (selectedSpeaker == null)
return;
MessagingService.Current.SendMessage(MessageKeys.NavigateToSpeaker, selectedSpeaker);
SelectedSpeaker = null;
}
}
ICommand favoriteCommand;
public ICommand FavoriteCommand =>
favoriteCommand ?? (favoriteCommand = new Command(async () => await ExecuteFavoriteCommandAsync()));
async Task ExecuteFavoriteCommandAsync()
{
await FavoriteService.ToggleFavorite(Session);
}
ICommand reminderCommand;
public ICommand ReminderCommand =>
reminderCommand ?? (reminderCommand = new Command(async () => await ExecuteReminderCommandAsync()));
async Task ExecuteReminderCommandAsync()
{
if(!IsReminderSet)
{
var result = await ReminderService.AddReminderAsync(Session.Id,
new Plugin.Calendars.Abstractions.CalendarEvent
{
AllDay = false,
Description = Session.Abstract,
Location = Session.Room?.Name ?? string.Empty,
Name = Session.Title,
Start = Session.StartTime.Value,
End = Session.EndTime.Value
});
if(!result)
return;
Logger.Track(ConferenceLoggerKeys.ReminderAdded, "Title", Session.Title);
IsReminderSet = true;
}
else
{
var result = await ReminderService.RemoveReminderAsync(Session.Id);
if(!result)
return;
Logger.Track(ConferenceLoggerKeys.ReminderRemoved, "Title", Session.Title);
IsReminderSet = false;
}
}
ICommand shareCommand;
public ICommand ShareCommand =>
shareCommand ?? (shareCommand = new Command(async () => await ExecuteShareCommandAsync()));
async Task ExecuteShareCommandAsync()
{
Logger.Track(ConferenceLoggerKeys.Share, "Title", Session.Title);
await Share.RequestAsync(new ShareTextRequest
{
Text = $"Can't wait for {Session.Title} at #Conference!",
Title = "Share"
});
}
ICommand loadSessionCommand;
public ICommand LoadSessionCommand =>
loadSessionCommand ?? (loadSessionCommand = new Command(async () => await ExecuteLoadSessionCommandAsync()));
public async Task ExecuteLoadSessionCommandAsync()
{
if(IsBusy)
return;
try
{
IsBusy = true;
IsReminderSet = await ReminderService.HasReminderAsync(Session.Id);
Session.FeedbackLeft = await StoreManager.FeedbackStore.LeftFeedback(Session);
}
catch (Exception ex)
{
Logger.Report(ex, "Method", "ExecuteLoadSessionCommandAsync");
MessagingService.Current.SendMessage(MessageKeys.Error, ex);
}
finally
{
IsBusy = false;
}
}
}
}
| 28.993902 | 122 | 0.539432 | [
"MIT"
] | lacomarcaDO/app-conference | src/Conference.Clients.Portable/ViewModel/SessionDetailsViewModel.cs | 4,757 | C# |
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Runtime.Versioning;
using Microsoft.Framework.Runtime;
namespace Microsoft.AspNet.Mvc.FunctionalTests
{
// Represents an application environment that overrides the base path of the original
// application environment in order to make it point to the folder of the original web
// aplication so that components like ViewEngines can find views as if they were executing
// in a regular context.
public class TestApplicationEnvironment : IApplicationEnvironment
{
private readonly IApplicationEnvironment _originalAppEnvironment;
private readonly string _applicationBasePath;
private readonly string _applicationName;
public TestApplicationEnvironment(IApplicationEnvironment originalAppEnvironment, string appBasePath, string appName)
{
_originalAppEnvironment = originalAppEnvironment;
_applicationBasePath = appBasePath;
_applicationName = appName;
}
public string ApplicationName
{
get { return _applicationName; }
}
public string Version
{
get { return _originalAppEnvironment.Version; }
}
public string ApplicationBasePath
{
get { return _applicationBasePath; }
}
public string Configuration
{
get
{
return _originalAppEnvironment.Configuration;
}
}
public FrameworkName RuntimeFramework
{
get { return _originalAppEnvironment.RuntimeFramework; }
}
}
} | 33.203704 | 125 | 0.670385 | [
"Apache-2.0"
] | walkeeperY/ManagementSystem | test/Microsoft.AspNet.Mvc.FunctionalTests/TestApplicationEnvironment.cs | 1,795 | C# |
using AllOverIt.Aws.Cdk.AppSync.Attributes.Types;
namespace AllOverIt.Aws.Cdk.AppSync.Schema.Types
{
/// <summary>A custom scalar type that will be interpreted as an AwsUrl type.</summary>
[SchemaScalar(nameof(AwsTypeUrl))]
public sealed class AwsTypeUrl
{
}
} | 28.2 | 91 | 0.72695 | [
"MIT"
] | mjfreelancing/AllOverIt | Source/AllOverIt.Aws.Cdk.AppSync/Schema/Types/AwsTypeUrl.cs | 284 | 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 Microsoft.CodeAnalysis.Navigation;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Language.CallHierarchy;
namespace Microsoft.CodeAnalysis.Editor.Implementation.CallHierarchy
{
internal class CallHierarchyDetail : ICallHierarchyItemDetails
{
private readonly TextSpan _span;
private readonly DocumentId _documentId;
private readonly Workspace _workspace;
private readonly int _endColumn;
private readonly int _endLine;
private readonly string _sourceFile;
private readonly int _startColumn;
private readonly int _startLine;
private readonly string _text;
public CallHierarchyDetail(Location location, Workspace workspace)
{
_span = location.SourceSpan;
_documentId = workspace.CurrentSolution.GetDocumentId(location.SourceTree);
_workspace = workspace;
_endColumn = location.GetLineSpan().Span.End.Character;
_endLine = location.GetLineSpan().EndLinePosition.Line;
_sourceFile = location.SourceTree.FilePath;
_startColumn = location.GetLineSpan().StartLinePosition.Character;
_startLine = location.GetLineSpan().StartLinePosition.Line;
_text = ComputeText(location);
}
private string ComputeText(Location location)
{
var lineSpan = location.GetLineSpan();
var start = location.SourceTree.GetText().Lines[lineSpan.StartLinePosition.Line].Start;
var end = location.SourceTree.GetText().Lines[lineSpan.EndLinePosition.Line].End;
return location.SourceTree.GetText().GetSubText(TextSpan.FromBounds(start, end)).ToString();
}
public int EndColumn => _endColumn;
public int EndLine => _endLine;
public string File => _sourceFile;
public int StartColumn => _startColumn;
public int StartLine => _startLine;
public bool SupportsNavigateTo => true;
public string Text => _text;
public void NavigateTo()
{
var document = _workspace.CurrentSolution.GetDocument(_documentId);
if (document != null)
{
var navigator = _workspace.Services.GetService<IDocumentNavigationService>();
var options = _workspace.Options.WithChangedOption(NavigationOptions.PreferProvisionalTab, true);
navigator.TryNavigateToSpan(_workspace, document.Id, _span, options);
}
}
}
}
| 38.676056 | 113 | 0.676985 | [
"MIT"
] | BertanAygun/roslyn | src/VisualStudio/Core/Def/Implementation/CallHierarchy/CallHierarchyDetail.cs | 2,748 | C# |
using AvalonStudio.Platforms;
using AvalonStudio.Projects;
using AvalonStudio.Toolchains.GCC;
using AvalonStudio.Utils;
using Mono.Debugging.Client;
using System;
using System.Composition;
using System.IO;
using System.Threading.Tasks;
namespace AvalonStudio.Debugging.GDB.Remote
{
[Shared]
[ExportDebugger]
internal class RemoteGdbDebugger : IDebugger2
{
public string BinDirectory => null;
public DebuggerSession CreateSession(IProject project)
{
if (project.ToolChain is GCCToolchain)
{
return new RemoteGdbSession(project, (project.ToolChain as GCCToolchain).GDBExecutable);
}
throw new Exception("No toolchain");
}
public DebuggerSessionOptions GetDebuggerSessionOptions(IProject project)
{
var evaluationOptions = EvaluationOptions.DefaultOptions.Clone();
evaluationOptions.EllipsizeStrings = false;
evaluationOptions.GroupPrivateMembers = false;
evaluationOptions.EvaluationTimeout = 1000;
return new DebuggerSessionOptions() { EvaluationOptions = evaluationOptions };
}
public DebuggerStartInfo GetDebuggerStartInfo(IProject project)
{
var startInfo = new DebuggerStartInfo()
{
Command = Path.Combine(project.CurrentDirectory, project.Executable).ToPlatformPath(),
Arguments = "",
WorkingDirectory = System.IO.Path.GetDirectoryName(Path.Combine(project.CurrentDirectory, project.Executable)),
UseExternalConsole = false,
RequiresManualStart = true,
CloseExternalConsoleOnExit = true
};
return startInfo;
}
public object GetSettingsControl(IProject project)
{
return new RemoteGdbSettingsFormViewModel(project);
}
public Task<bool> InstallAsync(IConsole console, IProject project)
{
return Task.FromResult(true);
}
}
}
| 31.469697 | 127 | 0.646606 | [
"MIT"
] | dorisoy/AvalonStudio | AvalonStudio/AvalonStudio.Debugging.GDB.Remote/RemoteGdbDebugger.cs | 2,079 | C# |
using Chloe.DbExpressions;
using Chloe.Utility;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
namespace Chloe.Query
{
public class ResultElement
{
public ResultElement()
{
this.Orderings = new List<DbOrdering>();
this.GroupSegments = new List<DbExpression>();
}
public IMappingObjectExpression MappingObjectExpression { get; set; }
public bool OrderingsComeFromSubQuery { get; set; }
public List<DbOrdering> Orderings { get; private set; }
public List<DbExpression> GroupSegments { get; private set; }
/// <summary>
/// 如 takequery 了以后,则 table 的 Expression 类似 (select T.Id.. from User as T),Alias 则为新生成的
/// </summary>
public DbFromTableExpression FromTable { get; set; }
public DbExpression Condition { get; set; }
public DbExpression HavingCondition { get; set; }
public void AppendCondition(DbExpression condition)
{
if (this.Condition == null)
this.Condition = condition;
else
this.Condition = new DbAndAlsoExpression(this.Condition, condition);
}
public void AppendHavingCondition(DbExpression condition)
{
if (this.HavingCondition == null)
this.HavingCondition = condition;
else
this.HavingCondition = new DbAndAlsoExpression(this.HavingCondition, condition);
}
public string GenerateUniqueTableAlias(string prefix = UtilConstants.DefaultTableAlias)
{
if (this.FromTable == null)
return prefix;
string alias = prefix;
int i = 0;
DbFromTableExpression fromTable = this.FromTable;
while (ExistTableAlias(fromTable, alias))
{
alias = prefix + i.ToString();
i++;
}
return alias;
}
static bool ExistTableAlias(DbFromTableExpression fromTable, string alias)
{
if (string.Equals(fromTable.Table.Alias, alias, StringComparison.OrdinalIgnoreCase))
return true;
foreach (var item in fromTable.JoinTables)
{
if (ExistTableAlias(item, alias))
return true;
}
return false;
}
static bool ExistTableAlias(DbJoinTableExpression joinTable, string alias)
{
if (string.Equals(joinTable.Table.Alias, alias, StringComparison.OrdinalIgnoreCase))
return true;
foreach (var item in joinTable.JoinTables)
{
if (ExistTableAlias(item, alias))
return true;
}
return false;
}
}
}
| 30.617021 | 96 | 0.578179 | [
"Apache-2.0"
] | kwonganding/Chloe | src/DotNet/Chloe/Query/ResultElement.cs | 2,910 | C# |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using Microsoft.Diagnostics.Runtime;
namespace MS.Dbg
{
[NsContainer( NameProperty = "TargetFriendlyName" )]
[DebuggerDisplay( "DbgKModeTarget: id {DbgEngSystemId}: {TargetFriendlyName}" )]
// public class DbgKModeTarget : DebuggerObject,
// ICanSetContext,
// IEquatable< DbgKModeTarget >,
// IComparable< DbgKModeTarget >
public class DbgKModeTarget : DbgTarget
{
// N.B. This assumes that the current debugger context is what is being represented.
// internal DbgKModeTarget( DbgEngDebugger debugger )
// : this( debugger, debugger.GetCurrentDbgEngContext() )
// {
// }
internal DbgKModeTarget( DbgEngDebugger debugger, DbgEngContext context )
: this( debugger, context, null )
{
}
internal DbgKModeTarget( DbgEngDebugger debugger,
DbgEngContext context,
string targetFriendlyName )
: base( debugger, context, targetFriendlyName )
{
} // end constructor
[NsContainer( "Processes" )]
public IEnumerable< DbgKmProcessInfo > EnumerateProcesses()
{
using( new DbgEngContextSaver( Debugger, Context ) )
{
IEnumerator< DbgKmProcessInfo > iter = null;
bool error = false;
try
{
iter = Debugger.KmEnumerateProcesses().GetEnumerator();
}
catch( DbgProviderException dpe )
{
error = true;
LogManager.Trace( "KmEnumerateProcesses failed (initializing enumeration): {0}",
Util.GetExceptionMessages( dpe ) );
}
if( null != iter )
{
while( iter.MoveNext() )
{
DbgKmProcessInfo kmp = null;
try
{
kmp = iter.Current;
}
catch( DbgProviderException dpe )
{
error = true;
LogManager.Trace( "KmEnumerateProcesses failed: {0}",
Util.GetExceptionMessages( dpe ) );
break;
}
yield return kmp;
}
}
if( !error )
yield break;
//
// We might not have enough memory in the dump to enumerate all processes
// (we might not even have nt!PsActiveProcessHead). In that case, we'll
// just return the one process we (hopefully) know about: the current one.
//
ulong addr = Debugger.GetImplicitProcessDataOffset();
yield return new DbgKmProcessInfo( Debugger, this, addr );
} // end using( DbgEngContextSaver )
} // end EnumerateProcesses()
} // end class DbgKModeTarget
}
| 35.861702 | 100 | 0.489172 | [
"MIT"
] | Bhaskers-Blu-Org2/DbgShell | DbgProvider/public/Debugger/DbgKModeTarget.cs | 3,373 | C# |
using BinaryObjectMapper;
using Microsoft.Build.Locator;
using Microsoft.CodeAnalysis.MSBuild;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Threading.Tasks;
namespace MapperRunner
{
public class CodeGenerationTask
{
public static async Task Main(string[] args)
{
MSBuildLocator.RegisterDefaults();
var workspace = MSBuildWorkspace.Create();
var proj = await workspace.OpenProjectAsync(args[0]);
foreach(var x in workspace.Diagnostics)
{
Debug.WriteLine(x);
}
proj = Mapping.ProcessProject(proj);
if (!workspace.TryApplyChanges(proj.Solution))
{
Debug.Fail("");
};
}
}
}
| 24.939394 | 65 | 0.606318 | [
"MIT"
] | MatricField/BinaryObjectMapper | MapperRunner/CodeGenerationTask.cs | 823 | C# |
using iot.solution.entity.Response;
using iot.solution.model.Repository.Interface;
using iot.solution.service.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace iot.solution.service.Implementation
{
public class ConfigurationService : IConfigurationService
{
private readonly ICompanyRepository _companyRepository;
public ConfigurationService(ICompanyRepository companyRepository)
{
_companyRepository = companyRepository;
}
public ConfgurationResponse GetConfguration(string key)
{
var companyDetail = _companyRepository.GetByUniqueId(r => r.Guid == component.helper.SolutionConfiguration.CompanyId);
ConfgurationResponse confgurationResponse = new ConfgurationResponse();
var setting = component.helper.SolutionConfiguration.Configuration.IOTConnectSettings.Where(s => s.SettingType.Equals(key, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();
if (setting != null && companyDetail != null)
{
confgurationResponse = new ConfgurationResponse()
{
cpId = companyDetail.CpId,
host = setting.Host,
isSecure = setting.IsSecure,
password = setting.Password,
port = setting.Port,
url = setting.Url,
user = setting.User,
vhost = setting.Vhost,
};
}
return confgurationResponse;
}
}
}
| 39.487805 | 196 | 0.631254 | [
"MIT"
] | iotconnect-apps/AppConnect-SmartElevator | iot.solution.service/Implementation/ConfigurationService.cs | 1,621 | C# |
// SPDX-License-Identifier: MIT
// Copyright (C) 2018-present iced project and contributors
using System;
using System.Linq;
namespace Generator.Constants.Encoder {
[TypeGen(TypeGenOrders.NoDeps)]
sealed class OpCodeInfoFlagsType {
OpCodeInfoFlagsType(GenTypes genTypes) {
var type = new ConstantsType(TypeIds.OpCodeInfoFlags, ConstantsTypeFlags.None, null, GetConstants());
genTypes.Add(type);
}
static Constant[] GetConstants() =>
typeof(OpCodeInfoKeywords).GetFields().Where(a => a.IsLiteral).OrderBy(a => a.MetadataToken).
Select(a => new Constant(ConstantKind.String, a.Name, a.GetRawConstantValue() ?? throw new InvalidOperationException())).ToArray();
}
}
| 34.4 | 135 | 0.752907 | [
"MIT"
] | 34736384/iced | src/csharp/Intel/Generator/Constants/Encoder/OpCodeInfoFlagsType.cs | 688 | C# |
using NUnit.Framework;
using System.ComponentModel.DataAnnotations;
using System.Linq;
namespace WhenItsDone.Models.Tests.PaymentTests
{
[TestFixture]
public class PaymentIdTests
{
[Test]
public void Id_ShouldHave_KeyAttribute()
{
var obj = new Payment();
var result = obj.GetType()
.GetProperty("Id")
.GetCustomAttributes(false)
.Where(x => x.GetType() == typeof(KeyAttribute))
.Any();
Assert.IsTrue(result);
}
[TestCase(2)]
[TestCase(7773777)]
public void Id_GetAndSetShould_WorkProperly(int randomNumber)
{
var obj = new Payment();
obj.Id = randomNumber;
Assert.AreEqual(randomNumber, obj.Id);
}
}
}
| 24.5 | 76 | 0.52381 | [
"MIT"
] | army-of-two/when-its-done | WhenItsDone/Tests/LibTests/WhenItsDone.Models.Tests/PaymentTests/PaymentIdTests.cs | 884 | C# |
using System;
using System.Xml.Serialization;
using System.Collections;
using System.Collections.Generic;
using Newtonsoft.Json;
namespace JdSdk.Domain.Service.AfsServiceManagerFacade
{
[Serializable]
public class ReturnCancelResult : JdObject
{
[JsonProperty("resultCode")]
public Nullable<Int32> ResultCode
{
get;
set;
}
[JsonProperty("resultErrorMsg")]
public String ResultErrorMsg
{
get;
set;
}
}
}
| 18.551724 | 54 | 0.598513 | [
"Apache-2.0"
] | starpeng/JdSdk2 | Source/JdSdk/domain/service/AfsServiceManagerFacade/ReturnCancelResult.cs | 544 | C# |
using PNet;
using System;
using System.Collections.Generic;
using System.Numerics;
using System.Text;
namespace PNetR
{
public partial class Room
{
private bool _shutdownQueued = false;
private readonly Dictionary<int, Player> _players = new Dictionary<int, Player>();
public readonly SerializationManager Serializer = new SerializationManager();
public readonly NetworkViewManager NetworkManager;
public readonly SceneViewManager SceneViewManager;
/// <summary>
/// event fired when a Player object is constructing, should be used to return the object used for Player.NetUserData
/// </summary>
public event Func<INetSerializable> ConstructNetData;
/// <summary>
/// unique identifier this room has on the server
/// </summary>
public Guid RoomId { get; internal set; }
/// <summary>
/// connection status to dispatch server
/// </summary>
public ConnectionStatus ServerStatus { get; private set; }
public Server Server { get; internal set; }
public NetworkConfiguration Configuration { get; private set; }
public IEnumerable<Player> Players { get { return _players.Values; } }
public event Action<Player> PlayerAdded;
public event Action<Player> PlayerRemoved;
public event Action ServerStatusChanged;
private readonly ARoomServer _roomServer;
private readonly ADispatchClient _dispatchClient;
public Room(NetworkConfiguration configuration, ARoomServer roomServer, ADispatchClient dispatchClient)
{
_roomServer = roomServer;
_roomServer.Room = this;
_dispatchClient = dispatchClient;
_dispatchClient.Room = this;
NetworkManager = new NetworkViewManager(this);
SceneViewManager = new SceneViewManager(this);
_players[0] = Player.Server;
NetComponentHelper.FindNetComponents();
Configuration = configuration;
_roomServer.Setup();
_dispatchClient.Setup();
PlayerRemoved += OnPlayerRemoved;
}
/// <summary>
/// start the server's networking.
/// </summary>
public void StartConnection()
{
_roomServer.Start();
_dispatchClient.Connect();
}
public void ReadQueue()
{
_roomServer.ReadQueue();
_dispatchClient.ReadQueue();
}
public void Shutdown(string reason = "Shutting down")
{
_shutdownQueued = true;
_dispatchClient.Disconnect(reason);
_roomServer.Shutdown(reason);
}
public Player GetPlayer(int id)
{
_players.TryGetValue(id, out var player);
return player;
}
private void OnPlayerRemoved(Player player)
{
foreach (var view in NetworkManager.AllViews)
{
if (view == null)
continue;
if (view.Owner == player)
view.Owner = player.CopyInvalid();
view.OnPlayerLeftRoom(player);
}
CleanupInvalidNetworkViewOwners();
}
void CleanupInvalidNetworkViewOwners()
{
foreach (var view in NetworkManager.AllViews)
{
if (view == null || !view.Owner.IsValid || _players.ContainsValue(view.Owner)) continue;
view.Owner = view.Owner.CopyInvalid();
}
}
/// <summary>
/// Instantiate a network view over the network, as the specified resource
/// </summary>
/// <param name="resource">path to the resource to instantiate</param>
/// <param name="position">starting position</param>
/// <param name="rotation">starting rotation</param>
/// <param name="owner">The owner of the networkview. Null is server.</param>
/// <param name="visCheck">subscribed to NetworkView.CheckVisibility</param>
/// <returns></returns>
public NetworkView Instantiate(string resource, Vector3 position, Vector3 rotation, Player owner = null, Func<Player, bool> visCheck = null)
{
CleanupInvalidNetworkViewOwners();
if (owner == null)
owner = Player.Server;
else if (!_players.ContainsValue(owner))
{
throw new ArgumentException("specified player is no longer connected!", "owner");
}
if (resource == null)
throw new ArgumentNullException("resource");
var view = NetworkManager.GetNew(owner);
view.CheckVisibility += visCheck;
view.Resource = resource;
var msg = ConstructInstMessage(view, position, rotation);
//rebuildvis causes msg to be recycled. need to clone it first.
var omsg = new NetMessage();
msg.Clone(omsg);
view.RebuildVisibility(msg);
//rebuild visiblity skips the owner.
if (owner.IsValid)
owner.SendMessage(omsg, ReliabilityMode.Ordered);
return view;
}
internal NetMessage ConstructInstMessage(NetworkView view, Vector3 position, Vector3 rotation)
{
var msg = RoomGetMessage(view.Resource.Length * 2 + 34);
msg.Write(RpcUtils.GetHeader(ReliabilityMode.Ordered, BroadcastMode.All, MsgType.Internal));
msg.Write(RandPRpcs.Instantiate);
msg.Write(view.Id.Id);
msg.Write(view.Owner.Id);
msg.Write(view.Resource);
msg.Write(position.X);
msg.Write(position.Y);
msg.Write(position.Z);
msg.Write(rotation.X);
msg.Write(rotation.Y);
msg.Write(rotation.Z);
return msg;
}
/// <summary>
/// Destroy view over the network
/// </summary>
/// <param name="view"></param>
/// <returns></returns>
public bool Destroy(NetworkView view, byte reasonCode = 0)
{
if (!NetworkManager.Contains(view))
return false;
view.Destroy();
NetworkManager.Remove(view);
var msg = GetDestroyMessage(view, RandPRpcs.Destroy, reasonCode);
SendToPlayers(msg, ReliabilityMode.Ordered);
return true;
}
internal NetMessage GetDestroyMessage(NetworkView view, byte destType, byte reasonCode = 0)
{
var msg = RoomGetMessage(6);
msg.Write(RpcUtils.GetHeader(ReliabilityMode.Ordered, BroadcastMode.All, MsgType.Internal));
msg.Write(destType);
msg.Write(view.Id.Id);
if (reasonCode != 0)
msg.Write(reasonCode);
return msg;
}
internal NetMessage RoomGetMessage(int size)
{
return _roomServer.GetMessage(size);
}
internal NetMessage ServerGetMessage(int size)
{
return _dispatchClient.GetMessage(size);
}
internal void UpdateDispatchConnectionStatus(ConnectionStatus status)
{
ServerStatus = status;
ServerStatusChanged.Raise();
}
internal void SendToDispatcher(NetMessage msg, ReliabilityMode mode)
{
_dispatchClient.SendMessage(msg, mode);
}
public string GetWholeState()
{
var sb = new StringBuilder();
sb.AppendFormat("Room {0}", RoomId).AppendLine();
sb.AppendLine("Players:");
foreach (var player in Players)
{
if (player == null) continue;
sb.AppendFormat(" player: id {0}, {1} - {2}", player.Id, player.UserData, player.NetUserData).AppendLine();
}
sb.AppendLine("Network views:");
foreach (var view in NetworkManager.AllViews)
{
if (view == null) continue;
sb.AppendFormat(" view: id {0} owner {1} - {2} resource {3}", view.Id.Id, view.Owner.Id, view.Owner.NetUserData, view.Resource).AppendLine();
}
return sb.ToString();
}
}
} | 34.783333 | 158 | 0.577264 | [
"MIT"
] | Ignis34Rus/LoE-Ghost.Server | libs/PNet2Room/Room/Room.cs | 8,350 | C# |
using System.Threading.Tasks;
using Mal.DocGen2.Services.Markdown;
namespace Mal.DocGen2.Services.XmlDocs
{
class TypeRefSpan : Span
{
public TypeRefSpan(string textValue) : base(textValue)
{ }
public override async Task WriteMarkdown(XmlDocWriteContext context, MarkdownWriter writer)
{
await writer.WriteAsync(" ");
var entry = context.ResolveReference(TextValue);
if (entry.Key == null)
await writer.WriteAsync(entry.Value ?? TextValue);
else
await writer.WriteAsync(MarkdownInline.HRef(entry.Value, entry.Key));
await writer.WriteAsync(" ");
}
}
} | 31.727273 | 99 | 0.620344 | [
"MIT"
] | ArcaneEye/MDK-SE | Source/DocGen2/Services/XmlDocs/TypeRefSpan.cs | 700 | C# |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading.Tasks;
using System.Windows.Input;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Storage;
using Windows.Storage.Pickers;
using Windows.UI;
using Windows.UI.Core;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using MyAlbum.ViewModels;
using MyAlbum.ContentDialogs;
using MyAlbum.Converters;
using System.Reflection;
using System.Text;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
namespace MyAlbum.Pages
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class AlbumPage : Page
{
public AlbumPage()
{
InitializeComponent();
}
public AlbumViewModel AlbumViewModel { get; set; }
protected override void OnNavigatedTo(NavigationEventArgs e)
{
AlbumViewModel = e.Parameter as AlbumViewModel;
DataContext = AlbumViewModel;
BindPhotoPropertyToValidationMessageConverter();
base.OnNavigatedTo(e);
}
private void BindPhotoPropertyToValidationMessageConverter()
{
object converter;
if (Resources.TryGetValue("PhotoPropertyToValidationMessageConverter", out converter))
{
BindingOperations.SetBinding(
converter as PropertyToValidationMessageConverter,
PropertyToValidationMessageConverter.ValidatorProperty,
new Binding
{
Source = AlbumViewModel,
Path = new PropertyPath(nameof(AlbumViewModel.ManipulatedPhoto))
});
}
}
private void Page_Loaded(object sender, RoutedEventArgs e)
{
AlbumViewModel?.SelectedPhotos?.ForEach(p =>
{
if (p.IsSelected ?? false)
photosGridView.SelectedItems.Add(p);
});
}
}
}
| 31.7 | 99 | 0.633675 | [
"MIT"
] | Avi-Meshulam/MyAlbum | MyAlbum/Pages/AlbumPage.xaml.cs | 2,538 | C# |
using System.Linq;
using Microsoft.EntityFrameworkCore;
using Abp.Authorization;
using Abp.Authorization.Roles;
using Abp.Authorization.Users;
using Abp.MultiTenancy;
using MyCompany.Authorization;
using MyCompany.Authorization.Roles;
using MyCompany.Authorization.Users;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Options;
namespace MyCompany.EntityFrameworkCore.Seed.Host
{
public class HostRoleAndUserCreator
{
private readonly MyCompanyDbContext _context;
public HostRoleAndUserCreator(MyCompanyDbContext context)
{
_context = context;
}
public void Create()
{
CreateHostRoleAndUsers();
}
private void CreateHostRoleAndUsers()
{
// Admin role for host
var adminRoleForHost = _context.Roles.IgnoreQueryFilters().FirstOrDefault(r => r.TenantId == null && r.Name == StaticRoleNames.Host.Admin);
if (adminRoleForHost == null)
{
adminRoleForHost = _context.Roles.Add(new Role(null, StaticRoleNames.Host.Admin, StaticRoleNames.Host.Admin) { IsStatic = true, IsDefault = true }).Entity;
_context.SaveChanges();
}
// Grant all permissions to admin role for host
var grantedPermissions = _context.Permissions.IgnoreQueryFilters()
.OfType<RolePermissionSetting>()
.Where(p => p.TenantId == null && p.RoleId == adminRoleForHost.Id)
.Select(p => p.Name)
.ToList();
var permissions = PermissionFinder
.GetAllPermissions(new MyCompanyAuthorizationProvider())
.Where(p => p.MultiTenancySides.HasFlag(MultiTenancySides.Host) &&
!grantedPermissions.Contains(p.Name))
.ToList();
if (permissions.Any())
{
_context.Permissions.AddRange(
permissions.Select(permission => new RolePermissionSetting
{
TenantId = null,
Name = permission.Name,
IsGranted = true,
RoleId = adminRoleForHost.Id
})
);
_context.SaveChanges();
}
// Admin user for host
var adminUserForHost = _context.Users.IgnoreQueryFilters().FirstOrDefault(u => u.TenantId == null && u.UserName == AbpUserBase.AdminUserName);
if (adminUserForHost == null)
{
var user = new User
{
TenantId = null,
UserName = AbpUserBase.AdminUserName,
Name = "admin",
Surname = "admin",
EmailAddress = "admin@aspnetboilerplate.com",
IsEmailConfirmed = true,
IsActive = true
};
user.Password = new PasswordHasher<User>(new OptionsWrapper<PasswordHasherOptions>(new PasswordHasherOptions())).HashPassword(user, "123qwe");
user.SetNormalizedNames();
adminUserForHost = _context.Users.Add(user).Entity;
_context.SaveChanges();
// Assign Admin role to admin user
_context.UserRoles.Add(new UserRole(null, adminUserForHost.Id, adminRoleForHost.Id));
_context.SaveChanges();
_context.SaveChanges();
}
}
}
}
| 35.969697 | 171 | 0.562763 | [
"MIT"
] | StefanKoenen/aspnetboilerplate-5844 | aspnet-core/src/MyCompany.EntityFrameworkCore/EntityFrameworkCore/Seed/Host/HostRoleAndUserCreator.cs | 3,561 | C# |
/*
* Copyright (c) 2019-2021 Angouri.
* AngouriMath is licensed under MIT.
* Details: https://github.com/asc-community/AngouriMath/blob/master/LICENSE.md.
* Website: https://am.angouri.org.
*/
using static AngouriMath.Entity;
using static AngouriMath.Entity.Number;
namespace AngouriMath.Functions
{
partial class Patterns
{
/// <summary>a ^ (-1) => 1 / a</summary>
internal static Entity InvertNegativePowers(Entity expr) =>
expr is Powf(var @base, Integer { IsNegative: true } pow)
? 1 / MathS.Pow(@base, -1 * pow)
: expr;
/// <summary>1 + (-x) => 1 - x</summary>
internal static Entity InvertNegativeMultipliers(Entity expr) =>
expr is Sumf(var any1, Mulf(Real { IsNegative: true } const1, var any2))
? any1 - (-1 * const1) * any2
: expr;
internal static Entity PowerRules(Entity x) => x switch
{
// {} / {} = 1
Divf(var any1, var any1a) when any1 == any1a => 1,
// {1}^({2} / log({3}, {1})) = {3}^{2}
Powf(var any1, Divf(var any2, Logf(var any3, var any1a))) when any1 == any1a => new Powf(any3, any2),
// {} ^ n * {}
Mulf(Powf(var any1, var any2), var any1a) when any1 == any1a => new Powf(any1, any2 + 1),
Mulf(var any1, Powf(var any1a, var any2)) when any1 == any1a => new Powf(any1, any2 + 1),
// {} ^ n * {} ^ m = {} ^ (n + m)
Mulf(Powf(var any1, var any2), Powf(var any1a, var any3)) when any1 == any1a => new Powf(any1, any2 + any3),
// {} ^ n / {} ^ m = {} ^ (n - m)
Divf(Powf(var any1, var any2), Powf(var any1a, var any3)) when any1 == any1a => new Powf(any1, any2 - any3),
// ({} ^ {}) ^ {} = {} ^ ({} * {})
Powf(Powf(var any1, var any2), var any3) => new Powf(any1, any2 * any3),
// {1} ^ n * {2} ^ n = ({1} * {2}) ^ n
Mulf(Powf(var any1, var any3), Powf(var any2, var any3a)) when any3 == any3a => new Powf(any1 * any2, any3),
Divf(Powf(var any1, var any3), Powf(var any2, var any3a)) when any3 == any3a => new Powf(any1 / any2, any3),
// x / x^n
Divf(var any1, Powf(var any1a, var any2)) when any1 == any1a => new Powf(any1, 1 - any2),
// x^n / x
Divf(Powf(var any1, var any2), var any1a) when any1 == any1a => new Powf(any1, any2 - 1),
// x^n / x^m
Divf(Powf(var any1, var any2), Powf(var any1a, var any3)) when any1 == any1a => new Powf(any1, any2 - any3),
// c ^ log(c, a) = a
Powf(Number const1, Logf(Number const1a, var any1)) when const1 == const1a => any1,
Mulf(Powf(var any1, var any3), Mulf(var any1a, var any2)) when any1 == any1a => new Powf(any1, any3 + 1) * any2,
Mulf(Powf(var any1, var any3), Mulf(var any2, var any1a)) when any1 == any1a => new Powf(any1, any3 + 1) * any2,
Mulf(Mulf(var any1, var any2), Powf(var any1a, var any3)) when any1 == any1a => new Powf(any1, any3 + 1) * any2,
Mulf(Mulf(var any2, var any1), Powf(var any1a, var any3)) when any1 == any1a => new Powf(any1, any3 + 1) * any2,
// (a * x) ^ c = a^c * x^c
Powf(Mulf(Number const1, var any1), Number const2) =>
new Powf(const1, const2) * new Powf(any1, const2),
// {1} ^ (-1) = 1 / {1}
Powf(var any1, Integer(-1)) => 1 / any1,
// (a / {})^b * {} = a^b * {}^(1-b)
Mulf(Powf(Divf(Number const1, var any1), Number const2), var any1a) when any1 == any1a =>
new Powf(const1, const2) * new Powf(any1, 1 - const2),
Mulf(Powf(Divf(Number const1, var any1), Number const2), Powf(var any1a, Number const3))
when any1 == any1a => new Powf(const1, const2) * new Powf(any1, const3 - const2),
// {1} / {2} / {2}
Divf(Divf(var any1, var any2), var any2a) when any2 == any2a =>
any1 / new Powf(any2, 2),
Divf(Divf(var any1, Powf(var any2, var any3)), var any2a) when any2 == any2a =>
any1 / new Powf(any2, any3 + 1),
Divf(Divf(var any1, var any2), Powf(var any2a, var any3)) when any2 == any2a =>
any1 / new Powf(any2, any3 + 1),
Divf(Divf(var any1, Powf(var any2, var any4)), Powf(var any2a, var any3)) when any2 == any2a =>
any1 / new Powf(any2, any3 + any4),
// x * {} ^ {} = {} ^ {} * x
Mulf(Variable var1, Powf(var any1, var any2)) => new Powf(any1, any2) * var1,
Logf(var any1, Powf(var any2, var any3)) => any3 * MathS.Log(any1, any2),
Logf(var any1, var any1a) when any1 == any1a => new Providedf(1, any1 > 0),
Logf(Divf(Integer(1), var any1), Divf(Integer(1), var any2)) => MathS.Log(any1, any2),
Logf(var any1, Divf(Integer(1), var any2)) => -MathS.Log(any1, any2),
Logf(Divf(Integer(1), var any1), var any2) => -MathS.Log(any1, any2),
Sumf(Logf(var any3, var any1), Logf(var any3a, var any2)) when any3 == any3a => any3.Log(any1 * any2),
Minusf(Logf(var any3, var any1), Logf(var any3a, var any2)) when any3 == any3a => any3.Log(any1 / any2),
_ => x
};
}
}
| 50 | 124 | 0.524112 | [
"MIT"
] | KuhakuPixel/AngouriMath | Sources/AngouriMath/Functions/Simplification/Patterns/Patterns.Power.cs | 5,352 | C# |
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Fortnox.SDK.Entities;
// ReSharper disable UnusedMember.Global
namespace Fortnox.SDK.Interfaces
{
/// <remarks/>
public interface IInvoiceFileConnectionConnector : IEntityConnector
{
[Obsolete(ApiConstants.ObsoleteSyncMethodWarning)]
InvoiceFileConnection Update(InvoiceFileConnection invoiceFileConnection);
[Obsolete(ApiConstants.ObsoleteSyncMethodWarning)]
InvoiceFileConnection Create(InvoiceFileConnection invoiceFileConnection);
[Obsolete(ApiConstants.ObsoleteSyncMethodWarning)]
void Delete(string id);
[Obsolete(ApiConstants.ObsoleteSyncMethodWarning)]
IList<InvoiceFileConnection> GetConnections(long? entityId, EntityType? entityType);
Task<InvoiceFileConnection> UpdateAsync(InvoiceFileConnection invoiceFileConnection);
Task<InvoiceFileConnection> CreateAsync(InvoiceFileConnection invoiceFileConnection);
Task DeleteAsync(string id);
Task<IList<InvoiceFileConnection>> GetConnectionsAsync(long? entityId, EntityType? entityType);
}
}
| 42.407407 | 103 | 0.775546 | [
"MIT"
] | FortnoxAB/csharp-api-sdk | FortnoxSDK/Interfaces/IInvoiceFileConnectionConnector.cs | 1,145 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by \generate-code.bat.
//
// Changes to this file will be lost when the code is regenerated.
// The build server regenerates the code before each build and a pre-build
// step will regenerate the code on each local build.
//
// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units.
//
// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities.
// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities.
//
// </auto-generated>
//------------------------------------------------------------------------------
// Licensed under MIT No Attribution, see LICENSE file at the root.
// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet.
using System;
using System.Globalization;
using System.Linq;
using System.Threading;
using UnitsNet.Units;
using Xunit;
// Disable build warning CS1718: Comparison made to same variable; did you mean to compare something else?
#pragma warning disable 1718
// ReSharper disable once CheckNamespace
namespace UnitsNet.Tests
{
/// <summary>
/// Test of HeatTransferCoefficient.
/// </summary>
// ReSharper disable once PartialTypeWithSinglePart
public abstract partial class HeatTransferCoefficientTestsBase
{
protected abstract double BtusPerSquareFootDegreeFahrenheitInOneWattPerSquareMeterKelvin { get; }
protected abstract double WattsPerSquareMeterCelsiusInOneWattPerSquareMeterKelvin { get; }
protected abstract double WattsPerSquareMeterKelvinInOneWattPerSquareMeterKelvin { get; }
// ReSharper disable VirtualMemberNeverOverriden.Global
protected virtual double BtusPerSquareFootDegreeFahrenheitTolerance { get { return 1e-5; } }
protected virtual double WattsPerSquareMeterCelsiusTolerance { get { return 1e-5; } }
protected virtual double WattsPerSquareMeterKelvinTolerance { get { return 1e-5; } }
// ReSharper restore VirtualMemberNeverOverriden.Global
[Fact]
public void Ctor_WithUndefinedUnit_ThrowsArgumentException()
{
Assert.Throws<ArgumentException>(() => new HeatTransferCoefficient((double)0.0, HeatTransferCoefficientUnit.Undefined));
}
[Fact]
public void DefaultCtor_ReturnsQuantityWithZeroValueAndBaseUnit()
{
var quantity = new HeatTransferCoefficient();
Assert.Equal(0, quantity.Value);
Assert.Equal(HeatTransferCoefficientUnit.WattPerSquareMeterKelvin, quantity.Unit);
}
[Fact]
public void Ctor_WithInfinityValue_ThrowsArgumentException()
{
Assert.Throws<ArgumentException>(() => new HeatTransferCoefficient(double.PositiveInfinity, HeatTransferCoefficientUnit.WattPerSquareMeterKelvin));
Assert.Throws<ArgumentException>(() => new HeatTransferCoefficient(double.NegativeInfinity, HeatTransferCoefficientUnit.WattPerSquareMeterKelvin));
}
[Fact]
public void Ctor_WithNaNValue_ThrowsArgumentException()
{
Assert.Throws<ArgumentException>(() => new HeatTransferCoefficient(double.NaN, HeatTransferCoefficientUnit.WattPerSquareMeterKelvin));
}
[Fact]
public void Ctor_NullAsUnitSystem_ThrowsArgumentNullException()
{
Assert.Throws<ArgumentNullException>(() => new HeatTransferCoefficient(value: 1.0, unitSystem: null));
}
[Fact]
public void HeatTransferCoefficient_QuantityInfo_ReturnsQuantityInfoDescribingQuantity()
{
var quantity = new HeatTransferCoefficient(1, HeatTransferCoefficientUnit.WattPerSquareMeterKelvin);
QuantityInfo<HeatTransferCoefficientUnit> quantityInfo = quantity.QuantityInfo;
Assert.Equal(HeatTransferCoefficient.Zero, quantityInfo.Zero);
Assert.Equal("HeatTransferCoefficient", quantityInfo.Name);
Assert.Equal(QuantityType.HeatTransferCoefficient, quantityInfo.QuantityType);
var units = EnumUtils.GetEnumValues<HeatTransferCoefficientUnit>().Except(new[] {HeatTransferCoefficientUnit.Undefined}).ToArray();
var unitNames = units.Select(x => x.ToString());
// Obsolete members
#pragma warning disable 618
Assert.Equal(units, quantityInfo.Units);
Assert.Equal(unitNames, quantityInfo.UnitNames);
#pragma warning restore 618
}
[Fact]
public void WattPerSquareMeterKelvinToHeatTransferCoefficientUnits()
{
HeatTransferCoefficient wattpersquaremeterkelvin = HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(1);
AssertEx.EqualTolerance(BtusPerSquareFootDegreeFahrenheitInOneWattPerSquareMeterKelvin, wattpersquaremeterkelvin.BtusPerSquareFootDegreeFahrenheit, BtusPerSquareFootDegreeFahrenheitTolerance);
AssertEx.EqualTolerance(WattsPerSquareMeterCelsiusInOneWattPerSquareMeterKelvin, wattpersquaremeterkelvin.WattsPerSquareMeterCelsius, WattsPerSquareMeterCelsiusTolerance);
AssertEx.EqualTolerance(WattsPerSquareMeterKelvinInOneWattPerSquareMeterKelvin, wattpersquaremeterkelvin.WattsPerSquareMeterKelvin, WattsPerSquareMeterKelvinTolerance);
}
[Fact]
public void From_ValueAndUnit_ReturnsQuantityWithSameValueAndUnit()
{
var quantity00 = HeatTransferCoefficient.From(1, HeatTransferCoefficientUnit.BtuPerSquareFootDegreeFahrenheit);
AssertEx.EqualTolerance(1, quantity00.BtusPerSquareFootDegreeFahrenheit, BtusPerSquareFootDegreeFahrenheitTolerance);
Assert.Equal(HeatTransferCoefficientUnit.BtuPerSquareFootDegreeFahrenheit, quantity00.Unit);
var quantity01 = HeatTransferCoefficient.From(1, HeatTransferCoefficientUnit.WattPerSquareMeterCelsius);
AssertEx.EqualTolerance(1, quantity01.WattsPerSquareMeterCelsius, WattsPerSquareMeterCelsiusTolerance);
Assert.Equal(HeatTransferCoefficientUnit.WattPerSquareMeterCelsius, quantity01.Unit);
var quantity02 = HeatTransferCoefficient.From(1, HeatTransferCoefficientUnit.WattPerSquareMeterKelvin);
AssertEx.EqualTolerance(1, quantity02.WattsPerSquareMeterKelvin, WattsPerSquareMeterKelvinTolerance);
Assert.Equal(HeatTransferCoefficientUnit.WattPerSquareMeterKelvin, quantity02.Unit);
}
[Fact]
public void FromWattsPerSquareMeterKelvin_WithInfinityValue_ThrowsArgumentException()
{
Assert.Throws<ArgumentException>(() => HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(double.PositiveInfinity));
Assert.Throws<ArgumentException>(() => HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(double.NegativeInfinity));
}
[Fact]
public void FromWattsPerSquareMeterKelvin_WithNanValue_ThrowsArgumentException()
{
Assert.Throws<ArgumentException>(() => HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(double.NaN));
}
[Fact]
public void As()
{
var wattpersquaremeterkelvin = HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(1);
AssertEx.EqualTolerance(BtusPerSquareFootDegreeFahrenheitInOneWattPerSquareMeterKelvin, wattpersquaremeterkelvin.As(HeatTransferCoefficientUnit.BtuPerSquareFootDegreeFahrenheit), BtusPerSquareFootDegreeFahrenheitTolerance);
AssertEx.EqualTolerance(WattsPerSquareMeterCelsiusInOneWattPerSquareMeterKelvin, wattpersquaremeterkelvin.As(HeatTransferCoefficientUnit.WattPerSquareMeterCelsius), WattsPerSquareMeterCelsiusTolerance);
AssertEx.EqualTolerance(WattsPerSquareMeterKelvinInOneWattPerSquareMeterKelvin, wattpersquaremeterkelvin.As(HeatTransferCoefficientUnit.WattPerSquareMeterKelvin), WattsPerSquareMeterKelvinTolerance);
}
[Fact]
public void ToUnit()
{
var wattpersquaremeterkelvin = HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(1);
var btupersquarefootdegreefahrenheitQuantity = wattpersquaremeterkelvin.ToUnit(HeatTransferCoefficientUnit.BtuPerSquareFootDegreeFahrenheit);
AssertEx.EqualTolerance(BtusPerSquareFootDegreeFahrenheitInOneWattPerSquareMeterKelvin, (double)btupersquarefootdegreefahrenheitQuantity.Value, BtusPerSquareFootDegreeFahrenheitTolerance);
Assert.Equal(HeatTransferCoefficientUnit.BtuPerSquareFootDegreeFahrenheit, btupersquarefootdegreefahrenheitQuantity.Unit);
var wattpersquaremetercelsiusQuantity = wattpersquaremeterkelvin.ToUnit(HeatTransferCoefficientUnit.WattPerSquareMeterCelsius);
AssertEx.EqualTolerance(WattsPerSquareMeterCelsiusInOneWattPerSquareMeterKelvin, (double)wattpersquaremetercelsiusQuantity.Value, WattsPerSquareMeterCelsiusTolerance);
Assert.Equal(HeatTransferCoefficientUnit.WattPerSquareMeterCelsius, wattpersquaremetercelsiusQuantity.Unit);
var wattpersquaremeterkelvinQuantity = wattpersquaremeterkelvin.ToUnit(HeatTransferCoefficientUnit.WattPerSquareMeterKelvin);
AssertEx.EqualTolerance(WattsPerSquareMeterKelvinInOneWattPerSquareMeterKelvin, (double)wattpersquaremeterkelvinQuantity.Value, WattsPerSquareMeterKelvinTolerance);
Assert.Equal(HeatTransferCoefficientUnit.WattPerSquareMeterKelvin, wattpersquaremeterkelvinQuantity.Unit);
}
[Fact]
public void ConversionRoundTrip()
{
HeatTransferCoefficient wattpersquaremeterkelvin = HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(1);
AssertEx.EqualTolerance(1, HeatTransferCoefficient.FromBtusPerSquareFootDegreeFahrenheit(wattpersquaremeterkelvin.BtusPerSquareFootDegreeFahrenheit).WattsPerSquareMeterKelvin, BtusPerSquareFootDegreeFahrenheitTolerance);
AssertEx.EqualTolerance(1, HeatTransferCoefficient.FromWattsPerSquareMeterCelsius(wattpersquaremeterkelvin.WattsPerSquareMeterCelsius).WattsPerSquareMeterKelvin, WattsPerSquareMeterCelsiusTolerance);
AssertEx.EqualTolerance(1, HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(wattpersquaremeterkelvin.WattsPerSquareMeterKelvin).WattsPerSquareMeterKelvin, WattsPerSquareMeterKelvinTolerance);
}
[Fact]
public void ArithmeticOperators()
{
HeatTransferCoefficient v = HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(1);
AssertEx.EqualTolerance(-1, -v.WattsPerSquareMeterKelvin, WattsPerSquareMeterKelvinTolerance);
AssertEx.EqualTolerance(2, (HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(3)-v).WattsPerSquareMeterKelvin, WattsPerSquareMeterKelvinTolerance);
AssertEx.EqualTolerance(2, (v + v).WattsPerSquareMeterKelvin, WattsPerSquareMeterKelvinTolerance);
AssertEx.EqualTolerance(10, (v*10).WattsPerSquareMeterKelvin, WattsPerSquareMeterKelvinTolerance);
AssertEx.EqualTolerance(10, (10*v).WattsPerSquareMeterKelvin, WattsPerSquareMeterKelvinTolerance);
AssertEx.EqualTolerance(2, (HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(10)/5).WattsPerSquareMeterKelvin, WattsPerSquareMeterKelvinTolerance);
AssertEx.EqualTolerance(2, HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(10)/HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(5), WattsPerSquareMeterKelvinTolerance);
}
[Fact]
public void ComparisonOperators()
{
HeatTransferCoefficient oneWattPerSquareMeterKelvin = HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(1);
HeatTransferCoefficient twoWattsPerSquareMeterKelvin = HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(2);
Assert.True(oneWattPerSquareMeterKelvin < twoWattsPerSquareMeterKelvin);
Assert.True(oneWattPerSquareMeterKelvin <= twoWattsPerSquareMeterKelvin);
Assert.True(twoWattsPerSquareMeterKelvin > oneWattPerSquareMeterKelvin);
Assert.True(twoWattsPerSquareMeterKelvin >= oneWattPerSquareMeterKelvin);
Assert.False(oneWattPerSquareMeterKelvin > twoWattsPerSquareMeterKelvin);
Assert.False(oneWattPerSquareMeterKelvin >= twoWattsPerSquareMeterKelvin);
Assert.False(twoWattsPerSquareMeterKelvin < oneWattPerSquareMeterKelvin);
Assert.False(twoWattsPerSquareMeterKelvin <= oneWattPerSquareMeterKelvin);
}
[Fact]
public void CompareToIsImplemented()
{
HeatTransferCoefficient wattpersquaremeterkelvin = HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(1);
Assert.Equal(0, wattpersquaremeterkelvin.CompareTo(wattpersquaremeterkelvin));
Assert.True(wattpersquaremeterkelvin.CompareTo(HeatTransferCoefficient.Zero) > 0);
Assert.True(HeatTransferCoefficient.Zero.CompareTo(wattpersquaremeterkelvin) < 0);
}
[Fact]
public void CompareToThrowsOnTypeMismatch()
{
HeatTransferCoefficient wattpersquaremeterkelvin = HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(1);
Assert.Throws<ArgumentException>(() => wattpersquaremeterkelvin.CompareTo(new object()));
}
[Fact]
public void CompareToThrowsOnNull()
{
HeatTransferCoefficient wattpersquaremeterkelvin = HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(1);
Assert.Throws<ArgumentNullException>(() => wattpersquaremeterkelvin.CompareTo(null));
}
[Fact]
public void EqualityOperators()
{
var a = HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(1);
var b = HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(2);
// ReSharper disable EqualExpressionComparison
Assert.True(a == a);
Assert.False(a != a);
Assert.True(a != b);
Assert.False(a == b);
Assert.False(a == null);
Assert.False(null == a);
// ReSharper restore EqualExpressionComparison
}
[Fact]
public void EqualsIsImplemented()
{
var a = HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(1);
var b = HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(2);
Assert.True(a.Equals(a));
Assert.False(a.Equals(b));
Assert.False(a.Equals(null));
}
[Fact]
public void EqualsRelativeToleranceIsImplemented()
{
var v = HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(1);
Assert.True(v.Equals(HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(1), WattsPerSquareMeterKelvinTolerance, ComparisonType.Relative));
Assert.False(v.Equals(HeatTransferCoefficient.Zero, WattsPerSquareMeterKelvinTolerance, ComparisonType.Relative));
}
[Fact]
public void EqualsReturnsFalseOnTypeMismatch()
{
HeatTransferCoefficient wattpersquaremeterkelvin = HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(1);
Assert.False(wattpersquaremeterkelvin.Equals(new object()));
}
[Fact]
public void EqualsReturnsFalseOnNull()
{
HeatTransferCoefficient wattpersquaremeterkelvin = HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(1);
Assert.False(wattpersquaremeterkelvin.Equals(null));
}
[Fact]
public void UnitsDoesNotContainUndefined()
{
Assert.DoesNotContain(HeatTransferCoefficientUnit.Undefined, HeatTransferCoefficient.Units);
}
[Fact]
public void HasAtLeastOneAbbreviationSpecified()
{
var units = Enum.GetValues(typeof(HeatTransferCoefficientUnit)).Cast<HeatTransferCoefficientUnit>();
foreach(var unit in units)
{
if(unit == HeatTransferCoefficientUnit.Undefined)
continue;
var defaultAbbreviation = UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit);
}
}
[Fact]
public void BaseDimensionsShouldNeverBeNull()
{
Assert.False(HeatTransferCoefficient.BaseDimensions is null);
}
[Fact]
public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture()
{
var prevCulture = Thread.CurrentThread.CurrentUICulture;
Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US");
try {
Assert.Equal("1 Btu/ft²·hr·°F", new HeatTransferCoefficient(1, HeatTransferCoefficientUnit.BtuPerSquareFootDegreeFahrenheit).ToString());
Assert.Equal("1 W/m²·°C", new HeatTransferCoefficient(1, HeatTransferCoefficientUnit.WattPerSquareMeterCelsius).ToString());
Assert.Equal("1 W/m²·K", new HeatTransferCoefficient(1, HeatTransferCoefficientUnit.WattPerSquareMeterKelvin).ToString());
}
finally
{
Thread.CurrentThread.CurrentUICulture = prevCulture;
}
}
[Fact]
public void ToString_WithSwedishCulture_ReturnsUnitAbbreviationForEnglishCultureSinceThereAreNoMappings()
{
// Chose this culture, because we don't currently have any abbreviations mapped for that culture and we expect the en-US to be used as fallback.
var swedishCulture = CultureInfo.GetCultureInfo("sv-SE");
Assert.Equal("1 Btu/ft²·hr·°F", new HeatTransferCoefficient(1, HeatTransferCoefficientUnit.BtuPerSquareFootDegreeFahrenheit).ToString(swedishCulture));
Assert.Equal("1 W/m²·°C", new HeatTransferCoefficient(1, HeatTransferCoefficientUnit.WattPerSquareMeterCelsius).ToString(swedishCulture));
Assert.Equal("1 W/m²·K", new HeatTransferCoefficient(1, HeatTransferCoefficientUnit.WattPerSquareMeterKelvin).ToString(swedishCulture));
}
[Fact]
public void ToString_SFormat_FormatsNumberWithGivenDigitsAfterRadixForCurrentCulture()
{
var oldCulture = CultureInfo.CurrentUICulture;
try
{
CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture;
Assert.Equal("0.1 W/m²·K", new HeatTransferCoefficient(0.123456, HeatTransferCoefficientUnit.WattPerSquareMeterKelvin).ToString("s1"));
Assert.Equal("0.12 W/m²·K", new HeatTransferCoefficient(0.123456, HeatTransferCoefficientUnit.WattPerSquareMeterKelvin).ToString("s2"));
Assert.Equal("0.123 W/m²·K", new HeatTransferCoefficient(0.123456, HeatTransferCoefficientUnit.WattPerSquareMeterKelvin).ToString("s3"));
Assert.Equal("0.1235 W/m²·K", new HeatTransferCoefficient(0.123456, HeatTransferCoefficientUnit.WattPerSquareMeterKelvin).ToString("s4"));
}
finally
{
CultureInfo.CurrentUICulture = oldCulture;
}
}
[Fact]
public void ToString_SFormatAndCulture_FormatsNumberWithGivenDigitsAfterRadixForGivenCulture()
{
var culture = CultureInfo.InvariantCulture;
Assert.Equal("0.1 W/m²·K", new HeatTransferCoefficient(0.123456, HeatTransferCoefficientUnit.WattPerSquareMeterKelvin).ToString("s1", culture));
Assert.Equal("0.12 W/m²·K", new HeatTransferCoefficient(0.123456, HeatTransferCoefficientUnit.WattPerSquareMeterKelvin).ToString("s2", culture));
Assert.Equal("0.123 W/m²·K", new HeatTransferCoefficient(0.123456, HeatTransferCoefficientUnit.WattPerSquareMeterKelvin).ToString("s3", culture));
Assert.Equal("0.1235 W/m²·K", new HeatTransferCoefficient(0.123456, HeatTransferCoefficientUnit.WattPerSquareMeterKelvin).ToString("s4", culture));
}
}
}
| 54.568306 | 235 | 0.72862 | [
"MIT"
] | DInozemtsev/UnitsNet | UnitsNet.Tests/GeneratedCode/TestsBase/HeatTransferCoefficientTestsBase.g.cs | 20,008 | C# |
// Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Symbols
{
public class AnonymousTypesSemanticsTests : CompilingTestBase
{
[Fact()]
public void AnonymousTypeSymbols_Simple()
{
var source = @"
public class ClassA
{
public struct SSS
{
}
public static void Test1(int x)
{
object v1 = [# new
{
[# aa #] = 1,
[# BB #] = """",
[# CCC #] = new SSS()
} #];
object v2 = [# new
{
[# aa #] = new SSS(),
[# BB #] = 123.456,
[# CCC #] = [# new
{
(new ClassA()).[# aa #],
ClassA.[# BB #],
ClassA.[# CCC #]
} #]
} #];
object v3 = [# new {} #];
var v4 = [# new {} #];
}
public int aa
{
get { return 123; }
}
public const string BB = ""-=-=-"";
public static SSS CCC = new SSS();
}";
var data = Compile(source, 14);
var info0 = GetAnonymousTypeInfoSummary(data, 0,
data.Tree.FindNodeOrTokenByKind(SyntaxKind.NewKeyword, 1).Span,
1, 2, 3);
var info1 = GetAnonymousTypeInfoSummary(data, 4,
data.Tree.FindNodeOrTokenByKind(SyntaxKind.NewKeyword, 3).Span,
5, 6, 7);
var info2 = GetAnonymousTypeInfoSummary(data, 8,
data.Tree.FindNodeOrTokenByKind(SyntaxKind.NewKeyword, 5).Span,
9, 10, 11);
Assert.Equal(info0.Type, info2.Type);
Assert.NotEqual(info0.Type, info1.Type);
var info3 = GetAnonymousTypeInfoSummary(data, 12,
data.Tree.FindNodeOrTokenByKind(SyntaxKind.NewKeyword, 7).Span);
var info4 = GetAnonymousTypeInfoSummary(data, 13,
data.Tree.FindNodeOrTokenByKind(SyntaxKind.NewKeyword, 8).Span);
Assert.Equal(info3.Type, info4.Type);
}
[Fact()]
public void AnonymousTypeSymbols_ContextualKeywordsInFields()
{
var source = @"
class ClassA
{
static void Test1(int x)
{
object v1 = [# new
{
[# var #] = ""var"",
[# get #] = new {},
[# partial #] = [# new
{
(new ClassA()).[# select #],
[# global #]
} #]
} #];
}
public int select
{
get { return 123; }
}
public const string global = ""-=-=-"";
}";
var data = Compile(source, 7);
var info0 = GetAnonymousTypeInfoSummary(data, 0,
data.Tree.FindNodeOrTokenByKind(SyntaxKind.NewKeyword, 1).Span,
1, 2, 3);
var info1 = GetAnonymousTypeInfoSummary(data, 4,
data.Tree.FindNodeOrTokenByKind(SyntaxKind.NewKeyword, 3).Span,
5, 6);
Assert.Equal(
"<anonymous type: System.String var, <empty anonymous type> get, <anonymous type: System.Int32 select, System.String global> partial>",
info0.Type.ToTestDisplayString());
Assert.Equal(
"<anonymous type: System.Int32 select, System.String global>..ctor(System.Int32 select, System.String global)",
info1.Symbol.ToTestDisplayString());
}
[Fact()]
public void AnonymousTypeSymbols_DelegateMembers()
{
var source = @"
delegate bool D1();
class ClassA
{
void Main()
{
var at1 = [# new { [# module #] = (D1)(() => false)} #].module();
}
}";
var data = Compile(source, 2);
var info0 = GetAnonymousTypeInfoSummary(data, 0,
data.Tree.FindNodeOrTokenByKind(SyntaxKind.NewKeyword, 1).Span,
1);
Assert.Equal("<anonymous type: D1 module>", info0.Type.ToTestDisplayString());
Assert.Equal("<anonymous type: D1 module>..ctor(D1 module)", info0.Symbol.ToTestDisplayString());
}
[Fact()]
public void AnonymousTypeSymbols_BaseAccessInMembers()
{
var source = @"
delegate bool D1();
class ClassB
{
protected System.Func<int, int> F = x => x;
}
class ClassA: ClassB
{
void Main()
{
var at1 = [# [# new { base.[# F #] } #].F(1) #];
}
}";
var data = Compile(source, 3);
var info0 = GetAnonymousTypeInfoSummary(data, 1,
data.Tree.FindNodeOrTokenByKind(SyntaxKind.NewKeyword, 1).Span,
2);
Assert.Equal("<anonymous type: System.Func<System.Int32, System.Int32> F>", info0.Type.ToTestDisplayString());
var info1 = data.Model.GetSemanticInfoSummary(data.Nodes[0]);
Assert.Equal("System.Int32 System.Func<System.Int32, System.Int32>.Invoke(System.Int32 arg)", info1.Symbol.ToTestDisplayString());
}
[Fact()]
public void AnonymousTypeSymbols_InFieldInitializer()
{
var source = @"
class ClassA
{
private static object F = [# new { [# F123 #] = typeof(ClassA) } #];
}";
var data = Compile(source, 2);
var info0 = GetAnonymousTypeInfoSummary(data, 0,
data.Tree.FindNodeOrTokenByKind(SyntaxKind.NewKeyword, 1).Span,
1);
Assert.Equal("<anonymous type: System.Type F123>", info0.Type.ToTestDisplayString());
}
[Fact()]
public void AnonymousTypeSymbols_Equals()
{
var source = @"
class ClassA
{
static void Test1(int x)
{
bool result = [# new { f1 = 1, f2 = """" }.Equals(new { }) #];
}
}";
var data = Compile(source, 1);
var info = data.Model.GetSemanticInfoSummary(data.Nodes[0]);
var method = info.Symbol;
Assert.NotNull(method);
Assert.Equal(SymbolKind.Method, method.Kind);
Assert.Equal("object.Equals(object)", method.ToDisplayString());
}
[Fact()]
public void AnonymousTypeSymbols_ToString()
{
var source = @"
class ClassA
{
static void Test1(int x)
{
string result = [# new { f1 = 1, f2 = """" }.ToString() #];
}
}";
var data = Compile(source, 1);
var info = data.Model.GetSemanticInfoSummary(data.Nodes[0]);
var method = info.Symbol;
Assert.NotNull(method);
Assert.Equal(SymbolKind.Method, method.Kind);
Assert.Equal("object.ToString()", method.ToDisplayString());
}
[Fact()]
public void AnonymousTypeSymbols_GetHashCode()
{
var source = @"
class ClassA
{
static void Test1(int x)
{
int result = [# new { f1 = 1, f2 = """" }.GetHashCode() #];
}
}";
var data = Compile(source, 1);
var info = data.Model.GetSemanticInfoSummary(data.Nodes[0]);
var method = info.Symbol;
Assert.NotNull(method);
Assert.Equal(SymbolKind.Method, method.Kind);
Assert.Equal("object.GetHashCode()", method.ToDisplayString());
}
[Fact()]
public void AnonymousTypeSymbols_Ctor()
{
var source = @"
class ClassA
{
static void Test1(int x)
{
var result = [# new { f1 = 1, f2 = """" } #];
}
}";
var data = Compile(source, 1);
var info = data.Model.GetSemanticInfoSummary(data.Nodes[0]);
var method = info.Symbol;
Assert.NotNull(method);
Assert.Equal(SymbolKind.Method, method.Kind);
Assert.Equal("<anonymous type: int f1, string f2>..ctor(int, string)", method.ToDisplayString());
Assert.Equal("<anonymous type: System.Int32 f1, System.String f2>..ctor(System.Int32 f1, System.String f2)", method.ToTestDisplayString());
}
[Fact()]
public void AnonymousTypeTemplateCannotConstruct()
{
var source = @"
class ClassA
{
object F = [# new { [# F123 #] = typeof(ClassA) } #];
}";
var data = Compile(source, 2);
var info0 = GetAnonymousTypeInfoSummary(data, 0,
data.Tree.FindNodeOrTokenByKind(SyntaxKind.NewKeyword, 1).Span,
1);
var type = info0.Type;
Assert.Equal("<anonymous type: System.Type F123>", type.ToTestDisplayString());
Assert.True(type.IsDefinition);
AssertCannotConstruct(type);
}
[Fact()]
public void AnonymousTypeTemplateCannotConstruct_Empty()
{
var source = @"
class ClassA
{
object F = [# new { } #];
}";
var data = Compile(source, 1);
var info0 = GetAnonymousTypeInfoSummary(data, 0,
data.Tree.FindNodeOrTokenByKind(SyntaxKind.NewKeyword, 1).Span);
var type = info0.Type;
Assert.Equal("<empty anonymous type>", type.ToTestDisplayString());
Assert.True(type.IsDefinition);
AssertCannotConstruct(type);
}
[Fact()]
public void AnonymousTypeFieldDeclarationIdentifier()
{
var source = @"
class ClassA
{
object F = new { [# F123 #] = typeof(ClassA) };
}";
var data = Compile(source, 1);
var info = data.Model.GetSymbolInfo((ExpressionSyntax)data.Nodes[0]);
Assert.NotNull(info.Symbol);
Assert.Equal(SymbolKind.Property, info.Symbol.Kind);
Assert.Equal("System.Type <anonymous type: System.Type F123>.F123 { get; }", info.Symbol.ToTestDisplayString());
}
[Fact()]
public void AnonymousTypeFieldCreatedInQuery()
{
var source = LINQ + @"
class ClassA
{
void m()
{
var o = from x in new List1<int>(1, 2, 3) select [# new { [# x #], [# y #] = x } #];
}
}";
var data = Compile(source, 3);
var info0 = GetAnonymousTypeInfoSummary(data, 0,
data.Tree.FindNodeOrTokenByKind(SyntaxKind.NewKeyword, NumberOfNewKeywords(LINQ) + 2).Span,
1, 2);
var info1 = data.Model.GetSymbolInfo(((AnonymousObjectMemberDeclaratorSyntax)data.Nodes[1]).Expression);
Assert.NotNull(info1.Symbol);
Assert.Equal(SymbolKind.RangeVariable, info1.Symbol.Kind);
Assert.Equal("x", info1.Symbol.ToDisplayString());
var info2 = data.Model.GetSymbolInfo((ExpressionSyntax)data.Nodes[2]);
Assert.NotNull(info2.Symbol);
Assert.Equal(SymbolKind.Property, info2.Symbol.Kind);
Assert.Equal("System.Int32 <anonymous type: System.Int32 x, System.Int32 y>.y { get; }", info2.Symbol.ToTestDisplayString());
}
[Fact()]
public void AnonymousTypeFieldCreatedInQuery2()
{
var source = LINQ + @"
class ClassA
{
void m()
{
var o = from x in new List1<int>(1, 2, 3) let y = """" select [# new { [# x #], [# y #] } #];
}
}";
var data = Compile(source, 3);
var info0 = GetAnonymousTypeInfoSummary(data, 0,
data.Tree.FindNodeOrTokenByKind(SyntaxKind.NewKeyword, NumberOfNewKeywords(LINQ) + 2).Span,
1, 2);
Assert.Equal("<anonymous type: System.Int32 x, System.String y>", info0.Type.ToTestDisplayString());
var info1 = data.Model.GetSymbolInfo(((AnonymousObjectMemberDeclaratorSyntax)data.Nodes[1]).Expression);
Assert.NotNull(info1.Symbol);
Assert.Equal(SymbolKind.RangeVariable, info1.Symbol.Kind);
Assert.Equal("x", info1.Symbol.ToDisplayString());
var info2 = data.Model.GetSymbolInfo(((AnonymousObjectMemberDeclaratorSyntax)data.Nodes[2]).Expression);
Assert.NotNull(info2.Symbol);
Assert.Equal(SymbolKind.RangeVariable, info2.Symbol.Kind);
Assert.Equal("y", info2.Symbol.ToDisplayString());
}
[Fact()]
public void AnonymousTypeFieldCreatedInLambda()
{
var source = @"
using System;
class ClassA
{
void m()
{
var o = (Action)(() => ( [# new { [# x #] = 1, [# y #] = [# new { } #] } #]).ToString());;
}
}";
var data = Compile(source, 4);
var info0 = GetAnonymousTypeInfoSummary(data, 0,
data.Tree.FindNodeOrTokenByKind(SyntaxKind.NewKeyword, 1).Span,
1, 2);
var info1 = GetAnonymousTypeInfoSummary(data, 3,
data.Tree.FindNodeOrTokenByKind(SyntaxKind.NewKeyword, 2).Span);
Assert.Equal("<anonymous type: System.Int32 x, <empty anonymous type> y>..ctor(System.Int32 x, <empty anonymous type> y)", info0.Symbol.ToTestDisplayString());
}
[Fact()]
public void AnonymousTypeFieldCreatedInLambda2()
{
var source = @"
using System;
class ClassA
{
void m()
{
var o = (Action)
(() =>
((Func<string>) (() => ( [# new { [# x #] = 1, [# y #] = [# new { } #] } #]).ToString())
).Invoke());
}
}";
var data = Compile(source, 4);
var info0 = GetAnonymousTypeInfoSummary(data, 0,
data.Tree.FindNodeOrTokenByKind(SyntaxKind.NewKeyword, 1).Span,
1, 2);
var info1 = GetAnonymousTypeInfoSummary(data, 3,
data.Tree.FindNodeOrTokenByKind(SyntaxKind.NewKeyword, 2).Span);
Assert.Equal("<anonymous type: System.Int32 x, <empty anonymous type> y>..ctor(System.Int32 x, <empty anonymous type> y)", info0.Symbol.ToTestDisplayString());
}
[Fact()]
public void AnonymousTypeSymbols_DontCrashIfNameIsQueriedBeforeEmit()
{
var source = @"
public class ClassA
{
public static void Test1(int x)
{
object v1 = [# new { [# aa #] = 1, [# BB #] = 2 } #];
object v2 = [# new { } #];
}
}";
var data = Compile(source, 4);
var info0 = GetAnonymousTypeInfoSummary(data, 0,
data.Tree.FindNodeOrTokenByKind(SyntaxKind.NewKeyword, 1).Span,
1, 2);
CheckAnonymousType(info0.Type, "", "");
info0 = GetAnonymousTypeInfoSummary(data, 3,
data.Tree.FindNodeOrTokenByKind(SyntaxKind.NewKeyword, 2).Span);
CheckAnonymousType(info0.Type, "", "");
// perform emit
CompileAndVerify(
data.Compilation,
symbolValidator: module => CheckAnonymousTypes(module)
);
}
#region "AnonymousTypeSymbols_DontCrashIfNameIsQueriedBeforeEmit"
private void CheckAnonymousType(ITypeSymbol type, string name, string metadataName)
{
Assert.NotNull(type);
Assert.Equal(name, type.Name);
Assert.Equal(metadataName, type.MetadataName);
}
private void CheckAnonymousTypes(ModuleSymbol module)
{
var ns = module.GlobalNamespace;
Assert.NotNull(ns);
CheckAnonymousType(ns.GetMember<NamedTypeSymbol>("<>f__AnonymousType0"), "<>f__AnonymousType0", "<>f__AnonymousType0`2");
CheckAnonymousType(ns.GetMember<NamedTypeSymbol>("<>f__AnonymousType1"), "<>f__AnonymousType1", "<>f__AnonymousType1");
}
#endregion
[Fact()]
public void AnonymousTypeSymbols_Error_Simple()
{
var source = @"
public class ClassA
{
public static void Test1(int x)
{
object v1 = [# new
{
[# aa #] = xyz,
[# BB #] = """",
[# CCC #] = new SSS()
} #];
object v2 = [# new
{
[# aa #] = new SSS(),
[# BB #] = 123.456,
[# CCC #] = [# new
{
(new ClassA()).[# aa #],
ClassA.[# BB #],
ClassA.[# CCC #]
} #]
} #];
}
}";
var data = Compile(source, 12,
// (8,25): error CS0103: The name 'xyz' does not exist in the current context
// aa = xyz,
Diagnostic(ErrorCode.ERR_NameNotInContext, "xyz").WithArguments("xyz"),
// (10,29): error CS0246: The type or namespace name 'SSS' could not be found (are you missing a using directive or an assembly reference?)
// CCC = new SSS()
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "SSS").WithArguments("SSS"),
// (15,29): error CS0246: The type or namespace name 'SSS' could not be found (are you missing a using directive or an assembly reference?)
// aa = new SSS(),
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "SSS").WithArguments("SSS"),
// (19,35): error CS1061: 'ClassA' does not contain a definition for 'aa' and no extension method 'aa' accepting a first argument of type 'ClassA' could be found (are you missing a using directive or an assembly reference?)
// (new ClassA()). aa ,
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "aa").WithArguments("ClassA", "aa"),
// (20,27): error CS0117: 'ClassA' does not contain a definition for 'BB'
// ClassA. BB ,
Diagnostic(ErrorCode.ERR_NoSuchMember, "BB").WithArguments("ClassA", "BB"),
// (21,27): error CS0117: 'ClassA' does not contain a definition for 'CCC'
// ClassA. CCC
Diagnostic(ErrorCode.ERR_NoSuchMember, "CCC").WithArguments("ClassA", "CCC")
);
var info0 = GetAnonymousTypeInfoSummary(data, 0,
data.Tree.FindNodeOrTokenByKind(SyntaxKind.NewKeyword, 1).Span,
1, 2, 3);
var info1 = GetAnonymousTypeInfoSummary(data, 4,
data.Tree.FindNodeOrTokenByKind(SyntaxKind.NewKeyword, 3).Span,
5, 6, 7);
var info2 = GetAnonymousTypeInfoSummary(data, 8,
data.Tree.FindNodeOrTokenByKind(SyntaxKind.NewKeyword, 5).Span,
9, 10, 11);
Assert.Equal("<anonymous type: ? aa, System.String BB, SSS CCC>", info0.Type.ToTestDisplayString());
Assert.Equal("<anonymous type: SSS aa, System.Double BB, <anonymous type: ? aa, ? BB, ? CCC> CCC>", info1.Type.ToTestDisplayString());
Assert.Equal("<anonymous type: ? aa, ? BB, ? CCC>", info2.Type.ToTestDisplayString());
}
[Fact()]
public void AnonymousTypeSymbols_Error_InUsingStatement()
{
var source = @"
public class ClassA
{
public static void Test1(int x)
{
using (var v1 = [# new { } #])
{
}
}
}";
var data = Compile(source, 1,
// (6,16): error CS1674: '<empty anonymous type>': type used in a using statement must be implicitly convertible to 'System.IDisposable'
// using (var v1 = new { } )
Diagnostic(ErrorCode.ERR_NoConvToIDisp, "var v1 = new { }").WithArguments("<empty anonymous type>")
);
var info0 = GetAnonymousTypeInfoSummary(data, 0,
data.Tree.FindNodeOrTokenByKind(SyntaxKind.NewKeyword, 1).Span);
Assert.Equal("<empty anonymous type>", info0.Type.ToTestDisplayString());
}
[Fact()]
public void AnonymousTypeSymbols_Error_DuplicateName()
{
var source = @"
public class ClassA
{
public static void Test1(int x)
{
object v1 = [# new
{
[# aa #] = 1,
ClassA.[# aa #],
[# bb #] = 1.2
} #];
}
public static string aa = ""-field-aa-"";
}";
var data = Compile(source, 4,
// (9,13): error CS0833: An anonymous type cannot have multiple properties with the same name
// ClassA. aa ,
Diagnostic(ErrorCode.ERR_AnonymousTypeDuplicatePropertyName, "ClassA. aa")
);
var info0 = GetAnonymousTypeInfoSummary(data, 0,
data.Tree.FindNodeOrTokenByKind(SyntaxKind.NewKeyword, 1).Span,
1, /*2,*/ 3);
Assert.Equal("<anonymous type: System.Int32 aa, System.String $1, System.Double bb>", info0.Type.ToTestDisplayString());
var properties = (from m in info0.Type.GetMembers() where m.Kind == SymbolKind.Property select m).ToArray();
Assert.Equal(3, properties.Length);
Assert.Equal("System.Int32 <anonymous type: System.Int32 aa, System.String $1, System.Double bb>.aa { get; }", properties[0].ToTestDisplayString());
Assert.Equal("System.String <anonymous type: System.Int32 aa, System.String $1, System.Double bb>.$1 { get; }", properties[1].ToTestDisplayString());
Assert.Equal("System.Double <anonymous type: System.Int32 aa, System.String $1, System.Double bb>.bb { get; }", properties[2].ToTestDisplayString());
}
[Fact()]
public void AnonymousTypeSymbols_LookupSymbols()
{
var source = @"
public class ClassA
{
public static void Test1(int x)
{
object v1 = [# new
{
[# aa #] = """",
[# abc #] = 123.456
} #];
object v2 = [# new{ } #];
}
}";
var data = Compile(source, 4);
var info0 = GetAnonymousTypeInfoSummary(data, 0,
data.Tree.FindNodeOrTokenByKind(SyntaxKind.NewKeyword, 1).Span,
1, 2);
Assert.Equal("<anonymous type: System.String aa, System.Double abc>", info0.Type.ToTestDisplayString());
var pos = data.Nodes[0].Span.End;
var syms = data.Model.LookupSymbols(pos, container: info0.Type).Select(x => x.ToTestDisplayString()).OrderBy(x => x).ToArray();
Assert.Equal(8, syms.Length);
int index = 0;
Assert.Equal("System.Boolean System.Object.Equals(System.Object obj)", syms[index++]);
Assert.Equal("System.Boolean System.Object.Equals(System.Object objA, System.Object objB)", syms[index++]);
Assert.Equal("System.Boolean System.Object.ReferenceEquals(System.Object objA, System.Object objB)", syms[index++]);
Assert.Equal("System.Double <anonymous type: System.String aa, System.Double abc>.abc { get; }", syms[index++]);
Assert.Equal("System.Int32 System.Object.GetHashCode()", syms[index++]);
Assert.Equal("System.String <anonymous type: System.String aa, System.Double abc>.aa { get; }", syms[index++]);
Assert.Equal("System.String System.Object.ToString()", syms[index++]);
Assert.Equal("System.Type System.Object.GetType()", syms[index++]);
info0 = GetAnonymousTypeInfoSummary(data, 3,
data.Tree.FindNodeOrTokenByKind(SyntaxKind.NewKeyword, 2).Span);
Assert.Equal("<empty anonymous type>", info0.Type.ToTestDisplayString());
pos = data.Nodes[3].Span.End;
syms = data.Model.LookupSymbols(pos, container: info0.Type).Select(x => x.ToTestDisplayString()).OrderBy(x => x).ToArray();
Assert.Equal(6, syms.Length);
index = 0;
Assert.Equal("System.Boolean System.Object.Equals(System.Object obj)", syms[index++]);
Assert.Equal("System.Boolean System.Object.Equals(System.Object objA, System.Object objB)", syms[index++]);
Assert.Equal("System.Boolean System.Object.ReferenceEquals(System.Object objA, System.Object objB)", syms[index++]);
Assert.Equal("System.Int32 System.Object.GetHashCode()", syms[index++]);
Assert.Equal("System.String System.Object.ToString()", syms[index++]);
Assert.Equal("System.Type System.Object.GetType()", syms[index++]);
}
[WorkItem(543189, "DevDiv")]
[Fact()]
public void CheckAnonymousTypeAsConstValue()
{
var source = @"
public class A
{
const int i = /*<bind>*/(new {a = 2}).a/*</bind>*/;
}";
var comp = CreateCompilationWithMscorlib(source);
var tuple = GetBindingNodeAndModel<ExpressionSyntax>(comp);
var info = tuple.Item2.GetSymbolInfo(tuple.Item1);
Assert.NotNull(info.Symbol);
Assert.Equal("<anonymous type: int a>.a", info.Symbol.ToDisplayString());
}
[WorkItem(546416, "DevDiv")]
[Fact()]
public void TestAnonymousTypeInsideGroupBy_Queryable()
{
CompileAndVerify(
@"using System.Linq;
public class Product
{
public int ProductID;
public string ProductName;
public int SupplierID;
}
public class DB
{
public IQueryable<Product> Products;
}
public class Program
{
public static void Main()
{
var db = new DB();
var q0 = db.Products.GroupBy(p => new { Conditional = false ? new { p.ProductID, p.ProductName, p.SupplierID } : new { p.ProductID, p.ProductName, p.SupplierID } }).ToList();
}
}", additionalRefs: new[] { SystemCoreRef }).VerifyDiagnostics();
}
[WorkItem(546416, "DevDiv")]
[Fact()]
public void TestAnonymousTypeInsideGroupBy_Enumerable()
{
CompileAndVerify(
@"using System.Linq;
using System.Collections.Generic;
public class Product
{
public int ProductID;
public string ProductName;
public int SupplierID;
}
public class DB
{
public IEnumerable<Product> Products;
}
public class Program
{
public static void Main()
{
var db = new DB();
var q0 = db.Products.GroupBy(p => new { Conditional = false ? new { p.ProductID, p.ProductName, p.SupplierID } : new { p.ProductID, p.ProductName, p.SupplierID } }).ToList();
}
}", additionalRefs: new[] { SystemCoreRef }).VerifyDiagnostics();
}
[WorkItem(546416, "DevDiv")]
[Fact()]
public void TestAnonymousTypeInsideGroupBy_Enumerable2()
{
CompileAndVerify(
@"using System.Linq;
using System.Collections.Generic;
public class Product
{
public int ProductID;
public int SupplierID;
}
public class DB
{
public IEnumerable<Product> Products;
}
public class Program
{
public static void Main()
{
var db = new DB();
var q0 = db.Products.GroupBy(p => new { Conditional = false ? new { p.ProductID, p.SupplierID } : new { p.ProductID, p.SupplierID } }).ToList();
var q1 = db.Products.GroupBy(p => new { Conditional = false ? new { p.ProductID, p.SupplierID } : new { p.ProductID, p.SupplierID } }).ToList();
}
}", additionalRefs: new[] { SystemCoreRef }).VerifyDiagnostics();
}
#region "Utility methods"
private void AssertCannotConstruct(ISymbol type)
{
var namedType = type as NamedTypeSymbol;
Assert.NotNull(namedType);
var objType = namedType.BaseType;
Assert.NotNull(objType);
Assert.Equal("System.Object", objType.ToTestDisplayString());
TypeSymbol[] args = new TypeSymbol[namedType.Arity];
for (int i = 0; i < namedType.Arity; i++)
{
args[i] = objType;
}
Assert.Throws<InvalidOperationException>(() => namedType.Construct(args));
}
private CompilationUtils.SemanticInfoSummary GetAnonymousTypeInfoSummary(TestData data, int node, TextSpan typeSpan, params int[] fields)
{
var info = data.Model.GetSemanticInfoSummary(data.Nodes[node]);
var type = info.Type;
Assert.True(type.IsAnonymousType);
Assert.False(type.CanBeReferencedByName);
Assert.Equal("System.Object", type.BaseType.ToTestDisplayString());
Assert.Equal(0, type.Interfaces.Length);
Assert.Equal(1, type.Locations.Length);
Assert.Equal(typeSpan, type.Locations[0].SourceSpan);
foreach (int field in fields)
{
CheckFieldNameAndLocation(data, type, data.Nodes[field]);
}
return info;
}
private void CheckFieldNameAndLocation(TestData data, ITypeSymbol type, SyntaxNode identifier)
{
var anonymousType = (NamedTypeSymbol)type;
var current = identifier;
while (current.Span == identifier.Span && !current.IsKind(SyntaxKind.IdentifierName))
{
current = current.ChildNodes().Single();
}
var node = (IdentifierNameSyntax)current;
Assert.NotNull(node);
var span = node.Span;
var fieldName = node.ToString();
var property = anonymousType.GetMember<PropertySymbol>(fieldName);
Assert.NotNull(property);
Assert.Equal(fieldName, property.Name);
Assert.Equal(1, property.Locations.Length);
Assert.Equal(span, property.Locations[0].SourceSpan);
MethodSymbol getter = property.GetMethod;
Assert.NotNull(getter);
Assert.Equal("get_" + fieldName, getter.Name);
}
struct TestData
{
public CSharpCompilation Compilation;
public SyntaxTree Tree;
public List<SyntaxNode> Nodes;
public SemanticModel Model;
}
private TestData Compile(string source, int expectedIntervals, params DiagnosticDescription[] diagnostics)
{
var intervals = ExtractTextIntervals(ref source);
Assert.Equal(expectedIntervals, intervals.Count);
var compilation = GetCompilationForEmit(
new[] { source },
new MetadataReference[] { },
TestOptions.ReleaseDll
);
compilation.VerifyDiagnostics(diagnostics);
var tree = compilation.SyntaxTrees[0];
var nodes = new List<SyntaxNode>();
foreach (var span in intervals)
{
var stack = new Stack<SyntaxNode>();
stack.Push(tree.GetCompilationUnitRoot());
while (stack.Count > 0)
{
var node = stack.Pop();
if (span.Contains(node.Span))
{
nodes.Add(node);
break;
}
foreach (var child in node.ChildNodes())
{
stack.Push(child);
}
}
}
Assert.Equal(expectedIntervals, nodes.Count);
return new TestData()
{
Compilation = compilation,
Tree = tree,
Model = compilation.GetSemanticModel(tree),
Nodes = nodes
};
}
private CSharpCompilation Compile(string source)
{
return GetCompilationForEmit(
new[] { source },
new MetadataReference[] { },
TestOptions.ReleaseDll
);
}
private static List<TextSpan> ExtractTextIntervals(ref string source)
{
const string startTag = "[#";
const string endTag = "#]";
List<TextSpan> intervals = new List<TextSpan>();
var all = (from s in FindAll(source, startTag)
select new { start = true, offset = s }).Union(
from s in FindAll(source, endTag)
select new { start = false, offset = s }
).OrderBy(value => value.offset).ToList();
while (all.Count > 0)
{
int i = 1;
bool added = false;
while (i < all.Count)
{
if (all[i - 1].start && !all[i].start)
{
intervals.Add(TextSpan.FromBounds(all[i - 1].offset, all[i].offset));
all.RemoveAt(i);
all.RemoveAt(i - 1);
added = true;
}
else
{
i++;
}
}
Assert.True(added);
}
source = source.Replace(startTag, " ").Replace(endTag, " ");
intervals.Sort((x, y) => x.Start.CompareTo(y.Start));
return intervals;
}
private static IEnumerable<int> FindAll(string source, string what)
{
int index = source.IndexOf(what);
while (index >= 0)
{
yield return index;
index = source.IndexOf(what, index + 1);
}
}
private int NumberOfNewKeywords(string source)
{
int cnt = 0;
foreach (var line in source.Split(new String[] { Environment.NewLine }, StringSplitOptions.None))
{
if (!string.IsNullOrWhiteSpace(line))
{
if (!line.Trim().StartsWith("//"))
{
for (int index = line.IndexOf("new "); index >= 0; )
{
cnt++;
index = line.IndexOf("new ", index + 1);
}
}
}
}
return cnt;
}
#endregion
}
} | 35.001008 | 239 | 0.540134 | [
"Apache-2.0"
] | enginekit/copy_of_roslyn | Src/Compilers/CSharp/Test/Symbol/Symbols/AnonymousTypesSemanticsTests.cs | 34,723 | 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.DataMigration.Outputs
{
[OutputType]
public sealed class ValidationErrorResponse
{
/// <summary>
/// Severity of the error
/// </summary>
public readonly string Severity;
/// <summary>
/// Error Text
/// </summary>
public readonly string Text;
[OutputConstructor]
private ValidationErrorResponse(
string severity,
string text)
{
Severity = severity;
Text = text;
}
}
}
| 23.888889 | 81 | 0.60814 | [
"Apache-2.0"
] | pulumi-bot/pulumi-azure-native | sdk/dotnet/DataMigration/Outputs/ValidationErrorResponse.cs | 860 | C# |
using Ryujinx.Common.Logging;
using Ryujinx.HLE.HOS.Services.Mm.Types;
using System.Collections.Generic;
namespace Ryujinx.HLE.HOS.Services.Mm
{
[Service("mm:u")]
class IRequest : IpcService
{
private static object _sessionListLock = new object();
private static List<MultiMediaSession> _sessionList = new List<MultiMediaSession>();
private static uint _uniqueId = 1;
public IRequest(ServiceCtx context) {}
[Command(0)]
// InitializeOld(u32, u32, u32)
public ResultCode InitializeOld(ServiceCtx context)
{
MultiMediaOperationType operationType = (MultiMediaOperationType)context.RequestData.ReadUInt32();
int fgmId = context.RequestData.ReadInt32();
bool isAutoClearEvent = context.RequestData.ReadInt32() != 0;
Logger.Stub?.PrintStub(LogClass.ServiceMm, new { operationType, fgmId, isAutoClearEvent });
Register(operationType, fgmId, isAutoClearEvent);
return ResultCode.Success;
}
[Command(1)]
// FinalizeOld(u32)
public ResultCode FinalizeOld(ServiceCtx context)
{
MultiMediaOperationType operationType = (MultiMediaOperationType)context.RequestData.ReadUInt32();
Logger.Stub?.PrintStub(LogClass.ServiceMm, new { operationType });
lock (_sessionListLock)
{
_sessionList.Remove(GetSessionByType(operationType));
}
return ResultCode.Success;
}
[Command(2)]
// SetAndWaitOld(u32, u32, u32)
public ResultCode SetAndWaitOld(ServiceCtx context)
{
MultiMediaOperationType operationType = (MultiMediaOperationType)context.RequestData.ReadUInt32();
uint value = context.RequestData.ReadUInt32();
int timeout = context.RequestData.ReadInt32();
Logger.Stub?.PrintStub(LogClass.ServiceMm, new { operationType, value, timeout });
lock (_sessionListLock)
{
GetSessionByType(operationType)?.SetAndWait(value, timeout);
}
return ResultCode.Success;
}
[Command(3)]
// GetOld(u32) -> u32
public ResultCode GetOld(ServiceCtx context)
{
MultiMediaOperationType operationType = (MultiMediaOperationType)context.RequestData.ReadUInt32();
Logger.Stub?.PrintStub(LogClass.ServiceMm, new { operationType });
lock (_sessionListLock)
{
MultiMediaSession session = GetSessionByType(operationType);
uint currentValue = session == null ? 0 : session.CurrentValue;
context.ResponseData.Write(currentValue);
}
return ResultCode.Success;
}
[Command(4)]
// Initialize(u32, u32, u32) -> u32
public ResultCode Initialize(ServiceCtx context)
{
MultiMediaOperationType operationType = (MultiMediaOperationType)context.RequestData.ReadUInt32();
int fgmId = context.RequestData.ReadInt32();
bool isAutoClearEvent = context.RequestData.ReadInt32() != 0;
Logger.Stub?.PrintStub(LogClass.ServiceMm, new { operationType, fgmId, isAutoClearEvent });
uint id = Register(operationType, fgmId, isAutoClearEvent);
context.ResponseData.Write(id);
return ResultCode.Success;
}
[Command(5)]
// Finalize(u32)
public ResultCode Finalize(ServiceCtx context)
{
uint id = context.RequestData.ReadUInt32();
Logger.Stub?.PrintStub(LogClass.ServiceMm, new { id });
lock (_sessionListLock)
{
_sessionList.Remove(GetSessionById(id));
}
return ResultCode.Success;
}
[Command(6)]
// SetAndWait(u32, u32, u32)
public ResultCode SetAndWait(ServiceCtx context)
{
uint id = context.RequestData.ReadUInt32();
uint value = context.RequestData.ReadUInt32();
int timeout = context.RequestData.ReadInt32();
Logger.Stub?.PrintStub(LogClass.ServiceMm, new { id, value, timeout });
lock (_sessionListLock)
{
GetSessionById(id)?.SetAndWait(value, timeout);
}
return ResultCode.Success;
}
[Command(7)]
// Get(u32) -> u32
public ResultCode Get(ServiceCtx context)
{
uint id = context.RequestData.ReadUInt32();
Logger.Stub?.PrintStub(LogClass.ServiceMm, new { id });
lock (_sessionListLock)
{
MultiMediaSession session = GetSessionById(id);
uint currentValue = session == null ? 0 : session.CurrentValue;
context.ResponseData.Write(currentValue);
}
return ResultCode.Success;
}
private MultiMediaSession GetSessionById(uint id)
{
foreach (MultiMediaSession session in _sessionList)
{
if (session.Id == id)
{
return session;
}
}
return null;
}
private MultiMediaSession GetSessionByType(MultiMediaOperationType type)
{
foreach (MultiMediaSession session in _sessionList)
{
if (session.Type == type)
{
return session;
}
}
return null;
}
private uint Register(MultiMediaOperationType type, int fgmId, bool isAutoClearEvent)
{
lock (_sessionListLock)
{
// Nintendo ignore the fgm id as the other interfaces were deprecated.
MultiMediaSession session = new MultiMediaSession(_uniqueId++, type, isAutoClearEvent);
_sessionList.Add(session);
return session.Id;
}
}
}
} | 32.076531 | 113 | 0.563544 | [
"MIT"
] | 0MrDarn0/Ryujinx | Ryujinx.HLE/HOS/Services/Mm/IRequest.cs | 6,287 | C# |
using Microsoft.AspNetCore.Builder;
namespace Timingz;
public static class ApplicationBuilderExtensions
{
public static IApplicationBuilder UseServerTiming(
this IApplicationBuilder app,
Action<ServerTimingOptions> configureOptions = null)
{
if (app == null) throw new ArgumentNullException(nameof(app));
var options = new ServerTimingOptions();
configureOptions?.Invoke(options);
return app.UseServerTiming(options);
}
public static IApplicationBuilder UseServerTiming(
this IApplicationBuilder app,
ServerTimingOptions options)
{
if (app == null) throw new ArgumentNullException(nameof(app));
if (options == null) throw new ArgumentNullException(nameof(options));
return app.UseMiddleware<ServerTimingMiddleware>(options);
}
} | 30.25 | 78 | 0.707202 | [
"MIT"
] | alexmg/Timingz | src/Timingz/ApplicationBuilderExtensions.cs | 849 | C# |
using System.Collections.Generic;
using System.Threading.Tasks;
using ChainLib.Wallets;
namespace ChainLib.WarpWallet
{
/// <summary>
/// Uses warpwallet's algorithm to produce a wallet secret:
/// <code>
/// s1 = scrypt(key=(passphrase||0x1), salt=(salt||0x1), N=2^18, r=8, p=1, dkLen=32)
/// s2 = pbkdf2(key=(passphrase||0x2), salt=(salt||0x2), c=2^16, dkLen=32, prf=HMAC_SHA256)
/// </code>
/// <see href="https://keybase.io/warp" />
/// </summary>
public class WarpWalletProvider : IWalletProvider
{
private readonly IWalletRepository _repository;
private readonly IWalletSecretProvider _secrets;
private readonly IWalletAddressProvider _addresses;
private readonly IWalletFactoryProvider _factory;
public WarpWalletProvider(IWalletRepository repository, IWalletAddressProvider addresses, IWalletFactoryProvider factory)
{
_repository = repository;
_secrets = new WarpWalletSecretProvider();
_addresses = addresses;
_factory = factory;
}
public string GenerateAddress(Wallet wallet)
{
return _addresses.GenerateAddress(wallet);
}
public byte[] GenerateSecret(params object[] args)
{
return _secrets.GenerateSecret(args);
}
public Wallet Create(params object[] args)
{
return _factory.Create(args);
}
public Task<IEnumerable<Wallet>> GetAllAsync()
{
return _repository.GetAllAsync();
}
public Task<Wallet> GetByIdAsync(string id)
{
return _repository.GetByIdAsync(id);
}
public Task<Wallet> AddAsync(Wallet wallet)
{
return _repository.AddAsync(wallet);
}
public Task SaveAddressesAsync(Wallet wallet)
{
return _repository.SaveAddressesAsync(wallet);
}
}
} | 25.784615 | 123 | 0.72494 | [
"Apache-2.0"
] | danielcrenna/graveyard | src/ChainLib.WarpWallet/WarpWalletProvider.cs | 1,676 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
namespace xharness
{
public enum HarnessAction
{
None,
Configure,
Run,
Install,
Uninstall,
Jenkins,
}
public class Harness
{
public HarnessAction Action { get; set; }
public int Verbosity { get; set; }
public Log HarnessLog { get; set; }
public bool UseSystem { get; set; } // if the system XI/XM should be used, or the locally build XI/XM.
// This is the maccore/tests directory.
string root_directory;
public string RootDirectory {
get {
if (root_directory == null) {
var testAssemblyDirectory = Path.GetDirectoryName (System.Reflection.Assembly.GetExecutingAssembly ().Location);
var dir = testAssemblyDirectory;
var path = Path.Combine (testAssemblyDirectory, ".git");
while (!Directory.Exists (path) && path.Length > 3) {
dir = Path.GetDirectoryName (dir);
path = Path.Combine (dir, ".git");
}
if (!Directory.Exists (path))
throw new Exception ("Could not find the xamarin-macios repo.");
path = Path.Combine (Path.GetDirectoryName (path), "tests");
if (!Directory.Exists (path))
throw new Exception ("Could not find the tests directory.");
root_directory = path;
}
return root_directory;
}
set {
root_directory = value;
}
}
public List<TestProject> IOSTestProjects { get; set; } = new List<TestProject> ();
public List<MacTestProject> MacTestProjects { get; set; } = new List<MacTestProject> ();
public List<string> BclTests { get; set; } = new List<string> ();
// Configure
public bool AutoConf { get; set; }
public bool Mac { get; set; }
public string WatchOSContainerTemplate { get; set; }
public string WatchOSAppTemplate { get; set; }
public string WatchOSExtensionTemplate { get; set; }
public string TodayContainerTemplate { get; set; }
public string TodayExtensionTemplate { get; set; }
public string MONO_PATH { get; set; } // Use same name as in Makefiles, so that a grep finds it.
public string WATCH_MONO_PATH { get; set; } // Use same name as in Makefiles, so that a grep finds it.
public string TVOS_MONO_PATH { get; set; } // Use same name as in Makefiles, so that a grep finds it.
public bool INCLUDE_WATCH { get; set; }
public string JENKINS_RESULTS_DIRECTORY { get; set; } // Use same name as in Makefiles, so that a grep finds it.
public string MAC_DESTDIR { get; set; }
public string IOS_DESTDIR { get; set; }
// Run
public AppRunnerTarget Target { get; set; }
public string SdkRoot { get; set; } = "/Applications/Xcode.app";
public string Configuration { get; set; } = "Debug";
public string LogFile { get; set; }
public string LogDirectory { get; set; } = Environment.CurrentDirectory;
public double Timeout { get; set; } = 10; // in minutes
public double LaunchTimeout { get; set; } // in minutes
public bool DryRun { get; set; } // Most things don't support this. If you need it somewhere, implement it!
public string JenkinsConfiguration { get; set; }
public Dictionary<string, string> EnvironmentVariables { get; set; } = new Dictionary<string, string> ();
public Harness ()
{
LaunchTimeout = InWrench ? 3 : 120;
}
public string XcodeRoot {
get {
var p = SdkRoot;
do {
if (p == "/") {
throw new Exception (string.Format ("Could not find Xcode.app in {0}", SdkRoot));
} else if (File.Exists (Path.Combine (p, "Contents", "MacOS", "Xcode"))) {
return p;
}
p = Path.GetDirectoryName (p);
} while (true);
}
}
object mlaunch_lock = new object ();
string DownloadMlaunch ()
{
// NOTE: the filename part in the url must be unique so that the caching logic works properly.
var mlaunch_url = "http://bosstoragemirror.blob.core.windows.net/public-builder/mlaunch/mlaunch-63121a575eff6fa291c28d0f70bacff97b0ecc72.zip";
var extraction_dir = Path.Combine (Path.GetTempPath (), Path.GetFileNameWithoutExtension (mlaunch_url));
var mlaunch_path = Path.Combine (extraction_dir, "bin", "mlaunch");
lock (mlaunch_lock) {
if (File.Exists (mlaunch_path))
return mlaunch_path;
try {
var local_zip = extraction_dir + ".zip";
Log ("Downloading mlaunch to: {0}", local_zip);
var wc = new System.Net.WebClient ();
wc.DownloadFile (mlaunch_url, local_zip);
Log ("Downloaded mlaunch.");
var tmp_extraction_dir = extraction_dir + ".tmp";
if (Directory.Exists (tmp_extraction_dir))
Directory.Delete (tmp_extraction_dir, true);
if (Directory.Exists (extraction_dir))
Directory.Delete (extraction_dir, true);
Log ("Extracting mlaunch...");
using (var p = new Process ()) {
p.StartInfo.FileName = "unzip";
p.StartInfo.Arguments = $"-d {Quote (tmp_extraction_dir)} {Quote (local_zip)}";
Log ("{0} {1}", p.StartInfo.FileName, p.StartInfo.Arguments);
p.Start ();
p.WaitForExit ();
if (p.ExitCode != 0) {
Log ("Could not unzip mlaunch, exit code: {0}", p.ExitCode);
return mlaunch_path;
}
}
Directory.Move (tmp_extraction_dir, extraction_dir);
Log ("Final mlaunch path: {0}", mlaunch_path);
} catch (Exception e) {
Log ("Could not download mlaunch: {0}", e);
}
return mlaunch_path;
}
}
public string MtouchPath {
get {
return Path.Combine (IOS_DESTDIR, "Library", "Frameworks", "Xamarin.iOS.framework", "Versions", "Current", "bin", "mtouch");
}
}
string mlaunch;
public string MlaunchPath {
get {
if (mlaunch == null) {
// First check if we've built mlaunch locally.
var filename = Path.GetFullPath (Path.Combine (IOS_DESTDIR, "Library", "Frameworks", "Xamarin.iOS.framework", "Versions", "Current", "bin", "mlaunch"));
if (File.Exists (filename)) {
Log ("Found mlaunch: {0}", filename);
return mlaunch = filename;
}
// Then check if we can download mlaunch.
Log ("Could not find a locally built mlaunch, will try downloading it.");
try {
filename = DownloadMlaunch ();
} catch (Exception e) {
Log ("Could not download mlaunch: {0}", e);
}
if (File.Exists (filename)) {
Log ("Found mlaunch: {0}", filename);
return mlaunch = filename;
}
// Then check if the system version of Xamarin.iOS has mlaunch.
// This may be a version of mlaunch we're not compatible with, since we don't control which XI version the system has.
Log ("Could not download mlaunch, will try the system's Xamarin.iOS.");
filename = "/Library/Frameworks/Xamarin.iOS.framework/Versions/Current/bin/mlaunch";
if (File.Exists (filename)) {
Log ("Found mlaunch: {0}", filename);
return mlaunch = filename;
}
throw new FileNotFoundException (string.Format ("Could not find mlaunch: {0}", filename));
}
return mlaunch;
}
}
public static string Quote (string f)
{
if (f.IndexOf (' ') == -1 && f.IndexOf ('\'') == -1 && f.IndexOf (',') == -1)
return f;
var s = new StringBuilder ();
s.Append ('"');
foreach (var c in f) {
if (c == '"' || c == '\\')
s.Append ('\\');
s.Append (c);
}
s.Append ('"');
return s.ToString ();
}
void CreateBCLProjects ()
{
foreach (var bclTest in BclTests) {
var target = new BCLTarget () {
Harness = this,
MonoPath = MONO_PATH,
WatchMonoPath = WATCH_MONO_PATH,
TestName = bclTest,
};
target.Convert ();
}
}
void LoadConfig ()
{
ParseConfigFiles ();
var src_root = Path.GetDirectoryName (RootDirectory);
MONO_PATH = Path.GetFullPath (Path.Combine (src_root, "external", "mono"));
WATCH_MONO_PATH = make_config ["WATCH_MONO_PATH"];
TVOS_MONO_PATH = MONO_PATH;
INCLUDE_WATCH = make_config.ContainsKey ("INCLUDE_WATCH") && !string.IsNullOrEmpty (make_config ["INCLUDE_WATCH"]);
JENKINS_RESULTS_DIRECTORY = make_config ["JENKINS_RESULTS_DIRECTORY"];
MAC_DESTDIR = make_config ["MAC_DESTDIR"];
IOS_DESTDIR = make_config ["IOS_DESTDIR"];
}
void AutoConfigureMac ()
{
var test_suites = new string[] { "apitest", "dontlink-mac" };
var hard_coded_test_suites = new string[] { "mmptest", "msbuild-mac" };
//var library_projects = new string[] { "BundledResources", "EmbeddedResources", "bindings-test", "bindings-framework-test" };
//var fsharp_test_suites = new string[] { "fsharp" };
//var fsharp_library_projects = new string[] { "fsharplibrary" };
//var bcl_suites = new string[] { "mscorlib", "System", "System.Core", "System.Data", "System.Net.Http", "System.Numerics", "System.Runtime.Serialization", "System.Transactions", "System.Web.Services", "System.Xml", "System.Xml.Linq", "Mono.Security", "System.ComponentModel.DataAnnotations", "System.Json", "System.ServiceModel.Web", "Mono.Data.Sqlite" };
foreach (var p in test_suites)
MacTestProjects.Add (new MacTestProject (Path.GetFullPath (Path.Combine (RootDirectory, p + "/" + p + ".csproj"))));
MacTestProjects.Add (new MacTestProject (Path.GetFullPath (Path.Combine (RootDirectory, "introspection", "Mac", "introspection-mac.csproj")), skipXMVariations : true));
foreach (var p in hard_coded_test_suites)
MacTestProjects.Add (new MacTestProject (Path.GetFullPath (Path.Combine (RootDirectory, p + "/" + p + ".csproj")), generateVariations: false));
//foreach (var p in fsharp_test_suites)
// TestProjects.Add (Path.GetFullPath (Path.Combine (RootDirectory, p + "/" + p + ".fsproj")));
//foreach (var p in library_projects)
//TestProjects.Add (Path.GetFullPath (Path.Combine (RootDirectory, p + "/" + p + ".csproj")));
//foreach (var p in fsharp_library_projects)
//TestProjects.Add (Path.GetFullPath (Path.Combine (RootDirectory, p + "/" + p + ".fsproj")));
//foreach (var p in bcl_suites)
//TestProjects.Add (Path.GetFullPath (Path.Combine (RootDirectory, "bcl-test/" + p + "/" + p + ".csproj")));
// BclTests.AddRange (bcl_suites);
}
void AutoConfigureIOS ()
{
var test_suites = new string [] { "monotouch-test", "framework-test", "mini" };
var library_projects = new string [] { "BundledResources", "EmbeddedResources", "bindings-test", "bindings-framework-test" };
var fsharp_test_suites = new string [] { "fsharp" };
var fsharp_library_projects = new string [] { "fsharplibrary" };
var bcl_suites = new string [] { "mscorlib", "System", "System.Core", "System.Data", "System.Net.Http", "System.Numerics", "System.Runtime.Serialization", "System.Transactions", "System.Web.Services", "System.Xml", "System.Xml.Linq", "Mono.Security", "System.ComponentModel.DataAnnotations", "System.Json", "System.ServiceModel.Web", "Mono.Data.Sqlite" };
IOSTestProjects.Add (new TestProject (Path.GetFullPath (Path.Combine (RootDirectory, "bcl-test/mscorlib/mscorlib-0.csproj")), false));
IOSTestProjects.Add (new TestProject (Path.GetFullPath (Path.Combine (RootDirectory, "bcl-test/mscorlib/mscorlib-1.csproj")), false));
foreach (var p in test_suites)
IOSTestProjects.Add (new TestProject (Path.GetFullPath (Path.Combine (RootDirectory, p + "/" + p + ".csproj"))));
foreach (var p in fsharp_test_suites)
IOSTestProjects.Add (new TestProject (Path.GetFullPath (Path.Combine (RootDirectory, p + "/" + p + ".fsproj"))));
foreach (var p in library_projects)
IOSTestProjects.Add (new TestProject (Path.GetFullPath (Path.Combine (RootDirectory, p + "/" + p + ".csproj")), false));
foreach (var p in fsharp_library_projects)
IOSTestProjects.Add (new TestProject (Path.GetFullPath (Path.Combine (RootDirectory, p + "/" + p + ".fsproj")), false));
foreach (var p in bcl_suites)
IOSTestProjects.Add (new TestProject (Path.GetFullPath (Path.Combine (RootDirectory, "bcl-test/" + p + "/" + p + ".csproj"))));
IOSTestProjects.Add (new TestProject (Path.GetFullPath (Path.Combine (RootDirectory, "introspection", "iOS", "introspection-ios.csproj"))));
IOSTestProjects.Add (new TestProject (Path.GetFullPath (Path.Combine (RootDirectory, "linker-ios", "dont link", "dont link.csproj"))));
IOSTestProjects.Add (new TestProject (Path.GetFullPath (Path.Combine (RootDirectory, "linker-ios", "link all", "link all.csproj"))));
IOSTestProjects.Add (new TestProject (Path.GetFullPath (Path.Combine (RootDirectory, "linker-ios", "link sdk", "link sdk.csproj"))));
BclTests.AddRange (bcl_suites);
WatchOSContainerTemplate = Path.GetFullPath (Path.Combine (RootDirectory, "templates/WatchContainer"));
WatchOSAppTemplate = Path.GetFullPath (Path.Combine (RootDirectory, "templates/WatchApp"));
WatchOSExtensionTemplate = Path.GetFullPath (Path.Combine (RootDirectory, "templates/WatchExtension"));
TodayContainerTemplate = Path.GetFullPath (Path.Combine (RootDirectory, "templates", "TodayContainer"));
TodayExtensionTemplate = Path.GetFullPath (Path.Combine (RootDirectory, "templates", "TodayExtension"));
}
Dictionary<string, string> make_config = new Dictionary<string, string> ();
IEnumerable<string> FindConfigFiles (string name)
{
var dir = Path.GetFullPath (RootDirectory);
while (dir != "/") {
var file = Path.Combine (dir, name);
if (File.Exists (file))
yield return file;
dir = Path.GetDirectoryName (dir);
}
}
void ParseConfigFiles ()
{
ParseConfigFiles (FindConfigFiles (UseSystem ? "test-system.config" : "test.config"));
ParseConfigFiles (FindConfigFiles ("Make.config.local"));
ParseConfigFiles (FindConfigFiles ("Make.config"));
}
void ParseConfigFiles (IEnumerable<string> files)
{
foreach (var file in files)
ParseConfigFile (file);
}
void ParseConfigFile (string file)
{
if (string.IsNullOrEmpty (file))
return;
foreach (var line in File.ReadAllLines (file)) {
var eq = line.IndexOf ('=');
if (eq == -1)
continue;
var key = line.Substring (0, eq);
if (!make_config.ContainsKey (key))
make_config [key] = line.Substring (eq + 1);
}
}
public int Configure ()
{
if (Mac)
ConfigureMac ();
else
ConfigureIOS ();
return 0;
}
void ConfigureMac ()
{
var classic_targets = new List<MacClassicTarget> ();
var unified_targets = new List<MacUnifiedTarget> ();
var hardcoded_unified_targets = new List<MacUnifiedTarget> ();
RootDirectory = Path.GetFullPath (RootDirectory).TrimEnd ('/');
if (AutoConf)
AutoConfigureMac ();
CreateBCLProjects ();
foreach (var proj in MacTestProjects.Where ((v) => v.GenerateVariations)) {
var file = proj.Path;
if (!File.Exists (file))
throw new FileNotFoundException (file);
foreach (bool thirtyTwoBit in new bool[] { false, true })
{
var unifiedMobile = new MacUnifiedTarget (true, thirtyTwoBit)
{
TemplateProjectPath = file,
Harness = this,
};
unifiedMobile.Execute ();
unified_targets.Add (unifiedMobile);
if (!proj.SkipXMVariations) {
var unifiedXM45 = new MacUnifiedTarget (false, thirtyTwoBit)
{
TemplateProjectPath = file,
Harness = this,
};
unifiedXM45.Execute ();
unified_targets.Add (unifiedXM45);
}
}
var classic = new MacClassicTarget () {
TemplateProjectPath = file,
Harness = this,
};
classic.Execute ();
classic_targets.Add (classic);
}
foreach (var proj in MacTestProjects.Where ((v) => !v.GenerateVariations)) {
var file = proj.Path;
var unifiedMobile = new MacUnifiedTarget (true, false, true)
{
TemplateProjectPath = file,
Harness = this,
};
unifiedMobile.Execute ();
hardcoded_unified_targets.Add (unifiedMobile);
}
MakefileGenerator.CreateMacMakefile (this, classic_targets.Union<MacTarget> (unified_targets).Union (hardcoded_unified_targets) );
}
void ConfigureIOS ()
{
var unified_targets = new List<UnifiedTarget> ();
var tvos_targets = new List<TVOSTarget> ();
var watchos_targets = new List<WatchOSTarget> ();
var today_targets = new List<TodayExtensionTarget> ();
RootDirectory = Path.GetFullPath (RootDirectory).TrimEnd ('/');
if (AutoConf)
AutoConfigureIOS ();
CreateBCLProjects ();
foreach (var proj in IOSTestProjects) {
var file = proj.Path;
if (!File.Exists (file))
throw new FileNotFoundException (file);
var watchos = new WatchOSTarget () {
TemplateProjectPath = file,
Harness = this,
};
watchos.Execute ();
watchos_targets.Add (watchos);
var tvos = new TVOSTarget () {
TemplateProjectPath = file,
Harness = this,
};
tvos.Execute ();
tvos_targets.Add (tvos);
var unified = new UnifiedTarget () {
TemplateProjectPath = file,
Harness = this,
};
unified.Execute ();
unified_targets.Add (unified);
var today = new TodayExtensionTarget
{
TemplateProjectPath = file,
Harness = this,
};
today.Execute ();
today_targets.Add (today);
}
SolutionGenerator.CreateSolution (this, watchos_targets, "watchos");
SolutionGenerator.CreateSolution (this, tvos_targets, "tvos");
SolutionGenerator.CreateSolution (this, today_targets, "today");
MakefileGenerator.CreateMakefile (this, unified_targets, tvos_targets, watchos_targets, today_targets);
}
public int Install ()
{
if (HarnessLog == null)
HarnessLog = new ConsoleLog ();
foreach (var project in IOSTestProjects) {
var runner = new AppRunner () {
Harness = this,
ProjectFile = project.Path,
MainLog = HarnessLog,
};
var rv = runner.InstallAsync ().Result;
if (!rv.Succeeded)
return rv.ExitCode;
}
return 0;
}
public int Uninstall ()
{
if (HarnessLog == null)
HarnessLog = new ConsoleLog ();
foreach (var project in IOSTestProjects) {
var runner = new AppRunner ()
{
Harness = this,
ProjectFile = project.Path,
MainLog = HarnessLog,
};
var rv = runner.UninstallAsync ().Result;
if (!rv.Succeeded)
return rv.ExitCode;
}
return 0;
}
public int Run ()
{
if (HarnessLog == null)
HarnessLog = new ConsoleLog ();
foreach (var project in IOSTestProjects) {
var runner = new AppRunner () {
Harness = this,
ProjectFile = project.Path,
MainLog = HarnessLog,
};
var rv = runner.RunAsync ().Result;
if (rv != 0)
return rv;
}
return 0;
}
public void Log (int min_level, string message)
{
if (Verbosity < min_level)
return;
Console.WriteLine (message);
HarnessLog?.WriteLine (message);
}
public void Log (int min_level, string message, params object[] args)
{
if (Verbosity < min_level)
return;
Console.WriteLine (message, args);
HarnessLog?.WriteLine (message, args);
}
public void Log (string message)
{
Log (0, message);
}
public void Log (string message, params object[] args)
{
Log (0, message, args);
}
public void LogWrench (string message, params object[] args)
{
if (!InWrench)
return;
Console.WriteLine (message, args);
}
public void LogWrench (string message)
{
if (!InWrench)
return;
Console.WriteLine (message);
}
public bool InWrench {
get {
var buildRev = Environment.GetEnvironmentVariable ("BUILD_REVISION");
return !string.IsNullOrEmpty (buildRev) && buildRev != "jenkins";
}
}
public bool InJenkins {
get {
var buildRev = Environment.GetEnvironmentVariable ("BUILD_REVISION");
return !string.IsNullOrEmpty (buildRev) && buildRev == "jenkins";
}
}
public int Execute ()
{
LoadConfig ();
switch (Action) {
case HarnessAction.Configure:
return Configure ();
case HarnessAction.Run:
return Run ();
case HarnessAction.Install:
return Install ();
case HarnessAction.Uninstall:
return Uninstall ();
case HarnessAction.Jenkins:
return Jenkins ();
default:
throw new NotImplementedException (Action.ToString ());
}
}
public int Jenkins ()
{
if (AutoConf) {
AutoConfigureIOS ();
AutoConfigureMac ();
}
var jenkins = new Jenkins ()
{
Harness = this,
};
return jenkins.Run ();
}
public void Save (XmlDocument doc, string path)
{
if (!File.Exists (path)) {
doc.Save (path);
Log (1, "Created {0}", path);
} else {
var tmpPath = path + ".tmp";
doc.Save (tmpPath);
var existing = File.ReadAllText (path);
var updated = File.ReadAllText (tmpPath);
if (existing == updated) {
File.Delete (tmpPath);
Log (1, "Not saved {0}, no change", path);
} else {
File.Delete (path);
File.Move (tmpPath, path);
Log (1, "Updated {0}", path);
}
}
}
public void Save (StringWriter doc, string path)
{
if (!File.Exists (path)) {
File.WriteAllText (path, doc.ToString ());
Log (1, "Created {0}", path);
} else {
var existing = File.ReadAllText (path);
var updated = doc.ToString ();
if (existing == updated) {
Log (1, "Not saved {0}, no change", path);
} else {
File.WriteAllText (path, updated);
Log (1, "Updated {0}", path);
}
}
}
public void Save (string doc, string path)
{
if (!File.Exists (path)) {
File.WriteAllText (path, doc);
Log (1, "Created {0}", path);
} else {
var existing = File.ReadAllText (path);
if (existing == doc) {
Log (1, "Not saved {0}, no change", path);
} else {
File.WriteAllText (path, doc);
Log (1, "Updated {0}", path);
}
}
}
// We want guids that nobody else has, but we also want to generate the same guid
// on subsequent invocations (so that csprojs don't change unnecessarily, which is
// annoying when XS reloads the projects, and also causes unnecessary rebuilds).
// Nothing really breaks when the sequence isn't identical from run to run, so
// this is just a best minimal effort.
static Random guid_generator = new Random (unchecked ((int) 0xdeadf00d));
public Guid NewStableGuid ()
{
var bytes = new byte [16];
guid_generator.NextBytes (bytes);
return new Guid (bytes);
}
bool? disable_watchos_on_wrench;
public bool DisableWatchOSOnWrench {
get {
if (!disable_watchos_on_wrench.HasValue)
disable_watchos_on_wrench = !string.IsNullOrEmpty (Environment.GetEnvironmentVariable ("DISABLE_WATCH_ON_WRENCH"));
return disable_watchos_on_wrench.Value;
}
}
public Task<ProcessExecutionResult> ExecuteXcodeCommandAsync (string executable, string args, Log log, TimeSpan timeout)
{
return ProcessHelper.ExecuteCommandAsync (Path.Combine (XcodeRoot, "Contents", "Developer", "usr", "bin", executable), args, log, timeout: timeout);
}
public async Task ShowSimulatorList (LogStream log)
{
await ExecuteXcodeCommandAsync ("simctl", "list", log, TimeSpan.FromSeconds (10));
}
public async Task<LogFile> SymbolicateCrashReportAsync (Log log, LogFile report)
{
var symbolicatecrash = Path.Combine (XcodeRoot, "Contents/SharedFrameworks/DTDeviceKitBase.framework/Versions/A/Resources/symbolicatecrash");
if (!File.Exists (symbolicatecrash))
symbolicatecrash = Path.Combine (XcodeRoot, "Contents/SharedFrameworks/DVTFoundation.framework/Versions/A/Resources/symbolicatecrash");
if (!File.Exists (symbolicatecrash)) {
log.WriteLine ("Can't symbolicate {0} because the symbolicatecrash script {1} does not exist", report.Path, symbolicatecrash);
return report;
}
var symbolicated = new LogFile ("Symbolicated crash report", report.Path + ".symbolicated");
var environment = new Dictionary<string, string> { { "DEVELOPER_DIR", Path.Combine (XcodeRoot, "Contents", "Developer") } };
var rv = await ProcessHelper.ExecuteCommandAsync (symbolicatecrash, Quote (report.Path), symbolicated, TimeSpan.FromMinutes (1), environment);
if (rv.Succeeded) {;
log.WriteLine ("Symbolicated {0} successfully.", report.Path);
return symbolicated;
} else {
log.WriteLine ("Failed to symbolicate {0}.", report.Path);
return report;
}
}
public async Task<HashSet<string>> CreateCrashReportsSnapshotAsync (Log log, bool simulatorOrDesktop, string device)
{
var rv = new HashSet<string> ();
if (simulatorOrDesktop) {
var dir = Path.Combine (Environment.GetEnvironmentVariable ("HOME"), "Library", "Logs", "DiagnosticReports");
if (Directory.Exists (dir))
rv.UnionWith (Directory.EnumerateFiles (dir));
} else {
var tmp = Path.GetTempFileName ();
try {
var sb = new StringBuilder ();
sb.Append (" --list-crash-reports=").Append (Quote (tmp));
sb.Append (" --sdkroot ").Append (Quote (XcodeRoot));
if (!string.IsNullOrEmpty (device))
sb.Append (" --devname ").Append (Quote (device));
var result = await ProcessHelper.ExecuteCommandAsync (MlaunchPath, sb.ToString (), log, TimeSpan.FromMinutes (1));
if (result.Succeeded)
rv.UnionWith (File.ReadAllLines (tmp));
} finally {
File.Delete (tmp);
}
}
return rv;
}
}
public class CrashReportSnapshot
{
public Harness Harness { get; set; }
public Log Log { get; set; }
public Logs Logs { get; set; }
public string LogDirectory { get; set; }
public bool Device { get; set; }
public string DeviceName { get; set; }
public HashSet<string> InitialSet { get; private set; }
public IEnumerable<string> Reports { get; private set; }
public async Task StartCaptureAsync ()
{
InitialSet = await Harness.CreateCrashReportsSnapshotAsync (Log, !Device, DeviceName);
}
public async Task EndCaptureAsync (TimeSpan timeout)
{
// Check for crash reports
var crash_report_search_done = false;
var crash_report_search_timeout = timeout.TotalSeconds;
var watch = new Stopwatch ();
watch.Start ();
do {
var end_crashes = await Harness.CreateCrashReportsSnapshotAsync (Log, !Device, DeviceName);
end_crashes.ExceptWith (InitialSet);
Reports = end_crashes;
if (end_crashes.Count > 0) {
Log.WriteLine ("Found {0} new crash report(s)", end_crashes.Count);
List<LogFile> crash_reports;
if (!Device) {
crash_reports = new List<LogFile> (end_crashes.Count);
foreach (var path in end_crashes) {
var logPath = Path.Combine (LogDirectory, Path.GetFileName (path));
File.Copy (path, logPath, true);
crash_reports.Add (Logs.CreateFile ("Crash report: " + Path.GetFileName (path), logPath));
}
} else {
// Download crash reports from the device. We put them in the project directory so that they're automatically deleted on wrench
// (if we put them in /tmp, they'd never be deleted).
var downloaded_crash_reports = new List<LogFile> ();
foreach (var file in end_crashes) {
var crash_report_target = Logs.CreateFile ("Crash report: " + Path.GetFileName (file), Path.Combine (LogDirectory, Path.GetFileName (file)));
var sb = new StringBuilder ();
sb.Append (" --download-crash-report=").Append (Harness.Quote (file));
sb.Append (" --download-crash-report-to=").Append (Harness.Quote (crash_report_target.Path));
sb.Append (" --sdkroot ").Append (Harness.Quote (Harness.XcodeRoot));
if (!string.IsNullOrEmpty (DeviceName))
sb.Append (" --devname ").Append (Harness.Quote (DeviceName));
var result = await ProcessHelper.ExecuteCommandAsync (Harness.MlaunchPath, sb.ToString (), Log, TimeSpan.FromMinutes (1));
if (result.Succeeded) {
Log.WriteLine ("Downloaded crash report {0} to {1}", file, crash_report_target.Path);
crash_report_target = await Harness.SymbolicateCrashReportAsync (Log, crash_report_target);
Logs.Add (crash_report_target);
downloaded_crash_reports.Add (crash_report_target);
} else {
Log.WriteLine ("Could not download crash report {0}", file);
}
}
crash_reports = downloaded_crash_reports;
}
foreach (var cp in crash_reports) {
Harness.LogWrench ("@MonkeyWrench: AddFile: {0}", cp.Path);
Log.WriteLine (" {0}", cp.Path);
}
crash_report_search_done = true;
} else {
if (watch.Elapsed.TotalSeconds > crash_report_search_timeout) {
crash_report_search_done = true;
} else {
Log.WriteLine ("No crash reports, waiting a second to see if the crash report service just didn't complete in time ({0})", (int) (crash_report_search_timeout - watch.Elapsed.TotalSeconds));
Thread.Sleep (TimeSpan.FromSeconds (1));
}
}
} while (!crash_report_search_done);
}
}
}
| 34.56506 | 359 | 0.66468 | [
"BSD-3-Clause"
] | ekhavana/xamarin-macios | tests/xharness/Harness.cs | 28,691 | C# |
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace HotChocolate.Execution
{
public static class ExecutionRequestExecutorExtensions
{
public static Task<IExecutionResult> ExecuteAsync(
this IRequestExecutor executor,
IReadOnlyQueryRequest request)
{
if (executor == null)
{
throw new ArgumentNullException(nameof(executor));
}
if (request == null)
{
throw new ArgumentNullException(nameof(request));
}
return executor.ExecuteAsync(
request,
CancellationToken.None);
}
public static Task<IExecutionResult> ExecuteAsync(
this IRequestExecutor executor,
string query)
{
if (executor == null)
{
throw new ArgumentNullException(nameof(executor));
}
if (string.IsNullOrEmpty(query))
{
throw new ArgumentException(
"The query mustn't be null or empty.",
nameof(query));
}
return executor.ExecuteAsync(
QueryRequestBuilder.New().SetQuery(query).Create(),
CancellationToken.None);
}
public static Task<IExecutionResult> ExecuteAsync(
this IRequestExecutor executor,
string query,
CancellationToken cancellationToken)
{
if (executor == null)
{
throw new ArgumentNullException(nameof(executor));
}
if (string.IsNullOrEmpty(query))
{
throw new ArgumentException(
"The query mustn't be null or empty.",
nameof(query));
}
return executor.ExecuteAsync(
QueryRequestBuilder.New().SetQuery(query).Create(),
cancellationToken);
}
public static Task<IExecutionResult> ExecuteAsync(
this IRequestExecutor executor,
string query,
IReadOnlyDictionary<string, object> variableValues)
{
if (executor == null)
{
throw new ArgumentNullException(nameof(executor));
}
if (string.IsNullOrEmpty(query))
{
throw new ArgumentException(
"The query mustn't be null or empty.",
nameof(query));
}
if (variableValues == null)
{
throw new ArgumentNullException(nameof(variableValues));
}
return executor.ExecuteAsync(
QueryRequestBuilder.New()
.SetQuery(query)
.SetVariableValues(variableValues)
.Create(),
CancellationToken.None);
}
public static Task<IExecutionResult> ExecuteAsync(
this IRequestExecutor executor,
string query,
IReadOnlyDictionary<string, object> variableValues,
CancellationToken cancellationToken)
{
if (executor == null)
{
throw new ArgumentNullException(nameof(executor));
}
if (string.IsNullOrEmpty(query))
{
throw new ArgumentException(
"The query mustn't be null or empty.",
nameof(query));
}
if (variableValues == null)
{
throw new ArgumentNullException(nameof(variableValues));
}
return executor.ExecuteAsync(
QueryRequestBuilder.New()
.SetQuery(query)
.SetVariableValues(variableValues)
.Create(),
cancellationToken);
}
public static IExecutionResult Execute(
this IRequestExecutor executor,
IReadOnlyQueryRequest request)
{
if (executor == null)
{
throw new ArgumentNullException(nameof(executor));
}
if (request == null)
{
throw new ArgumentNullException(nameof(request));
}
return Task.Factory.StartNew(
() => ExecuteAsync(executor, request))
.Unwrap()
.GetAwaiter()
.GetResult();
}
public static IExecutionResult Execute(
this IRequestExecutor executor,
string query)
{
if (executor == null)
{
throw new ArgumentNullException(nameof(executor));
}
if (string.IsNullOrEmpty(query))
{
throw new ArgumentException(
"The query mustn't be null or empty.",
nameof(query));
}
return executor.Execute(
QueryRequestBuilder.New()
.SetQuery(query)
.Create());
}
public static IExecutionResult Execute(
this IRequestExecutor executor,
string query,
IReadOnlyDictionary<string, object> variableValues)
{
if (executor == null)
{
throw new ArgumentNullException(nameof(executor));
}
if (string.IsNullOrEmpty(query))
{
throw new ArgumentException(
"The query mustn't be null or empty.",
nameof(query));
}
if (variableValues == null)
{
throw new ArgumentNullException(nameof(variableValues));
}
return executor.Execute(
QueryRequestBuilder.New()
.SetQuery(query)
.SetVariableValues(variableValues)
.Create());
}
public static Task<IExecutionResult> ExecuteAsync(
this IRequestExecutor executor,
Action<IQueryRequestBuilder> buildRequest,
CancellationToken cancellationToken)
{
if (executor == null)
{
throw new ArgumentNullException(nameof(executor));
}
if (buildRequest == null)
{
throw new ArgumentNullException(nameof(buildRequest));
}
var builder = new QueryRequestBuilder();
buildRequest(builder);
return executor.ExecuteAsync(
builder.Create(),
cancellationToken);
}
public static Task<IExecutionResult> ExecuteAsync(
this IRequestExecutor executor,
Action<IQueryRequestBuilder> buildRequest)
{
if (executor == null)
{
throw new ArgumentNullException(nameof(executor));
}
if (buildRequest == null)
{
throw new ArgumentNullException(nameof(buildRequest));
}
return executor.ExecuteAsync(
buildRequest,
CancellationToken.None);
}
}
}
| 29.814516 | 72 | 0.500811 | [
"MIT"
] | garybond/hotchocolate | src/HotChocolate/Core/src/Execution/Extensions/ExecutionRequestExecutorExtensions.cs | 7,394 | C# |
// Copyright (c) 2022 AccelByte Inc. All Rights Reserved.
// This is licensed software from AccelByte Inc, for limitations
// and restrictions contact your company contract manager.
// This code is generated by tool. DO NOT EDIT.
using System.Net;
using System.IO;
using System.Text.Json;
using AccelByte.Sdk.Api.Iam.Model;
using AccelByte.Sdk.Core;
using AccelByte.Sdk.Core.Util;
namespace AccelByte.Sdk.Api.Iam.Operation
{
/// <summary>
/// AdminBulkCheckValidUserIDV4
///
/// Use this endpoint to check if userID exists or not
///
/// Required permission ' ADMIN:NAMESPACE:{namespace}:USER [READ]'
///
/// Maximum number of userID to be checked is 50
/// </summary>
public class AdminBulkCheckValidUserIDV4 : AccelByte.Sdk.Core.Operation
{
#region Builder Part
public static AdminBulkCheckValidUserIDV4Builder Builder = new AdminBulkCheckValidUserIDV4Builder();
public class AdminBulkCheckValidUserIDV4Builder
: OperationBuilder<AdminBulkCheckValidUserIDV4Builder>
{
internal AdminBulkCheckValidUserIDV4Builder() { }
public AdminBulkCheckValidUserIDV4 Build(
ModelCheckValidUserIDRequestV4 body,
string namespace_
)
{
AdminBulkCheckValidUserIDV4 op = new AdminBulkCheckValidUserIDV4(this,
body,
namespace_
);
op.PreferredSecurityMethod = PreferredSecurityMethod;
return op;
}
}
private AdminBulkCheckValidUserIDV4(AdminBulkCheckValidUserIDV4Builder builder,
ModelCheckValidUserIDRequestV4 body,
string namespace_
)
{
PathParams["namespace"] = namespace_;
BodyParams = body;
Securities.Add(AccelByte.Sdk.Core.Operation.SECURITY_BEARER);
}
#endregion
public AdminBulkCheckValidUserIDV4(
string namespace_,
Model.ModelCheckValidUserIDRequestV4 body
)
{
PathParams["namespace"] = namespace_;
BodyParams = body;
Securities.Add(AccelByte.Sdk.Core.Operation.SECURITY_BEARER);
}
public override string Path => "/iam/v4/admin/namespaces/{namespace}/users/bulk/validate";
public override HttpMethod Method => HttpMethod.Post;
public override string[] Consumes => new string[] { "application/json" };
public override string[] Produces => new string[] { "application/json" };
[Obsolete("Use 'Securities' property instead.")]
public override string? Security { get; set; } = "Bearer";
public Model.ModelListValidUserIDResponseV4? ParseResponse(HttpStatusCode code, string contentType, Stream payload)
{
if (code == (HttpStatusCode)204)
{
return null;
}
else if (code == (HttpStatusCode)201)
{
return JsonSerializer.Deserialize<Model.ModelListValidUserIDResponseV4>(payload);
}
else if (code == (HttpStatusCode)200)
{
return JsonSerializer.Deserialize<Model.ModelListValidUserIDResponseV4>(payload);
}
var payloadString = Helper.ConvertInputStreamToString(payload);
throw new HttpResponseException(code, payloadString);
}
}
} | 30.447154 | 123 | 0.579973 | [
"MIT"
] | AccelByte/accelbyte-csharp-sdk | AccelByte.Sdk/Api/Iam/Operation/UsersV4/AdminBulkCheckValidUserIDV4.cs | 3,745 | C# |
using System;
namespace BulkOperations.EntityFramework.Tests.Models
{
public partial class ProductVendor
{
public virtual int ProductID { get; set; }
public virtual int BusinessEntityID { get; set; }
public virtual int AverageLeadTime { get; set; }
public virtual decimal StandardPrice { get; set; }
public virtual Nullable<decimal> LastReceiptCost { get; set; }
public virtual Nullable<System.DateTime> LastReceiptDate { get; set; }
public virtual int MinOrderQty { get; set; }
public virtual int MaxOrderQty { get; set; }
public virtual Nullable<int> OnOrderQty { get; set; }
public virtual string UnitMeasureCode { get; set; }
public virtual System.DateTime ModifiedDate { get; set; }
public virtual Product Product { get; set; }
public virtual UnitMeasure UnitMeasure { get; set; }
public virtual Vendor Vendor { get; set; }
}
}
| 41.652174 | 78 | 0.664927 | [
"MIT"
] | proff/BulkOperations | BulkOperations.EntityFramework.Tests/Models/ProductVendor.cs | 958 | C# |
using Microsoft.AspNetCore.Identity;
using Microsoft.IdentityModel.Tokens;
using Shop.Infrastructure;
using Shop.Module.Core.Cache;
using Shop.Module.Core.Data;
using Shop.Module.Core.Entities;
using Shop.Module.Core.Models;
using Shop.Module.Core.Services;
using Shop.Module.Core.Models.Cache;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.Options;
namespace Shop.Module.Core.Services
{
public class TokenService : ITokenService
{
private readonly AuthenticationOptions _config;
private readonly IStaticCacheManager _cacheManager;
private readonly UserManager<User> _userManager;
public TokenService(
IOptionsMonitor<AuthenticationOptions> config,
IStaticCacheManager cacheManager,
UserManager<User> userManager)
{
_config = config.CurrentValue;
_cacheManager = cacheManager;
_userManager = userManager;
}
public async Task<string> GenerateAccessToken(User user)
{
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config.Jwt.Key));
var minutes = _config.Jwt.AccessTokenDurationInMinutes;
var utcNow = DateTime.UtcNow;
var expires = utcNow.AddMinutes(minutes);
var claims = await BuildClaims(user);
var jwtToken = new JwtSecurityToken(
issuer: _config.Jwt.Issuer,
audience: "Anyone",
claims: claims,
notBefore: DateTime.UtcNow,
expires: expires,
signingCredentials: new SigningCredentials(key, SecurityAlgorithms.HmacSha256)
);
var token = new JwtSecurityTokenHandler().WriteToken(jwtToken);
_cacheManager.Set(ShopKeys.UserJwtTokenPrefix + user.Id, new UserTokenCache()
{
UserId = user.Id.ToString(),
Token = token,
TokenCreatedOnUtc = utcNow,
TokenUpdatedOnUtc = utcNow,
TokenExpiresOnUtc = expires
}, minutes);
return token;
}
public string GenerateRefreshToken()
{
var randomNumber = new byte[32];
using (var rng = RandomNumberGenerator.Create())
{
rng.GetBytes(randomNumber);
return Convert.ToBase64String(randomNumber);
}
}
public ClaimsPrincipal GetPrincipalFromExpiredToken(string token)
{
var tokenValidationParameters = new TokenValidationParameters
{
ValidateAudience = false,
ValidateIssuer = true,
ValidIssuer = _config.Jwt.Issuer,
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config.Jwt.Key)),
ValidateLifetime = false //in this case, we don't care about the token's expiration date
};
var tokenHandler = new JwtSecurityTokenHandler();
var principal = tokenHandler.ValidateToken(token, tokenValidationParameters, out SecurityToken securityToken);
if (!(securityToken is JwtSecurityToken jwtSecurityToken) || !string.Equals(jwtSecurityToken.Header.Alg, SecurityAlgorithms.HmacSha256, StringComparison.InvariantCultureIgnoreCase))
{
return null;
}
return principal;
}
public bool ValidateToken(string identityId, string token)
{
if (string.IsNullOrWhiteSpace(identityId) || string.IsNullOrWhiteSpace(token))
return false;
var utcNow = DateTime.UtcNow;
var userToken = _cacheManager.Get<UserTokenCache>(ShopKeys.UserJwtTokenPrefix + identityId);
if (userToken == null)
{
return false;
}
else if (string.IsNullOrWhiteSpace(userToken.Token))
{
_cacheManager.Remove(ShopKeys.UserJwtTokenPrefix + identityId);
return false;
}
var validate = userToken.Token.Equals(token, StringComparison.OrdinalIgnoreCase);
if (!validate)
{
_cacheManager.Remove(ShopKeys.UserJwtTokenPrefix + identityId);
return false;
}
var minutes = _config.Jwt.AccessTokenDurationInMinutes;
if (userToken.TokenExpiresOnUtc != null && userToken.TokenExpiresOnUtc < utcNow)
{
// 过期
validate = false;
_cacheManager.Remove(ShopKeys.UserJwtTokenPrefix + identityId);
}
else if (minutes > 0 && userToken.TokenExpiresOnUtc == null)
{
// 当调整配置时,访问时更新配置(无过期时间->有过期时间)
userToken.TokenUpdatedOnUtc = utcNow;
userToken.TokenExpiresOnUtc = utcNow.AddMinutes(minutes);
_cacheManager.Set(ShopKeys.UserJwtTokenPrefix + userToken.UserId, userToken, minutes);
}
else if (userToken.TokenExpiresOnUtc != null && userToken.TokenType != UserTokenType.Disposable && (utcNow - userToken.TokenUpdatedOnUtc).TotalMinutes >= 1)
{
// 如果是一次性令牌则不续签
// 每分钟自动续签
// 注意:默认jwt令牌不开启过期策略的
userToken.TokenUpdatedOnUtc = utcNow;
userToken.TokenExpiresOnUtc = utcNow.AddMinutes(minutes);
_cacheManager.Set(ShopKeys.UserJwtTokenPrefix + userToken.UserId, userToken, minutes);
}
return validate;
}
public void RemoveUserToken(int userId)
{
_cacheManager.Remove(ShopKeys.UserJwtTokenPrefix + userId);
}
public async Task<IList<Claim>> BuildClaims(User user)
{
var claims = new List<Claim>
{
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
// https://stackoverflow.com/questions/51119926/jwt-authentication-usermanager-getuserasync-returns-null
// default the value of UserIdClaimType is ClaimTypes.NameIdentifier, i.e. "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier"
new Claim(JwtRegisteredClaimNames.NameId, user.Id.ToString()),
new Claim(JwtRegisteredClaimNames.UniqueName, user.UserName),
};
var userRoles = await _userManager.GetRolesAsync(user);
foreach (var userRole in userRoles)
{
claims.Add(new Claim(ClaimTypes.Role, userRole));
}
return claims;
}
}
}
| 40.321637 | 193 | 0.608702 | [
"MIT"
] | LGinC/module-shop | src/server/src/Modules/Shop.Module.Core/Services/TokenService.cs | 7,021 | C# |
using Superpower.Parsers;
using Superpower.Tests.Support;
using Xunit;
namespace Superpower.Tests.Combinators
{
public class TryCombinatorTests
{
[Fact]
public void TryFailureConsumesNoInput()
{
var tryAb = Character.EqualTo('a').Then(_ => Character.EqualTo('b')).Try();
var result = tryAb.TryParse("ac");
Assert.False(result.HasValue);
Assert.True(result.Backtrack);
}
[Fact]
public void TrySuccessIsTransparent()
{
var tryAb = Character.EqualTo('a').Then(_ => Character.EqualTo('b')).Try();
var result = tryAb.TryParse("ab");
Assert.True(result.HasValue);
Assert.True(result.Remainder.IsAtEnd);
}
[Fact]
public void TryItemMakesManyBacktrack()
{
var ab = Character.EqualTo('a').Then(_ => Character.EqualTo('b'));
var list = ab.Try().Many();
AssertParser.SucceedsWithMany(list, "ababa", "bb".ToCharArray());
}
[Fact]
public void TryAlternativeMakesOrBacktrack()
{
var tryAOrAB = Character.EqualTo('a').Then(_ => Character.EqualTo('b')).Try().Or(Character.EqualTo('a'));
AssertParser.SucceedsWith(tryAOrAB, "a", 'a');
}
[Fact]
public void TokenTryFailureBacktracks()
{
var tryAb = Token.EqualTo('a').Then(_ => Token.EqualTo('b')).Try();
var result = tryAb.TryParse(StringAsCharTokenList.Tokenize("ac"));
Assert.False(result.HasValue);
Assert.True(result.Backtrack);
}
[Fact]
public void TokenTrySuccessIsTransparent()
{
var tryAb = Token.EqualTo('a').Then(_ => Token.EqualTo('b')).Try();
var result = tryAb.TryParse(StringAsCharTokenList.Tokenize("ab"));
Assert.True(result.HasValue);
Assert.True(result.Remainder.IsAtEnd);
}
[Fact]
public void TokenTryItemMakesManyBacktrack()
{
var ab = Token.EqualTo('a').Then(_ => Token.EqualTo('b'));
var list = ab.Try().Many();
AssertParser.SucceedsWithMany(list, "ababa", "bb".ToCharArray());
}
[Fact]
public void TokenTryAlternativeMakesOrBacktrack()
{
var tryAOrAB = Token.EqualTo('a').Then(_ => Token.EqualTo('b')).Try().Or(Token.EqualTo('a'));
AssertParser.SucceedsWith(tryAOrAB, "a", 'a');
}
}
}
| 33.289474 | 117 | 0.560474 | [
"Apache-2.0"
] | BenjaminHolland/superpower | test/Superpower.Tests/Combinators/TryCombinatorTests.cs | 2,532 | C# |
namespace bleak.Sql.VersionManager
{
public interface ISchema
{
string Name { get; set; }
}
} | 16.285714 | 35 | 0.605263 | [
"Unlicense"
] | jamalkhan/bleak.Sql | bleak.Sql.VersionManager/ISchema.cs | 116 | C# |
namespace NSUI.Controls
{
public class NSNewsButton : NSCircleButton
{
public NSNewsButton()
{
DefaultStyleKey = typeof(NSNewsButton);
}
}
} | 18.9 | 51 | 0.57672 | [
"MIT"
] | h82258652/NSUI | NSUI/NSUI.Uwp/Controls/NSNewsButton.cs | 191 | C# |
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.Extensions.Localization;
using OrchardCore.Environment.Shell;
using OrchardCore.Environment.Shell.Models;
using OrchardCore.Environment.Shell.Scope;
using OrchardCore.Workflows.Abstractions.Models;
using OrchardCore.Workflows.Activities;
using OrchardCore.Workflows.Models;
using OrchardCore.Workflows.Services;
namespace OrchardCore.Tenants.Workflows.Activities
{
public class CreateTenantTask : TenantTask
{
public CreateTenantTask(IShellSettingsManager shellSettingsManager, IShellHost shellHost, IWorkflowExpressionEvaluator expressionEvaluator, IWorkflowScriptEvaluator scriptEvaluator, IStringLocalizer<CreateTenantTask> localizer)
: base(shellSettingsManager, shellHost, expressionEvaluator, scriptEvaluator, localizer)
{
}
public override string Name => nameof(CreateTenantTask);
public override LocalizedString Category => S["Tenant"];
public override LocalizedString DisplayText => S["Create Tenant Task"];
public string ContentType
{
get => GetProperty<string>();
set => SetProperty(value);
}
public WorkflowExpression<string> Description
{
get => GetProperty(() => new WorkflowExpression<string>());
set => SetProperty(value);
}
public WorkflowExpression<string> RequestUrlPrefix
{
get => GetProperty(() => new WorkflowExpression<string>());
set => SetProperty(value);
}
public WorkflowExpression<string> RequestUrlHost
{
get => GetProperty(() => new WorkflowExpression<string>());
set => SetProperty(value);
}
public WorkflowExpression<string> DatabaseProvider
{
get => GetProperty(() => new WorkflowExpression<string>());
set => SetProperty(value);
}
public WorkflowExpression<string> ConnectionString
{
get => GetProperty(() => new WorkflowExpression<string>());
set => SetProperty(value);
}
public WorkflowExpression<string> TablePrefix
{
get => GetProperty(() => new WorkflowExpression<string>());
set => SetProperty(value);
}
public WorkflowExpression<string> RecipeName
{
get => GetProperty(() => new WorkflowExpression<string>());
set => SetProperty(value);
}
public override IEnumerable<Outcome> GetPossibleOutcomes(WorkflowExecutionContext workflowContext, ActivityContext activityContext)
{
return Outcomes(S["Done"], S["Failed"]);
}
public async override Task<ActivityExecutionResult> ExecuteAsync(WorkflowExecutionContext workflowContext, ActivityContext activityContext)
{
if (ShellScope.Context.Settings.Name != ShellHelper.DefaultShellName)
{
return Outcomes("Failed");
}
var tenantName = (await ExpressionEvaluator.EvaluateAsync(TenantName, workflowContext))?.Trim();
if (string.IsNullOrEmpty(tenantName))
{
return Outcomes("Failed");
}
if (ShellHost.TryGetSettings(tenantName, out var shellSettings))
{
return Outcomes("Failed");
}
var requestUrlPrefix = (await ExpressionEvaluator.EvaluateAsync(RequestUrlPrefix, workflowContext))?.Trim();
var requestUrlHost = (await ExpressionEvaluator.EvaluateAsync(RequestUrlHost, workflowContext))?.Trim();
var databaseProvider = (await ExpressionEvaluator.EvaluateAsync(DatabaseProvider, workflowContext))?.Trim();
var connectionString = (await ExpressionEvaluator.EvaluateAsync(ConnectionString, workflowContext))?.Trim();
var tablePrefix = (await ExpressionEvaluator.EvaluateAsync(TablePrefix, workflowContext))?.Trim();
var recipeName = (await ExpressionEvaluator.EvaluateAsync(RecipeName, workflowContext))?.Trim();
// Creates a default shell settings based on the configuration.
shellSettings = ShellSettingsManager.CreateDefaultSettings();
shellSettings.Name = tenantName;
if (!string.IsNullOrEmpty(requestUrlHost))
{
shellSettings.RequestUrlHost = requestUrlHost;
}
if (!string.IsNullOrEmpty(requestUrlPrefix))
{
shellSettings.RequestUrlPrefix = requestUrlPrefix;
}
shellSettings.State = TenantState.Uninitialized;
if (!string.IsNullOrEmpty(connectionString))
{
shellSettings["ConnectionString"] = connectionString;
}
if (!string.IsNullOrEmpty(tablePrefix))
{
shellSettings["TablePrefix"] = tablePrefix;
}
if (!string.IsNullOrEmpty(databaseProvider))
{
shellSettings["DatabaseProvider"] = databaseProvider;
}
if (!string.IsNullOrEmpty(recipeName))
{
shellSettings["RecipeName"] = recipeName;
}
shellSettings["Secret"] = Guid.NewGuid().ToString();
await ShellHost.UpdateShellSettingsAsync(shellSettings);
workflowContext.LastResult = shellSettings;
workflowContext.CorrelationId = shellSettings.Name;
return Outcomes("Done");
}
}
}
| 36.187097 | 235 | 0.631663 | [
"BSD-3-Clause"
] | Dryadepy/OrchardCore | src/OrchardCore.Modules/OrchardCore.Tenants/Workflows/Activities/CreateTenantTask.cs | 5,609 | C# |
using ClosedXML.Excel;
using FluentAssertions;
using IntNovAction.Utils.ExcelImporter.CellProcessors;
using IntNovAction.Utils.Importer;
using IntNovAction.Utils.Importer.Tests.SampleClasses;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Linq;
using System.Reflection;
namespace IntNovAction.Utils.ExcelImporter.Tests.Processors
{
[TestClass]
public class NullableDecimal_Should
{
private readonly PropertyInfo NullableDecimalProperty;
private NumberNullableCellProcessor<decimal, SampleImportInto> Processor;
private ImportResult<SampleImportInto> ImportResult;
private SampleImportInto ObjectToBeFilled;
public IXLCell Cell { get; private set; }
public NullableDecimal_Should()
{
NullableDecimalProperty = typeof(SampleImportInto).GetProperty(nameof(SampleImportInto.NullableDecimalColumn));
}
[TestInitialize()]
public void Initializer()
{
this.Processor = new NumberNullableCellProcessor<decimal, SampleImportInto>();
this.ImportResult = new ImportResult<SampleImportInto>();
this.ObjectToBeFilled = new SampleImportInto();
this.Cell = GetXLCell();
}
[TestMethod]
public void Process_Decimal_Ok()
{
Cell.Value = 1;
var cellProcessResult = this.Processor.SetValue(ImportResult, ObjectToBeFilled, NullableDecimalProperty, Cell);
cellProcessResult.Should().BeTrue();
ImportResult.Errors.Should().BeNullOrEmpty();
ObjectToBeFilled.NullableDecimalColumn.Should().Be(1);
}
[TestMethod]
public void Process_Letter_AsError()
{
Cell.Value = "S";
var cellProcessResult = this.Processor.SetValue(ImportResult, ObjectToBeFilled, NullableDecimalProperty, Cell);
cellProcessResult.Should().BeFalse();
ImportResult.Errors.Should().NotBeNullOrEmpty();
ImportResult.Errors.Count.Should().Be(1);
ImportResult.Errors[0].Column.Should().Be(1);
ImportResult.Errors[0].Row.Should().Be(1);
ImportResult.Errors[0].ErrorType.Should().Be(ImportErrorType.InvalidValue);
ObjectToBeFilled.NullableDecimalColumn.Should().Be(null);
}
[TestMethod]
public void Process_EmptyString_AsNull()
{
Cell.Value = "";
var cellProcessResult = this.Processor.SetValue(ImportResult, ObjectToBeFilled, NullableDecimalProperty, Cell);
cellProcessResult.Should().BeTrue();
ImportResult.Errors.Should().BeEmpty();
ObjectToBeFilled.NullableDecimalColumn.Should().Be(null);
}
[TestMethod]
public void Process_Null_AsNull()
{
Cell.Value = null;
var cellProcessResult = this.Processor.SetValue(ImportResult, ObjectToBeFilled, NullableDecimalProperty, Cell);
cellProcessResult.Should().BeTrue();
ImportResult.Errors.Should().BeEmpty();
ObjectToBeFilled.NullableDecimalColumn.Should().Be(null);
}
public IXLCell GetXLCell()
{
var wk = new XLWorkbook();
wk.AddWorksheet("Test1");
return wk.Worksheet(1).Cell(1, 1);
}
}
}
| 32.631068 | 123 | 0.651889 | [
"MIT"
] | JTOne123/IntNovAction.Utils.ExcelImporter | IntNovAction.Utils.ExcelImporter.Tests/Processors/NullableDecimal_Should.cs | 3,363 | C# |
/*
* Bungie.Net API
*
* These endpoints constitute the functionality exposed by Bungie.net, both for more traditional website functionality and for connectivity to Bungie video games and their related functionality.
*
* OpenAPI spec version: 2.1.1
* Contact: support@bungie.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using NUnit.Framework;
using System;
using System.Linq;
using System.IO;
using System.Collections.Generic;
using BungieNetPlatform.Api;
using BungieNetPlatform.Model;
using BungieNetPlatform.Client;
using System.Reflection;
using Newtonsoft.Json;
namespace BungieNetPlatform.Test
{
/// <summary>
/// Class for testing InlineResponse20022
/// </summary>
/// <remarks>
/// This file is automatically generated by Swagger Codegen.
/// Please update the test case below to test the model.
/// </remarks>
[TestFixture]
public class InlineResponse20022Tests
{
// TODO uncomment below to declare an instance variable for InlineResponse20022
//private InlineResponse20022 instance;
/// <summary>
/// Setup before each test
/// </summary>
[SetUp]
public void Init()
{
// TODO uncomment below to create an instance of InlineResponse20022
//instance = new InlineResponse20022();
}
/// <summary>
/// Clean up after each test
/// </summary>
[TearDown]
public void Cleanup()
{
}
/// <summary>
/// Test an instance of InlineResponse20022
/// </summary>
[Test]
public void InlineResponse20022InstanceTest()
{
// TODO uncomment below to test "IsInstanceOfType" InlineResponse20022
//Assert.IsInstanceOfType<InlineResponse20022> (instance, "variable 'instance' is a InlineResponse20022");
}
/// <summary>
/// Test the property 'Response'
/// </summary>
[Test]
public void ResponseTest()
{
// TODO unit test for the property 'Response'
}
/// <summary>
/// Test the property 'ErrorCode'
/// </summary>
[Test]
public void ErrorCodeTest()
{
// TODO unit test for the property 'ErrorCode'
}
/// <summary>
/// Test the property 'ThrottleSeconds'
/// </summary>
[Test]
public void ThrottleSecondsTest()
{
// TODO unit test for the property 'ThrottleSeconds'
}
/// <summary>
/// Test the property 'ErrorStatus'
/// </summary>
[Test]
public void ErrorStatusTest()
{
// TODO unit test for the property 'ErrorStatus'
}
/// <summary>
/// Test the property 'Message'
/// </summary>
[Test]
public void MessageTest()
{
// TODO unit test for the property 'Message'
}
/// <summary>
/// Test the property 'MessageData'
/// </summary>
[Test]
public void MessageDataTest()
{
// TODO unit test for the property 'MessageData'
}
}
}
| 26.826446 | 194 | 0.575169 | [
"MIT"
] | xlxCLUxlx/BungieNetPlatform | src/BungieNetPlatform.Test/Model/InlineResponse20022Tests.cs | 3,246 | C# |
/*
Copyright (C) 2009 Volker Berlin (vberlin@inetsoftware.de)
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
Jeroen Frijters
jeroen@frijters.net
*/
using System;
using System.Collections.Generic;
using System.Text;
using ikvm.debugger.requests;
using ikvm.debugger.win;
namespace ikvm.debugger
{
/// <summary>
/// Implementation of the JDWP Protocol. The documentation is at:
/// http://java.sun.com/javase/6/docs/platform/jpda/jdwp/jdwp-protocol.html
/// </summary>
class JdwpHandler
{
private readonly JdwpConnection conn;
// TODO Create a real implementation
private readonly TargetVM target;
internal JdwpHandler(JdwpConnection conn, TargetVM target)
{
this.conn = conn;
this.target = target;
}
internal void Run()
{
while (true)
{
Packet packet = conn.ReadPacket();
Console.Error.WriteLine("Packet:"+packet.CommandSet + " " + packet.Command);
switch (packet.CommandSet)
{
case CommandSet.VirtualMachine:
CommandSetVirtualMachine(packet);
break;
case CommandSet.ReferenceType:
CommandSetReferenceType(packet);
break;
case CommandSet.EventRequest:
CommandSetEventRequest(packet);
break;
default:
NotImplementedPacket(packet);
break;
}
conn.SendPacket(packet);
}
}
/// <summary>
/// http://java.sun.com/javase/6/docs/platform/jpda/jdwp/jdwp-protocol.html#JDWP_VirtualMachine
/// </summary>
/// <param name="packet"></param>
private void CommandSetVirtualMachine(Packet packet)
{
switch (packet.Command)
{
case VirtualMachine.Version:
packet.WriteString("IKVM Debugger");
packet.WriteInt(1);
packet.WriteInt(6);
packet.WriteString("1.6.0");
packet.WriteString("IKVM.NET");
break;
case VirtualMachine.ClassesBySignature:
String jniClassName = packet.ReadString();
IList<TargetType> types = target.FindTypes(jniClassName);
packet.WriteInt(types.Count); // count
foreach (TargetType type in types)
{
Console.Error.WriteLine("FindTypes:" + jniClassName + ":" + type.TypeId);
packet.WriteByte(TypeTag.CLASS); //TODO can also a interface
packet.WriteObjectID(type.TypeId);
packet.WriteInt(ClassStatus.INITIALIZED);
}
break;
case VirtualMachine.AllThreads:
int[] ids = target.GetThreadIDs();
packet.WriteInt(ids.Length);
for (int i = 0; i < ids.Length; i++)
{
packet.WriteObjectID(ids[i]);
}
break;
case VirtualMachine.IDSizes:
int size = 4; //we use a size of 4, a value of 8 is also possible
packet.WriteInt(size); // fieldID size in bytes
packet.WriteInt(size); // methodID size in bytes
packet.WriteInt(size); // objectID size in bytes
packet.WriteInt(size); // referenceTypeID size in bytes
packet.WriteInt(size); // frameID size in bytes
break;
case VirtualMachine.Suspend:
target.Suspend();
break;
case VirtualMachine.Resume:
target.Resume();
break;
case VirtualMachine.Exit:
target.Exit(packet.ReadInt());
break;
case VirtualMachine.Capabilities:
packet.WriteBool(false); // Can the VM watch field modification, and therefore can it send the Modification Watchpoint Event?
packet.WriteBool(false); // Can the VM watch field access, and therefore can it send the Access Watchpoint Event?
packet.WriteBool(false); // Can the VM get the bytecodes of a given method?
packet.WriteBool(false); // Can the VM determine whether a field or method is synthetic? (that is, can the VM determine if the method or the field was invented by the compiler?)
packet.WriteBool(false); // Can the VM get the owned monitors infornation for a thread?
packet.WriteBool(false); // Can the VM get the current contended monitor of a thread?
packet.WriteBool(false); // Can the VM get the monitor information for a given object?
break;
case VirtualMachine.CapabilitiesNew:
packet.WriteBool(false); // Can the VM watch field modification, and therefore can it send the Modification Watchpoint Event?
packet.WriteBool(false); // Can the VM watch field access, and therefore can it send the Access Watchpoint Event?
packet.WriteBool(false); // Can the VM get the bytecodes of a given method?
packet.WriteBool(false); // Can the VM determine whether a field or method is synthetic? (that is, can the VM determine if the method or the field was invented by the compiler?)
packet.WriteBool(false); // Can the VM get the owned monitors infornation for a thread?
packet.WriteBool(false); // Can the VM get the current contended monitor of a thread?
packet.WriteBool(false); // Can the VM get the monitor information for a given object?
packet.WriteBool(false); // Can the VM redefine classes?
packet.WriteBool(false); // Can the VM add methods when redefining classes?
packet.WriteBool(false); // Can the VM redefine classesin arbitrary ways?
packet.WriteBool(false); // Can the VM pop stack frames?
packet.WriteBool(false); // Can the VM filter events by specific object?
packet.WriteBool(false); // Can the VM get the source debug extension?
packet.WriteBool(false); // Can the VM request VM death events?
packet.WriteBool(false); // Can the VM set a default stratum?
packet.WriteBool(false); // Can the VM return instances, counts of instances of classes and referring objects?
packet.WriteBool(false); // Can the VM request monitor events?
packet.WriteBool(false); // Can the VM get monitors with frame depth info?
packet.WriteBool(false); // Can the VM filter class prepare events by source name?
packet.WriteBool(false); // Can the VM return the constant pool information?
packet.WriteBool(false); // Can the VM force early return from a method?
packet.WriteBool(false); // reserved22
packet.WriteBool(false); // reserved23
packet.WriteBool(false); // reserved24
packet.WriteBool(false); // reserved25
packet.WriteBool(false); // reserved26
packet.WriteBool(false); // reserved27
packet.WriteBool(false); // reserved28
packet.WriteBool(false); // reserved29
packet.WriteBool(false); // reserved30
packet.WriteBool(false); // reserved31
packet.WriteBool(false); // reserved32
break;
default:
NotImplementedPacket(packet); // include a SendPacket
break;
}
}
/// <summary>
/// http://java.sun.com/javase/6/docs/platform/jpda/jdwp/jdwp-protocol.html#JDWP_ReferenceType
/// </summary>
/// <param name="packet"></param>
private void CommandSetReferenceType(Packet packet)
{
switch (packet.Command)
{
case ReferenceType.Signature:
int typeID = packet.ReadObjectID();
TargetType type = target.FindType(typeID);
Console.Error.WriteLine(typeID + ":" + type.GetJniSignature());
packet.WriteString(type.GetJniSignature());
break;
case ReferenceType.ClassLoader:
int classLoaderID = packet.ReadObjectID();
packet.WriteObjectID(0); //TODO 0 - System Classloader, we can use module ID instead
break;
case ReferenceType.MethodsWithGeneric:
typeID = packet.ReadObjectID();
Console.Error.WriteLine(typeID);
type = target.FindType(typeID);
IList<TargetMethod> methods = type.GetMethods();
packet.WriteInt(methods.Count);
foreach (TargetMethod method in methods)
{
Console.Error.WriteLine(method.MethodId + ":" + method.Name + ":" + method.JniSignature + ":" + method.GenericSignature+":"+method.AccessFlags);
packet.WriteObjectID(method.MethodId);
packet.WriteString(method.Name);
packet.WriteString(method.JniSignature);
packet.WriteString(method.GenericSignature);
packet.WriteInt(method.AccessFlags);
}
break;
default:
NotImplementedPacket(packet);
break;
}
}
/// <summary>
/// http://java.sun.com/javase/6/docs/platform/jpda/jdwp/jdwp-protocol.html#JDWP_EventRequest
/// </summary>
/// <param name="packet"></param>
private void CommandSetEventRequest(Packet packet)
{
switch (packet.Command)
{
case EventRequest.CmdSet:
EventRequest eventRequest = EventRequest.create(packet);
Console.Error.WriteLine(eventRequest);
if (eventRequest == null)
{
NotImplementedPacket(packet);
}
else
{
target.AddEventRequest(eventRequest);
packet.WriteInt(eventRequest.RequestId);
}
break;
default:
NotImplementedPacket(packet);
break;
}
}
private void NotImplementedPacket(Packet packet)
{
Console.Error.WriteLine("================================");
Console.Error.WriteLine("Not Implemented Packet:" + packet.CommandSet + "-" + packet.Command);
Console.Error.WriteLine("================================");
packet.Error = Error.NOT_IMPLEMENTED;
}
}
}
| 48.733333 | 199 | 0.541241 | [
"Apache-2.0"
] | Distrotech/mono | external/ikvm/debugger/JdwpHandler.cs | 12,427 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BuilderDesignPattern
{
class Program
{
static void Main(string[] args)
{
#region Lab_1
//Directory directory = new Directory();
//IBuilder b_1 = new Builder_1();
//IBuilder b_2 = new Builder_2();
//directory.Constructor(b_1);
//Product p_1 = b_1.GetResult();
//p_1.Display();
//directory.Constructor(b_2);
//Product p_2 = b_2.GetResult();
//p_2.Display();
//Console.ReadKey();
#endregion
#region Lab_2
//ProductDirectory directory = new ProductDirectory();
//ProductBuilder builder = new A_ProductBuilder();
//directory.GenerateProduct(builder);
//var model = builder.GetModel();
//Console.WriteLine(model.Id);
//Console.WriteLine(model.ProductName);
//Console.WriteLine(model.UnitPrice);
//Console.WriteLine(model.DiscountPrice);
//Console.WriteLine(model.DiscountedApplied);
//Console.ReadKey();
#endregion
#region Lab_3
//KrediKartıBuilder gercekKart = new AMEXKartBuilder();
//KrediKartDictory kullan = new KrediKartDictory();
//kullan.KartKullan(gercekKart);
//Console.WriteLine(gercekKart.Kart.ToString());
//Console.ReadKey();
#endregion
}
}
}
| 26.311475 | 67 | 0.556386 | [
"MIT"
] | YagizcanSeheri/DesignPatternStorage | BuilderDesignPattern/Program.cs | 1,608 | C# |
using UnityEngine;
using UnityEditor;
[CustomPropertyDrawer(typeof(RangeFloat))]
public class RangeFloatDrawer : PropertyDrawer
{
private static GUIContent[] emptyContent = new GUIContent[2] { new GUIContent(" "), new GUIContent(" ") };
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
int lines = EditorGUIUtility.wideMode ? 1 : 2;
position.height = lines * EditorGUIUtility.singleLineHeight;
SerializedProperty r1Prop = property.FindPropertyRelative("r1");
SerializedProperty r2Prop = property.FindPropertyRelative("r2");
float[] r = new float[2] { r1Prop.floatValue, r2Prop.floatValue };
EditorGUI.BeginChangeCheck();
EditorGUI.MultiFloatField(position, label, emptyContent, r);
if(EditorGUI.EndChangeCheck())
{
r1Prop.floatValue = r[0];
r2Prop.floatValue = r[1];
}
}
public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
{
int lines = EditorGUIUtility.wideMode ? 1 : 2;
return lines * EditorGUIUtility.singleLineHeight;
}
} | 31.69697 | 107 | 0.755258 | [
"Unlicense",
"MIT"
] | LjutaPapricica/LockPick_Unity | Assets/Source/Editor/CustomDrawers/RangeFloatDrawer.cs | 1,048 | C# |
using System;
using UnityEngine.Serialization;
namespace UnityEngine.Rendering.PostProcessing
{
// For now and by popular request, this bloom effect is geared toward artists so they have full
// control over how it looks at the expense of physical correctness.
// Eventually we will need a "true" natural bloom effect with proper energy conservation.
/// <summary>
/// This class holds settings for the Bloom effect.
/// </summary>
[Serializable]
[PostProcess(typeof(BloomRenderer), "Unity/Bloom")]
public sealed class Bloom : PostProcessEffectSettings
{
/// <summary>
/// The strength of the bloom filter.
/// </summary>
[Min(0f), Tooltip("Strength of the bloom filter. Values higher than 1 will make bloom contribute more energy to the final render.")]
public FloatParameter intensity = new FloatParameter { value = 0f };
/// <summary>
/// Filters out pixels under this level of brightness. This value is expressed in
/// gamma-space.
/// </summary>
[Min(0f), Tooltip("Filters out pixels under this level of brightness. Value is in gamma-space.")]
public FloatParameter threshold = new FloatParameter { value = 1f };
/// <summary>
/// Makes transition between under/over-threshold gradual (0 = hard threshold, 1 = soft
/// threshold).
/// </summary>
[Range(0f, 1f), Tooltip("Makes transitions between under/over-threshold gradual. 0 for a hard threshold, 1 for a soft threshold).")]
public FloatParameter softKnee = new FloatParameter { value = 0.5f };
/// <summary>
/// Clamps pixels to control the bloom amount. This value is expressed in gamma-space.
/// </summary>
[Tooltip("Clamps pixels to control the bloom amount. Value is in gamma-space.")]
public FloatParameter clamp = new FloatParameter { value = 65472f };
/// <summary>
/// Changes extent of veiling effects in a screen resolution-independent fashion. For
/// maximum quality stick to integer values. Because this value changes the internal
/// iteration count, animating it isn't recommended as it may introduce small hiccups in
/// the perceived radius.
/// </summary>
[Range(1f, 10f), Tooltip("Changes the extent of veiling effects. For maximum quality, use integer values. Because this value changes the internal iteration count, You should not animating it as it may introduce issues with the perceived radius.")]
public FloatParameter diffusion = new FloatParameter { value = 7f };
/// <summary>
/// Distorts the bloom to give an anamorphic look. Negative values distort vertically,
/// positive values distort horizontally.
/// </summary>
[Range(-1f, 1f), Tooltip("Distorts the bloom to give an anamorphic look. Negative values distort vertically, positive values distort horizontally.")]
public FloatParameter anamorphicRatio = new FloatParameter { value = 0f };
/// <summary>
/// The tint of the Bloom filter.
/// </summary>
#if UNITY_2018_1_OR_NEWER
[ColorUsage(false, true), Tooltip("Global tint of the bloom filter.")]
#else
[ColorUsage(false, true, 0f, 8f, 0.125f, 3f), Tooltip("Global tint of the bloom filter.")]
#endif
public ColorParameter color = new ColorParameter { value = Color.white };
/// <summary>
/// Boost performances by lowering the effect quality.
/// </summary>
[FormerlySerializedAs("mobileOptimized")]
[Tooltip("Boost performance by lowering the effect quality. This settings is meant to be used on mobile and other low-end platforms but can also provide a nice performance boost on desktops and consoles.")]
public BoolParameter fastMode = new BoolParameter { value = false };
/// <summary>
/// The dirtiness texture to add smudges or dust to the lens.
/// </summary>
[Tooltip("The lens dirt texture used to add smudges or dust to the bloom effect."), DisplayName("Texture")]
public TextureParameter dirtTexture = new TextureParameter { value = null };
/// <summary>
/// The amount of lens dirtiness.
/// </summary>
[Min(0f), Tooltip("The intensity of the lens dirtiness."), DisplayName("Intensity")]
public FloatParameter dirtIntensity = new FloatParameter { value = 0f };
/// <inheritdoc />
public override bool IsEnabledAndSupported(PostProcessRenderContext context)
{
return enabled.value
&& intensity.value > 0f;
}
}
#if UNITY_2017_1_OR_NEWER
[UnityEngine.Scripting.Preserve]
#endif
internal sealed class BloomRenderer : PostProcessEffectRenderer<Bloom>
{
enum Pass
{
Prefilter13,
Prefilter4,
Downsample13,
Downsample4,
UpsampleTent,
UpsampleBox,
DebugOverlayThreshold,
DebugOverlayTent,
DebugOverlayBox
}
// [down,up]
Level[] m_Pyramid;
const int k_MaxPyramidSize = 16; // Just to make sure we handle 64k screens... Future-proof!
struct Level
{
internal int down;
internal int up;
}
public override void Init()
{
m_Pyramid = new Level[k_MaxPyramidSize];
for (int i = 0; i < k_MaxPyramidSize; i++)
{
m_Pyramid[i] = new Level
{
down = Shader.PropertyToID("_BloomMipDown" + i),
up = Shader.PropertyToID("_BloomMipUp" + i)
};
}
}
public override void Render(PostProcessRenderContext context)
{
var cmd = context.command;
cmd.BeginSample("BloomPyramid");
var sheet = context.propertySheets.Get(context.resources.shaders.bloom);
// Apply auto exposure adjustment in the prefiltering pass
sheet.properties.SetTexture(ShaderIDs.AutoExposureTex, context.autoExposureTexture);
// Negative anamorphic ratio values distort vertically - positive is horizontal
float ratio = Mathf.Clamp(settings.anamorphicRatio, -1, 1);
float rw = ratio < 0 ? -ratio : 0f;
float rh = ratio > 0 ? ratio : 0f;
// Do bloom on a half-res buffer, full-res doesn't bring much and kills performances on
// fillrate limited platforms
int tw = Mathf.FloorToInt(context.screenWidth / (2f - rw));
int th = Mathf.FloorToInt(context.screenHeight / (2f - rh));
bool singlePassDoubleWide = (context.stereoActive && (context.stereoRenderingMode == PostProcessRenderContext.StereoRenderingMode.SinglePass) && (context.camera.stereoTargetEye == StereoTargetEyeMask.Both));
int tw_stereo = singlePassDoubleWide ? tw * 2 : tw;
// Determine the iteration count
int s = Mathf.Max(tw, th);
float logs = Mathf.Log(s, 2f) + Mathf.Min(settings.diffusion.value, 10f) - 10f;
int logs_i = Mathf.FloorToInt(logs);
int iterations = Mathf.Clamp(logs_i, 1, k_MaxPyramidSize);
float sampleScale = 0.5f + logs - logs_i;
sheet.properties.SetFloat(ShaderIDs.SampleScale, sampleScale);
// Prefiltering parameters
float lthresh = Mathf.GammaToLinearSpace(settings.threshold.value);
float knee = lthresh * settings.softKnee.value + 1e-5f;
var threshold = new Vector4(lthresh, lthresh - knee, knee * 2f, 0.25f / knee);
sheet.properties.SetVector(ShaderIDs.Threshold, threshold);
float lclamp = Mathf.GammaToLinearSpace(settings.clamp.value);
sheet.properties.SetVector(ShaderIDs.Params, new Vector4(lclamp, 0f, 0f, 0f));
int qualityOffset = settings.fastMode ? 1 : 0;
// Downsample
var lastDown = context.source;
for (int i = 0; i < iterations; i++)
{
int mipDown = m_Pyramid[i].down;
int mipUp = m_Pyramid[i].up;
int pass = i == 0
? (int)Pass.Prefilter13 + qualityOffset
: (int)Pass.Downsample13 + qualityOffset;
context.GetScreenSpaceTemporaryRT(cmd, mipDown, 0, context.sourceFormat, RenderTextureReadWrite.Default, FilterMode.Bilinear, tw_stereo, th);
context.GetScreenSpaceTemporaryRT(cmd, mipUp, 0, context.sourceFormat, RenderTextureReadWrite.Default, FilterMode.Bilinear, tw_stereo, th);
cmd.BlitFullscreenTriangle(lastDown, mipDown, sheet, pass);
lastDown = mipDown;
tw_stereo = (singlePassDoubleWide && ((tw_stereo / 2) % 2 > 0)) ? 1 + tw_stereo / 2 : tw_stereo / 2;
tw_stereo = Mathf.Max(tw_stereo, 1);
th = Mathf.Max(th / 2, 1);
}
// Upsample
int lastUp = m_Pyramid[iterations - 1].down;
for (int i = iterations - 2; i >= 0; i--)
{
int mipDown = m_Pyramid[i].down;
int mipUp = m_Pyramid[i].up;
cmd.SetGlobalTexture(ShaderIDs.BloomTex, mipDown);
cmd.BlitFullscreenTriangle(lastUp, mipUp, sheet, (int)Pass.UpsampleTent + qualityOffset);
lastUp = mipUp;
}
var linearColor = settings.color.value.linear;
float intensity = RuntimeUtilities.Exp2(settings.intensity.value / 10f) - 1f;
var shaderSettings = new Vector4(sampleScale, intensity, settings.dirtIntensity.value, iterations);
// Debug overlays
if (context.IsDebugOverlayEnabled(DebugOverlay.BloomThreshold))
{
context.PushDebugOverlay(cmd, context.source, sheet, (int)Pass.DebugOverlayThreshold);
}
else if (context.IsDebugOverlayEnabled(DebugOverlay.BloomBuffer))
{
sheet.properties.SetVector(ShaderIDs.ColorIntensity, new Vector4(linearColor.r, linearColor.g, linearColor.b, intensity));
context.PushDebugOverlay(cmd, m_Pyramid[0].up, sheet, (int)Pass.DebugOverlayTent + qualityOffset);
}
// Lens dirtiness
// Keep the aspect ratio correct & center the dirt texture, we don't want it to be
// stretched or squashed
var dirtTexture = settings.dirtTexture.value == null
? RuntimeUtilities.blackTexture
: settings.dirtTexture.value;
var dirtRatio = (float)dirtTexture.width / (float)dirtTexture.height;
var screenRatio = (float)context.screenWidth / (float)context.screenHeight;
var dirtTileOffset = new Vector4(1f, 1f, 0f, 0f);
if (dirtRatio > screenRatio)
{
dirtTileOffset.x = screenRatio / dirtRatio;
dirtTileOffset.z = (1f - dirtTileOffset.x) * 0.5f;
}
else if (screenRatio > dirtRatio)
{
dirtTileOffset.y = dirtRatio / screenRatio;
dirtTileOffset.w = (1f - dirtTileOffset.y) * 0.5f;
}
// Shader properties
var uberSheet = context.uberSheet;
if (settings.fastMode)
uberSheet.EnableKeyword("BLOOM_LOW");
else
uberSheet.EnableKeyword("BLOOM");
uberSheet.properties.SetVector(ShaderIDs.Bloom_DirtTileOffset, dirtTileOffset);
uberSheet.properties.SetVector(ShaderIDs.Bloom_Settings, shaderSettings);
uberSheet.properties.SetColor(ShaderIDs.Bloom_Color, linearColor);
uberSheet.properties.SetTexture(ShaderIDs.Bloom_DirtTex, dirtTexture);
cmd.SetGlobalTexture(ShaderIDs.BloomTex, lastUp);
// Cleanup
for (int i = 0; i < iterations; i++)
{
if (m_Pyramid[i].down != lastUp)
cmd.ReleaseTemporaryRT(m_Pyramid[i].down);
if (m_Pyramid[i].up != lastUp)
cmd.ReleaseTemporaryRT(m_Pyramid[i].up);
}
cmd.EndSample("BloomPyramid");
context.bloomBufferNameID = lastUp;
}
}
}
| 45.549451 | 255 | 0.609972 | [
"MIT"
] | 25077667/Camera_Man_GameJam | 0905_GameJam/Library/PackageCache/com.unity.postprocessing@2.1.7/PostProcessing/Runtime/Effects/Bloom.cs | 12,435 | C# |
namespace Newbe.Claptrap.StorageProvider.Relational.EventStore
{
public interface IEventEntityMapper<T>
where T : IEventEntity
{
T Map(IEvent @event);
IEvent Map(T entity, IClaptrapIdentity identity);
}
} | 24.1 | 62 | 0.684647 | [
"MIT"
] | Z4t4r/Newbe.Claptrap | src/Newbe.Claptrap.StorageProvider.Relational/EventStore/IEventEntityMapper.cs | 241 | C# |
//-----------------------------------------------------------------------
// <copyright file="UnsafeUtilities.cs" company="Sirenix IVS">
// Copyright (c) 2018 Sirenix IVS
//
// 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 ToolBox.Serialization.OdinSerializer.Utilities.Unsafe
{
using System;
using System.Runtime.InteropServices;
/// <summary>
/// Contains utilities for performing common unsafe operations.
/// </summary>
public static class UnsafeUtilities
{
/// <summary>
/// Blindly creates an array of structs from an array of bytes via direct memory copy/blit.
/// </summary>
public static unsafe T[] StructArrayFromBytes<T>(byte[] bytes, int byteLength) where T : struct
{
return StructArrayFromBytes<T>(bytes, 0, 0);
}
/// <summary>
/// Blindly creates an array of structs from an array of bytes via direct memory copy/blit.
/// </summary>
public static unsafe T[] StructArrayFromBytes<T>(byte[] bytes, int byteLength, int byteOffset) where T : struct
{
if (bytes == null)
{
throw new ArgumentNullException("bytes");
}
if (byteLength <= 0)
{
throw new ArgumentException("Byte length must be larger than zero.");
}
if (byteOffset < 0)
{
throw new ArgumentException("Byte offset must be larger than or equal to zero.");
}
int typeSize = Marshal.SizeOf(typeof(T));
if (byteOffset % sizeof(ulong) != 0)
{
throw new ArgumentException("Byte offset must be divisible by " + sizeof(ulong) + " (IE, sizeof(ulong))");
}
if (byteLength + byteOffset >= bytes.Length)
{
throw new ArgumentException("Given byte array of size " + bytes.Length + " is not large enough to copy requested number of bytes " + byteLength + ".");
}
if ((byteLength - byteOffset) % typeSize != 0)
{
throw new ArgumentException("The length in the given byte array (" + bytes.Length + ", and " + (bytes.Length - byteOffset) + " minus byteOffset " + byteOffset + ") to convert to type " + typeof(T).Name + " is not divisible by the size of " + typeof(T).Name + " (" + typeSize + ").");
}
int elementCount = (bytes.Length - byteOffset) / typeSize;
T[] array = new T[elementCount];
MemoryCopy(bytes, array, byteLength, byteOffset, 0);
return array;
}
/// <summary>
/// Blindly copies an array of structs into an array of bytes via direct memory copy/blit.
/// </summary>
public static unsafe byte[] StructArrayToBytes<T>(T[] array) where T : struct
{
byte[] bytes = null;
return StructArrayToBytes(array, ref bytes, 0);
}
/// <summary>
/// Blindly copies an array of structs into an array of bytes via direct memory copy/blit.
/// </summary>
public static unsafe byte[] StructArrayToBytes<T>(T[] array, ref byte[] bytes, int byteOffset) where T : struct
{
if (array == null)
{
throw new ArgumentNullException("array");
}
if (byteOffset < 0)
{
throw new ArgumentException("Byte offset must be larger than or equal to zero.");
}
int typeSize = Marshal.SizeOf(typeof(T));
int byteCount = typeSize * array.Length;
if (bytes == null)
{
bytes = new byte[byteCount + byteOffset];
}
else if (bytes.Length + byteOffset > byteCount)
{
throw new ArgumentException("Byte array must be at least " + (bytes.Length + byteOffset) + " long with the given byteOffset.");
}
MemoryCopy(array, bytes, byteCount, 0, byteOffset);
return bytes;
}
/// <summary>
/// Creates a new string from the contents of a given byte buffer.
/// </summary>
public static unsafe string StringFromBytes(byte[] buffer, int charLength, bool needs16BitSupport)
{
int byteCount = needs16BitSupport ? charLength * 2 : charLength;
if (buffer.Length < byteCount)
{
throw new ArgumentException("Buffer is not large enough to contain the given string; a size of at least " + byteCount + " is required.");
}
GCHandle toHandle = default(GCHandle);
string result = new string(default(char), charLength); // Creaty empty string of required length
try
{
toHandle = GCHandle.Alloc(buffer, GCHandleType.Pinned);
if (needs16BitSupport)
{
if (BitConverter.IsLittleEndian)
{
fixed (char* charPtr1 = result)
{
ushort* fromPtr1 = (ushort*)toHandle.AddrOfPinnedObject().ToPointer();
ushort* toPtr1 = (ushort*)charPtr1;
for (int i = 0; i < byteCount; i += sizeof(ushort))
{
*toPtr1++ = *fromPtr1++;
}
}
}
else
{
fixed (char* charPtr2 = result)
{
byte* fromPtr2 = (byte*)toHandle.AddrOfPinnedObject().ToPointer();
byte* toPtr2 = (byte*)charPtr2;
for (int i = 0; i < byteCount; i += sizeof(ushort))
{
*toPtr2 = *(fromPtr2 + 1);
*(toPtr2 + 1) = *fromPtr2;
fromPtr2 += 2;
toPtr2 += 2;
}
}
}
}
else
{
if (BitConverter.IsLittleEndian)
{
fixed (char* charPtr3 = result)
{
byte* fromPtr3 = (byte*)toHandle.AddrOfPinnedObject().ToPointer();
byte* toPtr3 = (byte*)charPtr3;
for (int i = 0; i < byteCount; i += sizeof(byte))
{
*toPtr3++ = *fromPtr3++;
toPtr3++; // Skip every other string byte
}
}
}
else
{
fixed (char* charPtr4 = result)
{
byte* fromPtr4 = (byte*)toHandle.AddrOfPinnedObject().ToPointer();
byte* toPtr4 = (byte*)charPtr4;
for (int i = 0; i < byteCount; i += sizeof(byte))
{
toPtr4++; // Skip every other string byte
*toPtr4++ = *fromPtr4++;
}
}
}
}
}
finally
{
if (toHandle.IsAllocated)
{
toHandle.Free();
}
}
// Retrieve proper string reference from the intern pool.
// This code removed for now, as the slight decrease in memory use is not considered worth the performance cost of the intern lookup and the potential extra garbage to be collected.
// Might eventually become a global config option, if this is considered necessary.
//result = string.Intern(result);
return result;
}
/// <summary>
/// Writes the contents of a string into a given byte buffer.
/// </summary>
public static unsafe int StringToBytes(byte[] buffer, string value, bool needs16BitSupport)
{
int byteCount = needs16BitSupport ? value.Length * 2 : value.Length;
if (buffer.Length < byteCount)
{
throw new ArgumentException("Buffer is not large enough to contain the given string; a size of at least " + byteCount + " is required.");
}
GCHandle toHandle = default(GCHandle);
try
{
toHandle = GCHandle.Alloc(buffer, GCHandleType.Pinned);
if (needs16BitSupport)
{
if (BitConverter.IsLittleEndian)
{
fixed (char* charPtr1 = value)
{
ushort* fromPtr1 = (ushort*)charPtr1;
ushort* toPtr1 = (ushort*)toHandle.AddrOfPinnedObject().ToPointer();
for (int i = 0; i < byteCount; i += sizeof(ushort))
{
*toPtr1++ = *fromPtr1++;
}
}
}
else
{
fixed (char* charPtr2 = value)
{
byte* fromPtr2 = (byte*)charPtr2;
byte* toPtr2 = (byte*)toHandle.AddrOfPinnedObject().ToPointer();
for (int i = 0; i < byteCount; i += sizeof(ushort))
{
*toPtr2 = *(fromPtr2 + 1);
*(toPtr2 + 1) = *fromPtr2;
fromPtr2 += 2;
toPtr2 += 2;
}
}
}
}
else
{
if (BitConverter.IsLittleEndian)
{
fixed (char* charPtr3 = value)
{
byte* fromPtr3 = (byte*)charPtr3;
byte* toPtr3 = (byte*)toHandle.AddrOfPinnedObject().ToPointer();
for (int i = 0; i < byteCount; i += sizeof(byte))
{
fromPtr3++; // Skip every other string byte
*toPtr3++ = *fromPtr3++;
}
}
}
else
{
fixed (char* charPtr4 = value)
{
byte* fromPtr4 = (byte*)charPtr4;
byte* toPtr4 = (byte*)toHandle.AddrOfPinnedObject().ToPointer();
for (int i = 0; i < byteCount; i += sizeof(byte))
{
*toPtr4++ = *fromPtr4++;
fromPtr4++; // Skip every other string byte
}
}
}
}
}
finally
{
if (toHandle.IsAllocated)
{
toHandle.Free();
}
}
return byteCount;
}
private struct Struct256Bit
{
public decimal d1;
public decimal d2;
}
public static unsafe void MemoryCopy(void* from, void* to, int bytes)
{
byte* end = (byte*)to + bytes;
Struct256Bit* fromBigPtr = (Struct256Bit*)from;
Struct256Bit* toBigPtr = (Struct256Bit*)to;
while ((toBigPtr + 1) <= end)
{
*toBigPtr++ = *fromBigPtr++;
}
byte* fromSmallPtr = (byte*)fromBigPtr;
byte* toSmallPtr = (byte*)toBigPtr;
while (toSmallPtr < end)
{
*toSmallPtr++ = *fromSmallPtr++;
}
}
/// <summary>
/// Blindly mem-copies a given number of bytes from the memory location of one object to another. WARNING: This method is ridiculously dangerous. Only use if you know what you're doing.
/// </summary>
public static unsafe void MemoryCopy(object from, object to, int byteCount, int fromByteOffset, int toByteOffset)
{
GCHandle fromHandle = default(GCHandle);
GCHandle toHandle = default(GCHandle);
if (fromByteOffset % sizeof(ulong) != 0 || toByteOffset % sizeof(ulong) != 0)
{
throw new ArgumentException("Byte offset must be divisible by " + sizeof(ulong) + " (IE, sizeof(ulong))");
}
try
{
int restBytes = byteCount % sizeof(ulong);
int ulongCount = (byteCount - restBytes) / sizeof(ulong);
int fromOffsetCount = fromByteOffset / sizeof(ulong);
int toOffsetCount = toByteOffset / sizeof(ulong);
fromHandle = GCHandle.Alloc(from, GCHandleType.Pinned);
toHandle = GCHandle.Alloc(to, GCHandleType.Pinned);
ulong* fromUlongPtr = (ulong*)fromHandle.AddrOfPinnedObject().ToPointer();
ulong* toUlongPtr = (ulong*)toHandle.AddrOfPinnedObject().ToPointer();
if (fromOffsetCount > 0)
{
fromUlongPtr += fromOffsetCount;
}
if (toOffsetCount > 0)
{
toUlongPtr += toOffsetCount;
}
for (int i = 0; i < ulongCount; i++)
{
*toUlongPtr++ = *fromUlongPtr++;
}
if (restBytes > 0)
{
byte* fromBytePtr = (byte*)fromUlongPtr;
byte* toBytePtr = (byte*)toUlongPtr;
for (int i = 0; i < restBytes; i++)
{
*toBytePtr++ = *fromBytePtr++;
}
}
}
finally
{
if (fromHandle.IsAllocated)
{
fromHandle.Free();
}
if (toHandle.IsAllocated)
{
toHandle.Free();
}
}
}
}
} | 37.839901 | 299 | 0.444379 | [
"Apache-2.0",
"MIT"
] | IntoTheDev/Save-System-for-Unity | OdinSerializer/Utilities/Misc/UnsafeUtilities.cs | 15,363 | C# |
using System;
using System.IO;
using System.Linq;
using OpenMLTD.MilliSim.Contributed.Scores;
using OpenMLTD.MilliSim.Contributed.Scores.Extending;
using OpenMLTD.MilliSim.Contributed.Scores.Runtime;
using OpenMLTD.MilliSim.Contributed.Scores.Source;
using OpenMLTD.MilliSim.Core;
using OpenMLTD.MilliSim.Extension.Contributed.Scores.StandardScoreFormats.Mltd.Internal;
using OpenMLTD.MilliSim.Extension.Contributed.Scores.StandardScoreFormats.Mltd.Serialization;
using UnityStudio.Extensions;
using UnityStudio.Models;
using UnityStudio.Serialization;
namespace OpenMLTD.MilliSim.Extension.Contributed.Scores.StandardScoreFormats.Mltd {
internal sealed class Unity3DScoreReader : DisposableBase, IScoreReader {
public bool IsStreamingSupported => true;
public SourceScore ReadSourceScore(Stream stream, string fileName, ReadSourceOptions sourceOptions) {
var extension = Path.GetExtension(fileName);
if (extension == null) {
throw new ArgumentException();
}
var lz4Extension = Unity3DScoreFormat.Unity3DReadExtensions[1];
var isCompressed = extension.ToLowerInvariant().EndsWith(lz4Extension);
ScoreObject scoreObject = null;
using (var bundle = new BundleFile(stream, fileName, isCompressed)) {
foreach (var asset in bundle.AssetFiles) {
foreach (var preloadData in asset.PreloadDataList) {
if (preloadData.KnownType != KnownClassID.MonoBehaviour) {
continue;
}
var behaviour = preloadData.LoadAsMonoBehaviour(true);
if (!behaviour.Name.Contains("fumen")) {
continue;
}
behaviour = preloadData.LoadAsMonoBehaviour(false);
var serializer = new MonoBehaviourSerializer();
scoreObject = serializer.Deserialize<ScoreObject>(behaviour);
break;
}
}
}
if (scoreObject == null) {
throw new FormatException();
}
return ToSourceScore(scoreObject, sourceOptions);
}
public RuntimeScore ReadCompiledScore(Stream stream, string fileName, ReadSourceOptions sourceOptions, ScoreCompileOptions compileOptions) {
var score = ReadSourceScore(stream, fileName, sourceOptions);
using (var compiler = new Unity3DScoreCompiler()) {
return compiler.Compile(score, compileOptions);
}
}
protected override void Dispose(bool disposing) {
}
private static SourceScore ToSourceScore(ScoreObject scoreObject, ReadSourceOptions options) {
var score = new SourceScore();
var scoreIndex = options.ScoreIndex;
var difficulty = (Difficulty)scoreIndex;
var trackType = ScoreHelper.MapDifficultyToTrackType(difficulty);
var tracks = ScoreHelper.GetTrackIndicesFromTrackType(trackType);
score.Notes = scoreObject.NoteEvents
.Where(nd => Array.IndexOf(tracks, nd.Track) >= 0)
.Select(n => ToNote(n, tracks))
.Where(n => n != null).ToArray();
score.Conductors = scoreObject.ConductorEvents.Select(ToConductor).ToArray();
score.MusicOffset = scoreObject.BgmOffset;
score.ScoreIndex = scoreIndex;
score.TrackCount = tracks.Length;
return score;
}
private static SourceNote ToNote(EventNoteData noteData, int[] tracks) {
var mltdNoteType = (MltdNoteType)noteData.Type;
switch (mltdNoteType) {
case MltdNoteType.PrimaryBeat:
case MltdNoteType.SecondaryBeat:
// We don't generate notes for these types.
return null;
}
var note = new SourceNote();
// MLTD tick is divided by 8.
note.Ticks = noteData.Tick * (NoteBase.TicksPerBeat / 8);
note.Measure = noteData.Measure - 1;
note.Beat = noteData.Beat - 1;
note.StartX = noteData.StartPositionX;
note.EndX = noteData.EndPositionX;
note.Speed = noteData.Speed;
note.LeadTime = noteData.LeadTime;
note.TrackIndex = noteData.Track - tracks[0];
switch (mltdNoteType) {
case MltdNoteType.TapSmall:
note.Type = NoteType.Tap;
note.Size = NoteSize.Small;
break;
case MltdNoteType.TapLarge:
note.Type = NoteType.Tap;
note.Size = NoteSize.Large;
break;
case MltdNoteType.FlickLeft:
note.Type = NoteType.Flick;
note.FlickDirection = FlickDirection.Left;
break;
case MltdNoteType.FlickUp:
note.Type = NoteType.Flick;
note.FlickDirection = FlickDirection.Up;
break;
case MltdNoteType.FlickRight:
note.Type = NoteType.Flick;
note.FlickDirection = FlickDirection.Right;
break;
case MltdNoteType.HoldSmall:
case MltdNoteType.HoldLarge: {
note.Type = NoteType.Hold;
note.Size = mltdNoteType == MltdNoteType.HoldSmall ? NoteSize.Small : NoteSize.Large;
var n = new SourceNote();
var followingNotes = new[] { n };
n.StartX = note.StartX;
n.EndX = note.EndX;
// MLTD tick is divided by 8.
n.Ticks = note.Ticks + noteData.Duration * (NoteBase.TicksPerBeat / 8);
n.Speed = noteData.Speed;
n.LeadTime = noteData.LeadTime;
n.Type = note.Type;
switch ((MltdNoteEndType)noteData.EndType) {
case MltdNoteEndType.Tap:
break;
case MltdNoteEndType.FlickLeft:
n.FlickDirection = FlickDirection.Left;
break;
case MltdNoteEndType.FlickUp:
n.FlickDirection = FlickDirection.Up;
break;
case MltdNoteEndType.FlickRight:
n.FlickDirection = FlickDirection.Right;
break;
default:
throw new ArgumentOutOfRangeException();
}
note.FollowingNotes = followingNotes;
}
break;
case MltdNoteType.SlideSmall: {
note.Type = NoteType.Slide;
note.Size = NoteSize.Small;
var followingNotes = new SourceNote[noteData.Polypoints.Length - 1];
for (var i = 1; i < noteData.Polypoints.Length; ++i) {
var poly = noteData.Polypoints[i];
var followingNote = new SourceNote {
StartX = noteData.Polypoints[i - 1].PositionX,
EndX = poly.PositionX,
// MLTD tick is divided by 8.
Ticks = note.Ticks + poly.SubTick * (NoteBase.TicksPerBeat / 8),
Speed = noteData.Speed,
LeadTime = noteData.LeadTime,
Type = note.Type
};
if (i == noteData.Polypoints.Length - 1) {
switch ((MltdNoteEndType)noteData.EndType) {
case MltdNoteEndType.Tap:
break;
case MltdNoteEndType.FlickLeft:
followingNote.FlickDirection = FlickDirection.Left;
break;
case MltdNoteEndType.FlickUp:
followingNote.FlickDirection = FlickDirection.Up;
break;
case MltdNoteEndType.FlickRight:
followingNote.FlickDirection = FlickDirection.Right;
break;
default:
throw new ArgumentOutOfRangeException();
}
}
followingNotes[i - 1] = followingNote;
}
note.FollowingNotes = followingNotes;
}
break;
case MltdNoteType.Special:
note.Type = NoteType.Special;
break;
default:
throw new ArgumentOutOfRangeException();
}
return note;
}
private static Conductor ToConductor(EventConductorData conductorData) {
var conductor = new Conductor();
// MLTD tick is divided by 8.
conductor.Ticks = conductorData.Tick * (NoteBase.TicksPerBeat / 8);
conductor.Measure = conductorData.Measure - 1;
conductor.Beat = conductorData.Beat - 1;
conductor.Tempo = conductorData.Tempo;
conductor.SignatureNumerator = conductorData.SignatureNumerator;
conductor.SignatureDenominator = conductorData.SignatureDenominator;
return conductor;
}
private static NoteType MapMltdNoteType(MltdNoteType mltdNoteType) {
switch (mltdNoteType) {
case MltdNoteType.TapSmall:
case MltdNoteType.TapLarge:
return NoteType.Tap;
case MltdNoteType.FlickLeft:
case MltdNoteType.FlickUp:
case MltdNoteType.FlickRight:
return NoteType.Flick;
case MltdNoteType.HoldSmall:
case MltdNoteType.HoldLarge:
return NoteType.Hold;
case MltdNoteType.SlideSmall:
return NoteType.Slide;
case MltdNoteType.Special:
return NoteType.Special;
case MltdNoteType.PrimaryBeat:
case MltdNoteType.SecondaryBeat:
return NoteType.Invalid;
default:
throw new ArgumentOutOfRangeException(nameof(mltdNoteType), mltdNoteType, null);
}
}
}
}
| 44.169291 | 148 | 0.509849 | [
"MIT"
] | hozuki/TheaterDaysSim | src/plugins/StandardScoreFormats.Mltd/Unity3DScoreReader.cs | 11,219 | C# |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
using Hyak.Common;
using Microsoft.Azure.Commands.RecoveryServices.SiteRecovery.Properties;
using Microsoft.Azure.Management.RecoveryServices.SiteRecovery.Models;
namespace Microsoft.Azure.Commands.RecoveryServices.SiteRecovery
{
/// <summary>
/// Creates an Azure Site Recovery Protection Container within the specified fabric.
/// </summary>
[Cmdlet("New", ResourceManager.Common.AzureRMConstants.AzureRMPrefix + "RecoveryServicesAsrProtectionContainer",DefaultParameterSetName = ASRParameterSets.AzureToAzure,SupportsShouldProcess = true)]
[Alias("New-ASRProtectionContainer")]
[OutputType(typeof(ASRJob))]
public class NewAzureRmRecoveryServicesAsrProtectionContainer : SiteRecoveryCmdletBase
{
#region Parameters
/// <summary>
/// Gets or sets the name of the protection container.
/// </summary>
[Parameter(ParameterSetName = ASRParameterSets.AzureToAzure, Mandatory = true)]
[ValidateNotNullOrEmpty]
public string Name { get; set; }
/// <summary>
/// Gets or sets fabric in which protection container to be created.
/// </summary>
[Parameter(ParameterSetName = ASRParameterSets.AzureToAzure, Mandatory = true, ValueFromPipeline = true)]
[Alias("Fabric")]
[ValidateNotNullOrEmpty]
public ASRFabric InputObject { get; set; }
#endregion Parameters
/// <summary>
/// ProcessRecord of the command.
/// </summary>
public override void ExecuteSiteRecoveryCmdlet()
{
base.ExecuteSiteRecoveryCmdlet();
if (this.ShouldProcess(
this.Name,
VerbsCommon.New))
{
if (!this.InputObject.FabricType.Equals(Constants.Azure))
{
throw new Exception(
string.Format(
Resources.IncorrectFabricType,
Constants.Azure,
this.InputObject.FabricType));
}
var input = new CreateProtectionContainerInput()
{
Properties = new CreateProtectionContainerInputProperties()
};
var response =
RecoveryServicesClient.CreateProtectionContainer(
this.InputObject.Name,
this.Name,
input);
string jobId = PSRecoveryServicesClient.GetJobIdFromReponseLocation(response.Location);
var jobResponse =
RecoveryServicesClient
.GetAzureSiteRecoveryJobDetails(jobId);
WriteObject(new ASRJob(jobResponse));
}
}
}
}
| 40.826087 | 203 | 0.585729 | [
"MIT"
] | 3quanfeng/azure-powershell | src/RecoveryServices/RecoveryServices.SiteRecovery/ProtectionContainer/NewAzureRmRecoveryServicesAsrProtectionContainer.cs | 3,667 | C# |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using Foundation;
using osu.Framework.Configuration;
using osu.Framework.Graphics.Textures;
using osu.Framework.Graphics.Video;
using osu.Framework.Input;
using osu.Framework.Input.Bindings;
using osu.Framework.Input.Handlers;
using osu.Framework.Input.Handlers.Midi;
using osu.Framework.IO.Stores;
using osu.Framework.iOS.Graphics.Textures;
using osu.Framework.iOS.Graphics.Video;
using osu.Framework.iOS.Input;
using osu.Framework.Platform;
using UIKit;
namespace osu.Framework.iOS
{
public class IOSGameHost : OsuTKGameHost
{
private readonly IOSGameView gameView;
private IOSKeyboardHandler keyboardHandler;
private IOSRawKeyboardHandler rawKeyboardHandler;
public IOSGameHost(IOSGameView gameView)
{
this.gameView = gameView;
NSNotificationCenter.DefaultCenter.AddObserver(UIKeyboard.WillShowNotification, handleKeyboardNotification);
NSNotificationCenter.DefaultCenter.AddObserver(UIKeyboard.DidHideNotification, handleKeyboardNotification);
}
/// <summary>
/// If the keyboard visibility changes (including the hardware keyboard helper bar) we select the keyboard
/// handler based on the height of the on-screen keyboard at the end of the animation. If the height is above
/// an arbitrary value, we decide that the software keyboard handler should be enabled. Otherwise, enable the
/// raw keyboard handler.
/// This will also cover the case where there is no first responder, in which case the raw handler will still
/// successfully catch key events.
/// </summary>
private void handleKeyboardNotification(NSNotification notification)
{
NSValue nsKeyboardFrame = (NSValue)notification.UserInfo[UIKeyboard.FrameEndUserInfoKey];
RectangleF keyboardFrame = nsKeyboardFrame.RectangleFValue;
var softwareKeyboard = keyboardFrame.Height > 120;
if (keyboardHandler != null)
keyboardHandler.KeyboardActive = softwareKeyboard;
if (rawKeyboardHandler != null)
rawKeyboardHandler.KeyboardActive = !softwareKeyboard;
gameView.KeyboardTextField.SoftwareKeyboard = softwareKeyboard;
}
protected override void SetupForRun()
{
base.SetupForRun();
AllowScreenSuspension.Result.BindValueChanged(allow =>
InputThread.Scheduler.Add(() => UIApplication.SharedApplication.IdleTimerDisabled = !allow.NewValue),
true);
}
protected override IWindow CreateWindow() => new IOSGameWindow(gameView);
protected override void SetupConfig(IDictionary<FrameworkSetting, object> defaultOverrides)
{
if (!defaultOverrides.ContainsKey(FrameworkSetting.ExecutionMode))
defaultOverrides.Add(FrameworkSetting.ExecutionMode, ExecutionMode.SingleThread);
base.SetupConfig(defaultOverrides);
DebugConfig.SetValue(DebugSetting.BypassFrontToBackPass, true);
}
public override bool OnScreenKeyboardOverlapsGameWindow => true;
protected override bool LimitedMemoryEnvironment => true;
public override bool CanExit => false;
public override ITextInputSource GetTextInput() => new IOSTextInput(gameView);
protected override IEnumerable<InputHandler> CreateAvailableInputHandlers() =>
new InputHandler[]
{
new IOSTouchHandler(gameView),
keyboardHandler = new IOSKeyboardHandler(gameView),
rawKeyboardHandler = new IOSRawKeyboardHandler(),
new IOSMouseHandler(gameView),
new MidiHandler()
};
public override Storage GetStorage(string path) => new IOSStorage(path, this);
public override void OpenFileExternally(string filename) => throw new NotImplementedException();
public override void PresentFileExternally(string filename) => throw new NotImplementedException();
public override void OpenUrlExternally(string url)
{
UIApplication.SharedApplication.InvokeOnMainThread(() =>
{
NSUrl nsurl = NSUrl.FromString(url);
if (UIApplication.SharedApplication.CanOpenUrl(nsurl))
UIApplication.SharedApplication.OpenUrl(nsurl, new NSDictionary(), null);
});
}
public override Clipboard GetClipboard() => new IOSClipboard(gameView);
public override IResourceStore<TextureUpload> CreateTextureLoaderStore(IResourceStore<byte[]> underlyingStore)
=> new IOSTextureLoaderStore(underlyingStore);
public override VideoDecoder CreateVideoDecoder(Stream stream) => new IOSVideoDecoder(stream);
public override IEnumerable<KeyBinding> PlatformKeyBindings => new[]
{
new KeyBinding(new KeyCombination(InputKey.Super, InputKey.X), PlatformAction.Cut),
new KeyBinding(new KeyCombination(InputKey.Super, InputKey.C), PlatformAction.Copy),
new KeyBinding(new KeyCombination(InputKey.Super, InputKey.V), PlatformAction.Paste),
new KeyBinding(new KeyCombination(InputKey.Super, InputKey.A), PlatformAction.SelectAll),
new KeyBinding(InputKey.Left, PlatformAction.MoveBackwardChar),
new KeyBinding(InputKey.Right, PlatformAction.MoveForwardChar),
new KeyBinding(InputKey.BackSpace, PlatformAction.DeleteBackwardChar),
new KeyBinding(InputKey.Delete, PlatformAction.DeleteForwardChar),
new KeyBinding(new KeyCombination(InputKey.Shift, InputKey.Left), PlatformAction.SelectBackwardChar),
new KeyBinding(new KeyCombination(InputKey.Shift, InputKey.Right), PlatformAction.SelectForwardChar),
new KeyBinding(new KeyCombination(InputKey.Shift, InputKey.BackSpace), PlatformAction.DeleteBackwardChar),
new KeyBinding(new KeyCombination(InputKey.Shift, InputKey.Delete), PlatformAction.DeleteForwardChar),
new KeyBinding(new KeyCombination(InputKey.Alt, InputKey.Left), PlatformAction.MoveBackwardWord),
new KeyBinding(new KeyCombination(InputKey.Alt, InputKey.Right), PlatformAction.MoveForwardWord),
new KeyBinding(new KeyCombination(InputKey.Alt, InputKey.BackSpace), PlatformAction.DeleteBackwardWord),
new KeyBinding(new KeyCombination(InputKey.Alt, InputKey.Delete), PlatformAction.DeleteForwardWord),
new KeyBinding(new KeyCombination(InputKey.Alt, InputKey.Shift, InputKey.Left), PlatformAction.SelectBackwardWord),
new KeyBinding(new KeyCombination(InputKey.Alt, InputKey.Shift, InputKey.Right), PlatformAction.SelectForwardWord),
new KeyBinding(new KeyCombination(InputKey.Super, InputKey.Left), PlatformAction.MoveBackwardLine),
new KeyBinding(new KeyCombination(InputKey.Super, InputKey.Right), PlatformAction.MoveForwardLine),
new KeyBinding(new KeyCombination(InputKey.Super, InputKey.BackSpace), PlatformAction.DeleteBackwardLine),
new KeyBinding(new KeyCombination(InputKey.Super, InputKey.Delete), PlatformAction.DeleteForwardLine),
new KeyBinding(new KeyCombination(InputKey.Super, InputKey.Shift, InputKey.Left), PlatformAction.SelectBackwardLine),
new KeyBinding(new KeyCombination(InputKey.Super, InputKey.Shift, InputKey.Right), PlatformAction.SelectForwardLine),
new KeyBinding(new KeyCombination(InputKey.Alt, InputKey.Super, InputKey.Left), PlatformAction.DocumentPrevious),
new KeyBinding(new KeyCombination(InputKey.Alt, InputKey.Super, InputKey.Right), PlatformAction.DocumentNext),
new KeyBinding(new KeyCombination(InputKey.Control, InputKey.Tab), PlatformAction.DocumentNext),
new KeyBinding(new KeyCombination(InputKey.Control, InputKey.Shift, InputKey.Tab), PlatformAction.DocumentPrevious),
new KeyBinding(new KeyCombination(InputKey.Delete), PlatformAction.Delete),
};
}
}
| 53.54717 | 130 | 0.702138 | [
"MIT"
] | ppy/osu-framework | osu.Framework.iOS/IOSGameHost.cs | 8,514 | C# |
using System;
using NetRuntimeSystem = System;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.ComponentModel;
using System.Reflection;
using System.Collections.Generic;
using NetOffice;
namespace NetOffice.WordApi
{
///<summary>
/// DispatchInterface _OLEControl
/// SupportByVersion Word, 9,10,11,12,14,15
///</summary>
[SupportByVersionAttribute("Word", 9,10,11,12,14,15)]
[EntityTypeAttribute(EntityType.IsDispatchInterface)]
public class _OLEControl : COMObject
{
#pragma warning disable
#region Type Information
private static Type _type;
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public static Type LateBindingApiWrapperType
{
get
{
if (null == _type)
_type = typeof(_OLEControl);
return _type;
}
}
#endregion
#region Construction
///<param name="factory">current used factory core</param>
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
public _OLEControl(Core factory, COMObject parentObject, object comProxy) : base(factory, parentObject, comProxy)
{
}
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public _OLEControl(COMObject parentObject, object comProxy) : base(parentObject, comProxy)
{
}
///<param name="factory">current used factory core</param>
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
///<param name="comProxyType">Type of inner wrapped COM proxy"</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public _OLEControl(Core factory, COMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(factory, parentObject, comProxy, comProxyType)
{
}
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
///<param name="comProxyType">Type of inner wrapped COM proxy"</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public _OLEControl(COMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(parentObject, comProxy, comProxyType)
{
}
///<param name="replacedObject">object to replaced. replacedObject are not usable after this action</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public _OLEControl(COMObject replacedObject) : base(replacedObject)
{
}
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public _OLEControl() : base()
{
}
/// <param name="progId">registered ProgID</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public _OLEControl(string progId) : base(progId)
{
}
#endregion
#region Properties
/// <summary>
/// SupportByVersion Word 9, 10, 11, 12, 14, 15
/// Get/Set
/// </summary>
[SupportByVersionAttribute("Word", 9,10,11,12,14,15)]
public Single Left
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "Left", paramsArray);
return NetRuntimeSystem.Convert.ToSingle(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "Left", paramsArray);
}
}
/// <summary>
/// SupportByVersion Word 9, 10, 11, 12, 14, 15
/// Get/Set
/// </summary>
[SupportByVersionAttribute("Word", 9,10,11,12,14,15)]
public Single Top
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "Top", paramsArray);
return NetRuntimeSystem.Convert.ToSingle(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "Top", paramsArray);
}
}
/// <summary>
/// SupportByVersion Word 9, 10, 11, 12, 14, 15
/// Get/Set
/// </summary>
[SupportByVersionAttribute("Word", 9,10,11,12,14,15)]
public Single Height
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "Height", paramsArray);
return NetRuntimeSystem.Convert.ToSingle(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "Height", paramsArray);
}
}
/// <summary>
/// SupportByVersion Word 9, 10, 11, 12, 14, 15
/// Get/Set
/// </summary>
[SupportByVersionAttribute("Word", 9,10,11,12,14,15)]
public Single Width
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "Width", paramsArray);
return NetRuntimeSystem.Convert.ToSingle(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "Width", paramsArray);
}
}
/// <summary>
/// SupportByVersion Word 9, 10, 11, 12, 14, 15
/// Get/Set
/// </summary>
[SupportByVersionAttribute("Word", 9,10,11,12,14,15)]
public string Name
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "Name", paramsArray);
return NetRuntimeSystem.Convert.ToString(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "Name", paramsArray);
}
}
/// <summary>
/// SupportByVersion Word 9, 10, 11, 12, 14, 15
/// Get
/// Unknown COM Proxy
/// </summary>
[SupportByVersionAttribute("Word", 9,10,11,12,14,15)]
public object Automation
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "Automation", paramsArray);
COMObject newObject = Factory.CreateObjectFromComProxy(this,returnItem);
return newObject;
}
}
/// <summary>
/// SupportByVersion Word 9, 10, 11, 12, 14, 15
/// Get/Set
/// </summary>
[SupportByVersionAttribute("Word", 9,10,11,12,14,15)]
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public string AltHTML
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "AltHTML", paramsArray);
return NetRuntimeSystem.Convert.ToString(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "AltHTML", paramsArray);
}
}
#endregion
#region Methods
/// <summary>
/// SupportByVersion Word 9, 10, 11, 12, 14, 15
///
/// </summary>
[SupportByVersionAttribute("Word", 9,10,11,12,14,15)]
public void Select()
{
object[] paramsArray = null;
Invoker.Method(this, "Select", paramsArray);
}
/// <summary>
/// SupportByVersion Word 9, 10, 11, 12, 14, 15
///
/// </summary>
[SupportByVersionAttribute("Word", 9,10,11,12,14,15)]
public void Copy()
{
object[] paramsArray = null;
Invoker.Method(this, "Copy", paramsArray);
}
/// <summary>
/// SupportByVersion Word 9, 10, 11, 12, 14, 15
///
/// </summary>
[SupportByVersionAttribute("Word", 9,10,11,12,14,15)]
public void Cut()
{
object[] paramsArray = null;
Invoker.Method(this, "Cut", paramsArray);
}
/// <summary>
/// SupportByVersion Word 9, 10, 11, 12, 14, 15
///
/// </summary>
[SupportByVersionAttribute("Word", 9,10,11,12,14,15)]
public void Delete()
{
object[] paramsArray = null;
Invoker.Method(this, "Delete", paramsArray);
}
/// <summary>
/// SupportByVersion Word 9, 10, 11, 12, 14, 15
///
/// </summary>
[SupportByVersionAttribute("Word", 9,10,11,12,14,15)]
public void Activate()
{
object[] paramsArray = null;
Invoker.Method(this, "Activate", paramsArray);
}
#endregion
#pragma warning restore
}
} | 28.357143 | 166 | 0.639439 | [
"MIT"
] | NetOffice/NetOffice | Source/Word/DispatchInterfaces/_OLEControl.cs | 8,337 | C# |
using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
namespace RCNB
{
/// <summary>
/// Encodes and decodes RCNB.
/// </summary>
public static class RcnbConvert
{
// char
private const string cr = "rRŔŕŖŗŘřƦȐȑȒȓɌɍ";
private const string cc = "cCĆćĈĉĊċČčƇƈÇȻȼ";
private const string cn = "nNŃńŅņŇňƝƞÑǸǹȠȵ";
private const string cb = "bBƀƁƃƄƅßÞþ";
// size
private const int sr = 15; // cr.Length;
private const int sc = 15; // cc.Length;
private const int sn = 15; // cn.Length;
private const int sb = 10; // cb.Length;
private const int src = sr * sc;
private const int snb = sn * sb;
private const int scnb = sc * snb;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static void Swap<T>(ref T left, ref T right)
{
T temp = left;
left = right;
right = temp;
}
private unsafe static void EncodeFinalByte(byte inByte, char* outChars)
{
fixed (char* pr = cr)
fixed (char* pc = cc)
fixed (char* pn = cn)
fixed (char* pb = cb)
{
int i = inByte;
if (i > 0x7F)
{
i &= 0x7F;
outChars[0] = pn[i / sb];
outChars[1] = pb[i % sb];
}
else
{
outChars[0] = pr[i / sc];
outChars[1] = pc[i % sc];
}
}
}
/// <summary>
/// Encode RCNB, storing results to given location.
/// </summary>
/// <param name="inData"></param>
/// <param name="outChars"></param>
/// <param name="n">Bytes to encode.</param>
internal unsafe static void EncodeRcnb(byte* inData, char* outChars, int n)
{
// avoid unnecessary range checking
fixed (char* pr = cr)
fixed (char* pc = cc)
fixed (char* pn = cn)
fixed (char* pb = cb)
{
Span<int> resultIndexArray = stackalloc int[4];
for (int i = 0; i < n >> 1; i++)
{
int s = (inData[0] << 8) | inData[1];
Debug.Assert(s <= 0xFFFF);
var reverse = false;
if (s > 0x7FFF)
{
reverse = true;
s &= 0x7FFF;
}
#if NETSTANDARD1_1
resultIndexArray[0] = s / scnb;
resultIndexArray[1] = (s % scnb) / snb;
resultIndexArray[2] = (s % snb) / sb;
resultIndexArray[3] = s % sb;
#else
int temp;
resultIndexArray[0] = Math.DivRem(s, scnb, out temp);
resultIndexArray[1] = Math.DivRem(temp, snb, out temp);
resultIndexArray[2] = Math.DivRem(temp, sb, out temp);
resultIndexArray[3] = temp;
#endif
outChars[0] = pr[resultIndexArray[0]];
outChars[1] = pc[resultIndexArray[1]];
outChars[2] = pn[resultIndexArray[2]];
outChars[3] = pb[resultIndexArray[3]];
if (reverse)
{
Swap(ref outChars[0], ref outChars[2]);
Swap(ref outChars[1], ref outChars[3]);
}
inData += 2;
outChars += 4;
}
if ((n & 1) != 0)
{
EncodeFinalByte(*inData, outChars);
}
}
}
private static int CalculateLength(ReadOnlySpan<byte> bytes)
{
checked
{
return bytes.Length * 2;
}
}
/// <summary>
/// Encodes RCNB. Stores encoding result to <c>outChars</c>;
/// </summary>
/// <param name="inData">Data.</param>
/// <param name="outChars">Results.</param>
/// <exception cref="ArgumentOutOfRangeException"><c>outChars</c> does not have enough space to store the results.</exception>
public unsafe static void EncodeRcnb(ReadOnlySpan<byte> inData, Span<char> outChars)
{
if (CalculateLength(inData) > outChars.Length)
throw new ArgumentOutOfRangeException(nameof(inData), "rcnb overflow, data is too long or dest is too short.");
fixed (byte* bytesPtr = inData)
fixed (char* charsPtr = outChars)
{
EncodeRcnb(bytesPtr, charsPtr, inData.Length);
}
}
/// <summary>
/// Encode RCNB.
/// </summary>
/// <param name="inData">Data to encode.</param>
/// <returns>Encoded RCNB string.</returns>
#if NETSTANDARD1_1 || NETSTANDARD2_0
public static unsafe string ToRcnbString(ReadOnlySpan<byte> inData)
{
int resultLength = CalculateLength(inData);
char[] resultArray = new char[resultLength];
fixed (byte* bytesPtr = inData)
fixed (char* charsPtr = resultArray)
{
EncodeRcnb(bytesPtr, charsPtr, inData.Length);
}
return new string(resultArray);
}
#else
public static unsafe string ToRcnbString(ReadOnlySpan<byte> inData)
{
int length = CalculateLength(inData);
//fixed (byte* data = &inArray.GetPinnableReference())
fixed (byte* bytesPtr = inData) // it seems to work? --Yes! It is documented.
{
return string.Create(length,
new ByteMemoryMedium(bytesPtr, inData.Length),
(outChars, dataMedium) =>
{
fixed (char* charsPtr = outChars)
EncodeRcnb(dataMedium.Pointer, charsPtr, dataMedium.Length);
});
}
}
private unsafe readonly struct ByteMemoryMedium
{
public ByteMemoryMedium(byte* pointer, int length)
{
Pointer = pointer;
Length = length;
}
public byte* Pointer { get; }
public int Length { get; }
}
/// <summary>
/// Encode content to RCNB.
/// </summary>
/// <param name="inData">Content to encode.</param>
/// <returns>The encoded content.</returns>
public unsafe static string ToRcnbString(ReadOnlyMemory<byte> inData)
{
int length = CalculateLength(inData.Span);
return string.Create(length, inData, (outChars, bytes) =>
{
fixed (byte* bytesPtr = bytes.Span)
fixed (char* charsPtr = outChars)
EncodeRcnb(bytesPtr, charsPtr, bytes.Length);
});
}
/// <summary>
/// Encode content to RCNB.
/// </summary>
/// <param name="inArray">Content to encode.</param>
/// <returns>The encoded content.</returns>
public static string ToRcnbString(byte[] inArray) => ToRcnbString(inArray.AsMemory());
#endif
private static int DecodeShort(ReadOnlySpan<char> source, Span<byte> dest)
{
var reverse = cr.IndexOf(source[0]) < 0;
Span<int> idx = !reverse
? stackalloc int[] { cr.IndexOf(source[0]), cc.IndexOf(source[1]), cn.IndexOf(source[2]), cb.IndexOf(source[3]) }
: stackalloc int[] { cr.IndexOf(source[2]), cc.IndexOf(source[3]), cn.IndexOf(source[0]), cb.IndexOf(source[1]) };
if (idx[0] < 0 || idx[1] < 0 || idx[2] < 0 || idx[3] < 0)
throw new FormatException("not rcnb");
var result = idx[0] * scnb + idx[1] * snb + idx[2] * sb + idx[3];
if (result > 0x7FFF)
throw new FormatException("rcnb overflow");
result = reverse ? result | 0x8000 : result;
dest[0] = (byte)(result >> 8);
dest[1] = (byte)(result & 0xff);
return 2;
}
private static int DecodeByte(ReadOnlySpan<char> source, Span<byte> dest)
{
var nb = false;
Span<int> idx = stackalloc int[] { cr.IndexOf(source[0]), cc.IndexOf(source[1]) };
if (idx[0] < 0 || idx[1] < 0)
{
idx[0] = cn.IndexOf(source[0]);
idx[1] = cb.IndexOf(source[1]);
nb = true;
}
if (idx[0] < 0 || idx[1] < 0)
throw new FormatException("not rc/nb");
var result = nb ? idx[0] * sb + idx[1] : idx[0] * sc + idx[1];
if (result > 0x7F)
throw new FormatException("rc/nb overflow");
result = nb ? result | 0x80 : result;
dest[0] = (byte)result;
return 1;
}
/// <summary>
/// Decode RCNB char span, saving result to given span.
/// </summary>
/// <param name="str">RCNB char span.</param>
/// <param name="dest">Where to store result.</param>
/// <returns>Decoded count of bytes.</returns>
public static int FromRcnbString(ReadOnlySpan<char> str, Span<byte> dest)
{
if (str.Length / 2 > dest.Length)
throw new ArgumentException("The length of destination is not enough.", nameof(dest));
if ((str.Length & 1) != 0)
throw new FormatException("The length of RCNB string is not valid.");
var index = 0;
for (var i = 0; i < (str.Length >> 2); i++)
{
var l = DecodeShort(str.Slice(i * 4, 4), dest.Slice(index));
index += l;
}
if ((str.Length & 2) != 0)
{
var l = DecodeByte(str.Slice(str.Length - 2, 2), dest.Slice(index));
index += l;
}
return index;
}
/// <summary>
/// Decode RCNB string.
/// </summary>
/// <param name="str">RCNB string.</param>
/// <returns>Decoded data.</returns>
public static byte[] FromRcnbString(ReadOnlySpan<char> str)
{
byte[] result = new byte[str.Length / 2];
var decodedLength = FromRcnbString(str, result);
Debug.Assert(result.Length == decodedLength);
return result;
}
#if NETSTANDARD1_1 || NETSTANDARD2_0
/// <summary>
/// Decode RCNB string.
/// </summary>
/// <param name="str">RCNB string.</param>
/// <returns>Decoded data.</returns>
public static byte[] FromRcnbString(string str)
=> FromRcnbString(str.AsSpan());
#endif
}
}
| 36.885906 | 134 | 0.484443 | [
"MIT"
] | bltsheep/RCNB.csharp | RCNB/RcnbConvert.cs | 11,041 | C# |
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using static SigFlip.WinTrustData;
namespace SigFlip
{
public enum WinTrustDataUIChoice : uint
{
All = 1,
None = 2,
NoBad = 3,
NoGood = 4
}
public enum WinTrustDataRevocationChecks : uint
{
None = 0x00000000,
WholeChain = 0x00000001
}
public enum WinTrustDataChoice : uint
{
File = 1,
Catalog = 2,
Blob = 3,
Signer = 4,
Certificate = 5
}
public enum WinTrustDataStateAction : uint
{
Ignore = 0x00000000,
Verify = 0x00000001,
Close = 0x00000002,
AutoCache = 0x00000003,
AutoCacheFlush = 0x00000004
}
[FlagsAttribute]
public enum WinTrustDataProvFlags : uint
{
UseIe4TrustFlag = 0x00000001,
NoIe4ChainFlag = 0x00000002,
NoPolicyUsageFlag = 0x00000004,
RevocationCheckNone = 0x00000010,
RevocationCheckEndCert = 0x00000020,
RevocationCheckChain = 0x00000040,
RevocationCheckChainExcludeRoot = 0x00000080,
SaferFlag = 0x00000100,
HashOnlyFlag = 0x00000200,
UseDefaultOsverCheck = 0x00000400,
LifetimeSigningFlag = 0x00000800,
CacheOnlyUrlRetrieval = 0x00001000
}
public enum WinTrustDataUIContext : uint
{
Execute = 0,
Install = 1
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public class WinTrustFileInfo : IDisposable
{
public UInt32 StructSize = (UInt32)Marshal.SizeOf(typeof(WinTrustFileInfo));
public readonly IntPtr pszFilePath;
public IntPtr hFile = IntPtr.Zero;
public IntPtr pgKnownSubject = IntPtr.Zero;
public WinTrustFileInfo(String filePath)
{
pszFilePath = Marshal.StringToCoTaskMemAuto(filePath);
}
public void Dispose()
{
Marshal.FreeCoTaskMem(pszFilePath);
}
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public class WinTrustData : IDisposable
{
public UInt32 StructSize = (UInt32)Marshal.SizeOf(typeof(WinTrustData));
public IntPtr PolicyCallbackData = IntPtr.Zero;
public IntPtr SIPClientData = IntPtr.Zero;
public WinTrustDataUIChoice UIChoice = WinTrustDataUIChoice.None;
public WinTrustDataRevocationChecks RevocationChecks = WinTrustDataRevocationChecks.None;
public readonly WinTrustDataChoice UnionChoice;
public readonly IntPtr FileInfoPtr;
public WinTrustDataStateAction StateAction = WinTrustDataStateAction.Ignore;
public IntPtr StateData = IntPtr.Zero;
public String URLReference = null;
public WinTrustDataProvFlags ProvFlags = WinTrustDataProvFlags.SaferFlag;
public WinTrustDataUIContext UIContext = WinTrustDataUIContext.Execute;
public WinTrustData(String fileName)
{
WinTrustFileInfo wtfiData = new WinTrustFileInfo(fileName);
FileInfoPtr = Marshal.AllocCoTaskMem(Marshal.SizeOf(typeof(WinTrustFileInfo)));
Marshal.StructureToPtr(wtfiData, FileInfoPtr, false);
UnionChoice = WinTrustDataChoice.File;
}
public void Dispose()
{
Marshal.FreeCoTaskMem(FileInfoPtr);
}
public enum WinVerifyTrustResult : uint
{
Success = 0,
TRUST_E_SYSTEM_ERROR = 0x80096001,
TRUST_E_NO_SIGNER_CERT = 0x80096002,
TRUST_E_COUNTER_SIGNER = 0x80096003,
TRUST_E_CERT_SIGNATURE = 0x80096004,
TRUST_E_TIME_STAMP = 0x80096005,
TRUST_E_BAD_DIGEST = 0x80096010,
TRUST_E_BASIC_CONSTRAINTS = 0x80096019,
TRUST_E_FINANCIAL_CRITERIA = 0x8009601E,
TRUST_E_PROVIDER_UNKNOWN = 0x800B0001,
TRUST_E_ACTION_UNKNOWN = 0x800B0002,
TRUST_E_SUBJECT_FORM_UNKNOWN = 0x800B0003,
TRUST_E_SUBJECT_NOT_TRUSTED = 0x800B0004,
TRUST_E_NOSIGNATURE = 0x800B0100,
CERT_E_EXPIRED = 0x800B0101,
CERT_E_VALIDITYPERIODNESTING = 0x800B0102,
CERT_E_ROLE = 0x800B0103,
CERT_E_PATHLENCONST = 0x800B0104,
CERT_E_CRITICAL = 0x800B0105,
CERT_E_PURPOSE = 0x800B0106,
CERT_E_ISSUERCHAINING = 0x800B0107,
CERT_E_MALFORMED = 0x800B0108,
CERT_E_UNTRUSTEDROOT = 0x800B0109,
CERT_E_CHAINING = 0x800B010A,
TRUST_E_FAIL = 0x800B010B,
CERT_E_REVOKED = 0x800B010C,
CERT_E_UNTRUSTEDTESTROOT = 0x800B010D,
CERT_E_REVOCATION_FAILURE = 0x800B010E,
CERT_E_CN_NO_MATCH = 0x800B010F,
CERT_E_WRONG_USAGE = 0x800B0110,
TRUST_E_EXPLICIT_DISTRUST = 0x800B0111,
CERT_E_UNTRUSTEDCA = 0x800B0112,
CERT_E_INVALID_POLICY = 0x800B0113,
CERT_E_INVALID_NAME = 0x800B0114
}
public static class WinTrust
{
public static readonly IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1);
public const string WINTRUST_ACTION_GENERIC_VERIFY_V2 = "{00AAC56B-CD44-11d0-8CC2-00C04FC295EE}";
[DllImport("wintrust.dll", ExactSpelling = true, SetLastError = false, CharSet = CharSet.Unicode)]
public static extern WinVerifyTrustResult WinVerifyTrust(
[In] IntPtr hwnd,
[In] [MarshalAs(UnmanagedType.LPStruct)] Guid pgActionID,
[In] WinTrustData pWVTData
);
public static bool VerifyEmbeddedSignature(string fileName)
{
WinTrustData wtd = new WinTrustData(fileName);
Guid guidAction = new Guid(WINTRUST_ACTION_GENERIC_VERIFY_V2);
WinVerifyTrustResult result = WinVerifyTrust(INVALID_HANDLE_VALUE, guidAction, wtd);
bool ret = (result == WinVerifyTrustResult.Success);
return ret;
}
}
}
// http://www.pinvoke.net/default.aspx/wintrust.winverifytrust
public static class _WinVerifyTrust
{
const uint FORMAT_MESSAGE_ALLOCATE_BUFFER = 0x00000100;
const uint FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200;
const uint FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000;
static IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
static extern uint FormatMessage(
uint dwFlags, IntPtr lpSource,
uint dwMessageId, uint dwLanguageId,
[Out] StringBuilder lpBuffer,
uint nSize, IntPtr lpArguments
);
public static bool checkSig(string fileName, out string errorMessage)
{
using (var wtd = new WinTrustData(fileName)
{
UIChoice = WinTrustDataUIChoice.None,
UIContext = WinTrustDataUIContext.Execute,
RevocationChecks = WinTrustDataRevocationChecks.None,
StateAction = WinTrustDataStateAction.Verify,
ProvFlags = WinTrustDataProvFlags.RevocationCheckNone
})
{
var trustResult = WinTrust.WinVerifyTrust(
INVALID_HANDLE_VALUE, new Guid(WinTrust.WINTRUST_ACTION_GENERIC_VERIFY_V2), wtd
);
if (trustResult == WinVerifyTrustResult.Success)
{
errorMessage = null;
return true;
}
else
{
var sb = new StringBuilder(1024);
var charCount = FormatMessage(
FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
IntPtr.Zero, (uint)trustResult, 0,
sb, (uint)sb.Capacity, IntPtr.Zero
);
errorMessage = sb.ToString(0, (int)charCount);
return false;
}
}
}
}
}
| 32.879699 | 111 | 0.57432 | [
"MIT"
] | CrackerCat/sigFile | SigFlip/SigFlip/WinVerifyTrust.cs | 8,748 | C# |
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Windows;
using System.Windows.Controls;
using BuildNotifications.Resources.Icons;
using JetBrains.Annotations;
namespace BuildNotifications.Resources.Settings
{
internal class DecoratedComboBox : ComboBox, INotifyPropertyChanged
{
public DecoratedComboBox()
{
GotFocus += OnGotFocus;
}
private bool _toggleButtonActive = true;
public bool ToggleButtonActive
{
get => _toggleButtonActive;
set
{
_toggleButtonActive = value;
OnPropertyChanged();
}
}
private bool _itemsSourceCountIsSet;
public bool IsEmpty => _itemsSourceCountIsSet && ItemsSourceCount == 0;
public IconType Icon
{
get => (IconType) GetValue(IconProperty);
set => SetValue(IconProperty, value);
}
public string Label
{
get => (string) GetValue(LabelProperty);
set => SetValue(LabelProperty, value);
}
private void OnGotFocus(object sender, RoutedEventArgs e)
{
if (!Equals(e.Source, this))
return;
IsDropDownOpen = true;
}
public static readonly DependencyProperty IconProperty = DependencyProperty.Register(
"Icon", typeof(IconType), typeof(DecoratedComboBox), new PropertyMetadata(IconType.DownArrow));
public static readonly DependencyProperty LabelProperty = DependencyProperty.Register(
"Label", typeof(string), typeof(DecoratedComboBox), new PropertyMetadata(default(string)));
public static readonly DependencyProperty ItemsSourceCountProperty = DependencyProperty.Register(
"ItemsSourceCount", typeof(int), typeof(DecoratedComboBox), new PropertyMetadata(default(int), PropertyChangedCallback));
private static void PropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (d is DecoratedComboBox decoratedComboBox)
decoratedComboBox.UpdateBorderVisibility();
}
private void UpdateBorderVisibility()
{
ToggleButtonActive = ItemsSourceCount > 1;
_itemsSourceCountIsSet = true;
OnPropertyChanged(nameof(IsEmpty));
if (ItemsSourceCount == 1)
SelectedIndex = 0;
}
public int ItemsSourceCount
{
get => (int) GetValue(ItemsSourceCountProperty);
set => SetValue(ItemsSourceCountProperty, value);
}
public event PropertyChangedEventHandler? PropertyChanged;
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
} | 33.2 | 133 | 0.639224 | [
"MIT"
] | TheSylence/BuildNotifications | BuildNotifications/Resources/Settings/DecoratedComboBox.cs | 2,990 | C# |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
using System;
using System.Collections.Generic;
using Aliyun.Acs.Core.Transform;
using Aliyun.Acs.hsm.Model.V20180111;
namespace Aliyun.Acs.hsm.Transform.V20180111
{
public class ConfigNetworkResponseUnmarshaller
{
public static ConfigNetworkResponse Unmarshall(UnmarshallerContext context)
{
ConfigNetworkResponse configNetworkResponse = new ConfigNetworkResponse();
configNetworkResponse.HttpResponse = context.HttpResponse;
configNetworkResponse.RequestId = context.StringValue("ConfigNetwork.RequestId");
return configNetworkResponse;
}
}
}
| 35.475 | 84 | 0.755462 | [
"Apache-2.0"
] | AxiosCros/aliyun-openapi-net-sdk | aliyun-net-sdk-hsm/Hsm/Transform/V20180111/ConfigNetworkResponseUnmarshaller.cs | 1,419 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class Player : MonoBehaviour
{
[SerializeField] private int _speed = 10;
[SerializeField] private int _limit = 6;
private void Update()
{
Vector3 velocity = Vector3.zero;
if (Input.GetKey(KeyCode.LeftArrow))
velocity.x = Mathf.Clamp(velocity.x - 1, -1, 1);
if (Input.GetKey(KeyCode.RightArrow))
velocity.x = Mathf.Clamp(velocity.x + 1, -1, 1);
if (velocity != Vector3.zero)
{
velocity = LimitVelocity(velocity);
gameObject.transform.Translate(velocity * Time.deltaTime * _speed, Space.World);
}
}
private Vector3 LimitVelocity(Vector3 v)
{
if (Mathf.Abs(gameObject.transform.position.x + v.x) > _limit)
{
float diff = _limit - Mathf.Abs(gameObject.transform.position.x);
v.x = (v.x < 0) ? (-diff) : (diff);
}
return v;
}
private void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Obstacle"))
SceneManager.LoadScene("Menu");
}
}
| 27.837209 | 96 | 0.59315 | [
"MIT"
] | maxencedcx/Road42 | UnityFolder/Assets/Scripts/Game/Player.cs | 1,199 | C# |
using System.Resources;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Bluestreak")]
[assembly: AssemblyDescription("A .net class assembly to handle any cryptocurrency related tasks from within Grasshopper3d")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Bluestreak")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("5d08b3f5-aa7d-472c-a8cd-880c7a69201f")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.1")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: NeutralResourcesLanguage("en")]
| 38.775 | 125 | 0.753063 | [
"MIT"
] | Filippos-Filippidis/BlueStreak | src/BlueStreakGH/Properties/AssemblyInfo.cs | 1,554 | C# |
// <copyright file="ConversationRepository.cs" company="Microsoft Corporation">
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
// </copyright>
namespace Microsoft.Teams.Apps.Timesheet.Common.Repositories
{
using Microsoft.Teams.Apps.Timesheet.Common.Models;
/// <summary>
/// This class manages all database operations related to user conversation entity.
/// </summary>
public class ConversationRepository : BaseRepository<Conversation>, IConversationRepository
{
/// <summary>
/// Initializes a new instance of the <see cref="ConversationRepository"/> class.
/// </summary>
/// <param name="context">The timesheet context.</param>
public ConversationRepository(TimesheetContext context)
: base(context)
{
}
}
} | 34.958333 | 95 | 0.678188 | [
"MIT"
] | hunaidhanfee20/timesheet-app | Source/Microsoft.Teams.Apps.Timesheet.Common/Repositories/Conversation/ConversationRepository.cs | 841 | C# |
namespace Nuuvify.CommonPack.UnitOfWork
{
using System;
using System.Linq;
using System.Threading.Tasks;
/// <summary>
/// Defines the interface(s) for unit of work.
/// </summary>
public interface IUnitOfWork : IDisposable
{
/// <value>Get or Set user current context</value>
string UsernameContext { get; set; }
/// <value>Get or Set unique user identification current context</value>
string UserIdContext { get; set; }
/// <summary>
/// Asynchronously saves all changes made in this unit of work to the database.
/// </summary>
/// <param name="ensureAutoHistory">If configured, save changes to AutoHistory</param>
/// <param name="actualRegistry">In a processing loop, pass the registry count,
/// if the result of:
/// <code>
/// Math.DivRem(actualRegistry, limitCommit, out int resto);
/// if (resto == 0)
/// </code>
/// resto is zero, that is, every time the quantity established in limitCommit is processed,
/// it will be implemented in the database.
/// </param>
/// <param name="limitCommit">Number of records to run Commit</param>
/// <param name="toSave">Persist the data in the database</param>
/// <returns>A <see cref="Task{TResult}"/> that represents the asynchronous save operation. The task result contains the number of state entities written to database.</returns>
Task<int> SaveChangesAsync(bool ensureAutoHistory = false, int actualRegistry = 1, int limitCommit = 1, bool toSave = true);
/// <summary>
/// Executes the specified SQL command with the ExecuteSqlRaw method
/// </summary>
/// <param name="sql">The raw SQL.</param>
/// <param name="parameters">The parameters.</param>
/// <returns>The number of state entities written to database.</returns>
int ExecuteSqlCommand(string sql, params object[] parameters);
/// <summary>
/// Uses raw SQL queries to fetch the specified <typeparamref name="TEntity"/> data.
/// Use the FromSqlRaw
/// </summary>
/// <typeparam name="TEntity">The type of the entity.</typeparam>
/// <param name="sql">The raw SQL.</param>
/// <param name="parameters">The parameters.</param>
/// <returns>An <see cref="IQueryable{T}"/> that contains elements that satisfy the condition specified by raw SQL.</returns>
IQueryable<TEntity> FromSql<TEntity>(string sql, params object[] parameters) where TEntity : class;
}
}
| 47.690909 | 184 | 0.628288 | [
"MIT"
] | lzocateli00/Lzfy.DevPack | src/Nuuvify.CommonPack.UnitOfWork/Interfaces/IUnitOfWork.cs | 2,625 | C# |
#region Copyright notice and license
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://github.com/jskeet/dotnet-protobufs/
// Original C++/Java/Python code:
// http://code.google.com/p/protobuf/
//
// 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 Google Inc. 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.
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using Google.ProtocolBuffers.Descriptors;
namespace Google.ProtocolBuffers
{
/// <summary>
/// Provides ASCII text formatting support for messages.
/// TODO(jonskeet): Support for alternative line endings.
/// (Easy to print, via TextGenerator. Not sure about parsing.)
/// </summary>
public static class TextFormat
{
/// <summary>
/// Outputs a textual representation of the Protocol Message supplied into
/// the parameter output.
/// </summary>
public static void Print(IMessage message, TextWriter output)
{
TextGenerator generator = new TextGenerator(output, "\n");
Print(message, generator);
}
/// <summary>
/// Outputs a textual representation of the Protocol Message builder supplied into
/// the parameter output.
/// </summary>
public static void Print(IBuilder builder, TextWriter output)
{
TextGenerator generator = new TextGenerator(output, "\n");
Print(builder, generator);
}
/// <summary>
/// Outputs a textual representation of <paramref name="fields" /> to <paramref name="output"/>.
/// </summary>
public static void Print(UnknownFieldSet fields, TextWriter output)
{
TextGenerator generator = new TextGenerator(output, "\n");
PrintUnknownFields(fields, generator);
}
public static string PrintToString(IMessage message)
{
StringWriter text = new StringWriter();
Print(message, text);
return text.ToString();
}
public static string PrintToString(IBuilder builder)
{
StringWriter text = new StringWriter();
Print(builder, text);
return text.ToString();
}
public static string PrintToString(UnknownFieldSet fields)
{
StringWriter text = new StringWriter();
Print(fields, text);
return text.ToString();
}
private static void Print(IMessage message, TextGenerator generator)
{
foreach (KeyValuePair<FieldDescriptor, object> entry in message.AllFields)
{
PrintField(entry.Key, entry.Value, generator);
}
PrintUnknownFields(message.UnknownFields, generator);
}
private static void Print(IBuilder message, TextGenerator generator)
{
foreach (KeyValuePair<FieldDescriptor, object> entry in message.AllFields)
{
PrintField(entry.Key, entry.Value, generator);
}
PrintUnknownFields(message.UnknownFields, generator);
}
internal static void PrintField(FieldDescriptor field, object value, TextGenerator generator)
{
if (field.IsRepeated)
{
// Repeated field. Print each element.
foreach (object element in (IEnumerable) value)
{
PrintSingleField(field, element, generator);
}
}
else
{
PrintSingleField(field, value, generator);
}
}
private static void PrintSingleField(FieldDescriptor field, Object value, TextGenerator generator)
{
if (field.IsExtension)
{
generator.Print("[");
// We special-case MessageSet elements for compatibility with proto1.
if (field.ContainingType.Options.MessageSetWireFormat
&& field.FieldType == FieldType.Message
&& field.IsOptional
// object equality (TODO(jonskeet): Work out what this comment means!)
&& field.ExtensionScope == field.MessageType)
{
generator.Print(field.MessageType.FullName);
}
else
{
generator.Print(field.FullName);
}
generator.Print("]");
}
else
{
if (field.FieldType == FieldType.Group)
{
// Groups must be serialized with their original capitalization.
generator.Print(field.MessageType.Name);
}
else
{
generator.Print(field.Name);
}
}
if (field.MappedType == MappedType.Message)
{
generator.Print(" {\n");
generator.Indent();
}
else
{
generator.Print(": ");
}
PrintFieldValue(field, value, generator);
if (field.MappedType == MappedType.Message)
{
generator.Outdent();
generator.Print("}");
}
generator.Print("\n");
}
private static void PrintFieldValue(FieldDescriptor field, object value, TextGenerator generator)
{
switch (field.FieldType)
{
// The Float and Double types must specify the "r" format to preserve their precision, otherwise,
// the double to/from string will trim the precision to 6 places. As with other numeric formats
// below, always use the invariant culture so it's predictable.
case FieldType.Float:
generator.Print(((float)value).ToString("r", FrameworkPortability.InvariantCulture));
break;
case FieldType.Double:
generator.Print(((double)value).ToString("r", FrameworkPortability.InvariantCulture));
break;
case FieldType.Int32:
case FieldType.Int64:
case FieldType.SInt32:
case FieldType.SInt64:
case FieldType.SFixed32:
case FieldType.SFixed64:
case FieldType.UInt32:
case FieldType.UInt64:
case FieldType.Fixed32:
case FieldType.Fixed64:
// The simple Object.ToString converts using the current culture.
// We want to always use the invariant culture so it's predictable.
generator.Print(((IConvertible)value).ToString(FrameworkPortability.InvariantCulture));
break;
case FieldType.Bool:
// Explicitly use the Java true/false
generator.Print((bool) value ? "true" : "false");
break;
case FieldType.String:
generator.Print("\"");
generator.Print(EscapeText((string) value));
generator.Print("\"");
break;
case FieldType.Bytes:
{
generator.Print("\"");
generator.Print(EscapeBytes((ByteString) value));
generator.Print("\"");
break;
}
case FieldType.Enum:
{
if (value is IEnumLite && !(value is EnumValueDescriptor))
{
throw new NotSupportedException("Lite enumerations are not supported.");
}
generator.Print(((EnumValueDescriptor) value).Name);
break;
}
case FieldType.Message:
case FieldType.Group:
if (value is IMessageLite && !(value is IMessage))
{
throw new NotSupportedException("Lite messages are not supported.");
}
Print((IMessage) value, generator);
break;
}
}
private static void PrintUnknownFields(UnknownFieldSet unknownFields, TextGenerator generator)
{
foreach (KeyValuePair<int, UnknownField> entry in unknownFields.FieldDictionary)
{
String prefix = entry.Key.ToString() + ": ";
UnknownField field = entry.Value;
foreach (ulong value in field.VarintList)
{
generator.Print(prefix);
generator.Print(value.ToString());
generator.Print("\n");
}
foreach (uint value in field.Fixed32List)
{
generator.Print(prefix);
generator.Print(string.Format("0x{0:x8}", value));
generator.Print("\n");
}
foreach (ulong value in field.Fixed64List)
{
generator.Print(prefix);
generator.Print(string.Format("0x{0:x16}", value));
generator.Print("\n");
}
foreach (ByteString value in field.LengthDelimitedList)
{
generator.Print(entry.Key.ToString());
generator.Print(": \"");
generator.Print(EscapeBytes(value));
generator.Print("\"\n");
}
foreach (UnknownFieldSet value in field.GroupList)
{
generator.Print(entry.Key.ToString());
generator.Print(" {\n");
generator.Indent();
PrintUnknownFields(value, generator);
generator.Outdent();
generator.Print("}\n");
}
}
}
[CLSCompliant(false)]
public static ulong ParseUInt64(string text)
{
return (ulong) ParseInteger(text, false, true);
}
public static long ParseInt64(string text)
{
return ParseInteger(text, true, true);
}
[CLSCompliant(false)]
public static uint ParseUInt32(string text)
{
return (uint) ParseInteger(text, false, false);
}
public static int ParseInt32(string text)
{
return (int) ParseInteger(text, true, false);
}
public static float ParseFloat(string text)
{
switch (text)
{
case "-inf":
case "-infinity":
case "-inff":
case "-infinityf":
return float.NegativeInfinity;
case "inf":
case "infinity":
case "inff":
case "infinityf":
return float.PositiveInfinity;
case "nan":
case "nanf":
return float.NaN;
default:
return float.Parse(text, FrameworkPortability.InvariantCulture);
}
}
public static double ParseDouble(string text)
{
switch (text)
{
case "-inf":
case "-infinity":
return double.NegativeInfinity;
case "inf":
case "infinity":
return double.PositiveInfinity;
case "nan":
return double.NaN;
default:
return double.Parse(text, FrameworkPortability.InvariantCulture);
}
}
/// <summary>
/// Parses an integer in hex (leading 0x), decimal (no prefix) or octal (leading 0).
/// Only a negative sign is permitted, and it must come before the radix indicator.
/// </summary>
private static long ParseInteger(string text, bool isSigned, bool isLong)
{
string original = text;
bool negative = false;
if (text.StartsWith("-"))
{
if (!isSigned)
{
throw new FormatException("Number must be positive: " + original);
}
negative = true;
text = text.Substring(1);
}
int radix = 10;
if (text.StartsWith("0x"))
{
radix = 16;
text = text.Substring(2);
}
else if (text.StartsWith("0"))
{
radix = 8;
}
ulong result;
try
{
// Workaround for https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=278448
// We should be able to use Convert.ToUInt64 for all cases.
result = radix == 10 ? ulong.Parse(text) : Convert.ToUInt64(text, radix);
}
catch (OverflowException)
{
// Convert OverflowException to FormatException so there's a single exception type this method can throw.
string numberDescription = string.Format("{0}-bit {1}signed integer", isLong ? 64 : 32,
isSigned ? "" : "un");
throw new FormatException("Number out of range for " + numberDescription + ": " + original);
}
if (negative)
{
ulong max = isLong ? 0x8000000000000000UL : 0x80000000L;
if (result > max)
{
string numberDescription = string.Format("{0}-bit signed integer", isLong ? 64 : 32);
throw new FormatException("Number out of range for " + numberDescription + ": " + original);
}
return -((long) result);
}
else
{
ulong max = isSigned
? (isLong ? (ulong) long.MaxValue : int.MaxValue)
: (isLong ? ulong.MaxValue : uint.MaxValue);
if (result > max)
{
string numberDescription = string.Format("{0}-bit {1}signed integer", isLong ? 64 : 32,
isSigned ? "" : "un");
throw new FormatException("Number out of range for " + numberDescription + ": " + original);
}
return (long) result;
}
}
/// <summary>
/// Tests a character to see if it's an octal digit.
/// </summary>
private static bool IsOctal(char c)
{
return '0' <= c && c <= '7';
}
/// <summary>
/// Tests a character to see if it's a hex digit.
/// </summary>
private static bool IsHex(char c)
{
return ('0' <= c && c <= '9') ||
('a' <= c && c <= 'f') ||
('A' <= c && c <= 'F');
}
/// <summary>
/// Interprets a character as a digit (in any base up to 36) and returns the
/// numeric value.
/// </summary>
private static int ParseDigit(char c)
{
if ('0' <= c && c <= '9')
{
return c - '0';
}
else if ('a' <= c && c <= 'z')
{
return c - 'a' + 10;
}
else
{
return c - 'A' + 10;
}
}
/// <summary>
/// Unescapes a text string as escaped using <see cref="EscapeText(string)" />.
/// Two-digit hex escapes (starting with "\x" are also recognised.
/// </summary>
public static string UnescapeText(string input)
{
return UnescapeBytes(input).ToStringUtf8();
}
/// <summary>
/// Like <see cref="EscapeBytes" /> but escapes a text string.
/// The string is first encoded as UTF-8, then each byte escaped individually.
/// The returned value is guaranteed to be entirely ASCII.
/// </summary>
public static string EscapeText(string input)
{
return EscapeBytes(ByteString.CopyFromUtf8(input));
}
/// <summary>
/// Escapes bytes in the format used in protocol buffer text format, which
/// is the same as the format used for C string literals. All bytes
/// that are not printable 7-bit ASCII characters are escaped, as well as
/// backslash, single-quote, and double-quote characters. Characters for
/// which no defined short-hand escape sequence is defined will be escaped
/// using 3-digit octal sequences.
/// The returned value is guaranteed to be entirely ASCII.
/// </summary>
public static String EscapeBytes(ByteString input)
{
StringBuilder builder = new StringBuilder(input.Length);
foreach (byte b in input)
{
switch (b)
{
// C# does not use \a or \v
case 0x07:
builder.Append("\\a");
break;
case (byte) '\b':
builder.Append("\\b");
break;
case (byte) '\f':
builder.Append("\\f");
break;
case (byte) '\n':
builder.Append("\\n");
break;
case (byte) '\r':
builder.Append("\\r");
break;
case (byte) '\t':
builder.Append("\\t");
break;
case 0x0b:
builder.Append("\\v");
break;
case (byte) '\\':
builder.Append("\\\\");
break;
case (byte) '\'':
builder.Append("\\\'");
break;
case (byte) '"':
builder.Append("\\\"");
break;
default:
if (b >= 0x20 && b < 128)
{
builder.Append((char) b);
}
else
{
builder.Append('\\');
builder.Append((char) ('0' + ((b >> 6) & 3)));
builder.Append((char) ('0' + ((b >> 3) & 7)));
builder.Append((char) ('0' + (b & 7)));
}
break;
}
}
return builder.ToString();
}
/// <summary>
/// Performs string unescaping from C style (octal, hex, form feeds, tab etc) into a byte string.
/// </summary>
public static ByteString UnescapeBytes(string input)
{
byte[] result = new byte[input.Length];
int pos = 0;
for (int i = 0; i < input.Length; i++)
{
char c = input[i];
if (c > 127 || c < 32)
{
throw new FormatException("Escaped string must only contain ASCII");
}
if (c != '\\')
{
result[pos++] = (byte) c;
continue;
}
if (i + 1 >= input.Length)
{
throw new FormatException("Invalid escape sequence: '\\' at end of string.");
}
i++;
c = input[i];
if (c >= '0' && c <= '7')
{
// Octal escape.
int code = ParseDigit(c);
if (i + 1 < input.Length && IsOctal(input[i + 1]))
{
i++;
code = code*8 + ParseDigit(input[i]);
}
if (i + 1 < input.Length && IsOctal(input[i + 1]))
{
i++;
code = code*8 + ParseDigit(input[i]);
}
result[pos++] = (byte) code;
}
else
{
switch (c)
{
case 'a':
result[pos++] = 0x07;
break;
case 'b':
result[pos++] = (byte) '\b';
break;
case 'f':
result[pos++] = (byte) '\f';
break;
case 'n':
result[pos++] = (byte) '\n';
break;
case 'r':
result[pos++] = (byte) '\r';
break;
case 't':
result[pos++] = (byte) '\t';
break;
case 'v':
result[pos++] = 0x0b;
break;
case '\\':
result[pos++] = (byte) '\\';
break;
case '\'':
result[pos++] = (byte) '\'';
break;
case '"':
result[pos++] = (byte) '\"';
break;
case 'x':
// hex escape
int code;
if (i + 1 < input.Length && IsHex(input[i + 1]))
{
i++;
code = ParseDigit(input[i]);
}
else
{
throw new FormatException("Invalid escape sequence: '\\x' with no digits");
}
if (i + 1 < input.Length && IsHex(input[i + 1]))
{
++i;
code = code*16 + ParseDigit(input[i]);
}
result[pos++] = (byte) code;
break;
default:
throw new FormatException("Invalid escape sequence: '\\" + c + "'");
}
}
}
return ByteString.CopyFrom(result, 0, pos);
}
public static void Merge(string text, IBuilder builder)
{
Merge(text, ExtensionRegistry.Empty, builder);
}
public static void Merge(TextReader reader, IBuilder builder)
{
Merge(reader, ExtensionRegistry.Empty, builder);
}
public static void Merge(TextReader reader, ExtensionRegistry registry, IBuilder builder)
{
Merge(reader.ReadToEnd(), registry, builder);
}
public static void Merge(string text, ExtensionRegistry registry, IBuilder builder)
{
TextTokenizer tokenizer = new TextTokenizer(text);
while (!tokenizer.AtEnd)
{
MergeField(tokenizer, registry, builder);
}
}
/// <summary>
/// Parses a single field from the specified tokenizer and merges it into
/// the builder.
/// </summary>
private static void MergeField(TextTokenizer tokenizer, ExtensionRegistry extensionRegistry,
IBuilder builder)
{
FieldDescriptor field;
MessageDescriptor type = builder.DescriptorForType;
ExtensionInfo extension = null;
if (tokenizer.TryConsume("["))
{
// An extension.
StringBuilder name = new StringBuilder(tokenizer.ConsumeIdentifier());
while (tokenizer.TryConsume("."))
{
name.Append(".");
name.Append(tokenizer.ConsumeIdentifier());
}
extension = extensionRegistry.FindByName(type, name.ToString());
if (extension == null)
{
throw tokenizer.CreateFormatExceptionPreviousToken("Extension \"" + name +
"\" not found in the ExtensionRegistry.");
}
else if (extension.Descriptor.ContainingType != type)
{
throw tokenizer.CreateFormatExceptionPreviousToken("Extension \"" + name +
"\" does not extend message type \"" +
type.FullName + "\".");
}
tokenizer.Consume("]");
field = extension.Descriptor;
}
else
{
String name = tokenizer.ConsumeIdentifier();
field = type.FindDescriptor<FieldDescriptor>(name);
// Group names are expected to be capitalized as they appear in the
// .proto file, which actually matches their type names, not their field
// names.
if (field == null)
{
// Explicitly specify the invariant culture so that this code does not break when
// executing in Turkey.
#if PORTABLE_LIBRARY
String lowerName = name.ToLowerInvariant();
#else
String lowerName = name.ToLower(FrameworkPortability.InvariantCulture);
#endif
field = type.FindDescriptor<FieldDescriptor>(lowerName);
// If the case-insensitive match worked but the field is NOT a group,
// TODO(jonskeet): What? Java comment ends here!
if (field != null && field.FieldType != FieldType.Group)
{
field = null;
}
}
// Again, special-case group names as described above.
if (field != null && field.FieldType == FieldType.Group && field.MessageType.Name != name)
{
field = null;
}
if (field == null)
{
throw tokenizer.CreateFormatExceptionPreviousToken(
"Message type \"" + type.FullName + "\" has no field named \"" + name + "\".");
}
}
object value = null;
if (field.MappedType == MappedType.Message)
{
tokenizer.TryConsume(":"); // optional
String endToken;
if (tokenizer.TryConsume("<"))
{
endToken = ">";
}
else
{
tokenizer.Consume("{");
endToken = "}";
}
IBuilder subBuilder;
if (extension == null)
{
subBuilder = builder.CreateBuilderForField(field);
}
else
{
subBuilder = extension.DefaultInstance.WeakCreateBuilderForType() as IBuilder;
if (subBuilder == null)
{
throw new NotSupportedException("Lite messages are not supported.");
}
}
while (!tokenizer.TryConsume(endToken))
{
if (tokenizer.AtEnd)
{
throw tokenizer.CreateFormatException("Expected \"" + endToken + "\".");
}
MergeField(tokenizer, extensionRegistry, subBuilder);
}
value = subBuilder.WeakBuild();
}
else
{
tokenizer.Consume(":");
switch (field.FieldType)
{
case FieldType.Int32:
case FieldType.SInt32:
case FieldType.SFixed32:
value = tokenizer.ConsumeInt32();
break;
case FieldType.Int64:
case FieldType.SInt64:
case FieldType.SFixed64:
value = tokenizer.ConsumeInt64();
break;
case FieldType.UInt32:
case FieldType.Fixed32:
value = tokenizer.ConsumeUInt32();
break;
case FieldType.UInt64:
case FieldType.Fixed64:
value = tokenizer.ConsumeUInt64();
break;
case FieldType.Float:
value = tokenizer.ConsumeFloat();
break;
case FieldType.Double:
value = tokenizer.ConsumeDouble();
break;
case FieldType.Bool:
value = tokenizer.ConsumeBoolean();
break;
case FieldType.String:
value = tokenizer.ConsumeString();
break;
case FieldType.Bytes:
value = tokenizer.ConsumeByteString();
break;
case FieldType.Enum:
{
EnumDescriptor enumType = field.EnumType;
if (tokenizer.LookingAtInteger())
{
int number = tokenizer.ConsumeInt32();
value = enumType.FindValueByNumber(number);
if (value == null)
{
throw tokenizer.CreateFormatExceptionPreviousToken(
"Enum type \"" + enumType.FullName +
"\" has no value with number " + number + ".");
}
}
else
{
String id = tokenizer.ConsumeIdentifier();
value = enumType.FindValueByName(id);
if (value == null)
{
throw tokenizer.CreateFormatExceptionPreviousToken(
"Enum type \"" + enumType.FullName +
"\" has no value named \"" + id + "\".");
}
}
break;
}
case FieldType.Message:
case FieldType.Group:
throw new InvalidOperationException("Can't get here.");
}
}
if (field.IsRepeated)
{
builder.WeakAddRepeatedField(field, value);
}
else
{
builder.SetField(field, value);
}
}
}
} | 37.799778 | 121 | 0.444618 | [
"MIT"
] | protobuflab/protobuf-langserver | language-server/src/ConsoleApp/Internal/TextFormat.cs | 33,982 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Les informations générales relatives à un assembly dépendent de
// l'ensemble d'attributs suivant. Changez les valeurs de ces attributs pour modifier les informations
// associées à un assembly.
[assembly: AssemblyTitle("Sample")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Sample")]
[assembly: AssemblyCopyright("Copyright © 2018")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// L'affectation de la valeur false à ComVisible rend les types invisibles dans cet assembly
// aux composants COM. Si vous devez accéder à un type dans cet assembly à partir de
// COM, affectez la valeur true à l'attribut ComVisible sur ce type.
[assembly: ComVisible(false)]
// Le GUID suivant est pour l'ID de la typelib si ce projet est exposé à COM
[assembly: Guid("0bdb75bb-d000-466e-bc5b-662b3c3bc2e4")]
// Les informations de version pour un assembly se composent des quatre valeurs suivantes :
//
// Version principale
// Version secondaire
// Numéro de build
// Révision
//
// Vous pouvez spécifier toutes les valeurs ou indiquer les numéros de build et de révision par défaut
// en utilisant '*', comme indiqué ci-dessous :
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 39.972973 | 102 | 0.751183 | [
"Apache-2.0"
] | hawezo/LEA | Sample/Properties/AssemblyInfo.cs | 1,504 | C# |
extern alias scfx;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using SyscallCallback = scfx.Neo.SmartContract.Framework.Services.System.SyscallCallback;
namespace Neo.SmartContract.Framework.UnitTests
{
[TestClass]
public class SyscallCallbackTest
{
[TestMethod]
public void TestAllSyscallCallbacks()
{
// Current allowed syscalls
var current = new Dictionary<string, uint>();
foreach (var syscall in ApplicationEngine.Services)
{
if (!syscall.Value.AllowCallback) continue;
current.Add(syscall.Value.Name.Replace(".", "_"), syscall.Value.Hash);
}
// Check equals
foreach (var en in Enum.GetValues(typeof(SyscallCallback)))
{
if (!current.TryGetValue(en.ToString(), out var val))
{
Assert.Fail($"`{en}` Syscall is not defined in SyscallCallback");
}
current.Remove(en.ToString());
if (val != (uint)en)
{
Assert.Fail($"`{en}` Syscall has a different hash, found {((uint)en):x2}, expected: {val:x2}");
}
}
if (current.Count > 0)
{
Assert.Fail($"Not implemented syscalls: {string.Join("\n-", current.Keys)}");
}
}
}
}
| 28.882353 | 115 | 0.54243 | [
"MIT"
] | bettybao1209/neo-devpack-dotnet | tests/Neo.SmartContract.Framework.UnitTests/SyscallCallbackTest.cs | 1,473 | C# |
using LinkedMink.Data.Base;
using System;
using System.Linq;
namespace LinkedMink.Web.Infastructure.ViewModels
{
public class SortCriteriaViewModel
{
public string SortBy { get; set; }
public int? Order { get; set; }
public string SortAttribute => !string.IsNullOrEmpty(SortBy) ?
SortBy.First().ToString().ToUpper() + SortBy.Substring(1) : null;
public SortCriteria.SortOrder SortOrder => Order.HasValue ?
(SortCriteria.SortOrder)Order : SortCriteria.SortOrder.Descending;
public static SortCriteria ToModel(SortCriteriaViewModel viewModel, Type entityType)
{
var sortAttribute = viewModel.SortAttribute;
if (!string.IsNullOrEmpty(sortAttribute))
{
var sortProperty = entityType.GetProperty(sortAttribute);
if (sortProperty != null)
{
return new SortCriteria()
{
Order = viewModel.SortOrder,
Property = sortProperty
};
}
}
return null;
}
}
}
| 30.842105 | 92 | 0.56314 | [
"MIT"
] | LinkedMink/environ-manager-server | LinkedMink.Web.Infastructure/ViewModels/SortCriteriaViewModel.cs | 1,174 | C# |
#region PDFsharp - A .NET library for processing PDF
//
// Authors:
// Stefan Lange
//
// Copyright (c) 2005-2016 empira Software GmbH, Cologne Area (Germany)
//
// http://www.pdfsharp.com
// http://sourceforge.net/projects/pdfsharp
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.IsolatedStorage;
using System.Runtime.InteropServices;
namespace PdfSharp.Silverlight
{
/// <summary>
/// Useful stuff to show PDF files in Silverlight applications for
/// testing and debugging purposes.
/// Some functions require elevated trust.
/// </summary>
public class SilverlightHelper
{
/// <summary>
/// Gets the full path of UserStore for application.
/// </summary>
public static string FullPathOfUserStoreForApplication
{
get
{
if (_fullPathOfUserStoreForApplication != null)
return _fullPathOfUserStoreForApplication;
// More simple than I expected...
string root = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + @"Low\Microsoft\Silverlight\is";
IsolatedStorageFile userStore = IsolatedStorageFile.GetUserStoreForApplication();
string markerFile = Guid.NewGuid().ToString();
userStore.CreateFile(markerFile).Close();
// Won't use Linq here (FirstOrDefault).
IEnumerator<string> enumerator = Directory.EnumerateFileSystemEntries(root, markerFile, SearchOption.AllDirectories).GetEnumerator();
enumerator.MoveNext();
_fullPathOfUserStoreForApplication = Path.GetDirectoryName(enumerator.Current);
userStore.DeleteFile(markerFile);
return _fullPathOfUserStoreForApplication;
}
}
static string _fullPathOfUserStoreForApplication;
/// <summary>
/// Uses ShellExecute to open a PDF file in UserStore.
/// </summary>
public static void ShowPdfFileFromUserStore(string path)
{
string fullPath = Path.Combine(FullPathOfUserStoreForApplication, path);
ShellExecute(IntPtr.Zero, "open", fullPath, IntPtr.Zero, null, 5);
}
[DllImport("Shell32.dll")]
static extern UInt32 ShellExecute(IntPtr hwnd, string pOperation, string pFile,
IntPtr pParameters, string pDirectory, UInt32 nShowCmd);
}
}
| 42.47619 | 149 | 0.686659 | [
"MIT"
] | jumpchain/jumpmaker | JumpMaker/PDFSharp/PdfSharp/Silverlight/SilverlightHelper.cs | 3,570 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace NumbersFromOneToFifty.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
}
} | 19.6 | 67 | 0.571429 | [
"MIT"
] | kr056/SoftUni | Software Technologies July 2017/11_C# ASP.NET MVC Overview Lab/NumbersFromOneToFifty/NumbersFromOneToFifty/NumbersFromOneToFifty/Controllers/HomeController.cs | 590 | C# |
namespace Railway_express
{
partial class frmAdminResturent
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(frmAdminResturent));
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle1 = new System.Windows.Forms.DataGridViewCellStyle();
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle2 = new System.Windows.Forms.DataGridViewCellStyle();
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle3 = new System.Windows.Forms.DataGridViewCellStyle();
this.gunaElipse1 = new Guna.UI.WinForms.GunaElipse(this.components);
this.gunaTextBox1 = new Guna.UI.WinForms.GunaTextBox();
this.bunifuImageButton1 = new Bunifu.Framework.UI.BunifuImageButton();
this.btnSave = new Guna.UI.WinForms.GunaButton();
this.lblQuantityErr = new Guna.UI.WinForms.GunaLabel();
this.lblItemErr = new Guna.UI.WinForms.GunaLabel();
this.gunaLabel2 = new Guna.UI.WinForms.GunaLabel();
this.gunaLabel4 = new Guna.UI.WinForms.GunaLabel();
this.txtQuantity = new Guna.UI.WinForms.GunaTextBox();
this.TxtItemName = new Guna.UI.WinForms.GunaTextBox();
this.dgvResourt = new Guna.UI.WinForms.GunaDataGridView();
this.txtPrice = new Guna.UI.WinForms.GunaTextBox();
this.gunaLabel1 = new Guna.UI.WinForms.GunaLabel();
this.lblPriceErr = new Guna.UI.WinForms.GunaLabel();
this.iteam_Id = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.iteam_name = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.avalable_count = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.iteam_price = new System.Windows.Forms.DataGridViewTextBoxColumn();
((System.ComponentModel.ISupportInitialize)(this.bunifuImageButton1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.dgvResourt)).BeginInit();
this.SuspendLayout();
//
// gunaElipse1
//
this.gunaElipse1.TargetControl = this;
//
// gunaTextBox1
//
this.gunaTextBox1.BaseColor = System.Drawing.Color.White;
this.gunaTextBox1.BorderColor = System.Drawing.Color.Silver;
this.gunaTextBox1.BorderSize = 0;
this.gunaTextBox1.Cursor = System.Windows.Forms.Cursors.IBeam;
this.gunaTextBox1.FocusedBaseColor = System.Drawing.Color.White;
this.gunaTextBox1.FocusedBorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(100)))), ((int)(((byte)(88)))), ((int)(((byte)(255)))));
this.gunaTextBox1.FocusedForeColor = System.Drawing.SystemColors.ControlText;
this.gunaTextBox1.Font = new System.Drawing.Font("Segoe UI", 9F);
this.gunaTextBox1.Location = new System.Drawing.Point(747, 150);
this.gunaTextBox1.Name = "gunaTextBox1";
this.gunaTextBox1.PasswordChar = '\0';
this.gunaTextBox1.SelectedText = "";
this.gunaTextBox1.Size = new System.Drawing.Size(357, 39);
this.gunaTextBox1.TabIndex = 1;
//
// bunifuImageButton1
//
this.bunifuImageButton1.BackColor = System.Drawing.Color.SeaGreen;
this.bunifuImageButton1.Image = ((System.Drawing.Image)(resources.GetObject("bunifuImageButton1.Image")));
this.bunifuImageButton1.ImageActive = null;
this.bunifuImageButton1.Location = new System.Drawing.Point(1128, 150);
this.bunifuImageButton1.Name = "bunifuImageButton1";
this.bunifuImageButton1.Size = new System.Drawing.Size(49, 39);
this.bunifuImageButton1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom;
this.bunifuImageButton1.TabIndex = 2;
this.bunifuImageButton1.TabStop = false;
this.bunifuImageButton1.Zoom = 10;
//
// btnSave
//
this.btnSave.AnimationHoverSpeed = 0.07F;
this.btnSave.AnimationSpeed = 0.03F;
this.btnSave.BackColor = System.Drawing.Color.Transparent;
this.btnSave.BaseColor = System.Drawing.Color.FromArgb(((int)(((byte)(51)))), ((int)(((byte)(110)))), ((int)(((byte)(138)))));
this.btnSave.BorderColor = System.Drawing.Color.Black;
this.btnSave.DialogResult = System.Windows.Forms.DialogResult.None;
this.btnSave.FocusedColor = System.Drawing.Color.Empty;
this.btnSave.Font = new System.Drawing.Font("Segoe UI", 9F);
this.btnSave.ForeColor = System.Drawing.Color.White;
this.btnSave.Image = null;
this.btnSave.ImageSize = new System.Drawing.Size(20, 20);
this.btnSave.Location = new System.Drawing.Point(517, 526);
this.btnSave.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.btnSave.Name = "btnSave";
this.btnSave.OnHoverBaseColor = System.Drawing.Color.FromArgb(((int)(((byte)(28)))), ((int)(((byte)(61)))), ((int)(((byte)(77)))));
this.btnSave.OnHoverBorderColor = System.Drawing.Color.Black;
this.btnSave.OnHoverForeColor = System.Drawing.Color.White;
this.btnSave.OnHoverImage = null;
this.btnSave.OnPressedColor = System.Drawing.Color.Black;
this.btnSave.Radius = 5;
this.btnSave.Size = new System.Drawing.Size(160, 52);
this.btnSave.TabIndex = 16;
this.btnSave.Text = "Save";
this.btnSave.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
this.btnSave.Click += new System.EventHandler(this.btnSave_Click);
//
// lblQuantityErr
//
this.lblQuantityErr.AutoSize = true;
this.lblQuantityErr.Font = new System.Drawing.Font("Segoe UI", 9F);
this.lblQuantityErr.ForeColor = System.Drawing.Color.Red;
this.lblQuantityErr.Location = new System.Drawing.Point(38, 426);
this.lblQuantityErr.Name = "lblQuantityErr";
this.lblQuantityErr.Size = new System.Drawing.Size(0, 20);
this.lblQuantityErr.TabIndex = 14;
//
// lblItemErr
//
this.lblItemErr.AutoSize = true;
this.lblItemErr.Font = new System.Drawing.Font("Segoe UI", 9F);
this.lblItemErr.ForeColor = System.Drawing.Color.Red;
this.lblItemErr.Location = new System.Drawing.Point(38, 291);
this.lblItemErr.Name = "lblItemErr";
this.lblItemErr.Size = new System.Drawing.Size(0, 20);
this.lblItemErr.TabIndex = 15;
//
// gunaLabel2
//
this.gunaLabel2.AutoSize = true;
this.gunaLabel2.Font = new System.Drawing.Font("Segoe UI", 11F);
this.gunaLabel2.ForeColor = System.Drawing.SystemColors.Control;
this.gunaLabel2.Location = new System.Drawing.Point(29, 342);
this.gunaLabel2.Name = "gunaLabel2";
this.gunaLabel2.Size = new System.Drawing.Size(84, 25);
this.gunaLabel2.TabIndex = 12;
this.gunaLabel2.Text = "Quantity";
//
// gunaLabel4
//
this.gunaLabel4.AutoSize = true;
this.gunaLabel4.Font = new System.Drawing.Font("Segoe UI", 11F);
this.gunaLabel4.ForeColor = System.Drawing.SystemColors.Control;
this.gunaLabel4.Location = new System.Drawing.Point(29, 207);
this.gunaLabel4.Name = "gunaLabel4";
this.gunaLabel4.Size = new System.Drawing.Size(104, 25);
this.gunaLabel4.TabIndex = 13;
this.gunaLabel4.Text = "Item Name";
//
// txtQuantity
//
this.txtQuantity.BaseColor = System.Drawing.Color.White;
this.txtQuantity.BorderColor = System.Drawing.Color.Silver;
this.txtQuantity.BorderSize = 0;
this.txtQuantity.Cursor = System.Windows.Forms.Cursors.IBeam;
this.txtQuantity.FocusedBaseColor = System.Drawing.Color.White;
this.txtQuantity.FocusedBorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(100)))), ((int)(((byte)(88)))), ((int)(((byte)(255)))));
this.txtQuantity.FocusedForeColor = System.Drawing.SystemColors.ControlText;
this.txtQuantity.Font = new System.Drawing.Font("Segoe UI", 9F);
this.txtQuantity.Location = new System.Drawing.Point(34, 380);
this.txtQuantity.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.txtQuantity.Name = "txtQuantity";
this.txtQuantity.PasswordChar = '\0';
this.txtQuantity.SelectedText = "";
this.txtQuantity.Size = new System.Drawing.Size(299, 37);
this.txtQuantity.TabIndex = 10;
//
// TxtItemName
//
this.TxtItemName.BaseColor = System.Drawing.Color.White;
this.TxtItemName.BorderColor = System.Drawing.Color.Silver;
this.TxtItemName.BorderSize = 0;
this.TxtItemName.Cursor = System.Windows.Forms.Cursors.IBeam;
this.TxtItemName.FocusedBaseColor = System.Drawing.Color.White;
this.TxtItemName.FocusedBorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(100)))), ((int)(((byte)(88)))), ((int)(((byte)(255)))));
this.TxtItemName.FocusedForeColor = System.Drawing.SystemColors.ControlText;
this.TxtItemName.Font = new System.Drawing.Font("Segoe UI", 9F);
this.TxtItemName.Location = new System.Drawing.Point(34, 245);
this.TxtItemName.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.TxtItemName.Name = "TxtItemName";
this.TxtItemName.PasswordChar = '\0';
this.TxtItemName.SelectedText = "";
this.TxtItemName.Size = new System.Drawing.Size(299, 37);
this.TxtItemName.TabIndex = 11;
//
// dgvResourt
//
this.dgvResourt.AllowUserToAddRows = false;
this.dgvResourt.AllowUserToDeleteRows = false;
dataGridViewCellStyle1.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(26)))), ((int)(((byte)(29)))), ((int)(((byte)(33)))));
this.dgvResourt.AlternatingRowsDefaultCellStyle = dataGridViewCellStyle1;
this.dgvResourt.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.Fill;
this.dgvResourt.BackgroundColor = System.Drawing.Color.FromArgb(((int)(((byte)(26)))), ((int)(((byte)(29)))), ((int)(((byte)(33)))));
this.dgvResourt.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.dgvResourt.CellBorderStyle = System.Windows.Forms.DataGridViewCellBorderStyle.SingleHorizontal;
this.dgvResourt.ColumnHeadersBorderStyle = System.Windows.Forms.DataGridViewHeaderBorderStyle.None;
dataGridViewCellStyle2.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft;
dataGridViewCellStyle2.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(51)))), ((int)(((byte)(110)))), ((int)(((byte)(138)))));
dataGridViewCellStyle2.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Bold);
dataGridViewCellStyle2.ForeColor = System.Drawing.Color.White;
dataGridViewCellStyle2.SelectionBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(51)))), ((int)(((byte)(110)))), ((int)(((byte)(138)))));
dataGridViewCellStyle2.SelectionForeColor = System.Drawing.SystemColors.HighlightText;
dataGridViewCellStyle2.WrapMode = System.Windows.Forms.DataGridViewTriState.True;
this.dgvResourt.ColumnHeadersDefaultCellStyle = dataGridViewCellStyle2;
this.dgvResourt.ColumnHeadersHeight = 60;
this.dgvResourt.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.iteam_Id,
this.iteam_name,
this.avalable_count,
this.iteam_price});
dataGridViewCellStyle3.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft;
dataGridViewCellStyle3.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(26)))), ((int)(((byte)(29)))), ((int)(((byte)(33)))));
dataGridViewCellStyle3.Font = new System.Drawing.Font("Segoe UI", 10.5F);
dataGridViewCellStyle3.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(51)))), ((int)(((byte)(110)))), ((int)(((byte)(138)))));
dataGridViewCellStyle3.SelectionBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(26)))), ((int)(((byte)(29)))), ((int)(((byte)(33)))));
dataGridViewCellStyle3.SelectionForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(51)))), ((int)(((byte)(110)))), ((int)(((byte)(138)))));
dataGridViewCellStyle3.WrapMode = System.Windows.Forms.DataGridViewTriState.False;
this.dgvResourt.DefaultCellStyle = dataGridViewCellStyle3;
this.dgvResourt.EnableHeadersVisualStyles = false;
this.dgvResourt.GridColor = System.Drawing.Color.FromArgb(((int)(((byte)(26)))), ((int)(((byte)(29)))), ((int)(((byte)(33)))));
this.dgvResourt.Location = new System.Drawing.Point(747, 228);
this.dgvResourt.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.dgvResourt.Name = "dgvResourt";
this.dgvResourt.ReadOnly = true;
this.dgvResourt.RowHeadersVisible = false;
this.dgvResourt.RowHeadersWidth = 51;
this.dgvResourt.RowTemplate.Height = 24;
this.dgvResourt.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect;
this.dgvResourt.Size = new System.Drawing.Size(777, 395);
this.dgvResourt.TabIndex = 23;
this.dgvResourt.Theme = Guna.UI.WinForms.GunaDataGridViewPresetThemes.Guna;
this.dgvResourt.ThemeStyle.AlternatingRowsStyle.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(26)))), ((int)(((byte)(29)))), ((int)(((byte)(33)))));
this.dgvResourt.ThemeStyle.AlternatingRowsStyle.Font = null;
this.dgvResourt.ThemeStyle.AlternatingRowsStyle.ForeColor = System.Drawing.Color.Empty;
this.dgvResourt.ThemeStyle.AlternatingRowsStyle.SelectionBackColor = System.Drawing.Color.Empty;
this.dgvResourt.ThemeStyle.AlternatingRowsStyle.SelectionForeColor = System.Drawing.Color.Empty;
this.dgvResourt.ThemeStyle.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(26)))), ((int)(((byte)(29)))), ((int)(((byte)(33)))));
this.dgvResourt.ThemeStyle.GridColor = System.Drawing.Color.FromArgb(((int)(((byte)(26)))), ((int)(((byte)(29)))), ((int)(((byte)(33)))));
this.dgvResourt.ThemeStyle.HeaderStyle.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(51)))), ((int)(((byte)(110)))), ((int)(((byte)(138)))));
this.dgvResourt.ThemeStyle.HeaderStyle.BorderStyle = System.Windows.Forms.DataGridViewHeaderBorderStyle.None;
this.dgvResourt.ThemeStyle.HeaderStyle.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Bold);
this.dgvResourt.ThemeStyle.HeaderStyle.ForeColor = System.Drawing.Color.White;
this.dgvResourt.ThemeStyle.HeaderStyle.HeaightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.EnableResizing;
this.dgvResourt.ThemeStyle.HeaderStyle.Height = 60;
this.dgvResourt.ThemeStyle.ReadOnly = true;
this.dgvResourt.ThemeStyle.RowsStyle.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(26)))), ((int)(((byte)(29)))), ((int)(((byte)(33)))));
this.dgvResourt.ThemeStyle.RowsStyle.BorderStyle = System.Windows.Forms.DataGridViewCellBorderStyle.SingleHorizontal;
this.dgvResourt.ThemeStyle.RowsStyle.Font = new System.Drawing.Font("Segoe UI", 10.5F);
this.dgvResourt.ThemeStyle.RowsStyle.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(51)))), ((int)(((byte)(110)))), ((int)(((byte)(138)))));
this.dgvResourt.ThemeStyle.RowsStyle.Height = 24;
this.dgvResourt.ThemeStyle.RowsStyle.SelectionBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(26)))), ((int)(((byte)(29)))), ((int)(((byte)(33)))));
this.dgvResourt.ThemeStyle.RowsStyle.SelectionForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(51)))), ((int)(((byte)(110)))), ((int)(((byte)(138)))));
//
// txtPrice
//
this.txtPrice.BaseColor = System.Drawing.Color.White;
this.txtPrice.BorderColor = System.Drawing.Color.Silver;
this.txtPrice.BorderSize = 0;
this.txtPrice.Cursor = System.Windows.Forms.Cursors.IBeam;
this.txtPrice.FocusedBaseColor = System.Drawing.Color.White;
this.txtPrice.FocusedBorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(100)))), ((int)(((byte)(88)))), ((int)(((byte)(255)))));
this.txtPrice.FocusedForeColor = System.Drawing.SystemColors.ControlText;
this.txtPrice.Font = new System.Drawing.Font("Segoe UI", 9F);
this.txtPrice.Location = new System.Drawing.Point(378, 245);
this.txtPrice.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.txtPrice.Name = "txtPrice";
this.txtPrice.PasswordChar = '\0';
this.txtPrice.SelectedText = "";
this.txtPrice.Size = new System.Drawing.Size(299, 37);
this.txtPrice.TabIndex = 10;
//
// gunaLabel1
//
this.gunaLabel1.AutoSize = true;
this.gunaLabel1.Font = new System.Drawing.Font("Segoe UI", 11F);
this.gunaLabel1.ForeColor = System.Drawing.SystemColors.Control;
this.gunaLabel1.Location = new System.Drawing.Point(373, 207);
this.gunaLabel1.Name = "gunaLabel1";
this.gunaLabel1.Size = new System.Drawing.Size(54, 25);
this.gunaLabel1.TabIndex = 12;
this.gunaLabel1.Text = "Price";
//
// lblPriceErr
//
this.lblPriceErr.AutoSize = true;
this.lblPriceErr.Font = new System.Drawing.Font("Segoe UI", 9F);
this.lblPriceErr.ForeColor = System.Drawing.Color.Red;
this.lblPriceErr.Location = new System.Drawing.Point(382, 291);
this.lblPriceErr.Name = "lblPriceErr";
this.lblPriceErr.Size = new System.Drawing.Size(0, 20);
this.lblPriceErr.TabIndex = 14;
//
// iteam_Id
//
this.iteam_Id.DataPropertyName = "iteam_Id";
this.iteam_Id.HeaderText = "Item ID";
this.iteam_Id.MinimumWidth = 6;
this.iteam_Id.Name = "iteam_Id";
this.iteam_Id.ReadOnly = true;
//
// iteam_name
//
this.iteam_name.DataPropertyName = "iteam_name";
this.iteam_name.HeaderText = "Item";
this.iteam_name.MinimumWidth = 6;
this.iteam_name.Name = "iteam_name";
this.iteam_name.ReadOnly = true;
//
// avalable_count
//
this.avalable_count.DataPropertyName = "avalable_count";
this.avalable_count.HeaderText = "Quantity";
this.avalable_count.MinimumWidth = 6;
this.avalable_count.Name = "avalable_count";
this.avalable_count.ReadOnly = true;
//
// iteam_price
//
this.iteam_price.DataPropertyName = "iteam_price";
this.iteam_price.HeaderText = "Price";
this.iteam_price.MinimumWidth = 6;
this.iteam_price.Name = "iteam_price";
this.iteam_price.ReadOnly = true;
//
// frmAdminResturent
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(26)))), ((int)(((byte)(29)))), ((int)(((byte)(33)))));
this.ClientSize = new System.Drawing.Size(1564, 699);
this.Controls.Add(this.dgvResourt);
this.Controls.Add(this.btnSave);
this.Controls.Add(this.lblPriceErr);
this.Controls.Add(this.lblQuantityErr);
this.Controls.Add(this.lblItemErr);
this.Controls.Add(this.gunaLabel1);
this.Controls.Add(this.gunaLabel2);
this.Controls.Add(this.gunaLabel4);
this.Controls.Add(this.txtPrice);
this.Controls.Add(this.txtQuantity);
this.Controls.Add(this.TxtItemName);
this.Controls.Add(this.bunifuImageButton1);
this.Controls.Add(this.gunaTextBox1);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
this.Name = "frmAdminResturent";
this.Text = "frmAdminDash";
this.Load += new System.EventHandler(this.frmAdminResourt_Load);
((System.ComponentModel.ISupportInitialize)(this.bunifuImageButton1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.dgvResourt)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private Guna.UI.WinForms.GunaElipse gunaElipse1;
private Guna.UI.WinForms.GunaTextBox gunaTextBox1;
private Bunifu.Framework.UI.BunifuImageButton bunifuImageButton1;
private Guna.UI.WinForms.GunaButton btnSave;
private Guna.UI.WinForms.GunaLabel lblQuantityErr;
private Guna.UI.WinForms.GunaLabel lblItemErr;
private Guna.UI.WinForms.GunaLabel gunaLabel2;
private Guna.UI.WinForms.GunaLabel gunaLabel4;
private Guna.UI.WinForms.GunaTextBox txtQuantity;
private Guna.UI.WinForms.GunaTextBox TxtItemName;
private Guna.UI.WinForms.GunaDataGridView dgvResourt;
private Guna.UI.WinForms.GunaLabel lblPriceErr;
private Guna.UI.WinForms.GunaLabel gunaLabel1;
private Guna.UI.WinForms.GunaTextBox txtPrice;
private System.Windows.Forms.DataGridViewTextBoxColumn iteam_Id;
private System.Windows.Forms.DataGridViewTextBoxColumn iteam_name;
private System.Windows.Forms.DataGridViewTextBoxColumn avalable_count;
private System.Windows.Forms.DataGridViewTextBoxColumn iteam_price;
}
} | 61.345361 | 171 | 0.628813 | [
"MIT"
] | snafal/Train-Express-C- | Railway express/Railway express/frmAdminResturent.Designer.cs | 23,804 | 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 swf-2012-01-25.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.SimpleWorkflow.Model
{
/// <summary>
/// Provides details of the <code>CancelWorkflowExecutionFailed</code> event.
/// </summary>
public partial class CancelWorkflowExecutionFailedEventAttributes
{
private CancelWorkflowExecutionFailedCause _cause;
private long? _decisionTaskCompletedEventId;
/// <summary>
/// Gets and sets the property Cause.
/// <para>
/// The cause of the failure. This information is generated by the system and can be useful
/// for diagnostic purposes.
/// </para>
/// <note>If <b>cause</b> is set to OPERATION_NOT_PERMITTED, the decision failed because
/// it lacked sufficient permissions. For details and example IAM policies, see <a href="http://docs.aws.amazon.com/amazonswf/latest/developerguide/swf-dev-iam.html">Using
/// IAM to Manage Access to Amazon SWF Workflows</a>.</note>
/// </summary>
public CancelWorkflowExecutionFailedCause Cause
{
get { return this._cause; }
set { this._cause = value; }
}
// Check to see if Cause property is set
internal bool IsSetCause()
{
return this._cause != null;
}
/// <summary>
/// Gets and sets the property DecisionTaskCompletedEventId.
/// <para>
/// The ID of the <code>DecisionTaskCompleted</code> event corresponding to the decision
/// task that resulted in the <code>CancelWorkflowExecution</code> decision for this cancellation
/// request. This information can be useful for diagnosing problems by tracing back the
/// chain of events leading up to this event.
/// </para>
/// </summary>
public long DecisionTaskCompletedEventId
{
get { return this._decisionTaskCompletedEventId.GetValueOrDefault(); }
set { this._decisionTaskCompletedEventId = value; }
}
// Check to see if DecisionTaskCompletedEventId property is set
internal bool IsSetDecisionTaskCompletedEventId()
{
return this._decisionTaskCompletedEventId.HasValue;
}
}
} | 37.585366 | 179 | 0.665477 | [
"Apache-2.0"
] | Bynder/aws-sdk-net | sdk/src/Services/SimpleWorkflow/Generated/Model/CancelWorkflowExecutionFailedEventAttributes.cs | 3,082 | C# |
using System;
namespace SIL.Cog.Application.Import
{
public class ImportException : Exception
{
public ImportException(string message)
: base(message)
{
}
public ImportException(string message, Exception innerException)
: base(message, innerException)
{
}
}
}
| 15.722222 | 66 | 0.724382 | [
"MIT"
] | sillsdev/cog | Cog.Application/Import/ImportException.cs | 283 | 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.Management.IotHub
{
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// IotHubResourceOperations operations.
/// </summary>
public partial interface IIotHubResourceOperations
{
/// <summary>
/// Get the non-security related metadata of an IoT hub.
/// </summary>
/// <remarks>
/// Get the non-security related metadata of an IoT hub.
/// </remarks>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the IoT hub.
/// </param>
/// <param name='resourceName'>
/// The name of the IoT hub.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorDetailsException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IotHubDescription>> GetWithHttpMessagesAsync(string resourceGroupName, string resourceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Create or update the metadata of an IoT hub.
/// </summary>
/// <remarks>
/// Create or update the metadata of an Iot hub. The usual pattern to
/// modify a property is to retrieve the IoT hub metadata and
/// security metadata, and then combine them with the modified values
/// in a new body to update the IoT hub.
/// </remarks>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the IoT hub.
/// </param>
/// <param name='resourceName'>
/// The name of the IoT hub to create or update.
/// </param>
/// <param name='iotHubDescription'>
/// The IoT hub metadata and security metadata.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorDetailsException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IotHubDescription>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string resourceName, IotHubDescription iotHubDescription, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Create or update the metadata of an IoT hub.
/// </summary>
/// <remarks>
/// Create or update the metadata of an Iot hub. The usual pattern to
/// modify a property is to retrieve the IoT hub metadata and
/// security metadata, and then combine them with the modified values
/// in a new body to update the IoT hub.
/// </remarks>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the IoT hub.
/// </param>
/// <param name='resourceName'>
/// The name of the IoT hub to create or update.
/// </param>
/// <param name='iotHubDescription'>
/// The IoT hub metadata and security metadata.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorDetailsException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IotHubDescription>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string resourceName, IotHubDescription iotHubDescription, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Delete an IoT hub.
/// </summary>
/// <remarks>
/// Delete an IoT hub.
/// </remarks>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the IoT hub.
/// </param>
/// <param name='resourceName'>
/// The name of the IoT hub to delete.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorDetailsException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<object>> DeleteWithHttpMessagesAsync(string resourceGroupName, string resourceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Delete an IoT hub.
/// </summary>
/// <remarks>
/// Delete an IoT hub.
/// </remarks>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the IoT hub.
/// </param>
/// <param name='resourceName'>
/// The name of the IoT hub to delete.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorDetailsException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<object>> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string resourceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get all the IoT hubs in a subscription.
/// </summary>
/// <remarks>
/// Get all the IoT hubs in a subscription.
/// </remarks>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorDetailsException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<IotHubDescription>>> ListBySubscriptionWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get all the IoT hubs in a resource group.
/// </summary>
/// <remarks>
/// Get all the IoT hubs in a resource group.
/// </remarks>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the IoT hubs.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorDetailsException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<IotHubDescription>>> ListByResourceGroupWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get the statistics from an IoT hub.
/// </summary>
/// <remarks>
/// Get the statistics from an IoT hub.
/// </remarks>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the IoT hub.
/// </param>
/// <param name='resourceName'>
/// The name of the IoT hub.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorDetailsException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<RegistryStatistics>> GetStatsWithHttpMessagesAsync(string resourceGroupName, string resourceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get the list of valid SKUs for an IoT hub.
/// </summary>
/// <remarks>
/// Get the list of valid SKUs for an IoT hub.
/// </remarks>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the IoT hub.
/// </param>
/// <param name='resourceName'>
/// The name of the IoT hub.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorDetailsException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<IotHubSkuDescription>>> GetValidSkusWithHttpMessagesAsync(string resourceGroupName, string resourceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get a list of the consumer groups in the Event Hub-compatible
/// device-to-cloud endpoint in an IoT hub.
/// </summary>
/// <remarks>
/// Get a list of the consumer groups in the Event Hub-compatible
/// device-to-cloud endpoint in an IoT hub.
/// </remarks>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the IoT hub.
/// </param>
/// <param name='resourceName'>
/// The name of the IoT hub.
/// </param>
/// <param name='eventHubEndpointName'>
/// The name of the Event Hub-compatible endpoint.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorDetailsException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<string>>> ListEventHubConsumerGroupsWithHttpMessagesAsync(string resourceGroupName, string resourceName, string eventHubEndpointName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get a consumer group from the Event Hub-compatible device-to-cloud
/// endpoint for an IoT hub.
/// </summary>
/// <remarks>
/// Get a consumer group from the Event Hub-compatible device-to-cloud
/// endpoint for an IoT hub.
/// </remarks>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the IoT hub.
/// </param>
/// <param name='resourceName'>
/// The name of the IoT hub.
/// </param>
/// <param name='eventHubEndpointName'>
/// The name of the Event Hub-compatible endpoint in the IoT hub.
/// </param>
/// <param name='name'>
/// The name of the consumer group to retrieve.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorDetailsException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<EventHubConsumerGroupInfo>> GetEventHubConsumerGroupWithHttpMessagesAsync(string resourceGroupName, string resourceName, string eventHubEndpointName, string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Add a consumer group to an Event Hub-compatible endpoint in an IoT
/// hub.
/// </summary>
/// <remarks>
/// Add a consumer group to an Event Hub-compatible endpoint in an IoT
/// hub.
/// </remarks>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the IoT hub.
/// </param>
/// <param name='resourceName'>
/// The name of the IoT hub.
/// </param>
/// <param name='eventHubEndpointName'>
/// The name of the Event Hub-compatible endpoint in the IoT hub.
/// </param>
/// <param name='name'>
/// The name of the consumer group to add.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorDetailsException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<EventHubConsumerGroupInfo>> CreateEventHubConsumerGroupWithHttpMessagesAsync(string resourceGroupName, string resourceName, string eventHubEndpointName, string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Delete a consumer group from an Event Hub-compatible endpoint in
/// an IoT hub.
/// </summary>
/// <remarks>
/// Delete a consumer group from an Event Hub-compatible endpoint in
/// an IoT hub.
/// </remarks>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the IoT hub.
/// </param>
/// <param name='resourceName'>
/// The name of the IoT hub.
/// </param>
/// <param name='eventHubEndpointName'>
/// The name of the Event Hub-compatible endpoint in the IoT hub.
/// </param>
/// <param name='name'>
/// The name of the consumer group to delete.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorDetailsException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> DeleteEventHubConsumerGroupWithHttpMessagesAsync(string resourceGroupName, string resourceName, string eventHubEndpointName, string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get a list of all the jobs in an IoT hub. For more information,
/// see:
/// https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-identity-registry.
/// </summary>
/// <remarks>
/// Get a list of all the jobs in an IoT hub. For more information,
/// see:
/// https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-identity-registry.
/// </remarks>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the IoT hub.
/// </param>
/// <param name='resourceName'>
/// The name of the IoT hub.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorDetailsException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<JobResponse>>> ListJobsWithHttpMessagesAsync(string resourceGroupName, string resourceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get the details of a job from an IoT hub. For more information,
/// see:
/// https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-identity-registry.
/// </summary>
/// <remarks>
/// Get the details of a job from an IoT hub. For more information,
/// see:
/// https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-identity-registry.
/// </remarks>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the IoT hub.
/// </param>
/// <param name='resourceName'>
/// The name of the IoT hub.
/// </param>
/// <param name='jobId'>
/// The job identifier.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorDetailsException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<JobResponse>> GetJobWithHttpMessagesAsync(string resourceGroupName, string resourceName, string jobId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get the quota metrics for an IoT hub.
/// </summary>
/// <remarks>
/// Get the quota metrics for an IoT hub.
/// </remarks>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the IoT hub.
/// </param>
/// <param name='resourceName'>
/// The name of the IoT hub.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorDetailsException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<IotHubQuotaMetricInfo>>> GetQuotaMetricsWithHttpMessagesAsync(string resourceGroupName, string resourceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Check if an IoT hub name is available.
/// </summary>
/// <remarks>
/// Check if an IoT hub name is available.
/// </remarks>
/// <param name='operationInputs'>
/// Set the name parameter in the OperationInputs structure to the
/// name of the IoT hub to check.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorDetailsException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IotHubNameAvailabilityInfo>> CheckNameAvailabilityWithHttpMessagesAsync(OperationInputs operationInputs, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get the security metadata for an IoT hub. For more information,
/// see:
/// https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-security.
/// </summary>
/// <remarks>
/// Get the security metadata for an IoT hub. For more information,
/// see:
/// https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-security.
/// </remarks>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the IoT hub.
/// </param>
/// <param name='resourceName'>
/// The name of the IoT hub.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorDetailsException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<SharedAccessSignatureAuthorizationRule>>> ListKeysWithHttpMessagesAsync(string resourceGroupName, string resourceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get a shared access policy by name from an IoT hub. For more
/// information, see:
/// https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-security.
/// </summary>
/// <remarks>
/// Get a shared access policy by name from an IoT hub. For more
/// information, see:
/// https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-security.
/// </remarks>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the IoT hub.
/// </param>
/// <param name='resourceName'>
/// The name of the IoT hub.
/// </param>
/// <param name='keyName'>
/// The name of the shared access policy.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorDetailsException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<SharedAccessSignatureAuthorizationRule>> GetKeysForKeyNameWithHttpMessagesAsync(string resourceGroupName, string resourceName, string keyName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Exports all the device identities in the IoT hub identity registry
/// to an Azure Storage blob container. For more information, see:
/// https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-identity-registry#import-and-export-device-identities.
/// </summary>
/// <remarks>
/// Exports all the device identities in the IoT hub identity registry
/// to an Azure Storage blob container. For more information, see:
/// https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-identity-registry#import-and-export-device-identities.
/// </remarks>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the IoT hub.
/// </param>
/// <param name='resourceName'>
/// The name of the IoT hub.
/// </param>
/// <param name='exportDevicesParameters'>
/// The parameters that specify the export devices operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorDetailsException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<JobResponse>> ExportDevicesWithHttpMessagesAsync(string resourceGroupName, string resourceName, ExportDevicesRequest exportDevicesParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Import, update, or delete device identities in the IoT hub
/// identity registry from a blob. For more information, see:
/// https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-identity-registry#import-and-export-device-identities.
/// </summary>
/// <remarks>
/// Import, update, or delete device identities in the IoT hub
/// identity registry from a blob. For more information, see:
/// https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-identity-registry#import-and-export-device-identities.
/// </remarks>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the IoT hub.
/// </param>
/// <param name='resourceName'>
/// The name of the IoT hub.
/// </param>
/// <param name='importDevicesParameters'>
/// The parameters that specify the import devices operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorDetailsException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<JobResponse>> ImportDevicesWithHttpMessagesAsync(string resourceGroupName, string resourceName, ImportDevicesRequest importDevicesParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get all the IoT hubs in a subscription.
/// </summary>
/// <remarks>
/// Get all the IoT hubs in a subscription.
/// </remarks>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorDetailsException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<IotHubDescription>>> ListBySubscriptionNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get all the IoT hubs in a resource group.
/// </summary>
/// <remarks>
/// Get all the IoT hubs in a resource group.
/// </remarks>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorDetailsException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<IotHubDescription>>> ListByResourceGroupNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get the list of valid SKUs for an IoT hub.
/// </summary>
/// <remarks>
/// Get the list of valid SKUs for an IoT hub.
/// </remarks>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorDetailsException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<IotHubSkuDescription>>> GetValidSkusNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get a list of the consumer groups in the Event Hub-compatible
/// device-to-cloud endpoint in an IoT hub.
/// </summary>
/// <remarks>
/// Get a list of the consumer groups in the Event Hub-compatible
/// device-to-cloud endpoint in an IoT hub.
/// </remarks>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorDetailsException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<string>>> ListEventHubConsumerGroupsNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get a list of all the jobs in an IoT hub. For more information,
/// see:
/// https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-identity-registry.
/// </summary>
/// <remarks>
/// Get a list of all the jobs in an IoT hub. For more information,
/// see:
/// https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-identity-registry.
/// </remarks>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorDetailsException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<JobResponse>>> ListJobsNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get the quota metrics for an IoT hub.
/// </summary>
/// <remarks>
/// Get the quota metrics for an IoT hub.
/// </remarks>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorDetailsException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<IotHubQuotaMetricInfo>>> GetQuotaMetricsNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get the security metadata for an IoT hub. For more information,
/// see:
/// https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-security.
/// </summary>
/// <remarks>
/// Get the security metadata for an IoT hub. For more information,
/// see:
/// https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-security.
/// </remarks>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorDetailsException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<SharedAccessSignatureAuthorizationRule>>> ListKeysNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| 48.570104 | 323 | 0.611103 | [
"MIT"
] | azure-keyvault/azure-sdk-for-net | src/SDKs/IotHub/Management.IotHub/Generated/IIotHubResourceOperations.cs | 41,916 | 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.ContainerInstance.Models.Api20210901
{
using Microsoft.Azure.PowerShell.Cmdlets.ContainerInstance.Runtime.PowerShell;
/// <summary>
/// A PowerShell PSTypeConverter to support converting to an instance of <see cref="Components10Wh5UdSchemasContainergroupidentityPropertiesUserassignedidentitiesAdditionalproperties"
/// />
/// </summary>
public partial class Components10Wh5UdSchemasContainergroupidentityPropertiesUserassignedidentitiesAdditionalpropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter
{
/// <summary>
/// Determines if the converter can convert the <paramref name="sourceValue"/> parameter to the <paramref name="destinationType"
/// /> parameter.
/// </summary>
/// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param>
/// <param name="destinationType">the <see cref="System.Type" /> to convert to</param>
/// <returns>
/// <c>true</c> if the converter can convert the <paramref name="sourceValue"/> parameter to the <paramref name="destinationType"
/// /> parameter, otherwise <c>false</c>.
/// </returns>
public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue);
/// <summary>
/// Determines if the converter can convert the <paramref name="sourceValue"/> parameter to the <see cref="Components10Wh5UdSchemasContainergroupidentityPropertiesUserassignedidentitiesAdditionalproperties"/>
/// type.
/// </summary>
/// <param name="sourceValue">the <see cref="System.Object" /> instance to check if it can be converted to the <see cref="Components10Wh5UdSchemasContainergroupidentityPropertiesUserassignedidentitiesAdditionalproperties"
/// /> type.</param>
/// <returns>
/// <c>true</c> if the instance could be converted to a <see cref="Components10Wh5UdSchemasContainergroupidentityPropertiesUserassignedidentitiesAdditionalproperties"
/// /> type, otherwise <c>false</c>
/// </returns>
public static bool CanConvertFrom(dynamic sourceValue)
{
if (null == sourceValue)
{
return true;
}
global::System.Type type = sourceValue.GetType();
if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type))
{
// we say yest to PSObjects
return true;
}
if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type))
{
// we say yest to Hashtables/dictionaries
return true;
}
try
{
if (null != sourceValue.ToJsonString())
{
return true;
}
}
catch
{
// Not one of our objects
}
try
{
string text = sourceValue.ToString()?.Trim();
return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.ContainerInstance.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.ContainerInstance.Runtime.Json.JsonType.Object;
}
catch
{
// Doesn't look like it can be treated as JSON
}
return false;
}
/// <summary>
/// Determines if the <paramref name="sourceValue" /> parameter can be converted to the <paramref name="destinationType" />
/// parameter
/// </summary>
/// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param>
/// <param name="destinationType">the <see cref="System.Type" /> to convert to</param>
/// <returns>
/// <c>true</c> if the converter can convert the <paramref name="sourceValue" /> parameter to the <paramref name="destinationType"
/// /> parameter, otherwise <c>false</c>
/// </returns>
public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false;
/// <summary>
/// Converts the <paramref name="sourceValue" /> parameter to the <paramref name="destinationType" /> parameter using <paramref
/// name="formatProvider" /> and <paramref name="ignoreCase" />
/// </summary>
/// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param>
/// <param name="destinationType">the <see cref="System.Type" /> to convert to</param>
/// <param name="formatProvider">not used by this TypeConverter.</param>
/// <param name="ignoreCase">when set to <c>true</c>, will ignore the case when converting.</param>
/// <returns>
/// an instance of <see cref="Components10Wh5UdSchemasContainergroupidentityPropertiesUserassignedidentitiesAdditionalproperties"
/// />, or <c>null</c> if there is no suitable conversion.
/// </returns>
public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue);
/// <summary>
/// Converts the <paramref name="sourceValue" /> parameter into an instance of <see cref="Components10Wh5UdSchemasContainergroupidentityPropertiesUserassignedidentitiesAdditionalproperties"
/// />
/// </summary>
/// <param name="sourceValue">the value to convert into an instance of <see cref="Components10Wh5UdSchemasContainergroupidentityPropertiesUserassignedidentitiesAdditionalproperties"
/// />.</param>
/// <returns>
/// an instance of <see cref="Components10Wh5UdSchemasContainergroupidentityPropertiesUserassignedidentitiesAdditionalproperties"
/// />, or <c>null</c> if there is no suitable conversion.
/// </returns>
public static Microsoft.Azure.PowerShell.Cmdlets.ContainerInstance.Models.Api20210901.IComponents10Wh5UdSchemasContainergroupidentityPropertiesUserassignedidentitiesAdditionalproperties ConvertFrom(dynamic sourceValue)
{
if (null == sourceValue)
{
return null;
}
global::System.Type type = sourceValue.GetType();
if (typeof(Microsoft.Azure.PowerShell.Cmdlets.ContainerInstance.Models.Api20210901.IComponents10Wh5UdSchemasContainergroupidentityPropertiesUserassignedidentitiesAdditionalproperties).IsAssignableFrom(type))
{
return sourceValue;
}
try
{
return Components10Wh5UdSchemasContainergroupidentityPropertiesUserassignedidentitiesAdditionalproperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());;
}
catch
{
// Unable to use JSON pattern
}
if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type))
{
return Components10Wh5UdSchemasContainergroupidentityPropertiesUserassignedidentitiesAdditionalproperties.DeserializeFromPSObject(sourceValue);
}
if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type))
{
return Components10Wh5UdSchemasContainergroupidentityPropertiesUserassignedidentitiesAdditionalproperties.DeserializeFromDictionary(sourceValue);
}
return null;
}
/// <summary>NotImplemented -- this will return <c>null</c></summary>
/// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param>
/// <param name="destinationType">the <see cref="System.Type" /> to convert to</param>
/// <param name="formatProvider">not used by this TypeConverter.</param>
/// <param name="ignoreCase">when set to <c>true</c>, will ignore the case when converting.</param>
/// <returns>will always return <c>null</c>.</returns>
public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null;
}
} | 58.045752 | 265 | 0.642495 | [
"MIT"
] | imadan1996/azure-powershell | src/ContainerInstance/generated/api/Models/Api20210901/Components10Wh5UdSchemasContainergroupidentityPropertiesUserassignedidentitiesAdditionalproperties.TypeConverter.cs | 8,729 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("MissionariesCannibalsPassRiver")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("MissionariesCannibalsPassRiver")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("2c67d942-93a6-4d96-bfc0-8e1fba099cc8")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 39.216216 | 84 | 0.754652 | [
"MIT"
] | JYang17/SampleCode | Samples/MissionariesCannibalsPassRiver/MissionariesCannibalsPassRiver/Properties/AssemblyInfo.cs | 1,454 | C# |
using MessagePackLib.MessagePack;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Windows.Forms;
namespace Plugin
{
public static class Packet
{
public static FormChat GetFormChat;
public static void Read(object data)
{
try
{
MsgPack unpack_msgpack = new MsgPack();
unpack_msgpack.DecodeFromBytes((byte[])data);
switch (unpack_msgpack.ForcePathObject("Pac_ket").AsString)
{
case "chat":
{
new HandlerChat().CreateChat();
break;
}
case "chatWriteInput":
{
new HandlerChat().WriteInput(unpack_msgpack);
break;
}
case "chatExit":
{
new HandlerChat().ExitChat();
break;
}
}
}
catch { }
}
}
public class HandlerChat
{
public void CreateChat()
{
new Thread(() =>
{
Packet.GetFormChat = new FormChat();
Packet.GetFormChat.ShowDialog();
}).Start();
}
public void WriteInput(MsgPack unpack_msgpack)
{
if (Packet.GetFormChat.InvokeRequired)
{
Packet.GetFormChat.Invoke((MethodInvoker)(() =>
{
Console.Beep();
Packet.GetFormChat.richTextBox1.SelectionColor = Color.Blue;
Packet.GetFormChat.richTextBox1.AppendText(unpack_msgpack.ForcePathObject("Input").AsString);
Packet.GetFormChat.richTextBox1.SelectionColor = Color.Black;
Packet.GetFormChat.richTextBox1.AppendText(unpack_msgpack.ForcePathObject("Input2").AsString + Environment.NewLine);
}));
}
}
public void ExitChat()
{
if (Packet.GetFormChat.InvokeRequired)
{
Packet.GetFormChat.Invoke((MethodInvoker)(() =>
{
Packet.GetFormChat?.Close();
Packet.GetFormChat?.Dispose();
}));
}
Connection.Disconnected();
GC.Collect();
}
}
}
| 29.516484 | 136 | 0.473939 | [
"MIT"
] | Aekras1a/DeceasedRat | Plugin/Chat/Chat/Packet.cs | 2,688 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNextGen.Network.V20190201
{
/// <summary>
/// Virtual Network resource.
/// </summary>
[AzureNextGenResourceType("azure-nextgen:network/v20190201:VirtualNetwork")]
public partial class VirtualNetwork : Pulumi.CustomResource
{
/// <summary>
/// The AddressSpace that contains an array of IP address ranges that can be used by subnets.
/// </summary>
[Output("addressSpace")]
public Output<Outputs.AddressSpaceResponse?> AddressSpace { get; private set; } = null!;
/// <summary>
/// The DDoS protection plan associated with the virtual network.
/// </summary>
[Output("ddosProtectionPlan")]
public Output<Outputs.SubResourceResponse?> DdosProtectionPlan { get; private set; } = null!;
/// <summary>
/// The dhcpOptions that contains an array of DNS servers available to VMs deployed in the virtual network.
/// </summary>
[Output("dhcpOptions")]
public Output<Outputs.DhcpOptionsResponse?> DhcpOptions { get; private set; } = null!;
/// <summary>
/// Indicates if DDoS protection is enabled for all the protected resources in the virtual network. It requires a DDoS protection plan associated with the resource.
/// </summary>
[Output("enableDdosProtection")]
public Output<bool?> EnableDdosProtection { get; private set; } = null!;
/// <summary>
/// Indicates if VM protection is enabled for all the subnets in the virtual network.
/// </summary>
[Output("enableVmProtection")]
public Output<bool?> EnableVmProtection { get; private set; } = null!;
/// <summary>
/// Gets a unique read-only string that changes whenever the resource is updated.
/// </summary>
[Output("etag")]
public Output<string?> Etag { get; private set; } = null!;
/// <summary>
/// Resource location.
/// </summary>
[Output("location")]
public Output<string?> Location { get; private set; } = null!;
/// <summary>
/// Resource name.
/// </summary>
[Output("name")]
public Output<string> Name { get; private set; } = null!;
/// <summary>
/// The provisioning state of the PublicIP resource. Possible values are: 'Updating', 'Deleting', and 'Failed'.
/// </summary>
[Output("provisioningState")]
public Output<string?> ProvisioningState { get; private set; } = null!;
/// <summary>
/// The resourceGuid property of the Virtual Network resource.
/// </summary>
[Output("resourceGuid")]
public Output<string?> ResourceGuid { get; private set; } = null!;
/// <summary>
/// A list of subnets in a Virtual Network.
/// </summary>
[Output("subnets")]
public Output<ImmutableArray<Outputs.SubnetResponse>> Subnets { get; private set; } = null!;
/// <summary>
/// Resource tags.
/// </summary>
[Output("tags")]
public Output<ImmutableDictionary<string, string>?> Tags { get; private set; } = null!;
/// <summary>
/// Resource type.
/// </summary>
[Output("type")]
public Output<string> Type { get; private set; } = null!;
/// <summary>
/// A list of peerings in a Virtual Network.
/// </summary>
[Output("virtualNetworkPeerings")]
public Output<ImmutableArray<Outputs.VirtualNetworkPeeringResponse>> VirtualNetworkPeerings { get; private set; } = null!;
/// <summary>
/// Create a VirtualNetwork resource with the given unique name, arguments, and options.
/// </summary>
///
/// <param name="name">The unique name of the resource</param>
/// <param name="args">The arguments used to populate this resource's properties</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public VirtualNetwork(string name, VirtualNetworkArgs args, CustomResourceOptions? options = null)
: base("azure-nextgen:network/v20190201:VirtualNetwork", name, args ?? new VirtualNetworkArgs(), MakeResourceOptions(options, ""))
{
}
private VirtualNetwork(string name, Input<string> id, CustomResourceOptions? options = null)
: base("azure-nextgen:network/v20190201:VirtualNetwork", name, null, MakeResourceOptions(options, id))
{
}
private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id)
{
var defaultOptions = new CustomResourceOptions
{
Version = Utilities.Version,
Aliases =
{
new Pulumi.Alias { Type = "azure-nextgen:network:VirtualNetwork"},
new Pulumi.Alias { Type = "azure-nextgen:network/latest:VirtualNetwork"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20150501preview:VirtualNetwork"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20150615:VirtualNetwork"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20160330:VirtualNetwork"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20160601:VirtualNetwork"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20160901:VirtualNetwork"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20161201:VirtualNetwork"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20170301:VirtualNetwork"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20170601:VirtualNetwork"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20170801:VirtualNetwork"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20170901:VirtualNetwork"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20171001:VirtualNetwork"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20171101:VirtualNetwork"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20180101:VirtualNetwork"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20180201:VirtualNetwork"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20180401:VirtualNetwork"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20180601:VirtualNetwork"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20180701:VirtualNetwork"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20180801:VirtualNetwork"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20181001:VirtualNetwork"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20181101:VirtualNetwork"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20181201:VirtualNetwork"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20190401:VirtualNetwork"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20190601:VirtualNetwork"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20190701:VirtualNetwork"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20190801:VirtualNetwork"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20190901:VirtualNetwork"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20191101:VirtualNetwork"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20191201:VirtualNetwork"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20200301:VirtualNetwork"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20200401:VirtualNetwork"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20200501:VirtualNetwork"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20200601:VirtualNetwork"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20200701:VirtualNetwork"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20200801:VirtualNetwork"},
},
};
var merged = CustomResourceOptions.Merge(defaultOptions, options);
// Override the ID if one was specified for consistency with other language SDKs.
merged.Id = id ?? merged.Id;
return merged;
}
/// <summary>
/// Get an existing VirtualNetwork resource's state with the given name, ID, and optional extra
/// properties used to qualify the lookup.
/// </summary>
///
/// <param name="name">The unique name of the resulting resource.</param>
/// <param name="id">The unique provider ID of the resource to lookup.</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public static VirtualNetwork Get(string name, Input<string> id, CustomResourceOptions? options = null)
{
return new VirtualNetwork(name, id, options);
}
}
public sealed class VirtualNetworkArgs : Pulumi.ResourceArgs
{
/// <summary>
/// The AddressSpace that contains an array of IP address ranges that can be used by subnets.
/// </summary>
[Input("addressSpace")]
public Input<Inputs.AddressSpaceArgs>? AddressSpace { get; set; }
/// <summary>
/// The DDoS protection plan associated with the virtual network.
/// </summary>
[Input("ddosProtectionPlan")]
public Input<Inputs.SubResourceArgs>? DdosProtectionPlan { get; set; }
/// <summary>
/// The dhcpOptions that contains an array of DNS servers available to VMs deployed in the virtual network.
/// </summary>
[Input("dhcpOptions")]
public Input<Inputs.DhcpOptionsArgs>? DhcpOptions { get; set; }
/// <summary>
/// Indicates if DDoS protection is enabled for all the protected resources in the virtual network. It requires a DDoS protection plan associated with the resource.
/// </summary>
[Input("enableDdosProtection")]
public Input<bool>? EnableDdosProtection { get; set; }
/// <summary>
/// Indicates if VM protection is enabled for all the subnets in the virtual network.
/// </summary>
[Input("enableVmProtection")]
public Input<bool>? EnableVmProtection { get; set; }
/// <summary>
/// Gets a unique read-only string that changes whenever the resource is updated.
/// </summary>
[Input("etag")]
public Input<string>? Etag { get; set; }
/// <summary>
/// Resource ID.
/// </summary>
[Input("id")]
public Input<string>? Id { get; set; }
/// <summary>
/// Resource location.
/// </summary>
[Input("location")]
public Input<string>? Location { get; set; }
/// <summary>
/// The provisioning state of the PublicIP resource. Possible values are: 'Updating', 'Deleting', and 'Failed'.
/// </summary>
[Input("provisioningState")]
public Input<string>? ProvisioningState { get; set; }
/// <summary>
/// The name of the resource group.
/// </summary>
[Input("resourceGroupName", required: true)]
public Input<string> ResourceGroupName { get; set; } = null!;
/// <summary>
/// The resourceGuid property of the Virtual Network resource.
/// </summary>
[Input("resourceGuid")]
public Input<string>? ResourceGuid { get; set; }
[Input("subnets")]
private InputList<Inputs.SubnetArgs>? _subnets;
/// <summary>
/// A list of subnets in a Virtual Network.
/// </summary>
public InputList<Inputs.SubnetArgs> Subnets
{
get => _subnets ?? (_subnets = new InputList<Inputs.SubnetArgs>());
set => _subnets = value;
}
[Input("tags")]
private InputMap<string>? _tags;
/// <summary>
/// Resource tags.
/// </summary>
public InputMap<string> Tags
{
get => _tags ?? (_tags = new InputMap<string>());
set => _tags = value;
}
/// <summary>
/// The name of the virtual network.
/// </summary>
[Input("virtualNetworkName")]
public Input<string>? VirtualNetworkName { get; set; }
[Input("virtualNetworkPeerings")]
private InputList<Inputs.VirtualNetworkPeeringArgs>? _virtualNetworkPeerings;
/// <summary>
/// A list of peerings in a Virtual Network.
/// </summary>
public InputList<Inputs.VirtualNetworkPeeringArgs> VirtualNetworkPeerings
{
get => _virtualNetworkPeerings ?? (_virtualNetworkPeerings = new InputList<Inputs.VirtualNetworkPeeringArgs>());
set => _virtualNetworkPeerings = value;
}
public VirtualNetworkArgs()
{
EnableDdosProtection = false;
EnableVmProtection = false;
}
}
}
| 45.45515 | 172 | 0.601593 | [
"Apache-2.0"
] | pulumi/pulumi-azure-nextgen | sdk/dotnet/Network/V20190201/VirtualNetwork.cs | 13,682 | C# |
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
// Ported from um/wincrypt.h in the Windows SDK for Windows 10.0.20348.0
// Original source is Copyright © Microsoft. All rights reserved.
using NUnit.Framework;
using System;
using System.Runtime.InteropServices;
namespace TerraFX.Interop.Windows.UnitTests;
/// <summary>Provides validation of the <see cref="OCSP_BASIC_RESPONSE_INFO" /> struct.</summary>
public static unsafe partial class OCSP_BASIC_RESPONSE_INFOTests
{
/// <summary>Validates that the <see cref="OCSP_BASIC_RESPONSE_INFO" /> struct is blittable.</summary>
[Test]
public static void IsBlittableTest()
{
Assert.That(Marshal.SizeOf<OCSP_BASIC_RESPONSE_INFO>(), Is.EqualTo(sizeof(OCSP_BASIC_RESPONSE_INFO)));
}
/// <summary>Validates that the <see cref="OCSP_BASIC_RESPONSE_INFO" /> struct has the right <see cref="LayoutKind" />.</summary>
[Test]
public static void IsLayoutSequentialTest()
{
Assert.That(typeof(OCSP_BASIC_RESPONSE_INFO).IsLayoutSequential, Is.True);
}
/// <summary>Validates that the <see cref="OCSP_BASIC_RESPONSE_INFO" /> struct has the correct size.</summary>
[Test]
public static void SizeOfTest()
{
if (Environment.Is64BitProcess)
{
Assert.That(sizeof(OCSP_BASIC_RESPONSE_INFO), Is.EqualTo(64));
}
else
{
Assert.That(sizeof(OCSP_BASIC_RESPONSE_INFO), Is.EqualTo(40));
}
}
}
| 36.395349 | 145 | 0.704792 | [
"MIT"
] | IngmarBitter/terrafx.interop.windows | tests/Interop/Windows/Windows/um/wincrypt/OCSP_BASIC_RESPONSE_INFOTests.cs | 1,567 | C# |
using System;
namespace IxMilia.Step.Items
{
public abstract class StepAxis2Placement : StepPlacement
{
private StepDirection _refDirection;
public StepDirection RefDirection
{
get { return _refDirection; }
set
{
if (value == null)
{
throw new ArgumentNullException();
}
_refDirection = value;
}
}
protected StepAxis2Placement(string name)
: base(name)
{
}
protected StepAxis2Placement(string name , StepCartesianPoint stepCartesianPoint , StepDirection direction)
: base(name , stepCartesianPoint)
{
RefDirection = direction;
}
}
}
| 22.277778 | 115 | 0.523691 | [
"MIT"
] | R1C4RDO13/step | src/IxMilia.Step/Items/StepAxis2Placement.cs | 804 | C# |
using System;
using System.Threading.Tasks;
using HtcSharp.Abstractions.Manager;
namespace HtcSharp.Abstractions {
public interface IPlugin : IReadOnlyPlugin, IDisposable {
Task Init(IServiceProvider serviceProvider);
Task Enable();
Task Disable();
}
} | 22.153846 | 61 | 0.711806 | [
"Apache-2.0"
] | jpdante/HTCSharp | HtcSharp.Abstractions/IPlugin.cs | 290 | C# |
namespace MassTransit.Azure.ServiceBus.Core.Contexts
{
using System;
using System.Threading.Tasks;
using GreenPipes;
using Microsoft.Azure.ServiceBus;
using Microsoft.Azure.ServiceBus.Core;
public class MessageSendEndpointContext :
BasePipeContext,
SendEndpointContext
{
readonly IMessageSender _client;
public MessageSendEndpointContext(ConnectionContext connectionContext, IMessageSender client)
{
_client = client;
ConnectionContext = connectionContext;
}
public ConnectionContext ConnectionContext { get; }
public string EntityPath => _client.Path;
public Task Send(Message message)
{
return _client.SendAsync(message);
}
public Task<long> ScheduleSend(Message message, DateTime scheduleEnqueueTimeUtc)
{
return _client.ScheduleMessageAsync(message, scheduleEnqueueTimeUtc);
}
public Task CancelScheduledSend(long sequenceNumber)
{
return _client.CancelScheduledMessageAsync(sequenceNumber);
}
}
}
| 27.095238 | 101 | 0.66696 | [
"ECL-2.0",
"Apache-2.0"
] | Aerodynamite/MassTrans | src/Transports/MassTransit.Azure.ServiceBus.Core/Contexts/MessageSendEndpointContext.cs | 1,138 | C# |
using System;
using System.Threading.Tasks;
namespace Device.Net
{
/// <summary>
/// This interface is a work in progress. It is not production ready.
/// </summary>
public interface IDeviceManager
{
void QueueRequest(IRequest request);
Task<TResponse> WriteAndReadAsync<TResponse>(IRequest request, Func<byte[], TResponse> convertFunc);
void SelectDevice(ConnectedDeviceDefinition connectedDevice);
void Start();
}
} | 25.157895 | 108 | 0.6841 | [
"MIT"
] | D0ctorWh0/Device.Net | src/Device.Net.Reactive/IDeviceManager.cs | 480 | C# |
namespace AzureDevOpsKats.Common.Configuration
{
public class ElasticSearchConfiguration
{
public string ElasticUrl { get; set; }
public bool Enabled { get; set; }
}
}
| 19.8 | 47 | 0.661616 | [
"MIT"
] | FantasticFullStackDev/AzureDevOpsKats | src/AzureDevOpsKats.Common/Configuration/ElasticSearchConfiguration.cs | 200 | C# |
using Autofac;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Server.Kestrel.Core;
using Microsoft.Extensions.DependencyInjection;
using Common;
using Mesh.Dapr;
using System;
using System.Collections.Generic;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace IocModule
{
public static class ContainerBuilderExtension
{
/// <summary>
/// 依赖注入IOC模块
/// </summary>
/// <param name="builder"></param>
/// <returns></returns>
public static ContainerBuilder RegisterModule(this ContainerBuilder builder)
{
//注入通用服务
builder.RegisterModule(new Common.Module());
builder.RegisterModule(new Server.Kestrel.Module());
builder.RegisterModule(new ProxyGenerator.Module());
builder.RegisterModule(new Client.ServerProxyFactory.Module());
return builder;
}
}
}
| 28.705882 | 84 | 0.675205 | [
"MIT"
] | 107295472/DaprHost | Dapr/IocModule/ContainerBuilderExtension.cs | 1,002 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.